ManageLanguages.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380
  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. function ModifyLanguage()
  668. {
  669. global $settings, $context, $smcFunc, $txt, $modSettings, $boarddir, $sourcedir, $language;
  670. loadLanguage('ManageSettings');
  671. // Select the languages tab.
  672. $context['menu_data_' . $context['admin_menu_id']]['current_subsection'] = 'edit';
  673. $context['page_title'] = $txt['edit_languages'];
  674. $context['sub_template'] = 'modify_language_entries';
  675. $context['lang_id'] = $_GET['lid'];
  676. list($theme_id, $file_id) = empty($_REQUEST['tfid']) || strpos($_REQUEST['tfid'], '+') === false ? array(1, '') : explode('+', $_REQUEST['tfid']);
  677. // Clean the ID - just in case.
  678. preg_match('~([A-Za-z0-9_-]+)~', $context['lang_id'], $matches);
  679. $context['lang_id'] = $matches[1];
  680. // Get all the theme data.
  681. $request = $smcFunc['db_query']('', '
  682. SELECT id_theme, variable, value
  683. FROM {db_prefix}themes
  684. WHERE id_theme != {int:default_theme}
  685. AND id_member = {int:no_member}
  686. AND variable IN ({string:name}, {string:theme_dir})',
  687. array(
  688. 'default_theme' => 1,
  689. 'no_member' => 0,
  690. 'name' => 'name',
  691. 'theme_dir' => 'theme_dir',
  692. )
  693. );
  694. $themes = array(
  695. 1 => array(
  696. 'name' => $txt['dvc_default'],
  697. 'theme_dir' => $settings['default_theme_dir'],
  698. ),
  699. );
  700. while ($row = $smcFunc['db_fetch_assoc']($request))
  701. $themes[$row['id_theme']][$row['variable']] = $row['value'];
  702. $smcFunc['db_free_result']($request);
  703. // This will be where we look
  704. $lang_dirs = array();
  705. // Check we have themes with a path and a name - just in case - and add the path.
  706. foreach ($themes as $id => $data)
  707. {
  708. if (count($data) != 2)
  709. unset($themes[$id]);
  710. elseif (is_dir($data['theme_dir'] . '/languages'))
  711. $lang_dirs[$id] = $data['theme_dir'] . '/languages';
  712. // How about image directories?
  713. if (is_dir($data['theme_dir'] . '/images/' . $context['lang_id']))
  714. $images_dirs[$id] = $data['theme_dir'] . '/images/' . $context['lang_id'];
  715. }
  716. $current_file = $file_id ? $lang_dirs[$theme_id] . '/' . $file_id . '.' . $context['lang_id'] . '.php' : '';
  717. // Now for every theme get all the files and stick them in context!
  718. $context['possible_files'] = array();
  719. foreach ($lang_dirs as $theme => $theme_dir)
  720. {
  721. // Open it up.
  722. $dir = dir($theme_dir);
  723. while ($entry = $dir->read())
  724. {
  725. // We're only after the files for this language.
  726. if (preg_match('~^([A-Za-z]+)\.' . $context['lang_id'] . '\.php$~', $entry, $matches) == 0)
  727. continue;
  728. // @todo Temp!
  729. if ($matches[1] == 'EmailTemplates')
  730. continue;
  731. if (!isset($context['possible_files'][$theme]))
  732. $context['possible_files'][$theme] = array(
  733. 'id' => $theme,
  734. 'name' => $themes[$theme]['name'],
  735. 'files' => array(),
  736. );
  737. $context['possible_files'][$theme]['files'][] = array(
  738. 'id' => $matches[1],
  739. 'name' => isset($txt['lang_file_desc_' . $matches[1]]) ? $txt['lang_file_desc_' . $matches[1]] : $matches[1],
  740. 'selected' => $theme_id == $theme && $file_id == $matches[1],
  741. );
  742. }
  743. $dir->close();
  744. }
  745. // We no longer wish to speak this language.
  746. if (!empty($_POST['delete_main']) && $context['lang_id'] != 'english')
  747. {
  748. checkSession();
  749. validateToken('admin-mlang');
  750. // @todo Todo: FTP Controls?
  751. require_once($sourcedir . '/Subs-Package.php');
  752. // First, Make a backup?
  753. if (!empty($modSettings['package_make_backups']) && (!isset($_SESSION['last_backup_for']) || $_SESSION['last_backup_for'] != $context['lang_id'] . '$$$'))
  754. {
  755. $_SESSION['last_backup_for'] = $context['lang_id'] . '$$$';
  756. package_create_backup('backup_lang_' . $context['lang_id']);
  757. }
  758. // Second, loop through the array to remove the files.
  759. foreach ($lang_dirs as $curPath)
  760. {
  761. foreach ($context['possible_files'][1]['files'] as $lang)
  762. if (file_exists($curPath . '/' . $lang['id'] . '.' . $context['lang_id'] . '.php'))
  763. unlink($curPath . '/' . $lang['id'] . '.' . $context['lang_id'] . '.php');
  764. // Check for the email template.
  765. if (file_exists($curPath . '/EmailTemplates.' . $context['lang_id'] . '.php'))
  766. unlink($curPath . '/EmailTemplates.' . $context['lang_id'] . '.php');
  767. }
  768. // Third, the agreement file.
  769. if (file_exists($boarddir . '/agreement.' . $context['lang_id'] . '.txt'))
  770. unlink($boarddir . '/agreement.' . $context['lang_id'] . '.txt');
  771. // Fourth, a related images folder?
  772. foreach ($images_dirs as $curPath)
  773. if (is_dir($curPath))
  774. deltree($curPath);
  775. // Members can no longer use this language.
  776. $smcFunc['db_query']('', '
  777. UPDATE {db_prefix}members
  778. SET lngfile = {string:empty_string}
  779. WHERE lngfile = {string:current_language}',
  780. array(
  781. 'empty_string' => '',
  782. 'current_language' => $context['lang_id'],
  783. )
  784. );
  785. // Fifth, update getLanguages() cache.
  786. if (!empty($modSettings['cache_enable']))
  787. {
  788. cache_put_data('known_languages', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  789. cache_put_data('known_languages_all', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  790. }
  791. // Sixth, if we deleted the default language, set us back to english?
  792. if ($context['lang_id'] == $language)
  793. {
  794. require_once($sourcedir . '/Subs-Admin.php');
  795. $language = 'english';
  796. updateSettingsFile(array('language' => '\'' . $language . '\''));
  797. }
  798. // Seventh, get out of here.
  799. redirectexit('action=admin;area=languages;sa=edit;' . $context['session_var'] . '=' . $context['session_id']);
  800. }
  801. // Saving primary settings?
  802. $madeSave = false;
  803. if (!empty($_POST['save_main']) && !$current_file)
  804. {
  805. checkSession();
  806. validateToken('admin-mlang');
  807. // Read in the current file.
  808. $current_data = implode('', file($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php'));
  809. // These are the replacements. old => new
  810. $replace_array = array(
  811. '~\$txt\[\'lang_character_set\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_character_set\'] = \'' . addslashes($_POST['character_set']) . '\';',
  812. '~\$txt\[\'lang_locale\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_locale\'] = \'' . addslashes($_POST['locale']) . '\';',
  813. '~\$txt\[\'lang_dictionary\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_dictionary\'] = \'' . addslashes($_POST['dictionary']) . '\';',
  814. '~\$txt\[\'lang_spelling\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_spelling\'] = \'' . addslashes($_POST['spelling']) . '\';',
  815. '~\$txt\[\'lang_rtl\'\]\s=\s[A-Za-z0-9]+;~' => '$txt[\'lang_rtl\'] = ' . (!empty($_POST['rtl']) ? 'true' : 'false') . ';',
  816. );
  817. $current_data = preg_replace(array_keys($replace_array), array_values($replace_array), $current_data);
  818. $fp = fopen($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php', 'w+');
  819. fwrite($fp, $current_data);
  820. fclose($fp);
  821. $madeSave = true;
  822. }
  823. // Quickly load index language entries.
  824. $old_txt = $txt;
  825. require($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php');
  826. $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');
  827. // Setup the primary settings context.
  828. $context['primary_settings'] = array(
  829. 'name' => $smcFunc['ucwords'](strtr($context['lang_id'], array('_' => ' ', '-utf8' => ''))),
  830. 'character_set' => $txt['lang_character_set'],
  831. 'locale' => $txt['lang_locale'],
  832. 'dictionary' => $txt['lang_dictionary'],
  833. 'spelling' => $txt['lang_spelling'],
  834. 'rtl' => $txt['lang_rtl'],
  835. );
  836. // Restore normal service.
  837. $txt = $old_txt;
  838. // Are we saving?
  839. $save_strings = array();
  840. if (isset($_POST['save_entries']) && !empty($_POST['entry']))
  841. {
  842. checkSession();
  843. validateToken('admin-mlang');
  844. // Clean each entry!
  845. foreach ($_POST['entry'] as $k => $v)
  846. {
  847. // Only try to save if it's changed!
  848. if ($_POST['entry'][$k] != $_POST['comp'][$k])
  849. $save_strings[$k] = cleanLangString($v, false);
  850. }
  851. }
  852. // If we are editing a file work away at that.
  853. if ($current_file)
  854. {
  855. $context['entries_not_writable_message'] = is_writable($current_file) ? '' : sprintf($txt['lang_entries_not_writable'], $current_file);
  856. $entries = array();
  857. // We can't just require it I'm afraid - otherwise we pass in all kinds of variables!
  858. $multiline_cache = '';
  859. foreach (file($current_file) as $line)
  860. {
  861. // Got a new entry?
  862. if ($line[0] == '$' && !empty($multiline_cache))
  863. {
  864. preg_match('~\$(helptxt|txt)\[\'(.+)\'\]\s=\s(.+);~', strtr($multiline_cache, array("\n" => '', "\t" => '')), $matches);
  865. if (!empty($matches[3]))
  866. {
  867. $entries[$matches[2]] = array(
  868. 'type' => $matches[1],
  869. 'full' => $matches[0],
  870. 'entry' => $matches[3],
  871. );
  872. $multiline_cache = '';
  873. }
  874. }
  875. $multiline_cache .= $line . "\n";
  876. }
  877. // Last entry to add?
  878. if ($multiline_cache)
  879. {
  880. preg_match('~\$(helptxt|txt)\[\'(.+)\'\]\s=\s(.+);~', strtr($multiline_cache, array("\n" => '', "\t" => '')), $matches);
  881. if (!empty($matches[3]))
  882. $entries[$matches[2]] = array(
  883. 'type' => $matches[1],
  884. 'full' => $matches[0],
  885. 'entry' => $matches[3],
  886. );
  887. }
  888. // These are the entries we can definitely save.
  889. $final_saves = array();
  890. $context['file_entries'] = array();
  891. foreach ($entries as $entryKey => $entryValue)
  892. {
  893. // Ignore some things we set separately.
  894. $ignore_files = array('lang_character_set', 'lang_locale', 'lang_dictionary', 'lang_spelling', 'lang_rtl');
  895. if (in_array($entryKey, $ignore_files))
  896. continue;
  897. // These are arrays that need breaking out.
  898. $arrays = array('days', 'days_short', 'months', 'months_titles', 'months_short');
  899. if (in_array($entryKey, $arrays))
  900. {
  901. // Get off the first bits.
  902. $entryValue['entry'] = substr($entryValue['entry'], strpos($entryValue['entry'], '(') + 1, strrpos($entryValue['entry'], ')') - strpos($entryValue['entry'], '('));
  903. $entryValue['entry'] = explode(',', strtr($entryValue['entry'], array(' ' => '')));
  904. // Now create an entry for each item.
  905. $cur_index = 0;
  906. $save_cache = array(
  907. 'enabled' => false,
  908. 'entries' => array(),
  909. );
  910. foreach ($entryValue['entry'] as $id => $subValue)
  911. {
  912. // Is this a new index?
  913. if (preg_match('~^(\d+)~', $subValue, $matches))
  914. {
  915. $cur_index = $matches[1];
  916. $subValue = substr($subValue, strpos($subValue, '\''));
  917. }
  918. // Clean up some bits.
  919. $subValue = strtr($subValue, array('"' => '', '\'' => '', ')' => ''));
  920. // Can we save?
  921. if (isset($save_strings[$entryKey . '-+- ' . $cur_index]))
  922. {
  923. $save_cache['entries'][$cur_index] = strtr($save_strings[$entryKey . '-+- ' . $cur_index], array('\'' => ''));
  924. $save_cache['enabled'] = true;
  925. }
  926. else
  927. $save_cache['entries'][$cur_index] = $subValue;
  928. $context['file_entries'][] = array(
  929. 'key' => $entryKey . '-+- ' . $cur_index,
  930. 'value' => $subValue,
  931. 'rows' => 1,
  932. );
  933. $cur_index++;
  934. }
  935. // Do we need to save?
  936. if ($save_cache['enabled'])
  937. {
  938. // Format the string, checking the indexes first.
  939. $items = array();
  940. $cur_index = 0;
  941. foreach ($save_cache['entries'] as $k2 => $v2)
  942. {
  943. // Manually show the custom index.
  944. if ($k2 != $cur_index)
  945. {
  946. $items[] = $k2 . ' => \'' . $v2 . '\'';
  947. $cur_index = $k2;
  948. }
  949. else
  950. $items[] = '\'' . $v2 . '\'';
  951. $cur_index++;
  952. }
  953. // Now create the string!
  954. $final_saves[$entryKey] = array(
  955. 'find' => $entryValue['full'],
  956. 'replace' => '$' . $entryValue['type'] . '[\'' . $entryKey . '\'] = array(' . implode(', ', $items) . ');',
  957. );
  958. }
  959. }
  960. else
  961. {
  962. // Saving?
  963. if (isset($save_strings[$entryKey]) && $save_strings[$entryKey] != $entryValue['entry'])
  964. {
  965. // @todo Fix this properly.
  966. if ($save_strings[$entryKey] == '')
  967. $save_strings[$entryKey] = '\'\'';
  968. // Set the new value.
  969. $entryValue['entry'] = $save_strings[$entryKey];
  970. // And we know what to save now!
  971. $final_saves[$entryKey] = array(
  972. 'find' => $entryValue['full'],
  973. 'replace' => '$' . $entryValue['type'] . '[\'' . $entryKey . '\'] = ' . $save_strings[$entryKey] . ';',
  974. );
  975. }
  976. $editing_string = cleanLangString($entryValue['entry'], true);
  977. $context['file_entries'][] = array(
  978. 'key' => $entryKey,
  979. 'value' => $editing_string,
  980. 'rows' => (int) (strlen($editing_string) / 38) + substr_count($editing_string, "\n") + 1,
  981. );
  982. }
  983. }
  984. // Any saves to make?
  985. if (!empty($final_saves))
  986. {
  987. checkSession();
  988. $file_contents = implode('', file($current_file));
  989. foreach ($final_saves as $save)
  990. $file_contents = strtr($file_contents, array($save['find'] => $save['replace']));
  991. // Save the actual changes.
  992. $fp = fopen($current_file, 'w+');
  993. fwrite($fp, $file_contents);
  994. fclose($fp);
  995. $madeSave = true;
  996. }
  997. // Another restore.
  998. $txt = $old_txt;
  999. }
  1000. // If we saved, redirect.
  1001. if ($madeSave)
  1002. redirectexit('action=admin;area=languages;sa=editlang;lid=' . $context['lang_id']);
  1003. createToken('admin-mlang');
  1004. }
  1005. /**
  1006. * This function cleans language entries to/from display.
  1007. * @todo This function could be two functions?
  1008. *
  1009. * @param $string
  1010. * @param $to_display
  1011. */
  1012. function cleanLangString($string, $to_display = true)
  1013. {
  1014. global $smcFunc;
  1015. // If going to display we make sure it doesn't have any HTML in it - etc.
  1016. $new_string = '';
  1017. if ($to_display)
  1018. {
  1019. // Are we in a string (0 = no, 1 = single quote, 2 = parsed)
  1020. $in_string = 0;
  1021. $is_escape = false;
  1022. for ($i = 0; $i < strlen($string); $i++)
  1023. {
  1024. // Handle ecapes first.
  1025. if ($string{$i} == '\\')
  1026. {
  1027. // Toggle the escape.
  1028. $is_escape = !$is_escape;
  1029. // If we're now escaped don't add this string.
  1030. if ($is_escape)
  1031. continue;
  1032. }
  1033. // Special case - parsed string with line break etc?
  1034. elseif (($string{$i} == 'n' || $string{$i} == 't') && $in_string == 2 && $is_escape)
  1035. {
  1036. // Put the escape back...
  1037. $new_string .= $string{$i} == 'n' ? "\n" : "\t";
  1038. $is_escape = false;
  1039. continue;
  1040. }
  1041. // Have we got a single quote?
  1042. elseif ($string{$i} == '\'')
  1043. {
  1044. // Already in a parsed string, or escaped in a linear string, means we print it - otherwise something special.
  1045. if ($in_string != 2 && ($in_string != 1 || !$is_escape))
  1046. {
  1047. // Is it the end of a single quote string?
  1048. if ($in_string == 1)
  1049. $in_string = 0;
  1050. // Otherwise it's the start!
  1051. else
  1052. $in_string = 1;
  1053. // Don't actually include this character!
  1054. continue;
  1055. }
  1056. }
  1057. // Otherwise a double quote?
  1058. elseif ($string{$i} == '"')
  1059. {
  1060. // Already in a single quote string, or escaped in a parsed string, means we print it - otherwise something special.
  1061. if ($in_string != 1 && ($in_string != 2 || !$is_escape))
  1062. {
  1063. // Is it the end of a double quote string?
  1064. if ($in_string == 2)
  1065. $in_string = 0;
  1066. // Otherwise it's the start!
  1067. else
  1068. $in_string = 2;
  1069. // Don't actually include this character!
  1070. continue;
  1071. }
  1072. }
  1073. // A join/space outside of a string is simply removed.
  1074. elseif ($in_string == 0 && (empty($string{$i}) || $string{$i} == '.'))
  1075. continue;
  1076. // Start of a variable?
  1077. elseif ($in_string == 0 && $string{$i} == '$')
  1078. {
  1079. // Find the whole of it!
  1080. preg_match('~([\$A-Za-z0-9\'\[\]_-]+)~', substr($string, $i), $matches);
  1081. if (!empty($matches[1]))
  1082. {
  1083. // Come up with some pseudo thing to indicate this is a var.
  1084. /**
  1085. * @todo Do better than this, please!
  1086. */
  1087. $new_string .= '{%' . $matches[1] . '%}';
  1088. // We're not going to reparse this.
  1089. $i += strlen($matches[1]) - 1;
  1090. }
  1091. continue;
  1092. }
  1093. // Right, if we're outside of a string we have DANGER, DANGER!
  1094. elseif ($in_string == 0)
  1095. {
  1096. continue;
  1097. }
  1098. // Actually add the character to the string!
  1099. $new_string .= $string{$i};
  1100. // If anything was escaped it ain't any longer!
  1101. $is_escape = false;
  1102. }
  1103. // Unhtml then rehtml the whole thing!
  1104. $new_string = htmlspecialchars(un_htmlspecialchars($new_string));
  1105. }
  1106. else
  1107. {
  1108. // Keep track of what we're doing...
  1109. $in_string = 0;
  1110. // This is for deciding whether to HTML a quote.
  1111. $in_html = false;
  1112. for ($i = 0; $i < strlen($string); $i++)
  1113. {
  1114. // Handle line breaks!
  1115. if ($string{$i} == "\n" || $string{$i} == "\t")
  1116. {
  1117. // Are we in a string? Is it the right type?
  1118. if ($in_string == 1)
  1119. {
  1120. // Change type!
  1121. $new_string .= '\' . "\\' . ($string{$i} == "\n" ? 'n' : 't');
  1122. $in_string = 2;
  1123. }
  1124. elseif ($in_string == 2)
  1125. $new_string .= '\\' . ($string{$i} == "\n" ? 'n' : 't');
  1126. // Otherwise start one off - joining if required.
  1127. else
  1128. $new_string .= ($new_string ? ' . ' : '') . '"\\' . ($string{$i} == "\n" ? 'n' : 't');
  1129. continue;
  1130. }
  1131. // We don't do parsed strings apart from for breaks.
  1132. elseif ($in_string == 2)
  1133. {
  1134. $in_string = 0;
  1135. $new_string .= '"';
  1136. }
  1137. // Not in a string yet?
  1138. if ($in_string != 1)
  1139. {
  1140. $in_string = 1;
  1141. $new_string .= ($new_string ? ' . ' : '') . '\'';
  1142. }
  1143. // Is this a variable?
  1144. if ($string{$i} == '{' && $string{$i + 1} == '%' && $string{$i + 2} == '$')
  1145. {
  1146. // Grab the variable.
  1147. preg_match('~\{%([\$A-Za-z0-9\'\[\]_-]+)%\}~', substr($string, $i), $matches);
  1148. if (!empty($matches[1]))
  1149. {
  1150. if ($in_string == 1)
  1151. $new_string .= '\' . ';
  1152. elseif ($new_string)
  1153. $new_string .= ' . ';
  1154. $new_string .= $matches[1];
  1155. $i += strlen($matches[1]) + 3;
  1156. $in_string = 0;
  1157. }
  1158. continue;
  1159. }
  1160. // Is this a lt sign?
  1161. elseif ($string{$i} == '<')
  1162. {
  1163. // Probably HTML?
  1164. if ($string{$i + 1} != ' ')
  1165. $in_html = true;
  1166. // Assume we need an entity...
  1167. else
  1168. {
  1169. $new_string .= '&lt;';
  1170. continue;
  1171. }
  1172. }
  1173. // What about gt?
  1174. elseif ($string{$i} == '>')
  1175. {
  1176. // Will it be HTML?
  1177. if ($in_html)
  1178. $in_html = false;
  1179. // Otherwise we need an entity...
  1180. else
  1181. {
  1182. $new_string .= '&gt;';
  1183. continue;
  1184. }
  1185. }
  1186. // Is it a slash? If so escape it...
  1187. if ($string{$i} == '\\')
  1188. $new_string .= '\\';
  1189. // The infamous double quote?
  1190. elseif ($string{$i} == '"')
  1191. {
  1192. // If we're in HTML we leave it as a quote - otherwise we entity it.
  1193. if (!$in_html)
  1194. {
  1195. $new_string .= '&quot;';
  1196. continue;
  1197. }
  1198. }
  1199. // A single quote?
  1200. elseif ($string{$i} == '\'')
  1201. {
  1202. // Must be in a string so escape it.
  1203. $new_string .= '\\';
  1204. }
  1205. // Finally add the character to the string!
  1206. $new_string .= $string{$i};
  1207. }
  1208. // If we ended as a string then close it off.
  1209. if ($in_string == 1)
  1210. $new_string .= '\'';
  1211. elseif ($in_string == 2)
  1212. $new_string .= '"';
  1213. }
  1214. return $new_string;
  1215. }
  1216. ?>