2
0

ManageLanguages.php 44 KB

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