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. $config_vars = array();
  40. call_integration_hook('integrate_manage_languages', array(&$config_vars));
  41. // By default we're managing languages.
  42. $_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'edit';
  43. $context['sub_action'] = $_REQUEST['sa'];
  44. // Load up all the tabs...
  45. $context[$context['admin_menu_name']]['tab_data'] = array(
  46. 'title' => $txt['language_configuration'],
  47. 'description' => $txt['language_description'],
  48. );
  49. // Call the right function for this sub-acton.
  50. $subActions[$_REQUEST['sa']]();
  51. }
  52. /**
  53. * Interface for adding a new language
  54. *
  55. * @uses ManageLanguages template, add_language sub-template.
  56. */
  57. function AddLanguage()
  58. {
  59. global $context, $sourcedir, $forum_version, $boarddir, $txt, $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'] = htmlspecialchars(trim($_POST['smf_add']));
  66. // We're going to use this URL.
  67. $url = 'http://download.simplemachines.org/fetch_language.php?version=' . urlencode(strtr($forum_version, array('SMF ' => '')));
  68. // Load the class file and stick it into an array.
  69. loadClassFile('Class-Package.php');
  70. $language_list = new xmlArray(fetch_web_data($url), true);
  71. // Check it exists.
  72. if (!$language_list->exists('languages'))
  73. $context['smf_error'] = 'no_response';
  74. else
  75. {
  76. $language_list = $language_list->path('languages[0]');
  77. $lang_files = $language_list->set('language');
  78. $context['smf_languages'] = array();
  79. foreach ($lang_files as $file)
  80. {
  81. // Were we searching?
  82. if (!empty($context['smf_search_term']) && strpos($file->fetch('name'), $smcFunc['strtolower']($context['smf_search_term'])) === false)
  83. continue;
  84. $context['smf_languages'][] = array(
  85. 'id' => $file->fetch('id'),
  86. 'name' => $smcFunc['ucwords']($file->fetch('name')),
  87. 'version' => $file->fetch('version'),
  88. 'utf8' => $file->fetch('utf8'),
  89. 'description' => $file->fetch('description'),
  90. 'link' => $scripturl . '?action=admin;area=languages;sa=downloadlang;did=' . $file->fetch('id') . ';' . $context['session_var'] . '=' . $context['session_id'],
  91. );
  92. }
  93. if (empty($context['smf_languages']))
  94. $context['smf_error'] = 'no_files';
  95. }
  96. }
  97. $context['sub_template'] = 'add_language';
  98. }
  99. /**
  100. * Download a language file from the Simple Machines website.
  101. * Requires a valid download ID ("did") in the URL.
  102. * Also handles installing language files.
  103. * Attempts to chmod things as needed.
  104. * Uses a standard list to display information about all the files and where they'll be put.
  105. *
  106. * @uses ManageLanguages template, download_language sub-template.
  107. * @uses Admin template, show_list sub-template.
  108. */
  109. function DownloadLanguage()
  110. {
  111. global $context, $sourcedir, $forum_version, $boarddir, $txt, $smcFunc, $scripturl, $modSettings;
  112. loadLanguage('ManageSettings');
  113. require_once($sourcedir . '/Subs-Package.php');
  114. // Clearly we need to know what to request.
  115. if (!isset($_GET['did']))
  116. fatal_lang_error('no_access', false);
  117. // Some lovely context.
  118. $context['download_id'] = $_GET['did'];
  119. $context['sub_template'] = 'download_language';
  120. $context['menu_data_' . $context['admin_menu_id']]['current_subsection'] = 'add';
  121. // Can we actually do the installation - and do they want to?
  122. if (!empty($_POST['do_install']) && !empty($_POST['copy_file']))
  123. {
  124. checkSession('get');
  125. validateToken('admin-dlang');
  126. $chmod_files = array();
  127. $install_files = array();
  128. // Check writable status.
  129. foreach ($_POST['copy_file'] as $file)
  130. {
  131. // Check it's not very bad.
  132. if (strpos($file, '..') !== false || (strpos($file, 'Themes') !== 0 && !preg_match('~agreement\.[A-Za-z-_0-9]+\.txt$~', $file)))
  133. fatal_error($txt['languages_download_illegal_paths']);
  134. $chmod_files[] = $boarddir . '/' . $file;
  135. $install_files[] = $file;
  136. }
  137. // Call this in case we have work to do.
  138. $file_status = create_chmod_control($chmod_files);
  139. $files_left = $file_status['files']['notwritable'];
  140. // Something not writable?
  141. if (!empty($files_left))
  142. $context['error_message'] = $txt['languages_download_not_chmod'];
  143. // Otherwise, go go go!
  144. elseif (!empty($install_files))
  145. {
  146. $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);
  147. // Make sure the files aren't stuck in the cache.
  148. package_flush_cache();
  149. $context['install_complete'] = sprintf($txt['languages_download_complete_desc'], $scripturl . '?action=admin;area=languages');
  150. return;
  151. }
  152. }
  153. // Open up the old china.
  154. if (!isset($archive_content))
  155. $archive_content = read_tgz_file('http://download.simplemachines.org/fetch_language.php?version=' . urlencode(strtr($forum_version, array('SMF ' => ''))) . ';fetch=' . urlencode($_GET['did']), null);
  156. if (empty($archive_content))
  157. fatal_error($txt['add_language_error_no_response']);
  158. // Now for each of the files, let's do some *stuff*
  159. $context['files'] = array(
  160. 'lang' => array(),
  161. 'other' => array(),
  162. );
  163. $context['make_writable'] = array();
  164. foreach ($archive_content as $file)
  165. {
  166. $dirname = dirname($file['filename']);
  167. $filename = basename($file['filename']);
  168. $extension = substr($filename, strrpos($filename, '.') + 1);
  169. // Don't do anything with files we don't understand.
  170. if (!in_array($extension, array('php', 'jpg', 'gif', 'jpeg', 'png', 'txt')))
  171. continue;
  172. // Basic data.
  173. $context_data = array(
  174. 'name' => $filename,
  175. 'destination' => $boarddir . '/' . $file['filename'],
  176. 'generaldest' => $file['filename'],
  177. 'size' => $file['size'],
  178. // Does chmod status allow the copy?
  179. 'writable' => false,
  180. // Should we suggest they copy this file?
  181. 'default_copy' => true,
  182. // Does the file already exist, if so is it same or different?
  183. 'exists' => false,
  184. );
  185. // Does the file exist, is it different and can we overwrite?
  186. if (file_exists($boarddir . '/' . $file['filename']))
  187. {
  188. if (is_writable($boarddir . '/' . $file['filename']))
  189. $context_data['writable'] = true;
  190. // Finally, do we actually think the content has changed?
  191. if ($file['size'] == filesize($boarddir . '/' . $file['filename']) && $file['md5'] == md5_file($boarddir . '/' . $file['filename']))
  192. {
  193. $context_data['exists'] = 'same';
  194. $context_data['default_copy'] = false;
  195. }
  196. // Attempt to discover newline character differences.
  197. elseif ($file['md5'] == md5(preg_replace("~[\r]?\n~", "\r\n", file_get_contents($boarddir . '/' . $file['filename']))))
  198. {
  199. $context_data['exists'] = 'same';
  200. $context_data['default_copy'] = false;
  201. }
  202. else
  203. $context_data['exists'] = 'different';
  204. }
  205. // No overwrite?
  206. else
  207. {
  208. // Can we at least stick it in the directory...
  209. if (is_writable($boarddir . '/' . $dirname))
  210. $context_data['writable'] = true;
  211. }
  212. // 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...
  213. if ($extension == 'php' && preg_match('~\w+\.\w+(?:-utf8)?\.php~', $filename))
  214. {
  215. $context_data += array(
  216. 'version' => '??',
  217. 'cur_version' => false,
  218. 'version_compare' => 'newer',
  219. );
  220. list ($name, $language) = explode('.', $filename);
  221. // Let's get the new version, I like versions, they tell me that I'm up to date.
  222. if (preg_match('~\s*Version:\s+(.+?);\s*' . preg_quote($name, '~') . '~i', $file['preview'], $match) == 1)
  223. $context_data['version'] = $match[1];
  224. // Now does the old file exist - if so what is it's version?
  225. if (file_exists($boarddir . '/' . $file['filename']))
  226. {
  227. // OK - what is the current version?
  228. $fp = fopen($boarddir . '/' . $file['filename'], 'rb');
  229. $header = fread($fp, 768);
  230. fclose($fp);
  231. // Find the version.
  232. if (preg_match('~(?://|/\*)\s*Version:\s+(.+?);\s*' . preg_quote($name, '~') . '(?:[\s]{2}|\*/)~i', $header, $match) == 1)
  233. {
  234. $context_data['cur_version'] = $match[1];
  235. // How does this compare?
  236. if ($context_data['cur_version'] == $context_data['version'])
  237. $context_data['version_compare'] = 'same';
  238. elseif ($context_data['cur_version'] > $context_data['version'])
  239. $context_data['version_compare'] = 'older';
  240. // Don't recommend copying if the version is the same.
  241. if ($context_data['version_compare'] != 'newer')
  242. $context_data['default_copy'] = false;
  243. }
  244. }
  245. // Add the context data to the main set.
  246. $context['files']['lang'][] = $context_data;
  247. }
  248. else
  249. {
  250. // If we think it's a theme thing, work out what the theme is.
  251. if (strpos($dirname, 'Themes') === 0 && preg_match('~Themes[\\/]([^\\/]+)[\\/]~', $dirname, $match))
  252. $theme_name = $match[1];
  253. else
  254. $theme_name = 'misc';
  255. // Assume it's an image, could be an acceptance note etc but rare.
  256. $context['files']['images'][$theme_name][] = $context_data;
  257. }
  258. // Collect together all non-writable areas.
  259. if (!$context_data['writable'])
  260. $context['make_writable'][] = $context_data['destination'];
  261. }
  262. // So, I'm a perfectionist - let's get the theme names.
  263. $theme_indexes = array();
  264. foreach ($context['files']['images'] as $k => $dummy)
  265. $indexes[] = $k;
  266. $context['theme_names'] = array();
  267. if (!empty($indexes))
  268. {
  269. $value_data = array(
  270. 'query' => array(),
  271. 'params' => array(),
  272. );
  273. foreach ($indexes as $k => $index)
  274. {
  275. $value_data['query'][] = 'value LIKE {string:value_' . $k . '}';
  276. $value_data['params']['value_' . $k] = '%' . $index;
  277. }
  278. $request = $smcFunc['db_query']('', '
  279. SELECT id_theme, value
  280. FROM {db_prefix}themes
  281. WHERE id_member = {int:no_member}
  282. AND variable = {string:theme_dir}
  283. AND (' . implode(' OR ', $value_data['query']) . ')',
  284. array_merge($value_data['params'], array(
  285. 'no_member' => 0,
  286. 'theme_dir' => 'theme_dir',
  287. 'index_compare_explode' => 'value LIKE \'%' . implode('\' OR value LIKE \'%', $indexes) . '\'',
  288. ))
  289. );
  290. $themes = array();
  291. while ($row = $smcFunc['db_fetch_assoc']($request))
  292. {
  293. // Find the right one.
  294. foreach ($indexes as $index)
  295. if (strpos($row['value'], $index) !== false)
  296. $themes[$row['id_theme']] = $index;
  297. }
  298. $smcFunc['db_free_result']($request);
  299. if (!empty($themes))
  300. {
  301. // Now we have the id_theme we can get the pretty description.
  302. $request = $smcFunc['db_query']('', '
  303. SELECT id_theme, value
  304. FROM {db_prefix}themes
  305. WHERE id_member = {int:no_member}
  306. AND variable = {string:name}
  307. AND id_theme IN ({array_int:theme_list})',
  308. array(
  309. 'theme_list' => array_keys($themes),
  310. 'no_member' => 0,
  311. 'name' => 'name',
  312. )
  313. );
  314. while ($row = $smcFunc['db_fetch_assoc']($request))
  315. {
  316. // Now we have it...
  317. $context['theme_names'][$themes[$row['id_theme']]] = $row['value'];
  318. }
  319. $smcFunc['db_free_result']($request);
  320. }
  321. }
  322. // Before we go to far can we make anything writable, eh, eh?
  323. if (!empty($context['make_writable']))
  324. {
  325. // What is left to be made writable?
  326. $file_status = create_chmod_control($context['make_writable']);
  327. $context['still_not_writable'] = $file_status['files']['notwritable'];
  328. // Mark those which are now writable as such.
  329. foreach ($context['files'] as $type => $data)
  330. {
  331. if ($type == 'lang')
  332. {
  333. foreach ($data as $k => $file)
  334. if (!$file['writable'] && !in_array($file['destination'], $context['still_not_writable']))
  335. $context['files'][$type][$k]['writable'] = true;
  336. }
  337. else
  338. {
  339. foreach ($data as $theme => $files)
  340. foreach ($files as $k => $file)
  341. if (!$file['writable'] && !in_array($file['destination'], $context['still_not_writable']))
  342. $context['files'][$type][$theme][$k]['writable'] = true;
  343. }
  344. }
  345. // Are we going to need more language stuff?
  346. if (!empty($context['still_not_writable']))
  347. loadLanguage('Packages');
  348. }
  349. // This is the list for the main files.
  350. $listOptions = array(
  351. 'id' => 'lang_main_files_list',
  352. 'title' => $txt['languages_download_main_files'],
  353. 'get_items' => array(
  354. 'function' => create_function('', '
  355. global $context;
  356. return $context[\'files\'][\'lang\'];
  357. '),
  358. ),
  359. 'columns' => array(
  360. 'name' => array(
  361. 'header' => array(
  362. 'value' => $txt['languages_download_filename'],
  363. ),
  364. 'data' => array(
  365. 'function' => create_function('$rowData', '
  366. global $context, $txt;
  367. 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\'] : \'\');
  368. '),
  369. ),
  370. ),
  371. 'writable' => array(
  372. 'header' => array(
  373. 'value' => $txt['languages_download_writable'],
  374. ),
  375. 'data' => array(
  376. 'function' => create_function('$rowData', '
  377. global $txt;
  378. return \'<span style="color: \' . ($rowData[\'writable\'] ? \'green\' : \'red\') . \';">\' . ($rowData[\'writable\'] ? $txt[\'yes\'] : $txt[\'no\']) . \'</span>\';
  379. '),
  380. 'style' => 'text-align: center',
  381. ),
  382. ),
  383. 'version' => array(
  384. 'header' => array(
  385. 'value' => $txt['languages_download_version'],
  386. ),
  387. 'data' => array(
  388. 'function' => create_function('$rowData', '
  389. global $txt;
  390. return \'<span style="color: \' . ($rowData[\'version_compare\'] == \'older\' ? \'red\' : ($rowData[\'version_compare\'] == \'same\' ? \'orange\' : \'green\')) . \';">\' . $rowData[\'version\'] . \'</span>\';
  391. '),
  392. ),
  393. ),
  394. 'exists' => array(
  395. 'header' => array(
  396. 'value' => $txt['languages_download_exists'],
  397. ),
  398. 'data' => array(
  399. 'function' => create_function('$rowData', '
  400. global $txt;
  401. return $rowData[\'exists\'] ? ($rowData[\'exists\'] == \'same\' ? $txt[\'languages_download_exists_same\'] : $txt[\'languages_download_exists_different\']) : $txt[\'no\'];
  402. '),
  403. ),
  404. ),
  405. 'copy' => array(
  406. 'header' => array(
  407. 'value' => $txt['languages_download_copy'],
  408. ),
  409. 'data' => array(
  410. 'function' => create_function('$rowData', '
  411. return \'<input type="checkbox" name="copy_file[]" value="\' . $rowData[\'generaldest\'] . \'" \' . ($rowData[\'default_copy\'] ? \'checked="checked"\' : \'\') . \' class="input_check" />\';
  412. '),
  413. 'style' => 'text-align: center; width: 4%;',
  414. ),
  415. ),
  416. ),
  417. );
  418. // Kill the cache, as it is now invalid..
  419. if (!empty($modSettings['cache_enable']))
  420. {
  421. cache_put_data('known_languages', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  422. cache_put_data('known_languages_all', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  423. }
  424. require_once($sourcedir . '/Subs-List.php');
  425. createList($listOptions);
  426. $context['default_list'] = 'lang_main_files_list';
  427. createToken('admin-dlang');
  428. }
  429. /**
  430. * This lists all the current languages and allows editing of them.
  431. */
  432. function ModifyLanguages()
  433. {
  434. global $txt, $context, $scripturl;
  435. global $user_info, $smcFunc, $sourcedir, $language, $boarddir, $forum_version;
  436. // Setting a new default?
  437. if (!empty($_POST['set_default']) && !empty($_POST['def_language']))
  438. {
  439. checkSession();
  440. validateToken('admin-lang');
  441. if ($_POST['def_language'] != $language)
  442. {
  443. require_once($sourcedir . '/Subs-Admin.php');
  444. updateSettingsFile(array('language' => '\'' . $_POST['def_language'] . '\''));
  445. $language = $_POST['def_language'];
  446. }
  447. }
  448. // Create another one time token here.
  449. createToken('admin-lang');
  450. $listOptions = array(
  451. 'id' => 'language_list',
  452. 'items_per_page' => 20,
  453. 'base_href' => $scripturl . '?action=admin;area=languages',
  454. 'title' => $txt['edit_languages'],
  455. 'get_items' => array(
  456. 'function' => 'list_getLanguages',
  457. ),
  458. 'get_count' => array(
  459. 'function' => 'list_getNumLanguages',
  460. ),
  461. 'columns' => array(
  462. 'default' => array(
  463. 'header' => array(
  464. 'value' => $txt['languages_default'],
  465. ),
  466. 'data' => array(
  467. 'function' => create_function('$rowData', '
  468. return \'<input type="radio" name="def_language" value="\' . $rowData[\'id\'] . \'" \' . ($rowData[\'default\'] ? \'checked="checked"\' : \'\') . \' onclick="highlightSelected(\\\'list_language_list_\' . $rowData[\'id\'] . \'\\\');" class="input_radio" />\';
  469. '),
  470. 'style' => 'text-align: center; width: 8%;',
  471. ),
  472. ),
  473. 'name' => array(
  474. 'header' => array(
  475. 'value' => $txt['languages_lang_name'],
  476. ),
  477. 'data' => array(
  478. 'function' => create_function('$rowData', '
  479. global $scripturl, $context;
  480. return sprintf(\'<a href="%1$s?action=admin;area=languages;sa=editlang;lid=%2$s">%3$s</a>\', $scripturl, $rowData[\'id\'], $rowData[\'name\']);
  481. '),
  482. ),
  483. ),
  484. 'character_set' => array(
  485. 'header' => array(
  486. 'value' => $txt['languages_character_set'],
  487. ),
  488. 'data' => array(
  489. 'db_htmlsafe' => 'char_set',
  490. ),
  491. ),
  492. 'count' => array(
  493. 'header' => array(
  494. 'value' => $txt['languages_users'],
  495. ),
  496. 'data' => array(
  497. 'db_htmlsafe' => 'count',
  498. 'style' => 'text-align: center',
  499. ),
  500. ),
  501. 'locale' => array(
  502. 'header' => array(
  503. 'value' => $txt['languages_locale'],
  504. ),
  505. 'data' => array(
  506. 'db_htmlsafe' => 'locale',
  507. ),
  508. ),
  509. ),
  510. 'form' => array(
  511. 'href' => $scripturl . '?action=admin;area=languages',
  512. 'token' => 'admin-lang',
  513. ),
  514. 'additional_rows' => array(
  515. array(
  516. 'position' => 'below_table_data',
  517. '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" />',
  518. 'style' => 'text-align: right;',
  519. ),
  520. ),
  521. // For highlighting the default.
  522. 'javascript' => '
  523. var prevClass = "";
  524. var prevDiv = "";
  525. function highlightSelected(box)
  526. {
  527. if (prevClass != "")
  528. prevDiv.className = prevClass;
  529. prevDiv = document.getElementById(box);
  530. prevClass = prevDiv.className;
  531. prevDiv.className = "highlight2";
  532. }
  533. highlightSelected("list_language_list_' . ($language == '' ? 'english' : $language). '");
  534. ',
  535. );
  536. // Display a warning if we cannot edit the default setting.
  537. if (!is_writable($boarddir . '/Settings.php'))
  538. $listOptions['additional_rows'][] = array(
  539. 'position' => 'after_title',
  540. 'value' => $txt['language_settings_writable'],
  541. 'class' => 'smalltext alert',
  542. );
  543. require_once($sourcedir . '/Subs-List.php');
  544. createList($listOptions);
  545. $context['sub_template'] = 'show_list';
  546. $context['default_list'] = 'language_list';
  547. }
  548. /**
  549. * How many languages?
  550. * Callback for the list in ManageLanguageSettings().
  551. */
  552. function list_getNumLanguages()
  553. {
  554. return count(getLanguages(true, false));
  555. }
  556. /**
  557. * Fetch the actual language information.
  558. * Callback for $listOptions['get_items']['function'] in ManageLanguageSettings.
  559. * Determines which languages are available by looking for the "index.{language}.php" file.
  560. * Also figures out how many users are using a particular language.
  561. */
  562. function list_getLanguages()
  563. {
  564. global $settings, $smcFunc, $language, $context, $txt;
  565. $languages = array();
  566. // Keep our old entries.
  567. $old_txt = $txt;
  568. $backup_actual_theme_dir = $settings['actual_theme_dir'];
  569. $backup_base_theme_dir = !empty($settings['base_theme_dir']) ? $settings['base_theme_dir'] : '';
  570. // Override these for now.
  571. $settings['actual_theme_dir'] = $settings['base_theme_dir'] = $settings['default_theme_dir'];
  572. getLanguages(true, false);
  573. // Put them back.
  574. $settings['actual_theme_dir'] = $backup_actual_theme_dir;
  575. if (!empty($backup_base_theme_dir))
  576. $settings['base_theme_dir'] = $backup_base_theme_dir;
  577. else
  578. unset($settings['base_theme_dir']);
  579. // Get the language files and data...
  580. foreach ($context['languages'] as $lang)
  581. {
  582. // Load the file to get the character set.
  583. require($settings['default_theme_dir'] . '/languages/index.' . $lang['filename'] . '.php');
  584. $languages[$lang['filename']] = array(
  585. 'id' => $lang['filename'],
  586. 'count' => 0,
  587. 'char_set' => $txt['lang_character_set'],
  588. 'default' => $language == $lang['filename'] || ($language == '' && $lang['filename'] == 'english'),
  589. 'locale' => $txt['lang_locale'],
  590. 'name' => $smcFunc['ucwords'](strtr($lang['filename'], array('_' => ' ', '-utf8' => ''))),
  591. );
  592. }
  593. // Work out how many people are using each language.
  594. $request = $smcFunc['db_query']('', '
  595. SELECT lngfile, COUNT(*) AS num_users
  596. FROM {db_prefix}members
  597. GROUP BY lngfile',
  598. array(
  599. )
  600. );
  601. while ($row = $smcFunc['db_fetch_assoc']($request))
  602. {
  603. // Default?
  604. if (empty($row['lngfile']) || !isset($languages[$row['lngfile']]))
  605. $row['lngfile'] = $language;
  606. if (!isset($languages[$row['lngfile']]) && isset($languages['english']))
  607. $languages['english']['count'] += $row['num_users'];
  608. elseif (isset($languages[$row['lngfile']]))
  609. $languages[$row['lngfile']]['count'] += $row['num_users'];
  610. }
  611. $smcFunc['db_free_result']($request);
  612. // Restore the current users language.
  613. $txt = $old_txt;
  614. // Return how many we have.
  615. return $languages;
  616. }
  617. /**
  618. * Edit language related settings.
  619. *
  620. * @param bool $return_config = false
  621. */
  622. function ModifyLanguageSettings($return_config = false)
  623. {
  624. global $scripturl, $context, $txt, $boarddir, $settings, $smcFunc, $sourcedir;
  625. // We'll want to save them someday.
  626. require_once $sourcedir . '/ManageServer.php';
  627. // Warn the user if the backup of Settings.php failed.
  628. $settings_not_writable = !is_writable($boarddir . '/Settings.php');
  629. $settings_backup_fail = !@is_writable($boarddir . '/Settings_bak.php') || !@copy($boarddir . '/Settings.php', $boarddir . '/Settings_bak.php');
  630. /* If you're writing a mod, it's a bad idea to add things here....
  631. For each option:
  632. variable name, description, type (constant), size/possible values, helptext.
  633. OR an empty string for a horizontal rule.
  634. OR a string for a titled section. */
  635. $config_vars = array(
  636. 'language' => array('language', $txt['default_language'], 'file', 'select', array(), null, 'disabled' => $settings_not_writable),
  637. array('userLanguage', $txt['userLanguage'], 'db', 'check', null, 'userLanguage'),
  638. );
  639. call_integration_hook('integrate_language_settings', array(&$config_vars));
  640. if ($return_config)
  641. return $config_vars;
  642. // Get our languages. No cache and use utf8.
  643. getLanguages(false, false);
  644. foreach ($context['languages'] as $lang)
  645. $config_vars['language'][4][$lang['filename']] = array($lang['filename'], strtr($lang['name'], array('-utf8' => ' (UTF-8)')));
  646. // Saving settings?
  647. if (isset($_REQUEST['save']))
  648. {
  649. checkSession();
  650. call_integration_hook('integrate_save_language_settings');
  651. saveSettings($config_vars);
  652. redirectexit('action=admin;area=languages;sa=settings');
  653. }
  654. // Setup the template stuff.
  655. $context['post_url'] = $scripturl . '?action=admin;area=languages;sa=settings;save';
  656. $context['settings_title'] = $txt['language_settings'];
  657. $context['save_disabled'] = $settings_not_writable;
  658. if ($settings_not_writable)
  659. $context['settings_message'] = '<div class="centertext"><strong>' . $txt['settings_not_writable'] . '</strong></div><br />';
  660. elseif ($settings_backup_fail)
  661. $context['settings_message'] = '<div class="centertext"><strong>' . $txt['admin_backup_fail'] . '</strong></div><br />';
  662. // Fill the config array.
  663. prepareServerSettingsContext($config_vars);
  664. }
  665. /**
  666. * Edit a particular set of language entries.
  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. ?>