ManageLanguages.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  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, $modSettings;
  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, $forum_version, $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="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="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. package_create_backup('backup_lang_' . $context['lang_id']);
  828. }
  829. // Second, loop through the array to remove the files.
  830. foreach ($lang_dirs as $curPath)
  831. {
  832. foreach ($context['possible_files'][1]['files'] as $lang)
  833. if (file_exists($curPath . '/' . $lang['id'] . '.' . $context['lang_id'] . '.php'))
  834. unlink($curPath . '/' . $lang['id'] . '.' . $context['lang_id'] . '.php');
  835. // Check for the email template.
  836. if (file_exists($curPath . '/EmailTemplates.' . $context['lang_id'] . '.php'))
  837. unlink($curPath . '/EmailTemplates.' . $context['lang_id'] . '.php');
  838. }
  839. // Third, the agreement file.
  840. if (file_exists($boarddir . '/agreement.' . $context['lang_id'] . '.txt'))
  841. unlink($boarddir . '/agreement.' . $context['lang_id'] . '.txt');
  842. // Fourth, a related images folder?
  843. foreach ($images_dirs as $curPath)
  844. if (is_dir($curPath))
  845. deltree($curPath);
  846. // Members can no longer use this language.
  847. $smcFunc['db_query']('', '
  848. UPDATE {db_prefix}members
  849. SET lngfile = {empty}
  850. WHERE lngfile = {string:current_language}',
  851. array(
  852. 'empty_string' => '',
  853. 'current_language' => $context['lang_id'],
  854. )
  855. );
  856. // Fifth, update getLanguages() cache.
  857. if (!empty($modSettings['cache_enable']))
  858. {
  859. cache_put_data('known_languages', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  860. cache_put_data('known_languages_all', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  861. }
  862. // Sixth, if we deleted the default language, set us back to english?
  863. if ($context['lang_id'] == $language)
  864. {
  865. require_once($sourcedir . '/Subs-Admin.php');
  866. $language = 'english';
  867. updateSettingsFile(array('language' => '\'' . $language . '\''));
  868. }
  869. // Seventh, get out of here.
  870. redirectexit('action=admin;area=languages;sa=edit;' . $context['session_var'] . '=' . $context['session_id']);
  871. }
  872. // Saving primary settings?
  873. $madeSave = false;
  874. if (!empty($_POST['save_main']) && !$current_file)
  875. {
  876. checkSession();
  877. validateToken('admin-mlang');
  878. // Read in the current file.
  879. $current_data = implode('', file($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php'));
  880. // These are the replacements. old => new
  881. $replace_array = array(
  882. '~\$txt\[\'lang_character_set\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_character_set\'] = \'' . preg_replace('~[^\w-]~i', '', $_POST['character_set']) . '\';',
  883. '~\$txt\[\'lang_locale\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_locale\'] = \'' . preg_replace('~[^\w-]~i', '', $_POST['locale']) . '\';',
  884. '~\$txt\[\'lang_dictionary\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_dictionary\'] = \'' . preg_replace('~[^\w-]~i', '', $_POST['dictionary']) . '\';',
  885. '~\$txt\[\'lang_spelling\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_spelling\'] = \'' . preg_replace('~[^\w-]~i', '', $_POST['spelling']) . '\';',
  886. '~\$txt\[\'lang_rtl\'\]\s=\s[A-Za-z0-9]+;~' => '$txt[\'lang_rtl\'] = ' . (!empty($_POST['rtl']) ? 'true' : 'false') . ';',
  887. );
  888. $current_data = preg_replace(array_keys($replace_array), array_values($replace_array), $current_data);
  889. $fp = fopen($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php', 'w+');
  890. fwrite($fp, $current_data);
  891. fclose($fp);
  892. $madeSave = true;
  893. }
  894. // Quickly load index language entries.
  895. $old_txt = $txt;
  896. require($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php');
  897. $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');
  898. // Setup the primary settings context.
  899. $context['primary_settings'] = array(
  900. 'name' => $smcFunc['ucwords'](strtr($context['lang_id'], array('_' => ' ', '-utf8' => ''))),
  901. 'character_set' => $txt['lang_character_set'],
  902. 'locale' => $txt['lang_locale'],
  903. 'dictionary' => $txt['lang_dictionary'],
  904. 'spelling' => $txt['lang_spelling'],
  905. 'rtl' => $txt['lang_rtl'],
  906. );
  907. // Restore normal service.
  908. $txt = $old_txt;
  909. // Are we saving?
  910. $save_strings = array();
  911. if (isset($_POST['save_entries']) && !empty($_POST['entry']))
  912. {
  913. checkSession();
  914. validateToken('admin-mlang');
  915. // Clean each entry!
  916. foreach ($_POST['entry'] as $k => $v)
  917. {
  918. // Only try to save if it's changed!
  919. if ($_POST['entry'][$k] != $_POST['comp'][$k])
  920. $save_strings[$k] = cleanLangString($v, false);
  921. }
  922. }
  923. // If we are editing a file work away at that.
  924. if ($current_file)
  925. {
  926. $context['entries_not_writable_message'] = is_writable($current_file) ? '' : sprintf($txt['lang_entries_not_writable'], $current_file);
  927. $entries = array();
  928. // We can't just require it I'm afraid - otherwise we pass in all kinds of variables!
  929. $multiline_cache = '';
  930. foreach (file($current_file) as $line)
  931. {
  932. // Got a new entry?
  933. if ($line[0] == '$' && !empty($multiline_cache))
  934. {
  935. preg_match('~\$(helptxt|txt|editortxt)\[\'(.+)\'\]\s?=\s?(.+);~ms', strtr($multiline_cache, array("\r" => '')), $matches);
  936. if (!empty($matches[3]))
  937. {
  938. $entries[$matches[2]] = array(
  939. 'type' => $matches[1],
  940. 'full' => $matches[0],
  941. 'entry' => $matches[3],
  942. );
  943. $multiline_cache = '';
  944. }
  945. }
  946. $multiline_cache .= $line;
  947. }
  948. // Last entry to add?
  949. if ($multiline_cache)
  950. {
  951. preg_match('~\$(helptxt|txt|editortxt)\[\'(.+)\'\]\s?=\s?(.+);~ms', strtr($multiline_cache, array("\r" => '')), $matches);
  952. if (!empty($matches[3]))
  953. $entries[$matches[2]] = array(
  954. 'type' => $matches[1],
  955. 'full' => $matches[0],
  956. 'entry' => $matches[3],
  957. );
  958. }
  959. // These are the entries we can definitely save.
  960. $final_saves = array();
  961. $context['file_entries'] = array();
  962. foreach ($entries as $entryKey => $entryValue)
  963. {
  964. // Ignore some things we set separately.
  965. $ignore_files = array('lang_character_set', 'lang_locale', 'lang_dictionary', 'lang_spelling', 'lang_rtl');
  966. if (in_array($entryKey, $ignore_files))
  967. continue;
  968. // These are arrays that need breaking out.
  969. $arrays = array('days', 'days_short', 'months', 'months_titles', 'months_short', 'happy_birthday_author', 'karlbenson1_author', 'nite0859_author', 'zwaldowski_author', 'geezmo_author', 'karlbenson2_author');
  970. if (in_array($entryKey, $arrays))
  971. {
  972. // Get off the first bits.
  973. $entryValue['entry'] = substr($entryValue['entry'], strpos($entryValue['entry'], '(') + 1, strrpos($entryValue['entry'], ')') - strpos($entryValue['entry'], '('));
  974. $entryValue['entry'] = explode(',', strtr($entryValue['entry'], array(' ' => '')));
  975. // Now create an entry for each item.
  976. $cur_index = 0;
  977. $save_cache = array(
  978. 'enabled' => false,
  979. 'entries' => array(),
  980. );
  981. foreach ($entryValue['entry'] as $id => $subValue)
  982. {
  983. // Is this a new index?
  984. if (preg_match('~^(\d+)~', $subValue, $matches))
  985. {
  986. $cur_index = $matches[1];
  987. $subValue = substr($subValue, strpos($subValue, '\''));
  988. }
  989. // Clean up some bits.
  990. $subValue = strtr($subValue, array('"' => '', '\'' => '', ')' => ''));
  991. // Can we save?
  992. if (isset($save_strings[$entryKey . '-+- ' . $cur_index]))
  993. {
  994. $save_cache['entries'][$cur_index] = strtr($save_strings[$entryKey . '-+- ' . $cur_index], array('\'' => ''));
  995. $save_cache['enabled'] = true;
  996. }
  997. else
  998. $save_cache['entries'][$cur_index] = $subValue;
  999. $context['file_entries'][] = array(
  1000. 'key' => $entryKey . '-+- ' . $cur_index,
  1001. 'value' => $subValue,
  1002. 'rows' => 1,
  1003. );
  1004. $cur_index++;
  1005. }
  1006. // Do we need to save?
  1007. if ($save_cache['enabled'])
  1008. {
  1009. // Format the string, checking the indexes first.
  1010. $items = array();
  1011. $cur_index = 0;
  1012. foreach ($save_cache['entries'] as $k2 => $v2)
  1013. {
  1014. // Manually show the custom index.
  1015. if ($k2 != $cur_index)
  1016. {
  1017. $items[] = $k2 . ' => \'' . $v2 . '\'';
  1018. $cur_index = $k2;
  1019. }
  1020. else
  1021. $items[] = '\'' . $v2 . '\'';
  1022. $cur_index++;
  1023. }
  1024. // Now create the string!
  1025. $final_saves[$entryKey] = array(
  1026. 'find' => $entryValue['full'],
  1027. 'replace' => '$' . $entryValue['type'] . '[\'' . $entryKey . '\'] = array(' . implode(', ', $items) . ');',
  1028. );
  1029. }
  1030. }
  1031. else
  1032. {
  1033. // Saving?
  1034. if (isset($save_strings[$entryKey]) && $save_strings[$entryKey] != $entryValue['entry'])
  1035. {
  1036. // @todo Fix this properly.
  1037. if ($save_strings[$entryKey] == '')
  1038. $save_strings[$entryKey] = '\'\'';
  1039. // Set the new value.
  1040. $entryValue['entry'] = $save_strings[$entryKey];
  1041. // And we know what to save now!
  1042. $final_saves[$entryKey] = array(
  1043. 'find' => $entryValue['full'],
  1044. 'replace' => '$' . $entryValue['type'] . '[\'' . $entryKey . '\'] = ' . $save_strings[$entryKey] . ';',
  1045. );
  1046. }
  1047. $editing_string = cleanLangString($entryValue['entry'], true);
  1048. $context['file_entries'][] = array(
  1049. 'key' => $entryKey,
  1050. 'value' => $editing_string,
  1051. 'rows' => (int) (strlen($editing_string) / 38) + substr_count($editing_string, "\n") + 1,
  1052. );
  1053. }
  1054. }
  1055. // Any saves to make?
  1056. if (!empty($final_saves))
  1057. {
  1058. checkSession();
  1059. $file_contents = implode('', file($current_file));
  1060. foreach ($final_saves as $save)
  1061. $file_contents = strtr($file_contents, array($save['find'] => $save['replace']));
  1062. // Save the actual changes.
  1063. $fp = fopen($current_file, 'w+');
  1064. fwrite($fp, strtr($file_contents, array("\r" => '')));
  1065. fclose($fp);
  1066. $madeSave = true;
  1067. }
  1068. // Another restore.
  1069. $txt = $old_txt;
  1070. }
  1071. // If we saved, redirect.
  1072. if ($madeSave)
  1073. redirectexit('action=admin;area=languages;sa=editlang;lid=' . $context['lang_id']);
  1074. createToken('admin-mlang');
  1075. }
  1076. /**
  1077. * This function cleans language entries to/from display.
  1078. * @todo This function could be two functions?
  1079. *
  1080. * @param $string
  1081. * @param $to_display
  1082. */
  1083. function cleanLangString($string, $to_display = true)
  1084. {
  1085. global $smcFunc;
  1086. // If going to display we make sure it doesn't have any HTML in it - etc.
  1087. $new_string = '';
  1088. if ($to_display)
  1089. {
  1090. // Are we in a string (0 = no, 1 = single quote, 2 = parsed)
  1091. $in_string = 0;
  1092. $is_escape = false;
  1093. for ($i = 0; $i < strlen($string); $i++)
  1094. {
  1095. // Handle ecapes first.
  1096. if ($string{$i} == '\\')
  1097. {
  1098. // Toggle the escape.
  1099. $is_escape = !$is_escape;
  1100. // If we're now escaped don't add this string.
  1101. if ($is_escape)
  1102. continue;
  1103. }
  1104. // Special case - parsed string with line break etc?
  1105. elseif (($string{$i} == 'n' || $string{$i} == 't') && $in_string == 2 && $is_escape)
  1106. {
  1107. // Put the escape back...
  1108. $new_string .= $string{$i} == 'n' ? "\n" : "\t";
  1109. $is_escape = false;
  1110. continue;
  1111. }
  1112. // Have we got a single quote?
  1113. elseif ($string{$i} == '\'')
  1114. {
  1115. // Already in a parsed string, or escaped in a linear string, means we print it - otherwise something special.
  1116. if ($in_string != 2 && ($in_string != 1 || !$is_escape))
  1117. {
  1118. // Is it the end of a single quote string?
  1119. if ($in_string == 1)
  1120. $in_string = 0;
  1121. // Otherwise it's the start!
  1122. else
  1123. $in_string = 1;
  1124. // Don't actually include this character!
  1125. continue;
  1126. }
  1127. }
  1128. // Otherwise a double quote?
  1129. elseif ($string{$i} == '"')
  1130. {
  1131. // Already in a single quote string, or escaped in a parsed string, means we print it - otherwise something special.
  1132. if ($in_string != 1 && ($in_string != 2 || !$is_escape))
  1133. {
  1134. // Is it the end of a double quote string?
  1135. if ($in_string == 2)
  1136. $in_string = 0;
  1137. // Otherwise it's the start!
  1138. else
  1139. $in_string = 2;
  1140. // Don't actually include this character!
  1141. continue;
  1142. }
  1143. }
  1144. // A join/space outside of a string is simply removed.
  1145. elseif ($in_string == 0 && (empty($string{$i}) || $string{$i} == '.'))
  1146. continue;
  1147. // Start of a variable?
  1148. elseif ($in_string == 0 && $string{$i} == '$')
  1149. {
  1150. // Find the whole of it!
  1151. preg_match('~([\$A-Za-z0-9\'\[\]_-]+)~', substr($string, $i), $matches);
  1152. if (!empty($matches[1]))
  1153. {
  1154. // Come up with some pseudo thing to indicate this is a var.
  1155. /**
  1156. * @todo Do better than this, please!
  1157. */
  1158. $new_string .= '{%' . $matches[1] . '%}';
  1159. // We're not going to reparse this.
  1160. $i += strlen($matches[1]) - 1;
  1161. }
  1162. continue;
  1163. }
  1164. // Right, if we're outside of a string we have DANGER, DANGER!
  1165. elseif ($in_string == 0)
  1166. {
  1167. continue;
  1168. }
  1169. // Actually add the character to the string!
  1170. $new_string .= $string{$i};
  1171. // If anything was escaped it ain't any longer!
  1172. $is_escape = false;
  1173. }
  1174. // Unhtml then rehtml the whole thing!
  1175. $new_string = $smcFunc['htmlspecialchars'](un_htmlspecialchars($new_string));
  1176. }
  1177. else
  1178. {
  1179. // Keep track of what we're doing...
  1180. $in_string = 0;
  1181. // This is for deciding whether to HTML a quote.
  1182. $in_html = false;
  1183. for ($i = 0; $i < strlen($string); $i++)
  1184. {
  1185. // We don't do parsed strings apart from for breaks.
  1186. if ($in_string == 2)
  1187. {
  1188. $in_string = 0;
  1189. $new_string .= '"';
  1190. }
  1191. // Not in a string yet?
  1192. if ($in_string != 1)
  1193. {
  1194. $in_string = 1;
  1195. $new_string .= ($new_string ? ' . ' : '') . '\'';
  1196. }
  1197. // Is this a variable?
  1198. if ($string{$i} == '{' && $string{$i + 1} == '%' && $string{$i + 2} == '$')
  1199. {
  1200. // Grab the variable.
  1201. preg_match('~\{%([\$A-Za-z0-9\'\[\]_-]+)%\}~', substr($string, $i), $matches);
  1202. if (!empty($matches[1]))
  1203. {
  1204. if ($in_string == 1)
  1205. $new_string .= '\' . ';
  1206. elseif ($new_string)
  1207. $new_string .= ' . ';
  1208. $new_string .= $matches[1];
  1209. $i += strlen($matches[1]) + 3;
  1210. $in_string = 0;
  1211. }
  1212. continue;
  1213. }
  1214. // Is this a lt sign?
  1215. elseif ($string{$i} == '<')
  1216. {
  1217. // Probably HTML?
  1218. if ($string{$i + 1} != ' ')
  1219. $in_html = true;
  1220. // Assume we need an entity...
  1221. else
  1222. {
  1223. $new_string .= '&lt;';
  1224. continue;
  1225. }
  1226. }
  1227. // What about gt?
  1228. elseif ($string{$i} == '>')
  1229. {
  1230. // Will it be HTML?
  1231. if ($in_html)
  1232. $in_html = false;
  1233. // Otherwise we need an entity...
  1234. else
  1235. {
  1236. $new_string .= '&gt;';
  1237. continue;
  1238. }
  1239. }
  1240. // Is it a slash? If so escape it...
  1241. if ($string{$i} == '\\')
  1242. $new_string .= '\\';
  1243. // The infamous double quote?
  1244. elseif ($string{$i} == '"')
  1245. {
  1246. // If we're in HTML we leave it as a quote - otherwise we entity it.
  1247. if (!$in_html)
  1248. {
  1249. $new_string .= '&quot;';
  1250. continue;
  1251. }
  1252. }
  1253. // A single quote?
  1254. elseif ($string{$i} == '\'')
  1255. {
  1256. // Must be in a string so escape it.
  1257. $new_string .= '\\';
  1258. }
  1259. // Finally add the character to the string!
  1260. $new_string .= $string{$i};
  1261. }
  1262. // If we ended as a string then close it off.
  1263. if ($in_string == 1)
  1264. $new_string .= '\'';
  1265. elseif ($in_string == 2)
  1266. $new_string .= '"';
  1267. }
  1268. return $new_string;
  1269. }
  1270. ?>