ManageLanguages.php 42 KB

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