ManageLanguages.php 42 KB

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