ManageLanguages.php 42 KB

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