ManageLanguages.php 44 KB

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