ManageLanguages.php 43 KB

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