ManageLanguages.php 44 KB

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