ManageLanguages.php 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  1. <?php
  2. /**
  3. * This file handles the administration of languages tasks.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines
  9. * @copyright 2014 Simple Machines and individual contributors
  10. * @license http://www.simplemachines.org/about/smf/license.php BSD
  11. *
  12. * @version 2.1 Alpha 1
  13. */
  14. if (!defined('SMF'))
  15. die('No direct access...');
  16. /**
  17. * This is the main function for the languages area.
  18. * It dispatches the requests.
  19. * Loads the ManageLanguages template. (sub-actions will use it)
  20. * @todo lazy loading.
  21. *
  22. * @uses ManageSettings language file
  23. */
  24. function ManageLanguages()
  25. {
  26. global $context, $txt, $scripturl;
  27. loadTemplate('ManageLanguages');
  28. loadLanguage('ManageSettings');
  29. $context['page_title'] = $txt['edit_languages'];
  30. $context['sub_template'] = 'show_settings';
  31. $subActions = array(
  32. 'edit' => 'ModifyLanguages',
  33. 'add' => 'AddLanguage',
  34. 'settings' => 'ModifyLanguageSettings',
  35. 'downloadlang' => 'DownloadLanguage',
  36. 'editlang' => 'ModifyLanguage',
  37. );
  38. call_integration_hook('integrate_manage_languages', array(&$subActions));
  39. // By default we're managing languages.
  40. $_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'edit';
  41. $context['sub_action'] = $_REQUEST['sa'];
  42. // Load up all the tabs...
  43. $context[$context['admin_menu_name']]['tab_data'] = array(
  44. 'title' => $txt['language_configuration'],
  45. 'description' => $txt['language_description'],
  46. );
  47. // Call the right function for this sub-action.
  48. $subActions[$_REQUEST['sa']]();
  49. }
  50. /**
  51. * Interface for adding a new language
  52. *
  53. * @uses ManageLanguages template, add_language sub-template.
  54. */
  55. function AddLanguage()
  56. {
  57. global $context, $sourcedir, $boarddir, $txt, $smcFunc, $scripturl;
  58. // Are we searching for new languages courtesy of Simple Machines?
  59. if (!empty($_POST['smf_add_sub']))
  60. {
  61. // Need fetch_web_data.
  62. require_once($sourcedir . '/Subs-Package.php');
  63. $context['smf_search_term'] = $smcFunc['htmlspecialchars'](trim($_POST['smf_add']));
  64. $listOptions = array(
  65. 'id' => 'smf_languages',
  66. 'get_items' => array(
  67. 'function' => 'list_getLanguagesList',
  68. ),
  69. 'columns' => array(
  70. 'name' => array(
  71. 'header' => array(
  72. 'value' => $txt['name'],
  73. ),
  74. 'data' => array(
  75. 'db' => 'name',
  76. ),
  77. ),
  78. 'description' => array(
  79. 'header' => array(
  80. 'value' => $txt['add_language_smf_desc'],
  81. ),
  82. 'data' => array(
  83. 'db' => 'description',
  84. ),
  85. ),
  86. 'version' => array(
  87. 'header' => array(
  88. 'value' => $txt['add_language_smf_version'],
  89. ),
  90. 'data' => array(
  91. 'db' => 'version',
  92. ),
  93. ),
  94. 'utf8' => array(
  95. 'header' => array(
  96. 'value' => $txt['add_language_smf_utf8'],
  97. ),
  98. 'data' => array(
  99. 'db' => 'utf8',
  100. ),
  101. ),
  102. 'install_link' => array(
  103. 'header' => array(
  104. 'value' => $txt['add_language_smf_install'],
  105. 'class' => 'centercol',
  106. ),
  107. 'data' => array(
  108. 'db' => 'install_link',
  109. 'class' => 'centercol',
  110. ),
  111. ),
  112. ),
  113. );
  114. require_once($sourcedir . '/Subs-List.php');
  115. createList($listOptions);
  116. $context['default_list'] = 'smf_languages';
  117. }
  118. $context['sub_template'] = 'add_language';
  119. }
  120. /**
  121. * Gets a list of available languages from the mother ship
  122. * Will return a subset if searching, otherwise all avaialble
  123. *
  124. * @return string
  125. */
  126. function list_getLanguagesList()
  127. {
  128. global $forum_version, $context, $sourcedir, $smcFunc, $txt, $scripturl;
  129. // We're going to use this URL.
  130. $url = 'http://download.simplemachines.org/fetch_language.php?version=' . urlencode(strtr($forum_version, array('SMF ' => '')));
  131. // Load the class file and stick it into an array.
  132. require_once($sourcedir . '/Class-Package.php');
  133. $language_list = new xmlArray(fetch_web_data($url), true);
  134. // Check that the site responded and that the language exists.
  135. if (!$language_list->exists('languages'))
  136. $context['smf_error'] = 'no_response';
  137. elseif (!$language_list->exists('languages/language'))
  138. $context['smf_error'] = 'no_files';
  139. else
  140. {
  141. $language_list = $language_list->path('languages[0]');
  142. $lang_files = $language_list->set('language');
  143. $smf_languages = array();
  144. foreach ($lang_files as $file)
  145. {
  146. // Were we searching?
  147. if (!empty($context['smf_search_term']) && strpos($file->fetch('name'), $smcFunc['strtolower']($context['smf_search_term'])) === false)
  148. continue;
  149. $smf_languages[] = array(
  150. 'id' => $file->fetch('id'),
  151. 'name' => $smcFunc['ucwords']($file->fetch('name')),
  152. 'version' => $file->fetch('version'),
  153. 'utf8' => $file->fetch('utf8') ? $txt['yes'] : $txt['no'],
  154. 'description' => $file->fetch('description'),
  155. 'install_link' => '<a href="' . $scripturl . '?action=admin;area=languages;sa=downloadlang;did=' . $file->fetch('id') . ';' . $context['session_var'] . '=' . $context['session_id'] . '">' . $txt['add_language_smf_install'] . '</a>',
  156. );
  157. }
  158. if (empty($smf_languages))
  159. $context['smf_error'] = 'no_files';
  160. else
  161. return $smf_languages;
  162. }
  163. }
  164. /**
  165. * Download a language file from the Simple Machines website.
  166. * Requires a valid download ID ("did") in the URL.
  167. * Also handles installing language files.
  168. * Attempts to chmod things as needed.
  169. * Uses a standard list to display information about all the files and where they'll be put.
  170. *
  171. * @uses ManageLanguages template, download_language sub-template.
  172. * @uses Admin template, show_list sub-template.
  173. */
  174. function DownloadLanguage()
  175. {
  176. global $context, $sourcedir, $forum_version, $boarddir, $txt, $smcFunc, $scripturl, $modSettings;
  177. loadLanguage('ManageSettings');
  178. require_once($sourcedir . '/Subs-Package.php');
  179. // Clearly we need to know what to request.
  180. if (!isset($_GET['did']))
  181. fatal_lang_error('no_access', false);
  182. // Some lovely context.
  183. $context['download_id'] = $_GET['did'];
  184. $context['sub_template'] = 'download_language';
  185. $context['menu_data_' . $context['admin_menu_id']]['current_subsection'] = 'add';
  186. // Can we actually do the installation - and do they want to?
  187. if (!empty($_POST['do_install']) && !empty($_POST['copy_file']))
  188. {
  189. checkSession('get');
  190. validateToken('admin-dlang');
  191. $chmod_files = array();
  192. $install_files = array();
  193. // Check writable status.
  194. foreach ($_POST['copy_file'] as $file)
  195. {
  196. // Check it's not very bad.
  197. if (strpos($file, '..') !== false || (strpos($file, 'Themes') !== 0 && !preg_match('~agreement\.[A-Za-z-_0-9]+\.txt$~', $file)))
  198. fatal_error($txt['languages_download_illegal_paths']);
  199. $chmod_files[] = $boarddir . '/' . $file;
  200. $install_files[] = $file;
  201. }
  202. // Call this in case we have work to do.
  203. $file_status = create_chmod_control($chmod_files);
  204. $files_left = $file_status['files']['notwritable'];
  205. // Something not writable?
  206. if (!empty($files_left))
  207. $context['error_message'] = $txt['languages_download_not_chmod'];
  208. // Otherwise, go go go!
  209. elseif (!empty($install_files))
  210. {
  211. $archive_content = read_tgz_file('http://download.simplemachines.org/fetch_language.php?version=' . urlencode(strtr($forum_version, array('SMF ' => ''))) . ';fetch=' . urlencode($_GET['did']), $boarddir, false, true, $install_files);
  212. // Make sure the files aren't stuck in the cache.
  213. package_flush_cache();
  214. $context['install_complete'] = sprintf($txt['languages_download_complete_desc'], $scripturl . '?action=admin;area=languages');
  215. return;
  216. }
  217. }
  218. // Open up the old china.
  219. if (!isset($archive_content))
  220. $archive_content = read_tgz_file('http://download.simplemachines.org/fetch_language.php?version=' . urlencode(strtr($forum_version, array('SMF ' => ''))) . ';fetch=' . urlencode($_GET['did']), null);
  221. if (empty($archive_content))
  222. fatal_error($txt['add_language_error_no_response']);
  223. // Now for each of the files, let's do some *stuff*
  224. $context['files'] = array(
  225. 'lang' => array(),
  226. 'other' => array(),
  227. );
  228. $context['make_writable'] = array();
  229. foreach ($archive_content as $file)
  230. {
  231. $dirname = dirname($file['filename']);
  232. $filename = basename($file['filename']);
  233. $extension = substr($filename, strrpos($filename, '.') + 1);
  234. // Don't do anything with files we don't understand.
  235. if (!in_array($extension, array('php', 'jpg', 'gif', 'jpeg', 'png', 'txt')))
  236. continue;
  237. // Basic data.
  238. $context_data = array(
  239. 'name' => $filename,
  240. 'destination' => $boarddir . '/' . $file['filename'],
  241. 'generaldest' => $file['filename'],
  242. 'size' => $file['size'],
  243. // Does chmod status allow the copy?
  244. 'writable' => false,
  245. // Should we suggest they copy this file?
  246. 'default_copy' => true,
  247. // Does the file already exist, if so is it same or different?
  248. 'exists' => false,
  249. );
  250. // Does the file exist, is it different and can we overwrite?
  251. if (file_exists($boarddir . '/' . $file['filename']))
  252. {
  253. if (is_writable($boarddir . '/' . $file['filename']))
  254. $context_data['writable'] = true;
  255. // Finally, do we actually think the content has changed?
  256. if ($file['size'] == filesize($boarddir . '/' . $file['filename']) && $file['md5'] == md5_file($boarddir . '/' . $file['filename']))
  257. {
  258. $context_data['exists'] = 'same';
  259. $context_data['default_copy'] = false;
  260. }
  261. // Attempt to discover newline character differences.
  262. elseif ($file['md5'] == md5(preg_replace("~[\r]?\n~", "\r\n", file_get_contents($boarddir . '/' . $file['filename']))))
  263. {
  264. $context_data['exists'] = 'same';
  265. $context_data['default_copy'] = false;
  266. }
  267. else
  268. $context_data['exists'] = 'different';
  269. }
  270. // No overwrite?
  271. else
  272. {
  273. // Can we at least stick it in the directory...
  274. if (is_writable($boarddir . '/' . $dirname))
  275. $context_data['writable'] = true;
  276. }
  277. // I love PHP files, that's why I'm a developer and not an artistic type spending my time drinking absinth and living a life of sin...
  278. if ($extension == 'php' && preg_match('~\w+\.\w+(?:-utf8)?\.php~', $filename))
  279. {
  280. $context_data += array(
  281. 'version' => '??',
  282. 'cur_version' => false,
  283. 'version_compare' => 'newer',
  284. );
  285. list ($name, $language) = explode('.', $filename);
  286. // Let's get the new version, I like versions, they tell me that I'm up to date.
  287. if (preg_match('~\s*Version:\s+(.+?);\s*' . preg_quote($name, '~') . '~i', $file['preview'], $match) == 1)
  288. $context_data['version'] = $match[1];
  289. // Now does the old file exist - if so what is it's version?
  290. if (file_exists($boarddir . '/' . $file['filename']))
  291. {
  292. // OK - what is the current version?
  293. $fp = fopen($boarddir . '/' . $file['filename'], 'rb');
  294. $header = fread($fp, 768);
  295. fclose($fp);
  296. // Find the version.
  297. if (preg_match('~(?://|/\*)\s*Version:\s+(.+?);\s*' . preg_quote($name, '~') . '(?:[\s]{2}|\*/)~i', $header, $match) == 1)
  298. {
  299. $context_data['cur_version'] = $match[1];
  300. // How does this compare?
  301. if ($context_data['cur_version'] == $context_data['version'])
  302. $context_data['version_compare'] = 'same';
  303. elseif ($context_data['cur_version'] > $context_data['version'])
  304. $context_data['version_compare'] = 'older';
  305. // Don't recommend copying if the version is the same.
  306. if ($context_data['version_compare'] != 'newer')
  307. $context_data['default_copy'] = false;
  308. }
  309. }
  310. // Add the context data to the main set.
  311. $context['files']['lang'][] = $context_data;
  312. }
  313. else
  314. {
  315. // If we think it's a theme thing, work out what the theme is.
  316. if (strpos($dirname, 'Themes') === 0 && preg_match('~Themes[\\/]([^\\/]+)[\\/]~', $dirname, $match))
  317. $theme_name = $match[1];
  318. else
  319. $theme_name = 'misc';
  320. // Assume it's an image, could be an acceptance note etc but rare.
  321. $context['files']['images'][$theme_name][] = $context_data;
  322. }
  323. // Collect together all non-writable areas.
  324. if (!$context_data['writable'])
  325. $context['make_writable'][] = $context_data['destination'];
  326. }
  327. // So, I'm a perfectionist - let's get the theme names.
  328. $theme_indexes = array();
  329. foreach ($context['files']['images'] as $k => $dummy)
  330. $indexes[] = $k;
  331. $context['theme_names'] = array();
  332. if (!empty($indexes))
  333. {
  334. $value_data = array(
  335. 'query' => array(),
  336. 'params' => array(),
  337. );
  338. foreach ($indexes as $k => $index)
  339. {
  340. $value_data['query'][] = 'value LIKE {string:value_' . $k . '}';
  341. $value_data['params']['value_' . $k] = '%' . $index;
  342. }
  343. $request = $smcFunc['db_query']('', '
  344. SELECT id_theme, value
  345. FROM {db_prefix}themes
  346. WHERE id_member = {int:no_member}
  347. AND variable = {string:theme_dir}
  348. AND (' . implode(' OR ', $value_data['query']) . ')',
  349. array_merge($value_data['params'], array(
  350. 'no_member' => 0,
  351. 'theme_dir' => 'theme_dir',
  352. 'index_compare_explode' => 'value LIKE \'%' . implode('\' OR value LIKE \'%', $indexes) . '\'',
  353. ))
  354. );
  355. $themes = array();
  356. while ($row = $smcFunc['db_fetch_assoc']($request))
  357. {
  358. // Find the right one.
  359. foreach ($indexes as $index)
  360. if (strpos($row['value'], $index) !== false)
  361. $themes[$row['id_theme']] = $index;
  362. }
  363. $smcFunc['db_free_result']($request);
  364. if (!empty($themes))
  365. {
  366. // Now we have the id_theme we can get the pretty description.
  367. $request = $smcFunc['db_query']('', '
  368. SELECT id_theme, value
  369. FROM {db_prefix}themes
  370. WHERE id_member = {int:no_member}
  371. AND variable = {string:name}
  372. AND id_theme IN ({array_int:theme_list})',
  373. array(
  374. 'theme_list' => array_keys($themes),
  375. 'no_member' => 0,
  376. 'name' => 'name',
  377. )
  378. );
  379. while ($row = $smcFunc['db_fetch_assoc']($request))
  380. {
  381. // Now we have it...
  382. $context['theme_names'][$themes[$row['id_theme']]] = $row['value'];
  383. }
  384. $smcFunc['db_free_result']($request);
  385. }
  386. }
  387. // Before we go to far can we make anything writable, eh, eh?
  388. if (!empty($context['make_writable']))
  389. {
  390. // What is left to be made writable?
  391. $file_status = create_chmod_control($context['make_writable']);
  392. $context['still_not_writable'] = $file_status['files']['notwritable'];
  393. // Mark those which are now writable as such.
  394. foreach ($context['files'] as $type => $data)
  395. {
  396. if ($type == 'lang')
  397. {
  398. foreach ($data as $k => $file)
  399. if (!$file['writable'] && !in_array($file['destination'], $context['still_not_writable']))
  400. $context['files'][$type][$k]['writable'] = true;
  401. }
  402. else
  403. {
  404. foreach ($data as $theme => $files)
  405. foreach ($files as $k => $file)
  406. if (!$file['writable'] && !in_array($file['destination'], $context['still_not_writable']))
  407. $context['files'][$type][$theme][$k]['writable'] = true;
  408. }
  409. }
  410. // Are we going to need more language stuff?
  411. if (!empty($context['still_not_writable']))
  412. loadLanguage('Packages');
  413. }
  414. // This is the list for the main files.
  415. $listOptions = array(
  416. 'id' => 'lang_main_files_list',
  417. 'title' => $txt['languages_download_main_files'],
  418. 'get_items' => array(
  419. 'function' => create_function('', '
  420. global $context;
  421. return $context[\'files\'][\'lang\'];
  422. '),
  423. ),
  424. 'columns' => array(
  425. 'name' => array(
  426. 'header' => array(
  427. 'value' => $txt['languages_download_filename'],
  428. ),
  429. 'data' => array(
  430. 'function' => create_function('$rowData', '
  431. global $context, $txt;
  432. return \'<strong>\' . $rowData[\'name\'] . \'</strong><br /><span class="smalltext">\' . $txt[\'languages_download_dest\'] . \': \' . $rowData[\'destination\'] . \'</span>\' . ($rowData[\'version_compare\'] == \'older\' ? \'<br />\' . $txt[\'languages_download_older\'] : \'\');
  433. '),
  434. ),
  435. ),
  436. 'writable' => array(
  437. 'header' => array(
  438. 'value' => $txt['languages_download_writable'],
  439. ),
  440. 'data' => array(
  441. 'function' => create_function('$rowData', '
  442. global $txt;
  443. return \'<span style="color: \' . ($rowData[\'writable\'] ? \'green\' : \'red\') . \';">\' . ($rowData[\'writable\'] ? $txt[\'yes\'] : $txt[\'no\']) . \'</span>\';
  444. '),
  445. ),
  446. ),
  447. 'version' => array(
  448. 'header' => array(
  449. 'value' => $txt['languages_download_version'],
  450. ),
  451. 'data' => array(
  452. 'function' => create_function('$rowData', '
  453. global $txt;
  454. return \'<span style="color: \' . ($rowData[\'version_compare\'] == \'older\' ? \'red\' : ($rowData[\'version_compare\'] == \'same\' ? \'orange\' : \'green\')) . \';">\' . $rowData[\'version\'] . \'</span>\';
  455. '),
  456. ),
  457. ),
  458. 'exists' => array(
  459. 'header' => array(
  460. 'value' => $txt['languages_download_exists'],
  461. ),
  462. 'data' => array(
  463. 'function' => create_function('$rowData', '
  464. global $txt;
  465. return $rowData[\'exists\'] ? ($rowData[\'exists\'] == \'same\' ? $txt[\'languages_download_exists_same\'] : $txt[\'languages_download_exists_different\']) : $txt[\'no\'];
  466. '),
  467. ),
  468. ),
  469. 'copy' => array(
  470. 'header' => array(
  471. 'value' => $txt['languages_download_copy'],
  472. 'class' => 'centercol',
  473. ),
  474. 'data' => array(
  475. 'function' => create_function('$rowData', '
  476. return \'<input type="checkbox" name="copy_file[]" value="\' . $rowData[\'generaldest\'] . \'"\' . ($rowData[\'default_copy\'] ? \' checked\' : \'\') . \' class="input_check" />\';
  477. '),
  478. 'style' => 'width: 4%;',
  479. 'class' => 'centercol',
  480. ),
  481. ),
  482. ),
  483. );
  484. // Kill the cache, as it is now invalid..
  485. if (!empty($modSettings['cache_enable']))
  486. {
  487. cache_put_data('known_languages', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  488. cache_put_data('known_languages_all', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  489. }
  490. require_once($sourcedir . '/Subs-List.php');
  491. createList($listOptions);
  492. $context['default_list'] = 'lang_main_files_list';
  493. createToken('admin-dlang');
  494. }
  495. /**
  496. * This lists all the current languages and allows editing of them.
  497. */
  498. function ModifyLanguages()
  499. {
  500. global $txt, $context, $scripturl;
  501. global $user_info, $smcFunc, $sourcedir, $language, $boarddir, $forum_version;
  502. // Setting a new default?
  503. if (!empty($_POST['set_default']) && !empty($_POST['def_language']))
  504. {
  505. checkSession();
  506. validateToken('admin-lang');
  507. getLanguages(true, false);
  508. $lang_exists = false;
  509. foreach ($context['languages'] as $lang)
  510. {
  511. if ($_POST['def_language'] == $lang['filename'])
  512. {
  513. $lang_exists = true;
  514. break;
  515. }
  516. }
  517. if ($_POST['def_language'] != $language && $lang_exists)
  518. {
  519. require_once($sourcedir . '/Subs-Admin.php');
  520. updateSettingsFile(array('language' => '\'' . $_POST['def_language'] . '\''));
  521. $language = $_POST['def_language'];
  522. }
  523. }
  524. // Create another one time token here.
  525. createToken('admin-lang');
  526. $listOptions = array(
  527. 'id' => 'language_list',
  528. 'items_per_page' => 20,
  529. 'base_href' => $scripturl . '?action=admin;area=languages',
  530. 'title' => $txt['edit_languages'],
  531. 'get_items' => array(
  532. 'function' => 'list_getLanguages',
  533. ),
  534. 'get_count' => array(
  535. 'function' => 'list_getNumLanguages',
  536. ),
  537. 'columns' => array(
  538. 'default' => array(
  539. 'header' => array(
  540. 'value' => $txt['languages_default'],
  541. 'class' => 'centercol',
  542. ),
  543. 'data' => array(
  544. 'function' => create_function('$rowData', '
  545. return \'<input type="radio" name="def_language" value="\' . $rowData[\'id\'] . \'"\' . ($rowData[\'default\'] ? \' checked\' : \'\') . \' onclick="highlightSelected(\\\'list_language_list_\' . $rowData[\'id\'] . \'\\\');" class="input_radio" />\';
  546. '),
  547. 'style' => 'width: 8%;',
  548. 'class' => 'centercol',
  549. ),
  550. ),
  551. 'name' => array(
  552. 'header' => array(
  553. 'value' => $txt['languages_lang_name'],
  554. ),
  555. 'data' => array(
  556. 'function' => create_function('$rowData', '
  557. global $scripturl, $context;
  558. return sprintf(\'<a href="%1$s?action=admin;area=languages;sa=editlang;lid=%2$s">%3$s</a>\', $scripturl, $rowData[\'id\'], $rowData[\'name\']);
  559. '),
  560. ),
  561. ),
  562. 'character_set' => array(
  563. 'header' => array(
  564. 'value' => $txt['languages_character_set'],
  565. ),
  566. 'data' => array(
  567. 'db_htmlsafe' => 'char_set',
  568. ),
  569. ),
  570. 'count' => array(
  571. 'header' => array(
  572. 'value' => $txt['languages_users'],
  573. ),
  574. 'data' => array(
  575. 'db_htmlsafe' => 'count',
  576. ),
  577. ),
  578. 'locale' => array(
  579. 'header' => array(
  580. 'value' => $txt['languages_locale'],
  581. ),
  582. 'data' => array(
  583. 'db_htmlsafe' => 'locale',
  584. ),
  585. ),
  586. ),
  587. 'form' => array(
  588. 'href' => $scripturl . '?action=admin;area=languages',
  589. 'token' => 'admin-lang',
  590. ),
  591. 'additional_rows' => array(
  592. array(
  593. 'position' => 'bottom_of_list',
  594. 'value' => '<input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '" /><input type="submit" name="set_default" value="' . $txt['save'] . '"' . (is_writable($boarddir . '/Settings.php') ? '' : ' disabled="disabled"') . ' class="button_submit" />',
  595. ),
  596. ),
  597. );
  598. // We want to highlight the selected language. Need some Javascript for this.
  599. addInlineJavascript('
  600. function highlightSelected(box)
  601. {
  602. $("tr.highlight2").removeClass("highlight2");
  603. $("#" + box).addClass("highlight2");
  604. }
  605. highlightSelected("list_language_list_' . ($language == '' ? 'english' : $language). '");', true);
  606. // Display a warning if we cannot edit the default setting.
  607. if (!is_writable($boarddir . '/Settings.php'))
  608. $listOptions['additional_rows'][] = array(
  609. 'position' => 'after_title',
  610. 'value' => $txt['language_settings_writable'],
  611. 'class' => 'smalltext alert',
  612. );
  613. require_once($sourcedir . '/Subs-List.php');
  614. createList($listOptions);
  615. $context['sub_template'] = 'show_list';
  616. $context['default_list'] = 'language_list';
  617. }
  618. /**
  619. * How many languages?
  620. * Callback for the list in ManageLanguageSettings().
  621. */
  622. function list_getNumLanguages()
  623. {
  624. return count(getLanguages(true, false));
  625. }
  626. /**
  627. * Fetch the actual language information.
  628. * Callback for $listOptions['get_items']['function'] in ManageLanguageSettings.
  629. * Determines which languages are available by looking for the "index.{language}.php" file.
  630. * Also figures out how many users are using a particular language.
  631. */
  632. function list_getLanguages()
  633. {
  634. global $settings, $smcFunc, $language, $context, $txt;
  635. $languages = array();
  636. // Keep our old entries.
  637. $old_txt = $txt;
  638. $backup_actual_theme_dir = $settings['actual_theme_dir'];
  639. $backup_base_theme_dir = !empty($settings['base_theme_dir']) ? $settings['base_theme_dir'] : '';
  640. // Override these for now.
  641. $settings['actual_theme_dir'] = $settings['base_theme_dir'] = $settings['default_theme_dir'];
  642. getLanguages(true, false);
  643. // Put them back.
  644. $settings['actual_theme_dir'] = $backup_actual_theme_dir;
  645. if (!empty($backup_base_theme_dir))
  646. $settings['base_theme_dir'] = $backup_base_theme_dir;
  647. else
  648. unset($settings['base_theme_dir']);
  649. // Get the language files and data...
  650. foreach ($context['languages'] as $lang)
  651. {
  652. // Load the file to get the character set.
  653. require($settings['default_theme_dir'] . '/languages/index.' . $lang['filename'] . '.php');
  654. $languages[$lang['filename']] = array(
  655. 'id' => $lang['filename'],
  656. 'count' => 0,
  657. 'char_set' => $txt['lang_character_set'],
  658. 'default' => $language == $lang['filename'] || ($language == '' && $lang['filename'] == 'english'),
  659. 'locale' => $txt['lang_locale'],
  660. 'name' => $smcFunc['ucwords'](strtr($lang['filename'], array('_' => ' ', '-utf8' => ''))),
  661. );
  662. }
  663. // Work out how many people are using each language.
  664. $request = $smcFunc['db_query']('', '
  665. SELECT lngfile, COUNT(*) AS num_users
  666. FROM {db_prefix}members
  667. GROUP BY lngfile',
  668. array(
  669. )
  670. );
  671. while ($row = $smcFunc['db_fetch_assoc']($request))
  672. {
  673. // Default?
  674. if (empty($row['lngfile']) || !isset($languages[$row['lngfile']]))
  675. $row['lngfile'] = $language;
  676. if (!isset($languages[$row['lngfile']]) && isset($languages['english']))
  677. $languages['english']['count'] += $row['num_users'];
  678. elseif (isset($languages[$row['lngfile']]))
  679. $languages[$row['lngfile']]['count'] += $row['num_users'];
  680. }
  681. $smcFunc['db_free_result']($request);
  682. // Restore the current users language.
  683. $txt = $old_txt;
  684. // Return how many we have.
  685. return $languages;
  686. }
  687. /**
  688. * Edit language related settings.
  689. *
  690. * @param bool $return_config = false
  691. */
  692. function ModifyLanguageSettings($return_config = false)
  693. {
  694. global $scripturl, $context, $txt, $boarddir, $settings, $smcFunc, $sourcedir;
  695. // We'll want to save them someday.
  696. require_once $sourcedir . '/ManageServer.php';
  697. // Warn the user if the backup of Settings.php failed.
  698. $settings_not_writable = !is_writable($boarddir . '/Settings.php');
  699. $settings_backup_fail = !@is_writable($boarddir . '/Settings_bak.php') || !@copy($boarddir . '/Settings.php', $boarddir . '/Settings_bak.php');
  700. /* If you're writing a mod, it's a bad idea to add things here....
  701. For each option:
  702. variable name, description, type (constant), size/possible values, helptext.
  703. OR an empty string for a horizontal rule.
  704. OR a string for a titled section. */
  705. $config_vars = array(
  706. 'language' => array('language', $txt['default_language'], 'file', 'select', array(), null, 'disabled' => $settings_not_writable),
  707. array('userLanguage', $txt['userLanguage'], 'db', 'check', null, 'userLanguage'),
  708. );
  709. call_integration_hook('integrate_language_settings', array(&$config_vars));
  710. if ($return_config)
  711. return $config_vars;
  712. // Get our languages. No cache and use utf8.
  713. getLanguages(false, false);
  714. foreach ($context['languages'] as $lang)
  715. $config_vars['language'][4][$lang['filename']] = array($lang['filename'], strtr($lang['name'], array('-utf8' => ' (UTF-8)')));
  716. // Saving settings?
  717. if (isset($_REQUEST['save']))
  718. {
  719. checkSession();
  720. call_integration_hook('integrate_save_language_settings', array(&$config_vars));
  721. saveSettings($config_vars);
  722. if (!$settings_not_writable && !$settings_backup_fail)
  723. $_SESSION['adm-save'] = true;
  724. redirectexit('action=admin;area=languages;sa=settings');
  725. }
  726. // Setup the template stuff.
  727. $context['post_url'] = $scripturl . '?action=admin;area=languages;sa=settings;save';
  728. $context['settings_title'] = $txt['language_settings'];
  729. $context['save_disabled'] = $settings_not_writable;
  730. if ($settings_not_writable)
  731. $context['settings_message'] = '<div class="centertext"><strong>' . $txt['settings_not_writable'] . '</strong></div><br />';
  732. elseif ($settings_backup_fail)
  733. $context['settings_message'] = '<div class="centertext"><strong>' . $txt['admin_backup_fail'] . '</strong></div><br />';
  734. // Fill the config array.
  735. prepareServerSettingsContext($config_vars);
  736. }
  737. /**
  738. * Edit a particular set of language entries.
  739. */
  740. function ModifyLanguage()
  741. {
  742. global $settings, $context, $smcFunc, $txt, $modSettings, $boarddir, $sourcedir, $language;
  743. loadLanguage('ManageSettings');
  744. // Select the languages tab.
  745. $context['menu_data_' . $context['admin_menu_id']]['current_subsection'] = 'edit';
  746. $context['page_title'] = $txt['edit_languages'];
  747. $context['sub_template'] = 'modify_language_entries';
  748. $context['lang_id'] = $_GET['lid'];
  749. list($theme_id, $file_id) = empty($_REQUEST['tfid']) || strpos($_REQUEST['tfid'], '+') === false ? array(1, '') : explode('+', $_REQUEST['tfid']);
  750. // Clean the ID - just in case.
  751. preg_match('~([A-Za-z0-9_-]+)~', $context['lang_id'], $matches);
  752. $context['lang_id'] = $matches[1];
  753. // Get all the theme data.
  754. $request = $smcFunc['db_query']('', '
  755. SELECT id_theme, variable, value
  756. FROM {db_prefix}themes
  757. WHERE id_theme != {int:default_theme}
  758. AND id_member = {int:no_member}
  759. AND variable IN ({string:name}, {string:theme_dir})',
  760. array(
  761. 'default_theme' => 1,
  762. 'no_member' => 0,
  763. 'name' => 'name',
  764. 'theme_dir' => 'theme_dir',
  765. )
  766. );
  767. $themes = array(
  768. 1 => array(
  769. 'name' => $txt['dvc_default'],
  770. 'theme_dir' => $settings['default_theme_dir'],
  771. ),
  772. );
  773. while ($row = $smcFunc['db_fetch_assoc']($request))
  774. $themes[$row['id_theme']][$row['variable']] = $row['value'];
  775. $smcFunc['db_free_result']($request);
  776. // This will be where we look
  777. $lang_dirs = array();
  778. // Check we have themes with a path and a name - just in case - and add the path.
  779. foreach ($themes as $id => $data)
  780. {
  781. if (count($data) != 2)
  782. unset($themes[$id]);
  783. elseif (is_dir($data['theme_dir'] . '/languages'))
  784. $lang_dirs[$id] = $data['theme_dir'] . '/languages';
  785. // How about image directories?
  786. if (is_dir($data['theme_dir'] . '/images/' . $context['lang_id']))
  787. $images_dirs[$id] = $data['theme_dir'] . '/images/' . $context['lang_id'];
  788. }
  789. $current_file = $file_id ? $lang_dirs[$theme_id] . '/' . $file_id . '.' . $context['lang_id'] . '.php' : '';
  790. // Now for every theme get all the files and stick them in context!
  791. $context['possible_files'] = array();
  792. foreach ($lang_dirs as $theme => $theme_dir)
  793. {
  794. // Open it up.
  795. $dir = dir($theme_dir);
  796. while ($entry = $dir->read())
  797. {
  798. // We're only after the files for this language.
  799. if (preg_match('~^([A-Za-z]+)\.' . $context['lang_id'] . '\.php$~', $entry, $matches) == 0)
  800. continue;
  801. if (!isset($context['possible_files'][$theme]))
  802. $context['possible_files'][$theme] = array(
  803. 'id' => $theme,
  804. 'name' => $themes[$theme]['name'],
  805. 'files' => array(),
  806. );
  807. $context['possible_files'][$theme]['files'][] = array(
  808. 'id' => $matches[1],
  809. 'name' => isset($txt['lang_file_desc_' . $matches[1]]) ? $txt['lang_file_desc_' . $matches[1]] : $matches[1],
  810. 'selected' => $theme_id == $theme && $file_id == $matches[1],
  811. );
  812. }
  813. $dir->close();
  814. usort($context['possible_files'][$theme]['files'], create_function('$val1, $val2', 'return strcmp($val1[\'name\'], $val2[\'name\']);'));
  815. }
  816. // We no longer wish to speak this language.
  817. if (!empty($_POST['delete_main']) && $context['lang_id'] != 'english')
  818. {
  819. checkSession();
  820. validateToken('admin-mlang');
  821. // @todo Todo: FTP Controls?
  822. require_once($sourcedir . '/Subs-Package.php');
  823. // First, Make a backup?
  824. if (!empty($modSettings['package_make_backups']) && (!isset($_SESSION['last_backup_for']) || $_SESSION['last_backup_for'] != $context['lang_id'] . '$$$'))
  825. {
  826. $_SESSION['last_backup_for'] = $context['lang_id'] . '$$$';
  827. $result = package_create_backup('backup_lang_' . $context['lang_id']);
  828. if (!$result)
  829. fatal_lang_error('could_not_language_backup', false);
  830. }
  831. // Second, loop through the array to remove the files.
  832. foreach ($lang_dirs as $curPath)
  833. {
  834. foreach ($context['possible_files'][1]['files'] as $lang)
  835. if (file_exists($curPath . '/' . $lang['id'] . '.' . $context['lang_id'] . '.php'))
  836. unlink($curPath . '/' . $lang['id'] . '.' . $context['lang_id'] . '.php');
  837. // Check for the email template.
  838. if (file_exists($curPath . '/EmailTemplates.' . $context['lang_id'] . '.php'))
  839. unlink($curPath . '/EmailTemplates.' . $context['lang_id'] . '.php');
  840. }
  841. // Third, the agreement file.
  842. if (file_exists($boarddir . '/agreement.' . $context['lang_id'] . '.txt'))
  843. unlink($boarddir . '/agreement.' . $context['lang_id'] . '.txt');
  844. // Fourth, a related images folder?
  845. foreach ($images_dirs as $curPath)
  846. if (is_dir($curPath))
  847. deltree($curPath);
  848. // Members can no longer use this language.
  849. $smcFunc['db_query']('', '
  850. UPDATE {db_prefix}members
  851. SET lngfile = {empty}
  852. WHERE lngfile = {string:current_language}',
  853. array(
  854. 'empty_string' => '',
  855. 'current_language' => $context['lang_id'],
  856. )
  857. );
  858. // Fifth, update getLanguages() cache.
  859. if (!empty($modSettings['cache_enable']))
  860. {
  861. cache_put_data('known_languages', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  862. cache_put_data('known_languages_all', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  863. }
  864. // Sixth, if we deleted the default language, set us back to english?
  865. if ($context['lang_id'] == $language)
  866. {
  867. require_once($sourcedir . '/Subs-Admin.php');
  868. $language = 'english';
  869. updateSettingsFile(array('language' => '\'' . $language . '\''));
  870. }
  871. // Seventh, get out of here.
  872. redirectexit('action=admin;area=languages;sa=edit;' . $context['session_var'] . '=' . $context['session_id']);
  873. }
  874. // Saving primary settings?
  875. $madeSave = false;
  876. if (!empty($_POST['save_main']) && !$current_file)
  877. {
  878. checkSession();
  879. validateToken('admin-mlang');
  880. // Read in the current file.
  881. $current_data = implode('', file($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php'));
  882. // These are the replacements. old => new
  883. $replace_array = array(
  884. '~\$txt\[\'lang_character_set\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_character_set\'] = \'' . preg_replace('~[^\w-]~i', '', $_POST['character_set']) . '\';',
  885. '~\$txt\[\'lang_locale\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_locale\'] = \'' . preg_replace('~[^\w-]~i', '', $_POST['locale']) . '\';',
  886. '~\$txt\[\'lang_dictionary\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_dictionary\'] = \'' . preg_replace('~[^\w-]~i', '', $_POST['dictionary']) . '\';',
  887. '~\$txt\[\'lang_spelling\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_spelling\'] = \'' . preg_replace('~[^\w-]~i', '', $_POST['spelling']) . '\';',
  888. '~\$txt\[\'lang_rtl\'\]\s=\s[A-Za-z0-9]+;~' => '$txt[\'lang_rtl\'] = ' . (!empty($_POST['rtl']) ? 'true' : 'false') . ';',
  889. );
  890. $current_data = preg_replace(array_keys($replace_array), array_values($replace_array), $current_data);
  891. $fp = fopen($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php', 'w+');
  892. fwrite($fp, $current_data);
  893. fclose($fp);
  894. $madeSave = true;
  895. }
  896. // Quickly load index language entries.
  897. $old_txt = $txt;
  898. require($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php');
  899. $context['lang_file_not_writable_message'] = is_writable($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php') ? '' : sprintf($txt['lang_file_not_writable'], $settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php');
  900. // Setup the primary settings context.
  901. $context['primary_settings'] = array(
  902. 'name' => $smcFunc['ucwords'](strtr($context['lang_id'], array('_' => ' ', '-utf8' => ''))),
  903. 'character_set' => $txt['lang_character_set'],
  904. 'locale' => $txt['lang_locale'],
  905. 'dictionary' => $txt['lang_dictionary'],
  906. 'spelling' => $txt['lang_spelling'],
  907. 'rtl' => $txt['lang_rtl'],
  908. );
  909. // Restore normal service.
  910. $txt = $old_txt;
  911. // Are we saving?
  912. $save_strings = array();
  913. if (isset($_POST['save_entries']) && !empty($_POST['entry']))
  914. {
  915. checkSession();
  916. validateToken('admin-mlang');
  917. // Clean each entry!
  918. foreach ($_POST['entry'] as $k => $v)
  919. {
  920. // Only try to save if it's changed!
  921. if ($_POST['entry'][$k] != $_POST['comp'][$k])
  922. $save_strings[$k] = cleanLangString($v, false);
  923. }
  924. }
  925. // If we are editing a file work away at that.
  926. if ($current_file)
  927. {
  928. $context['entries_not_writable_message'] = is_writable($current_file) ? '' : sprintf($txt['lang_entries_not_writable'], $current_file);
  929. $entries = array();
  930. // We can't just require it I'm afraid - otherwise we pass in all kinds of variables!
  931. $multiline_cache = '';
  932. foreach (file($current_file) as $line)
  933. {
  934. // Got a new entry?
  935. if ($line[0] == '$' && !empty($multiline_cache))
  936. {
  937. preg_match('~\$(helptxt|txt|editortxt)\[\'(.+)\'\]\s?=\s?(.+);~ms', strtr($multiline_cache, array("\r" => '')), $matches);
  938. if (!empty($matches[3]))
  939. {
  940. $entries[$matches[2]] = array(
  941. 'type' => $matches[1],
  942. 'full' => $matches[0],
  943. 'entry' => $matches[3],
  944. );
  945. $multiline_cache = '';
  946. }
  947. }
  948. $multiline_cache .= $line;
  949. }
  950. // Last entry to add?
  951. if ($multiline_cache)
  952. {
  953. preg_match('~\$(helptxt|txt|editortxt)\[\'(.+)\'\]\s?=\s?(.+);~ms', strtr($multiline_cache, array("\r" => '')), $matches);
  954. if (!empty($matches[3]))
  955. $entries[$matches[2]] = array(
  956. 'type' => $matches[1],
  957. 'full' => $matches[0],
  958. 'entry' => $matches[3],
  959. );
  960. }
  961. // These are the entries we can definitely save.
  962. $final_saves = array();
  963. $context['file_entries'] = array();
  964. foreach ($entries as $entryKey => $entryValue)
  965. {
  966. // Ignore some things we set separately.
  967. $ignore_files = array('lang_character_set', 'lang_locale', 'lang_dictionary', 'lang_spelling', 'lang_rtl');
  968. if (in_array($entryKey, $ignore_files))
  969. continue;
  970. // These are arrays that need breaking out.
  971. $arrays = array('days', 'days_short', 'months', 'months_titles', 'months_short', 'happy_birthday_author', 'karlbenson1_author', 'nite0859_author', 'zwaldowski_author', 'geezmo_author', 'karlbenson2_author');
  972. if (in_array($entryKey, $arrays))
  973. {
  974. // Get off the first bits.
  975. $entryValue['entry'] = substr($entryValue['entry'], strpos($entryValue['entry'], '(') + 1, strrpos($entryValue['entry'], ')') - strpos($entryValue['entry'], '('));
  976. $entryValue['entry'] = explode(',', strtr($entryValue['entry'], array(' ' => '')));
  977. // Now create an entry for each item.
  978. $cur_index = 0;
  979. $save_cache = array(
  980. 'enabled' => false,
  981. 'entries' => array(),
  982. );
  983. foreach ($entryValue['entry'] as $id => $subValue)
  984. {
  985. // Is this a new index?
  986. if (preg_match('~^(\d+)~', $subValue, $matches))
  987. {
  988. $cur_index = $matches[1];
  989. $subValue = substr($subValue, strpos($subValue, '\''));
  990. }
  991. // Clean up some bits.
  992. $subValue = strtr($subValue, array('"' => '', '\'' => '', ')' => ''));
  993. // Can we save?
  994. if (isset($save_strings[$entryKey . '-+- ' . $cur_index]))
  995. {
  996. $save_cache['entries'][$cur_index] = strtr($save_strings[$entryKey . '-+- ' . $cur_index], array('\'' => ''));
  997. $save_cache['enabled'] = true;
  998. }
  999. else
  1000. $save_cache['entries'][$cur_index] = $subValue;
  1001. $context['file_entries'][] = array(
  1002. 'key' => $entryKey . '-+- ' . $cur_index,
  1003. 'value' => $subValue,
  1004. 'rows' => 1,
  1005. );
  1006. $cur_index++;
  1007. }
  1008. // Do we need to save?
  1009. if ($save_cache['enabled'])
  1010. {
  1011. // Format the string, checking the indexes first.
  1012. $items = array();
  1013. $cur_index = 0;
  1014. foreach ($save_cache['entries'] as $k2 => $v2)
  1015. {
  1016. // Manually show the custom index.
  1017. if ($k2 != $cur_index)
  1018. {
  1019. $items[] = $k2 . ' => \'' . $v2 . '\'';
  1020. $cur_index = $k2;
  1021. }
  1022. else
  1023. $items[] = '\'' . $v2 . '\'';
  1024. $cur_index++;
  1025. }
  1026. // Now create the string!
  1027. $final_saves[$entryKey] = array(
  1028. 'find' => $entryValue['full'],
  1029. 'replace' => '$' . $entryValue['type'] . '[\'' . $entryKey . '\'] = array(' . implode(', ', $items) . ');',
  1030. );
  1031. }
  1032. }
  1033. else
  1034. {
  1035. // Saving?
  1036. if (isset($save_strings[$entryKey]) && $save_strings[$entryKey] != $entryValue['entry'])
  1037. {
  1038. // @todo Fix this properly.
  1039. if ($save_strings[$entryKey] == '')
  1040. $save_strings[$entryKey] = '\'\'';
  1041. // Set the new value.
  1042. $entryValue['entry'] = $save_strings[$entryKey];
  1043. // And we know what to save now!
  1044. $final_saves[$entryKey] = array(
  1045. 'find' => $entryValue['full'],
  1046. 'replace' => '$' . $entryValue['type'] . '[\'' . $entryKey . '\'] = ' . $save_strings[$entryKey] . ';',
  1047. );
  1048. }
  1049. $editing_string = cleanLangString($entryValue['entry'], true);
  1050. $context['file_entries'][] = array(
  1051. 'key' => $entryKey,
  1052. 'value' => $editing_string,
  1053. 'rows' => (int) (strlen($editing_string) / 38) + substr_count($editing_string, "\n") + 1,
  1054. );
  1055. }
  1056. }
  1057. // Any saves to make?
  1058. if (!empty($final_saves))
  1059. {
  1060. checkSession();
  1061. $file_contents = implode('', file($current_file));
  1062. foreach ($final_saves as $save)
  1063. $file_contents = strtr($file_contents, array($save['find'] => $save['replace']));
  1064. // Save the actual changes.
  1065. $fp = fopen($current_file, 'w+');
  1066. fwrite($fp, strtr($file_contents, array("\r" => '')));
  1067. fclose($fp);
  1068. $madeSave = true;
  1069. }
  1070. // Another restore.
  1071. $txt = $old_txt;
  1072. }
  1073. // If we saved, redirect.
  1074. if ($madeSave)
  1075. redirectexit('action=admin;area=languages;sa=editlang;lid=' . $context['lang_id']);
  1076. createToken('admin-mlang');
  1077. }
  1078. /**
  1079. * This function cleans language entries to/from display.
  1080. * @todo This function could be two functions?
  1081. *
  1082. * @param $string
  1083. * @param $to_display
  1084. */
  1085. function cleanLangString($string, $to_display = true)
  1086. {
  1087. global $smcFunc;
  1088. // If going to display we make sure it doesn't have any HTML in it - etc.
  1089. $new_string = '';
  1090. if ($to_display)
  1091. {
  1092. // Are we in a string (0 = no, 1 = single quote, 2 = parsed)
  1093. $in_string = 0;
  1094. $is_escape = false;
  1095. for ($i = 0; $i < strlen($string); $i++)
  1096. {
  1097. // Handle ecapes first.
  1098. if ($string{$i} == '\\')
  1099. {
  1100. // Toggle the escape.
  1101. $is_escape = !$is_escape;
  1102. // If we're now escaped don't add this string.
  1103. if ($is_escape)
  1104. continue;
  1105. }
  1106. // Special case - parsed string with line break etc?
  1107. elseif (($string{$i} == 'n' || $string{$i} == 't') && $in_string == 2 && $is_escape)
  1108. {
  1109. // Put the escape back...
  1110. $new_string .= $string{$i} == 'n' ? "\n" : "\t";
  1111. $is_escape = false;
  1112. continue;
  1113. }
  1114. // Have we got a single quote?
  1115. elseif ($string{$i} == '\'')
  1116. {
  1117. // Already in a parsed string, or escaped in a linear string, means we print it - otherwise something special.
  1118. if ($in_string != 2 && ($in_string != 1 || !$is_escape))
  1119. {
  1120. // Is it the end of a single quote string?
  1121. if ($in_string == 1)
  1122. $in_string = 0;
  1123. // Otherwise it's the start!
  1124. else
  1125. $in_string = 1;
  1126. // Don't actually include this character!
  1127. continue;
  1128. }
  1129. }
  1130. // Otherwise a double quote?
  1131. elseif ($string{$i} == '"')
  1132. {
  1133. // Already in a single quote string, or escaped in a parsed string, means we print it - otherwise something special.
  1134. if ($in_string != 1 && ($in_string != 2 || !$is_escape))
  1135. {
  1136. // Is it the end of a double quote string?
  1137. if ($in_string == 2)
  1138. $in_string = 0;
  1139. // Otherwise it's the start!
  1140. else
  1141. $in_string = 2;
  1142. // Don't actually include this character!
  1143. continue;
  1144. }
  1145. }
  1146. // A join/space outside of a string is simply removed.
  1147. elseif ($in_string == 0 && (empty($string{$i}) || $string{$i} == '.'))
  1148. continue;
  1149. // Start of a variable?
  1150. elseif ($in_string == 0 && $string{$i} == '$')
  1151. {
  1152. // Find the whole of it!
  1153. preg_match('~([\$A-Za-z0-9\'\[\]_-]+)~', substr($string, $i), $matches);
  1154. if (!empty($matches[1]))
  1155. {
  1156. // Come up with some pseudo thing to indicate this is a var.
  1157. /**
  1158. * @todo Do better than this, please!
  1159. */
  1160. $new_string .= '{%' . $matches[1] . '%}';
  1161. // We're not going to reparse this.
  1162. $i += strlen($matches[1]) - 1;
  1163. }
  1164. continue;
  1165. }
  1166. // Right, if we're outside of a string we have DANGER, DANGER!
  1167. elseif ($in_string == 0)
  1168. {
  1169. continue;
  1170. }
  1171. // Actually add the character to the string!
  1172. $new_string .= $string{$i};
  1173. // If anything was escaped it ain't any longer!
  1174. $is_escape = false;
  1175. }
  1176. // Unhtml then rehtml the whole thing!
  1177. $new_string = $smcFunc['htmlspecialchars'](un_htmlspecialchars($new_string));
  1178. }
  1179. else
  1180. {
  1181. // Keep track of what we're doing...
  1182. $in_string = 0;
  1183. // This is for deciding whether to HTML a quote.
  1184. $in_html = false;
  1185. for ($i = 0; $i < strlen($string); $i++)
  1186. {
  1187. // We don't do parsed strings apart from for breaks.
  1188. if ($in_string == 2)
  1189. {
  1190. $in_string = 0;
  1191. $new_string .= '"';
  1192. }
  1193. // Not in a string yet?
  1194. if ($in_string != 1)
  1195. {
  1196. $in_string = 1;
  1197. $new_string .= ($new_string ? ' . ' : '') . '\'';
  1198. }
  1199. // Is this a variable?
  1200. if ($string{$i} == '{' && $string{$i + 1} == '%' && $string{$i + 2} == '$')
  1201. {
  1202. // Grab the variable.
  1203. preg_match('~\{%([\$A-Za-z0-9\'\[\]_-]+)%\}~', substr($string, $i), $matches);
  1204. if (!empty($matches[1]))
  1205. {
  1206. if ($in_string == 1)
  1207. $new_string .= '\' . ';
  1208. elseif ($new_string)
  1209. $new_string .= ' . ';
  1210. $new_string .= $matches[1];
  1211. $i += strlen($matches[1]) + 3;
  1212. $in_string = 0;
  1213. }
  1214. continue;
  1215. }
  1216. // Is this a lt sign?
  1217. elseif ($string{$i} == '<')
  1218. {
  1219. // Probably HTML?
  1220. if ($string{$i + 1} != ' ')
  1221. $in_html = true;
  1222. // Assume we need an entity...
  1223. else
  1224. {
  1225. $new_string .= '&lt;';
  1226. continue;
  1227. }
  1228. }
  1229. // What about gt?
  1230. elseif ($string{$i} == '>')
  1231. {
  1232. // Will it be HTML?
  1233. if ($in_html)
  1234. $in_html = false;
  1235. // Otherwise we need an entity...
  1236. else
  1237. {
  1238. $new_string .= '&gt;';
  1239. continue;
  1240. }
  1241. }
  1242. // Is it a slash? If so escape it...
  1243. if ($string{$i} == '\\')
  1244. $new_string .= '\\';
  1245. // The infamous double quote?
  1246. elseif ($string{$i} == '"')
  1247. {
  1248. // If we're in HTML we leave it as a quote - otherwise we entity it.
  1249. if (!$in_html)
  1250. {
  1251. $new_string .= '&quot;';
  1252. continue;
  1253. }
  1254. }
  1255. // A single quote?
  1256. elseif ($string{$i} == '\'')
  1257. {
  1258. // Must be in a string so escape it.
  1259. $new_string .= '\\';
  1260. }
  1261. // Finally add the character to the string!
  1262. $new_string .= $string{$i};
  1263. }
  1264. // If we ended as a string then close it off.
  1265. if ($in_string == 1)
  1266. $new_string .= '\'';
  1267. elseif ($in_string == 2)
  1268. $new_string .= '"';
  1269. }
  1270. return $new_string;
  1271. }
  1272. ?>