ManageLanguages.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  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 2012 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. 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. if ($_POST['def_language'] != $language)
  509. {
  510. require_once($sourcedir . '/Subs-Admin.php');
  511. updateSettingsFile(array('language' => '\'' . $_POST['def_language'] . '\''));
  512. $language = $_POST['def_language'];
  513. }
  514. }
  515. // Create another one time token here.
  516. createToken('admin-lang');
  517. $listOptions = array(
  518. 'id' => 'language_list',
  519. 'items_per_page' => 20,
  520. 'base_href' => $scripturl . '?action=admin;area=languages',
  521. 'title' => $txt['edit_languages'],
  522. 'get_items' => array(
  523. 'function' => 'list_getLanguages',
  524. ),
  525. 'get_count' => array(
  526. 'function' => 'list_getNumLanguages',
  527. ),
  528. 'columns' => array(
  529. 'default' => array(
  530. 'header' => array(
  531. 'value' => $txt['languages_default'],
  532. 'class' => 'centercol',
  533. ),
  534. 'data' => array(
  535. 'function' => create_function('$rowData', '
  536. return \'<input type="radio" name="def_language" value="\' . $rowData[\'id\'] . \'" \' . ($rowData[\'default\'] ? \'checked="checked"\' : \'\') . \' onclick="highlightSelected(\\\'list_language_list_\' . $rowData[\'id\'] . \'\\\');" class="input_radio" />\';
  537. '),
  538. 'style' => 'width: 8%;',
  539. 'class' => 'centercol',
  540. ),
  541. ),
  542. 'name' => array(
  543. 'header' => array(
  544. 'value' => $txt['languages_lang_name'],
  545. ),
  546. 'data' => array(
  547. 'function' => create_function('$rowData', '
  548. global $scripturl, $context;
  549. return sprintf(\'<a href="%1$s?action=admin;area=languages;sa=editlang;lid=%2$s">%3$s</a>\', $scripturl, $rowData[\'id\'], $rowData[\'name\']);
  550. '),
  551. ),
  552. ),
  553. 'character_set' => array(
  554. 'header' => array(
  555. 'value' => $txt['languages_character_set'],
  556. ),
  557. 'data' => array(
  558. 'db_htmlsafe' => 'char_set',
  559. ),
  560. ),
  561. 'count' => array(
  562. 'header' => array(
  563. 'value' => $txt['languages_users'],
  564. ),
  565. 'data' => array(
  566. 'db_htmlsafe' => 'count',
  567. ),
  568. ),
  569. 'locale' => array(
  570. 'header' => array(
  571. 'value' => $txt['languages_locale'],
  572. ),
  573. 'data' => array(
  574. 'db_htmlsafe' => 'locale',
  575. ),
  576. ),
  577. ),
  578. 'form' => array(
  579. 'href' => $scripturl . '?action=admin;area=languages',
  580. 'token' => 'admin-lang',
  581. ),
  582. 'additional_rows' => array(
  583. array(
  584. 'position' => 'bottom_of_list',
  585. '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" />',
  586. ),
  587. ),
  588. // For highlighting the default.
  589. 'javascript' => '
  590. var prevClass = "";
  591. var prevDiv = "";
  592. function highlightSelected(box)
  593. {
  594. if (prevClass != "")
  595. prevDiv.className = prevClass;
  596. prevDiv = document.getElementById(box);
  597. prevClass = prevDiv.className;
  598. prevDiv.className = "highlight2";
  599. }
  600. highlightSelected("list_language_list_' . ($language == '' ? 'english' : $language). '");
  601. ',
  602. );
  603. // Display a warning if we cannot edit the default setting.
  604. if (!is_writable($boarddir . '/Settings.php'))
  605. $listOptions['additional_rows'][] = array(
  606. 'position' => 'after_title',
  607. 'value' => $txt['language_settings_writable'],
  608. 'class' => 'smalltext alert',
  609. );
  610. require_once($sourcedir . '/Subs-List.php');
  611. createList($listOptions);
  612. $context['sub_template'] = 'show_list';
  613. $context['default_list'] = 'language_list';
  614. }
  615. /**
  616. * How many languages?
  617. * Callback for the list in ManageLanguageSettings().
  618. */
  619. function list_getNumLanguages()
  620. {
  621. return count(getLanguages(true, false));
  622. }
  623. /**
  624. * Fetch the actual language information.
  625. * Callback for $listOptions['get_items']['function'] in ManageLanguageSettings.
  626. * Determines which languages are available by looking for the "index.{language}.php" file.
  627. * Also figures out how many users are using a particular language.
  628. */
  629. function list_getLanguages()
  630. {
  631. global $settings, $smcFunc, $language, $context, $txt;
  632. $languages = array();
  633. // Keep our old entries.
  634. $old_txt = $txt;
  635. $backup_actual_theme_dir = $settings['actual_theme_dir'];
  636. $backup_base_theme_dir = !empty($settings['base_theme_dir']) ? $settings['base_theme_dir'] : '';
  637. // Override these for now.
  638. $settings['actual_theme_dir'] = $settings['base_theme_dir'] = $settings['default_theme_dir'];
  639. getLanguages(true, false);
  640. // Put them back.
  641. $settings['actual_theme_dir'] = $backup_actual_theme_dir;
  642. if (!empty($backup_base_theme_dir))
  643. $settings['base_theme_dir'] = $backup_base_theme_dir;
  644. else
  645. unset($settings['base_theme_dir']);
  646. // Get the language files and data...
  647. foreach ($context['languages'] as $lang)
  648. {
  649. // Load the file to get the character set.
  650. require($settings['default_theme_dir'] . '/languages/index.' . $lang['filename'] . '.php');
  651. $languages[$lang['filename']] = array(
  652. 'id' => $lang['filename'],
  653. 'count' => 0,
  654. 'char_set' => $txt['lang_character_set'],
  655. 'default' => $language == $lang['filename'] || ($language == '' && $lang['filename'] == 'english'),
  656. 'locale' => $txt['lang_locale'],
  657. 'name' => $smcFunc['ucwords'](strtr($lang['filename'], array('_' => ' ', '-utf8' => ''))),
  658. );
  659. }
  660. // Work out how many people are using each language.
  661. $request = $smcFunc['db_query']('', '
  662. SELECT lngfile, COUNT(*) AS num_users
  663. FROM {db_prefix}members
  664. GROUP BY lngfile',
  665. array(
  666. )
  667. );
  668. while ($row = $smcFunc['db_fetch_assoc']($request))
  669. {
  670. // Default?
  671. if (empty($row['lngfile']) || !isset($languages[$row['lngfile']]))
  672. $row['lngfile'] = $language;
  673. if (!isset($languages[$row['lngfile']]) && isset($languages['english']))
  674. $languages['english']['count'] += $row['num_users'];
  675. elseif (isset($languages[$row['lngfile']]))
  676. $languages[$row['lngfile']]['count'] += $row['num_users'];
  677. }
  678. $smcFunc['db_free_result']($request);
  679. // Restore the current users language.
  680. $txt = $old_txt;
  681. // Return how many we have.
  682. return $languages;
  683. }
  684. /**
  685. * Edit language related settings.
  686. *
  687. * @param bool $return_config = false
  688. */
  689. function ModifyLanguageSettings($return_config = false)
  690. {
  691. global $scripturl, $context, $txt, $boarddir, $settings, $smcFunc, $sourcedir;
  692. // We'll want to save them someday.
  693. require_once $sourcedir . '/ManageServer.php';
  694. // Warn the user if the backup of Settings.php failed.
  695. $settings_not_writable = !is_writable($boarddir . '/Settings.php');
  696. $settings_backup_fail = !@is_writable($boarddir . '/Settings_bak.php') || !@copy($boarddir . '/Settings.php', $boarddir . '/Settings_bak.php');
  697. /* If you're writing a mod, it's a bad idea to add things here....
  698. For each option:
  699. variable name, description, type (constant), size/possible values, helptext.
  700. OR an empty string for a horizontal rule.
  701. OR a string for a titled section. */
  702. $config_vars = array(
  703. 'language' => array('language', $txt['default_language'], 'file', 'select', array(), null, 'disabled' => $settings_not_writable),
  704. array('userLanguage', $txt['userLanguage'], 'db', 'check', null, 'userLanguage'),
  705. );
  706. call_integration_hook('integrate_language_settings', array($config_vars));
  707. if ($return_config)
  708. return $config_vars;
  709. // Get our languages. No cache and use utf8.
  710. getLanguages(false, false);
  711. foreach ($context['languages'] as $lang)
  712. $config_vars['language'][4][$lang['filename']] = array($lang['filename'], strtr($lang['name'], array('-utf8' => ' (UTF-8)')));
  713. // Saving settings?
  714. if (isset($_REQUEST['save']))
  715. {
  716. checkSession();
  717. call_integration_hook('integrate_save_language_settings', array($config_vars));
  718. saveSettings($config_vars);
  719. redirectexit('action=admin;area=languages;sa=settings');
  720. }
  721. // Setup the template stuff.
  722. $context['post_url'] = $scripturl . '?action=admin;area=languages;sa=settings;save';
  723. $context['settings_title'] = $txt['language_settings'];
  724. $context['save_disabled'] = $settings_not_writable;
  725. if ($settings_not_writable)
  726. $context['settings_message'] = '<div class="centertext"><strong>' . $txt['settings_not_writable'] . '</strong></div><br />';
  727. elseif ($settings_backup_fail)
  728. $context['settings_message'] = '<div class="centertext"><strong>' . $txt['admin_backup_fail'] . '</strong></div><br />';
  729. // Fill the config array.
  730. prepareServerSettingsContext($config_vars);
  731. }
  732. /**
  733. * Edit a particular set of language entries.
  734. */
  735. function ModifyLanguage()
  736. {
  737. global $settings, $context, $smcFunc, $txt, $modSettings, $boarddir, $sourcedir, $language;
  738. loadLanguage('ManageSettings');
  739. // Select the languages tab.
  740. $context['menu_data_' . $context['admin_menu_id']]['current_subsection'] = 'edit';
  741. $context['page_title'] = $txt['edit_languages'];
  742. $context['sub_template'] = 'modify_language_entries';
  743. $context['lang_id'] = $_GET['lid'];
  744. list($theme_id, $file_id) = empty($_REQUEST['tfid']) || strpos($_REQUEST['tfid'], '+') === false ? array(1, '') : explode('+', $_REQUEST['tfid']);
  745. // Clean the ID - just in case.
  746. preg_match('~([A-Za-z0-9_-]+)~', $context['lang_id'], $matches);
  747. $context['lang_id'] = $matches[1];
  748. // Get all the theme data.
  749. $request = $smcFunc['db_query']('', '
  750. SELECT id_theme, variable, value
  751. FROM {db_prefix}themes
  752. WHERE id_theme != {int:default_theme}
  753. AND id_member = {int:no_member}
  754. AND variable IN ({string:name}, {string:theme_dir})',
  755. array(
  756. 'default_theme' => 1,
  757. 'no_member' => 0,
  758. 'name' => 'name',
  759. 'theme_dir' => 'theme_dir',
  760. )
  761. );
  762. $themes = array(
  763. 1 => array(
  764. 'name' => $txt['dvc_default'],
  765. 'theme_dir' => $settings['default_theme_dir'],
  766. ),
  767. );
  768. while ($row = $smcFunc['db_fetch_assoc']($request))
  769. $themes[$row['id_theme']][$row['variable']] = $row['value'];
  770. $smcFunc['db_free_result']($request);
  771. // This will be where we look
  772. $lang_dirs = array();
  773. // Check we have themes with a path and a name - just in case - and add the path.
  774. foreach ($themes as $id => $data)
  775. {
  776. if (count($data) != 2)
  777. unset($themes[$id]);
  778. elseif (is_dir($data['theme_dir'] . '/languages'))
  779. $lang_dirs[$id] = $data['theme_dir'] . '/languages';
  780. // How about image directories?
  781. if (is_dir($data['theme_dir'] . '/images/' . $context['lang_id']))
  782. $images_dirs[$id] = $data['theme_dir'] . '/images/' . $context['lang_id'];
  783. }
  784. $current_file = $file_id ? $lang_dirs[$theme_id] . '/' . $file_id . '.' . $context['lang_id'] . '.php' : '';
  785. // Now for every theme get all the files and stick them in context!
  786. $context['possible_files'] = array();
  787. foreach ($lang_dirs as $theme => $theme_dir)
  788. {
  789. // Open it up.
  790. $dir = dir($theme_dir);
  791. while ($entry = $dir->read())
  792. {
  793. // We're only after the files for this language.
  794. if (preg_match('~^([A-Za-z]+)\.' . $context['lang_id'] . '\.php$~', $entry, $matches) == 0)
  795. continue;
  796. if (!isset($context['possible_files'][$theme]))
  797. $context['possible_files'][$theme] = array(
  798. 'id' => $theme,
  799. 'name' => $themes[$theme]['name'],
  800. 'files' => array(),
  801. );
  802. $context['possible_files'][$theme]['files'][] = array(
  803. 'id' => $matches[1],
  804. 'name' => isset($txt['lang_file_desc_' . $matches[1]]) ? $txt['lang_file_desc_' . $matches[1]] : $matches[1],
  805. 'selected' => $theme_id == $theme && $file_id == $matches[1],
  806. );
  807. }
  808. $dir->close();
  809. usort($context['possible_files'][$theme]['files'], create_function('$val1, $val2', 'return strcmp($val1[\'name\'], $val2[\'name\']);'));
  810. }
  811. // We no longer wish to speak this language.
  812. if (!empty($_POST['delete_main']) && $context['lang_id'] != 'english')
  813. {
  814. checkSession();
  815. validateToken('admin-mlang');
  816. // @todo Todo: FTP Controls?
  817. require_once($sourcedir . '/Subs-Package.php');
  818. // First, Make a backup?
  819. if (!empty($modSettings['package_make_backups']) && (!isset($_SESSION['last_backup_for']) || $_SESSION['last_backup_for'] != $context['lang_id'] . '$$$'))
  820. {
  821. $_SESSION['last_backup_for'] = $context['lang_id'] . '$$$';
  822. package_create_backup('backup_lang_' . $context['lang_id']);
  823. }
  824. // Second, loop through the array to remove the files.
  825. foreach ($lang_dirs as $curPath)
  826. {
  827. foreach ($context['possible_files'][1]['files'] as $lang)
  828. if (file_exists($curPath . '/' . $lang['id'] . '.' . $context['lang_id'] . '.php'))
  829. unlink($curPath . '/' . $lang['id'] . '.' . $context['lang_id'] . '.php');
  830. // Check for the email template.
  831. if (file_exists($curPath . '/EmailTemplates.' . $context['lang_id'] . '.php'))
  832. unlink($curPath . '/EmailTemplates.' . $context['lang_id'] . '.php');
  833. }
  834. // Third, the agreement file.
  835. if (file_exists($boarddir . '/agreement.' . $context['lang_id'] . '.txt'))
  836. unlink($boarddir . '/agreement.' . $context['lang_id'] . '.txt');
  837. // Fourth, a related images folder?
  838. foreach ($images_dirs as $curPath)
  839. if (is_dir($curPath))
  840. deltree($curPath);
  841. // Members can no longer use this language.
  842. $smcFunc['db_query']('', '
  843. UPDATE {db_prefix}members
  844. SET lngfile = {string:empty_string}
  845. WHERE lngfile = {string:current_language}',
  846. array(
  847. 'empty_string' => '',
  848. 'current_language' => $context['lang_id'],
  849. )
  850. );
  851. // Fifth, update getLanguages() cache.
  852. if (!empty($modSettings['cache_enable']))
  853. {
  854. cache_put_data('known_languages', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  855. cache_put_data('known_languages_all', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  856. }
  857. // Sixth, if we deleted the default language, set us back to english?
  858. if ($context['lang_id'] == $language)
  859. {
  860. require_once($sourcedir . '/Subs-Admin.php');
  861. $language = 'english';
  862. updateSettingsFile(array('language' => '\'' . $language . '\''));
  863. }
  864. // Seventh, get out of here.
  865. redirectexit('action=admin;area=languages;sa=edit;' . $context['session_var'] . '=' . $context['session_id']);
  866. }
  867. // Saving primary settings?
  868. $madeSave = false;
  869. if (!empty($_POST['save_main']) && !$current_file)
  870. {
  871. checkSession();
  872. validateToken('admin-mlang');
  873. // Read in the current file.
  874. $current_data = implode('', file($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php'));
  875. // These are the replacements. old => new
  876. $replace_array = array(
  877. '~\$txt\[\'lang_character_set\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_character_set\'] = \'' . addslashes($_POST['character_set']) . '\';',
  878. '~\$txt\[\'lang_locale\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_locale\'] = \'' . addslashes($_POST['locale']) . '\';',
  879. '~\$txt\[\'lang_dictionary\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_dictionary\'] = \'' . addslashes($_POST['dictionary']) . '\';',
  880. '~\$txt\[\'lang_spelling\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_spelling\'] = \'' . addslashes($_POST['spelling']) . '\';',
  881. '~\$txt\[\'lang_rtl\'\]\s=\s[A-Za-z0-9]+;~' => '$txt[\'lang_rtl\'] = ' . (!empty($_POST['rtl']) ? 'true' : 'false') . ';',
  882. );
  883. $current_data = preg_replace(array_keys($replace_array), array_values($replace_array), $current_data);
  884. $fp = fopen($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php', 'w+');
  885. fwrite($fp, $current_data);
  886. fclose($fp);
  887. $madeSave = true;
  888. }
  889. // Quickly load index language entries.
  890. $old_txt = $txt;
  891. require($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php');
  892. $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');
  893. // Setup the primary settings context.
  894. $context['primary_settings'] = array(
  895. 'name' => $smcFunc['ucwords'](strtr($context['lang_id'], array('_' => ' ', '-utf8' => ''))),
  896. 'character_set' => $txt['lang_character_set'],
  897. 'locale' => $txt['lang_locale'],
  898. 'dictionary' => $txt['lang_dictionary'],
  899. 'spelling' => $txt['lang_spelling'],
  900. 'rtl' => $txt['lang_rtl'],
  901. );
  902. // Restore normal service.
  903. $txt = $old_txt;
  904. // Are we saving?
  905. $save_strings = array();
  906. if (isset($_POST['save_entries']) && !empty($_POST['entry']))
  907. {
  908. checkSession();
  909. validateToken('admin-mlang');
  910. // Clean each entry!
  911. foreach ($_POST['entry'] as $k => $v)
  912. {
  913. // Only try to save if it's changed!
  914. if ($_POST['entry'][$k] != $_POST['comp'][$k])
  915. $save_strings[$k] = cleanLangString($v, false);
  916. }
  917. }
  918. // If we are editing a file work away at that.
  919. if ($current_file)
  920. {
  921. $context['entries_not_writable_message'] = is_writable($current_file) ? '' : sprintf($txt['lang_entries_not_writable'], $current_file);
  922. $entries = array();
  923. // We can't just require it I'm afraid - otherwise we pass in all kinds of variables!
  924. $multiline_cache = '';
  925. foreach (file($current_file) as $line)
  926. {
  927. // Got a new entry?
  928. if ($line[0] == '$' && !empty($multiline_cache))
  929. {
  930. preg_match('~\$(helptxt|txt|editortxt)\[\'(.+)\'\]\s?=\s?(.+);~ms', strtr($multiline_cache, array("\r" => '')), $matches);
  931. if (!empty($matches[3]))
  932. {
  933. $entries[$matches[2]] = array(
  934. 'type' => $matches[1],
  935. 'full' => $matches[0],
  936. 'entry' => $matches[3],
  937. );
  938. $multiline_cache = '';
  939. }
  940. }
  941. $multiline_cache .= $line;
  942. }
  943. // Last entry to add?
  944. if ($multiline_cache)
  945. {
  946. preg_match('~\$(helptxt|txt|editortxt)\[\'(.+)\'\]\s?=\s?(.+);~ms', strtr($multiline_cache, array("\r" => '')), $matches);
  947. if (!empty($matches[3]))
  948. $entries[$matches[2]] = array(
  949. 'type' => $matches[1],
  950. 'full' => $matches[0],
  951. 'entry' => $matches[3],
  952. );
  953. }
  954. // These are the entries we can definitely save.
  955. $final_saves = array();
  956. $context['file_entries'] = array();
  957. foreach ($entries as $entryKey => $entryValue)
  958. {
  959. // Ignore some things we set separately.
  960. $ignore_files = array('lang_character_set', 'lang_locale', 'lang_dictionary', 'lang_spelling', 'lang_rtl');
  961. if (in_array($entryKey, $ignore_files))
  962. continue;
  963. // These are arrays that need breaking out.
  964. $arrays = array('days', 'days_short', 'months', 'months_titles', 'months_short', 'happy_birthday_author', 'karlbenson1_author', 'nite0859_author', 'zwaldowski_author', 'geezmo_author', 'karlbenson2_author');
  965. if (in_array($entryKey, $arrays))
  966. {
  967. // Get off the first bits.
  968. $entryValue['entry'] = substr($entryValue['entry'], strpos($entryValue['entry'], '(') + 1, strrpos($entryValue['entry'], ')') - strpos($entryValue['entry'], '('));
  969. $entryValue['entry'] = explode(',', strtr($entryValue['entry'], array(' ' => '')));
  970. // Now create an entry for each item.
  971. $cur_index = 0;
  972. $save_cache = array(
  973. 'enabled' => false,
  974. 'entries' => array(),
  975. );
  976. foreach ($entryValue['entry'] as $id => $subValue)
  977. {
  978. // Is this a new index?
  979. if (preg_match('~^(\d+)~', $subValue, $matches))
  980. {
  981. $cur_index = $matches[1];
  982. $subValue = substr($subValue, strpos($subValue, '\''));
  983. }
  984. // Clean up some bits.
  985. $subValue = strtr($subValue, array('"' => '', '\'' => '', ')' => ''));
  986. // Can we save?
  987. if (isset($save_strings[$entryKey . '-+- ' . $cur_index]))
  988. {
  989. $save_cache['entries'][$cur_index] = strtr($save_strings[$entryKey . '-+- ' . $cur_index], array('\'' => ''));
  990. $save_cache['enabled'] = true;
  991. }
  992. else
  993. $save_cache['entries'][$cur_index] = $subValue;
  994. $context['file_entries'][] = array(
  995. 'key' => $entryKey . '-+- ' . $cur_index,
  996. 'value' => $subValue,
  997. 'rows' => 1,
  998. );
  999. $cur_index++;
  1000. }
  1001. // Do we need to save?
  1002. if ($save_cache['enabled'])
  1003. {
  1004. // Format the string, checking the indexes first.
  1005. $items = array();
  1006. $cur_index = 0;
  1007. foreach ($save_cache['entries'] as $k2 => $v2)
  1008. {
  1009. // Manually show the custom index.
  1010. if ($k2 != $cur_index)
  1011. {
  1012. $items[] = $k2 . ' => \'' . $v2 . '\'';
  1013. $cur_index = $k2;
  1014. }
  1015. else
  1016. $items[] = '\'' . $v2 . '\'';
  1017. $cur_index++;
  1018. }
  1019. // Now create the string!
  1020. $final_saves[$entryKey] = array(
  1021. 'find' => $entryValue['full'],
  1022. 'replace' => '$' . $entryValue['type'] . '[\'' . $entryKey . '\'] = array(' . implode(', ', $items) . ');',
  1023. );
  1024. }
  1025. }
  1026. else
  1027. {
  1028. // Saving?
  1029. if (isset($save_strings[$entryKey]) && $save_strings[$entryKey] != $entryValue['entry'])
  1030. {
  1031. // @todo Fix this properly.
  1032. if ($save_strings[$entryKey] == '')
  1033. $save_strings[$entryKey] = '\'\'';
  1034. // Set the new value.
  1035. $entryValue['entry'] = $save_strings[$entryKey];
  1036. // And we know what to save now!
  1037. $final_saves[$entryKey] = array(
  1038. 'find' => $entryValue['full'],
  1039. 'replace' => '$' . $entryValue['type'] . '[\'' . $entryKey . '\'] = ' . $save_strings[$entryKey] . ';',
  1040. );
  1041. }
  1042. $editing_string = cleanLangString($entryValue['entry'], true);
  1043. $context['file_entries'][] = array(
  1044. 'key' => $entryKey,
  1045. 'value' => $editing_string,
  1046. 'rows' => (int) (strlen($editing_string) / 38) + substr_count($editing_string, "\n") + 1,
  1047. );
  1048. }
  1049. }
  1050. // Any saves to make?
  1051. if (!empty($final_saves))
  1052. {
  1053. checkSession();
  1054. $file_contents = implode('', file($current_file));
  1055. foreach ($final_saves as $save)
  1056. $file_contents = strtr($file_contents, array($save['find'] => $save['replace']));
  1057. // Save the actual changes.
  1058. $fp = fopen($current_file, 'w+');
  1059. fwrite($fp, strtr($file_contents, array("\r" => '')));
  1060. fclose($fp);
  1061. $madeSave = true;
  1062. }
  1063. // Another restore.
  1064. $txt = $old_txt;
  1065. }
  1066. // If we saved, redirect.
  1067. if ($madeSave)
  1068. redirectexit('action=admin;area=languages;sa=editlang;lid=' . $context['lang_id']);
  1069. createToken('admin-mlang');
  1070. }
  1071. /**
  1072. * This function cleans language entries to/from display.
  1073. * @todo This function could be two functions?
  1074. *
  1075. * @param $string
  1076. * @param $to_display
  1077. */
  1078. function cleanLangString($string, $to_display = true)
  1079. {
  1080. global $smcFunc;
  1081. // If going to display we make sure it doesn't have any HTML in it - etc.
  1082. $new_string = '';
  1083. if ($to_display)
  1084. {
  1085. // Are we in a string (0 = no, 1 = single quote, 2 = parsed)
  1086. $in_string = 0;
  1087. $is_escape = false;
  1088. for ($i = 0; $i < strlen($string); $i++)
  1089. {
  1090. // Handle ecapes first.
  1091. if ($string{$i} == '\\')
  1092. {
  1093. // Toggle the escape.
  1094. $is_escape = !$is_escape;
  1095. // If we're now escaped don't add this string.
  1096. if ($is_escape)
  1097. continue;
  1098. }
  1099. // Special case - parsed string with line break etc?
  1100. elseif (($string{$i} == 'n' || $string{$i} == 't') && $in_string == 2 && $is_escape)
  1101. {
  1102. // Put the escape back...
  1103. $new_string .= $string{$i} == 'n' ? "\n" : "\t";
  1104. $is_escape = false;
  1105. continue;
  1106. }
  1107. // Have we got a single quote?
  1108. elseif ($string{$i} == '\'')
  1109. {
  1110. // Already in a parsed string, or escaped in a linear string, means we print it - otherwise something special.
  1111. if ($in_string != 2 && ($in_string != 1 || !$is_escape))
  1112. {
  1113. // Is it the end of a single quote string?
  1114. if ($in_string == 1)
  1115. $in_string = 0;
  1116. // Otherwise it's the start!
  1117. else
  1118. $in_string = 1;
  1119. // Don't actually include this character!
  1120. continue;
  1121. }
  1122. }
  1123. // Otherwise a double quote?
  1124. elseif ($string{$i} == '"')
  1125. {
  1126. // Already in a single quote string, or escaped in a parsed string, means we print it - otherwise something special.
  1127. if ($in_string != 1 && ($in_string != 2 || !$is_escape))
  1128. {
  1129. // Is it the end of a double quote string?
  1130. if ($in_string == 2)
  1131. $in_string = 0;
  1132. // Otherwise it's the start!
  1133. else
  1134. $in_string = 2;
  1135. // Don't actually include this character!
  1136. continue;
  1137. }
  1138. }
  1139. // A join/space outside of a string is simply removed.
  1140. elseif ($in_string == 0 && (empty($string{$i}) || $string{$i} == '.'))
  1141. continue;
  1142. // Start of a variable?
  1143. elseif ($in_string == 0 && $string{$i} == '$')
  1144. {
  1145. // Find the whole of it!
  1146. preg_match('~([\$A-Za-z0-9\'\[\]_-]+)~', substr($string, $i), $matches);
  1147. if (!empty($matches[1]))
  1148. {
  1149. // Come up with some pseudo thing to indicate this is a var.
  1150. /**
  1151. * @todo Do better than this, please!
  1152. */
  1153. $new_string .= '{%' . $matches[1] . '%}';
  1154. // We're not going to reparse this.
  1155. $i += strlen($matches[1]) - 1;
  1156. }
  1157. continue;
  1158. }
  1159. // Right, if we're outside of a string we have DANGER, DANGER!
  1160. elseif ($in_string == 0)
  1161. {
  1162. continue;
  1163. }
  1164. // Actually add the character to the string!
  1165. $new_string .= $string{$i};
  1166. // If anything was escaped it ain't any longer!
  1167. $is_escape = false;
  1168. }
  1169. // Unhtml then rehtml the whole thing!
  1170. $new_string = $smcFunc['htmlspecialchars'](un_htmlspecialchars($new_string));
  1171. }
  1172. else
  1173. {
  1174. // Keep track of what we're doing...
  1175. $in_string = 0;
  1176. // This is for deciding whether to HTML a quote.
  1177. $in_html = false;
  1178. for ($i = 0; $i < strlen($string); $i++)
  1179. {
  1180. // We don't do parsed strings apart from for breaks.
  1181. if ($in_string == 2)
  1182. {
  1183. $in_string = 0;
  1184. $new_string .= '"';
  1185. }
  1186. // Not in a string yet?
  1187. if ($in_string != 1)
  1188. {
  1189. $in_string = 1;
  1190. $new_string .= ($new_string ? ' . ' : '') . '\'';
  1191. }
  1192. // Is this a variable?
  1193. if ($string{$i} == '{' && $string{$i + 1} == '%' && $string{$i + 2} == '$')
  1194. {
  1195. // Grab the variable.
  1196. preg_match('~\{%([\$A-Za-z0-9\'\[\]_-]+)%\}~', substr($string, $i), $matches);
  1197. if (!empty($matches[1]))
  1198. {
  1199. if ($in_string == 1)
  1200. $new_string .= '\' . ';
  1201. elseif ($new_string)
  1202. $new_string .= ' . ';
  1203. $new_string .= $matches[1];
  1204. $i += strlen($matches[1]) + 3;
  1205. $in_string = 0;
  1206. }
  1207. continue;
  1208. }
  1209. // Is this a lt sign?
  1210. elseif ($string{$i} == '<')
  1211. {
  1212. // Probably HTML?
  1213. if ($string{$i + 1} != ' ')
  1214. $in_html = true;
  1215. // Assume we need an entity...
  1216. else
  1217. {
  1218. $new_string .= '&lt;';
  1219. continue;
  1220. }
  1221. }
  1222. // What about gt?
  1223. elseif ($string{$i} == '>')
  1224. {
  1225. // Will it be HTML?
  1226. if ($in_html)
  1227. $in_html = false;
  1228. // Otherwise we need an entity...
  1229. else
  1230. {
  1231. $new_string .= '&gt;';
  1232. continue;
  1233. }
  1234. }
  1235. // Is it a slash? If so escape it...
  1236. if ($string{$i} == '\\')
  1237. $new_string .= '\\';
  1238. // The infamous double quote?
  1239. elseif ($string{$i} == '"')
  1240. {
  1241. // If we're in HTML we leave it as a quote - otherwise we entity it.
  1242. if (!$in_html)
  1243. {
  1244. $new_string .= '&quot;';
  1245. continue;
  1246. }
  1247. }
  1248. // A single quote?
  1249. elseif ($string{$i} == '\'')
  1250. {
  1251. // Must be in a string so escape it.
  1252. $new_string .= '\\';
  1253. }
  1254. // Finally add the character to the string!
  1255. $new_string .= $string{$i};
  1256. }
  1257. // If we ended as a string then close it off.
  1258. if ($in_string == 1)
  1259. $new_string .= '\'';
  1260. elseif ($in_string == 2)
  1261. $new_string .= '"';
  1262. }
  1263. return $new_string;
  1264. }
  1265. ?>