ManageLanguages.php 44 KB

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