2
0

ManageLanguages.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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. validateToken('admin-dlang');
  124. $chmod_files = array();
  125. $install_files = array();
  126. // Check writable status.
  127. foreach ($_POST['copy_file'] as $file)
  128. {
  129. // Check it's not very bad.
  130. if (strpos($file, '..') !== false || (substr($file, 0, 6) != 'Themes' && !preg_match('~agreement\.[A-Za-z-_0-9]+\.txt$~', $file)))
  131. fatal_error($txt['languages_download_illegal_paths']);
  132. $chmod_files[] = $boarddir . '/' . $file;
  133. $install_files[] = $file;
  134. }
  135. // Call this in case we have work to do.
  136. $file_status = create_chmod_control($chmod_files);
  137. $files_left = $file_status['files']['notwritable'];
  138. // Something not writable?
  139. if (!empty($files_left))
  140. $context['error_message'] = $txt['languages_download_not_chmod'];
  141. // Otherwise, go go go!
  142. elseif (!empty($install_files))
  143. {
  144. $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);
  145. // Make sure the files aren't stuck in the cache.
  146. package_flush_cache();
  147. $context['install_complete'] = sprintf($txt['languages_download_complete_desc'], $scripturl . '?action=admin;area=languages');
  148. return;
  149. }
  150. }
  151. // Open up the old china.
  152. if (!isset($archive_content))
  153. $archive_content = read_tgz_file('http://download.simplemachines.org/fetch_language.php?version=' . urlencode(strtr($forum_version, array('SMF ' => ''))) . ';fetch=' . urlencode($_GET['did']), null);
  154. if (empty($archive_content))
  155. fatal_error($txt['add_language_error_no_response']);
  156. // Now for each of the files, let's do some *stuff*
  157. $context['files'] = array(
  158. 'lang' => array(),
  159. 'other' => array(),
  160. );
  161. $context['make_writable'] = array();
  162. foreach ($archive_content as $file)
  163. {
  164. $dirname = dirname($file['filename']);
  165. $filename = basename($file['filename']);
  166. $extension = substr($filename, strrpos($filename, '.') + 1);
  167. // Don't do anything with files we don't understand.
  168. if (!in_array($extension, array('php', 'jpg', 'gif', 'jpeg', 'png', 'txt')))
  169. continue;
  170. // Basic data.
  171. $context_data = array(
  172. 'name' => $filename,
  173. 'destination' => $boarddir . '/' . $file['filename'],
  174. 'generaldest' => $file['filename'],
  175. 'size' => $file['size'],
  176. // Does chmod status allow the copy?
  177. 'writable' => false,
  178. // Should we suggest they copy this file?
  179. 'default_copy' => true,
  180. // Does the file already exist, if so is it same or different?
  181. 'exists' => false,
  182. );
  183. // Does the file exist, is it different and can we overwrite?
  184. if (file_exists($boarddir . '/' . $file['filename']))
  185. {
  186. if (is_writable($boarddir . '/' . $file['filename']))
  187. $context_data['writable'] = true;
  188. // Finally, do we actually think the content has changed?
  189. if ($file['size'] == filesize($boarddir . '/' . $file['filename']) && $file['md5'] == md5_file($boarddir . '/' . $file['filename']))
  190. {
  191. $context_data['exists'] = 'same';
  192. $context_data['default_copy'] = false;
  193. }
  194. // Attempt to discover newline character differences.
  195. elseif ($file['md5'] == md5(preg_replace("~[\r]?\n~", "\r\n", file_get_contents($boarddir . '/' . $file['filename']))))
  196. {
  197. $context_data['exists'] = 'same';
  198. $context_data['default_copy'] = false;
  199. }
  200. else
  201. $context_data['exists'] = 'different';
  202. }
  203. // No overwrite?
  204. else
  205. {
  206. // Can we at least stick it in the directory...
  207. if (is_writable($boarddir . '/' . $dirname))
  208. $context_data['writable'] = true;
  209. }
  210. // 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...
  211. if ($extension == 'php' && preg_match('~\w+\.\w+(?:-utf8)?\.php~', $filename))
  212. {
  213. $context_data += array(
  214. 'version' => '??',
  215. 'cur_version' => false,
  216. 'version_compare' => 'newer',
  217. );
  218. list ($name, $language) = explode('.', $filename);
  219. // Let's get the new version, I like versions, they tell me that I'm up to date.
  220. if (preg_match('~\s*Version:\s+(.+?);\s*' . preg_quote($name, '~') . '~i', $file['preview'], $match) == 1)
  221. $context_data['version'] = $match[1];
  222. // Now does the old file exist - if so what is it's version?
  223. if (file_exists($boarddir . '/' . $file['filename']))
  224. {
  225. // OK - what is the current version?
  226. $fp = fopen($boarddir . '/' . $file['filename'], 'rb');
  227. $header = fread($fp, 768);
  228. fclose($fp);
  229. // Find the version.
  230. if (preg_match('~(?://|/\*)\s*Version:\s+(.+?);\s*' . preg_quote($name, '~') . '(?:[\s]{2}|\*/)~i', $header, $match) == 1)
  231. {
  232. $context_data['cur_version'] = $match[1];
  233. // How does this compare?
  234. if ($context_data['cur_version'] == $context_data['version'])
  235. $context_data['version_compare'] = 'same';
  236. elseif ($context_data['cur_version'] > $context_data['version'])
  237. $context_data['version_compare'] = 'older';
  238. // Don't recommend copying if the version is the same.
  239. if ($context_data['version_compare'] != 'newer')
  240. $context_data['default_copy'] = false;
  241. }
  242. }
  243. // Add the context data to the main set.
  244. $context['files']['lang'][] = $context_data;
  245. }
  246. else
  247. {
  248. // If we think it's a theme thing, work out what the theme is.
  249. if (substr($dirname, 0, 6) == 'Themes' && preg_match('~Themes[\\/]([^\\/]+)[\\/]~', $dirname, $match))
  250. $theme_name = $match[1];
  251. else
  252. $theme_name = 'misc';
  253. // Assume it's an image, could be an acceptance note etc but rare.
  254. $context['files']['images'][$theme_name][] = $context_data;
  255. }
  256. // Collect together all non-writable areas.
  257. if (!$context_data['writable'])
  258. $context['make_writable'][] = $context_data['destination'];
  259. }
  260. // So, I'm a perfectionist - let's get the theme names.
  261. $theme_indexes = array();
  262. foreach ($context['files']['images'] as $k => $dummy)
  263. $indexes[] = $k;
  264. $context['theme_names'] = array();
  265. if (!empty($indexes))
  266. {
  267. $value_data = array(
  268. 'query' => array(),
  269. 'params' => array(),
  270. );
  271. foreach ($indexes as $k => $index)
  272. {
  273. $value_data['query'][] = 'value LIKE {string:value_' . $k . '}';
  274. $value_data['params']['value_' . $k] = '%' . $index;
  275. }
  276. $request = $smcFunc['db_query']('', '
  277. SELECT id_theme, value
  278. FROM {db_prefix}themes
  279. WHERE id_member = {int:no_member}
  280. AND variable = {string:theme_dir}
  281. AND (' . implode(' OR ', $value_data['query']) . ')',
  282. array_merge($value_data['params'], array(
  283. 'no_member' => 0,
  284. 'theme_dir' => 'theme_dir',
  285. 'index_compare_explode' => 'value LIKE \'%' . implode('\' OR value LIKE \'%', $indexes) . '\'',
  286. ))
  287. );
  288. $themes = array();
  289. while ($row = $smcFunc['db_fetch_assoc']($request))
  290. {
  291. // Find the right one.
  292. foreach ($indexes as $index)
  293. if (strpos($row['value'], $index) !== false)
  294. $themes[$row['id_theme']] = $index;
  295. }
  296. $smcFunc['db_free_result']($request);
  297. if (!empty($themes))
  298. {
  299. // Now we have the id_theme we can get the pretty description.
  300. $request = $smcFunc['db_query']('', '
  301. SELECT id_theme, value
  302. FROM {db_prefix}themes
  303. WHERE id_member = {int:no_member}
  304. AND variable = {string:name}
  305. AND id_theme IN ({array_int:theme_list})',
  306. array(
  307. 'theme_list' => array_keys($themes),
  308. 'no_member' => 0,
  309. 'name' => 'name',
  310. )
  311. );
  312. while ($row = $smcFunc['db_fetch_assoc']($request))
  313. {
  314. // Now we have it...
  315. $context['theme_names'][$themes[$row['id_theme']]] = $row['value'];
  316. }
  317. $smcFunc['db_free_result']($request);
  318. }
  319. }
  320. // Before we go to far can we make anything writable, eh, eh?
  321. if (!empty($context['make_writable']))
  322. {
  323. // What is left to be made writable?
  324. $file_status = create_chmod_control($context['make_writable']);
  325. $context['still_not_writable'] = $file_status['files']['notwritable'];
  326. // Mark those which are now writable as such.
  327. foreach ($context['files'] as $type => $data)
  328. {
  329. if ($type == 'lang')
  330. {
  331. foreach ($data as $k => $file)
  332. if (!$file['writable'] && !in_array($file['destination'], $context['still_not_writable']))
  333. $context['files'][$type][$k]['writable'] = true;
  334. }
  335. else
  336. {
  337. foreach ($data as $theme => $files)
  338. foreach ($files as $k => $file)
  339. if (!$file['writable'] && !in_array($file['destination'], $context['still_not_writable']))
  340. $context['files'][$type][$theme][$k]['writable'] = true;
  341. }
  342. }
  343. // Are we going to need more language stuff?
  344. if (!empty($context['still_not_writable']))
  345. loadLanguage('Packages');
  346. }
  347. // This is the list for the main files.
  348. $listOptions = array(
  349. 'id' => 'lang_main_files_list',
  350. 'title' => $txt['languages_download_main_files'],
  351. 'get_items' => array(
  352. 'function' => create_function('', '
  353. global $context;
  354. return $context[\'files\'][\'lang\'];
  355. '),
  356. ),
  357. 'columns' => array(
  358. 'name' => array(
  359. 'header' => array(
  360. 'value' => $txt['languages_download_filename'],
  361. ),
  362. 'data' => array(
  363. 'function' => create_function('$rowData', '
  364. global $context, $txt;
  365. 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\'] : \'\');
  366. '),
  367. ),
  368. ),
  369. 'writable' => array(
  370. 'header' => array(
  371. 'value' => $txt['languages_download_writable'],
  372. ),
  373. 'data' => array(
  374. 'function' => create_function('$rowData', '
  375. global $txt;
  376. return \'<span style="color: \' . ($rowData[\'writable\'] ? \'green\' : \'red\') . \';">\' . ($rowData[\'writable\'] ? $txt[\'yes\'] : $txt[\'no\']) . \'</span>\';
  377. '),
  378. 'style' => 'text-align: center',
  379. ),
  380. ),
  381. 'version' => array(
  382. 'header' => array(
  383. 'value' => $txt['languages_download_version'],
  384. ),
  385. 'data' => array(
  386. 'function' => create_function('$rowData', '
  387. global $txt;
  388. return \'<span style="color: \' . ($rowData[\'version_compare\'] == \'older\' ? \'red\' : ($rowData[\'version_compare\'] == \'same\' ? \'orange\' : \'green\')) . \';">\' . $rowData[\'version\'] . \'</span>\';
  389. '),
  390. ),
  391. ),
  392. 'exists' => array(
  393. 'header' => array(
  394. 'value' => $txt['languages_download_exists'],
  395. ),
  396. 'data' => array(
  397. 'function' => create_function('$rowData', '
  398. global $txt;
  399. return $rowData[\'exists\'] ? ($rowData[\'exists\'] == \'same\' ? $txt[\'languages_download_exists_same\'] : $txt[\'languages_download_exists_different\']) : $txt[\'no\'];
  400. '),
  401. ),
  402. ),
  403. 'copy' => array(
  404. 'header' => array(
  405. 'value' => $txt['languages_download_copy'],
  406. ),
  407. 'data' => array(
  408. 'function' => create_function('$rowData', '
  409. return \'<input type="checkbox" name="copy_file[]" value="\' . $rowData[\'generaldest\'] . \'" \' . ($rowData[\'default_copy\'] ? \'checked="checked"\' : \'\') . \' class="input_check" />\';
  410. '),
  411. 'style' => 'text-align: center; width: 4%;',
  412. ),
  413. ),
  414. ),
  415. );
  416. // Kill the cache, as it is now invalid..
  417. if (!empty($modSettings['cache_enable']))
  418. {
  419. cache_put_data('known_languages', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  420. cache_put_data('known_languages_all', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  421. }
  422. require_once($sourcedir . '/Subs-List.php');
  423. createList($listOptions);
  424. $context['default_list'] = 'lang_main_files_list';
  425. createToken('admin-dlang');
  426. }
  427. /**
  428. * This lists all the current languages and allows editing of them.
  429. */
  430. function ModifyLanguages()
  431. {
  432. global $txt, $context, $scripturl;
  433. global $user_info, $smcFunc, $sourcedir, $language, $boarddir, $forum_version;
  434. // Setting a new default?
  435. if (!empty($_POST['set_default']) && !empty($_POST['def_language']))
  436. {
  437. checkSession();
  438. validateToken('admin-lang');
  439. if ($_POST['def_language'] != $language)
  440. {
  441. require_once($sourcedir . '/Subs-Admin.php');
  442. updateSettingsFile(array('language' => '\'' . $_POST['def_language'] . '\''));
  443. $language = $_POST['def_language'];
  444. }
  445. }
  446. // Create another one time token here.
  447. createToken('admin-lang');
  448. $listOptions = array(
  449. 'id' => 'language_list',
  450. 'items_per_page' => 20,
  451. 'base_href' => $scripturl . '?action=admin;area=languages',
  452. 'title' => $txt['edit_languages'],
  453. 'get_items' => array(
  454. 'function' => 'list_getLanguages',
  455. ),
  456. 'get_count' => array(
  457. 'function' => 'list_getNumLanguages',
  458. ),
  459. 'columns' => array(
  460. 'default' => array(
  461. 'header' => array(
  462. 'value' => $txt['languages_default'],
  463. ),
  464. 'data' => array(
  465. 'function' => create_function('$rowData', '
  466. return \'<input type="radio" name="def_language" value="\' . $rowData[\'id\'] . \'" \' . ($rowData[\'default\'] ? \'checked="checked"\' : \'\') . \' onclick="highlightSelected(\\\'list_language_list_\' . $rowData[\'id\'] . \'\\\');" class="input_radio" />\';
  467. '),
  468. 'style' => 'text-align: center; width: 8%;',
  469. ),
  470. ),
  471. 'name' => array(
  472. 'header' => array(
  473. 'value' => $txt['languages_lang_name'],
  474. ),
  475. 'data' => array(
  476. 'function' => create_function('$rowData', '
  477. global $scripturl, $context;
  478. return sprintf(\'<a href="%1$s?action=admin;area=languages;sa=editlang;lid=%2$s">%3$s</a>\', $scripturl, $rowData[\'id\'], $rowData[\'name\']);
  479. '),
  480. ),
  481. ),
  482. 'character_set' => array(
  483. 'header' => array(
  484. 'value' => $txt['languages_character_set'],
  485. ),
  486. 'data' => array(
  487. 'db_htmlsafe' => 'char_set',
  488. ),
  489. ),
  490. 'count' => array(
  491. 'header' => array(
  492. 'value' => $txt['languages_users'],
  493. ),
  494. 'data' => array(
  495. 'db_htmlsafe' => 'count',
  496. 'style' => 'text-align: center',
  497. ),
  498. ),
  499. 'locale' => array(
  500. 'header' => array(
  501. 'value' => $txt['languages_locale'],
  502. ),
  503. 'data' => array(
  504. 'db_htmlsafe' => 'locale',
  505. ),
  506. ),
  507. ),
  508. 'form' => array(
  509. 'href' => $scripturl . '?action=admin;area=languages',
  510. 'token' => 'admin-lang',
  511. ),
  512. 'additional_rows' => array(
  513. array(
  514. 'position' => 'below_table_data',
  515. '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" />',
  516. 'style' => 'text-align: right;',
  517. ),
  518. ),
  519. // For highlighting the default.
  520. 'javascript' => '
  521. var prevClass = "";
  522. var prevDiv = "";
  523. function highlightSelected(box)
  524. {
  525. if (prevClass != "")
  526. prevDiv.className = prevClass;
  527. prevDiv = document.getElementById(box);
  528. prevClass = prevDiv.className;
  529. prevDiv.className = "highlight2";
  530. }
  531. highlightSelected("list_language_list_' . ($language == '' ? 'english' : $language). '");
  532. ',
  533. );
  534. // Display a warning if we cannot edit the default setting.
  535. if (!is_writable($boarddir . '/Settings.php'))
  536. $listOptions['additional_rows'][] = array(
  537. 'position' => 'after_title',
  538. 'value' => $txt['language_settings_writable'],
  539. 'class' => 'smalltext alert',
  540. );
  541. require_once($sourcedir . '/Subs-List.php');
  542. createList($listOptions);
  543. $context['sub_template'] = 'show_list';
  544. $context['default_list'] = 'language_list';
  545. }
  546. /**
  547. * How many languages?
  548. * Callback for the list in ManageLanguageSettings().
  549. */
  550. function list_getNumLanguages()
  551. {
  552. global $settings;
  553. // Return how many we have.
  554. return count(getLanguages(true, false));
  555. }
  556. /**
  557. * Fetch the actual language information.
  558. * Callback for $listOptions['get_items']['function'] in ManageLanguageSettings.
  559. * Determines which languages are available by looking for the "index.{language}.php" file.
  560. * Also figures out how many users are using a particular language.
  561. */
  562. function list_getLanguages()
  563. {
  564. global $settings, $smcFunc, $language, $context, $txt;
  565. $languages = array();
  566. // Keep our old entries.
  567. $old_txt = $txt;
  568. $backup_actual_theme_dir = $settings['actual_theme_dir'];
  569. $backup_base_theme_dir = !empty($settings['base_theme_dir']) ? $settings['base_theme_dir'] : '';
  570. // Override these for now.
  571. $settings['actual_theme_dir'] = $settings['base_theme_dir'] = $settings['default_theme_dir'];
  572. getLanguages(true, false);
  573. // Put them back.
  574. $settings['actual_theme_dir'] = $backup_actual_theme_dir;
  575. if (!empty($backup_base_theme_dir))
  576. $settings['base_theme_dir'] = $backup_base_theme_dir;
  577. else
  578. unset($settings['base_theme_dir']);
  579. // Get the language files and data...
  580. foreach ($context['languages'] as $lang)
  581. {
  582. // Load the file to get the character set.
  583. require($settings['default_theme_dir'] . '/languages/index.' . $lang['filename'] . '.php');
  584. $languages[$lang['filename']] = array(
  585. 'id' => $lang['filename'],
  586. 'count' => 0,
  587. 'char_set' => $txt['lang_character_set'],
  588. 'default' => $language == $lang['filename'] || ($language == '' && $lang['filename'] == 'english'),
  589. 'locale' => $txt['lang_locale'],
  590. 'name' => $smcFunc['ucwords'](strtr($lang['filename'], array('_' => ' ', '-utf8' => ''))),
  591. );
  592. }
  593. // Work out how many people are using each language.
  594. $request = $smcFunc['db_query']('', '
  595. SELECT lngfile, COUNT(*) AS num_users
  596. FROM {db_prefix}members
  597. GROUP BY lngfile',
  598. array(
  599. )
  600. );
  601. while ($row = $smcFunc['db_fetch_assoc']($request))
  602. {
  603. // Default?
  604. if (empty($row['lngfile']) || !isset($languages[$row['lngfile']]))
  605. $row['lngfile'] = $language;
  606. if (!isset($languages[$row['lngfile']]) && isset($languages['english']))
  607. $languages['english']['count'] += $row['num_users'];
  608. elseif (isset($languages[$row['lngfile']]))
  609. $languages[$row['lngfile']]['count'] += $row['num_users'];
  610. }
  611. $smcFunc['db_free_result']($request);
  612. // Restore the current users language.
  613. $txt = $old_txt;
  614. // Return how many we have.
  615. return $languages;
  616. }
  617. /**
  618. * Edit language related settings.
  619. *
  620. * @param bool $return_config = false
  621. */
  622. function ModifyLanguageSettings($return_config = false)
  623. {
  624. global $scripturl, $context, $txt, $boarddir, $settings, $smcFunc, $sourcedir;
  625. // We'll want to save them someday.
  626. require_once $sourcedir . '/ManageServer.php';
  627. // Warn the user if the backup of Settings.php failed.
  628. $settings_not_writable = !is_writable($boarddir . '/Settings.php');
  629. $settings_backup_fail = !@is_writable($boarddir . '/Settings_bak.php') || !@copy($boarddir . '/Settings.php', $boarddir . '/Settings_bak.php');
  630. /* If you're writing a mod, it's a bad idea to add things here....
  631. For each option:
  632. variable name, description, type (constant), size/possible values, helptext.
  633. OR an empty string for a horizontal rule.
  634. OR a string for a titled section. */
  635. $config_vars = array(
  636. 'language' => array('language', $txt['default_language'], 'file', 'select', array(), null, 'disabled' => $settings_not_writable),
  637. array('userLanguage', $txt['userLanguage'], 'db', 'check', null, 'userLanguage'),
  638. );
  639. if ($return_config)
  640. return $config_vars;
  641. // Get our languages. No cache and use utf8.
  642. getLanguages(false, false);
  643. foreach ($context['languages'] as $lang)
  644. $config_vars['language'][4][$lang['filename']] = array($lang['filename'], strtr($lang['name'], array('-utf8' => ' (UTF-8)')));
  645. // Saving settings?
  646. if (isset($_REQUEST['save']))
  647. {
  648. checkSession();
  649. saveSettings($config_vars);
  650. redirectexit('action=admin;area=languages;sa=settings');
  651. }
  652. // Setup the template stuff.
  653. $context['post_url'] = $scripturl . '?action=admin;area=languages;sa=settings;save';
  654. $context['settings_title'] = $txt['language_settings'];
  655. $context['save_disabled'] = $settings_not_writable;
  656. if ($settings_not_writable)
  657. $context['settings_message'] = '<div class="centertext"><strong>' . $txt['settings_not_writable'] . '</strong></div><br />';
  658. elseif ($settings_backup_fail)
  659. $context['settings_message'] = '<div class="centertext"><strong>' . $txt['admin_backup_fail'] . '</strong></div><br />';
  660. // Fill the config array.
  661. prepareServerSettingsContext($config_vars);
  662. }
  663. /**
  664. * Edit a particular set of language entries.
  665. *
  666. */
  667. function ModifyLanguage()
  668. {
  669. global $settings, $context, $smcFunc, $txt, $modSettings, $boarddir, $sourcedir, $language;
  670. loadLanguage('ManageSettings');
  671. // Select the languages tab.
  672. $context['menu_data_' . $context['admin_menu_id']]['current_subsection'] = 'edit';
  673. $context['page_title'] = $txt['edit_languages'];
  674. $context['sub_template'] = 'modify_language_entries';
  675. $context['lang_id'] = $_GET['lid'];
  676. list($theme_id, $file_id) = empty($_REQUEST['tfid']) || strpos($_REQUEST['tfid'], '+') === false ? array(1, '') : explode('+', $_REQUEST['tfid']);
  677. // Clean the ID - just in case.
  678. preg_match('~([A-Za-z0-9_-]+)~', $context['lang_id'], $matches);
  679. $context['lang_id'] = $matches[1];
  680. // Get all the theme data.
  681. $request = $smcFunc['db_query']('', '
  682. SELECT id_theme, variable, value
  683. FROM {db_prefix}themes
  684. WHERE id_theme != {int:default_theme}
  685. AND id_member = {int:no_member}
  686. AND variable IN ({string:name}, {string:theme_dir})',
  687. array(
  688. 'default_theme' => 1,
  689. 'no_member' => 0,
  690. 'name' => 'name',
  691. 'theme_dir' => 'theme_dir',
  692. )
  693. );
  694. $themes = array(
  695. 1 => array(
  696. 'name' => $txt['dvc_default'],
  697. 'theme_dir' => $settings['default_theme_dir'],
  698. ),
  699. );
  700. while ($row = $smcFunc['db_fetch_assoc']($request))
  701. $themes[$row['id_theme']][$row['variable']] = $row['value'];
  702. $smcFunc['db_free_result']($request);
  703. // This will be where we look
  704. $lang_dirs = array();
  705. // Check we have themes with a path and a name - just in case - and add the path.
  706. foreach ($themes as $id => $data)
  707. {
  708. if (count($data) != 2)
  709. unset($themes[$id]);
  710. elseif (is_dir($data['theme_dir'] . '/languages'))
  711. $lang_dirs[$id] = $data['theme_dir'] . '/languages';
  712. // How about image directories?
  713. if (is_dir($data['theme_dir'] . '/images/' . $context['lang_id']))
  714. $images_dirs[$id] = $data['theme_dir'] . '/images/' . $context['lang_id'];
  715. }
  716. $current_file = $file_id ? $lang_dirs[$theme_id] . '/' . $file_id . '.' . $context['lang_id'] . '.php' : '';
  717. // Now for every theme get all the files and stick them in context!
  718. $context['possible_files'] = array();
  719. foreach ($lang_dirs as $theme => $theme_dir)
  720. {
  721. // Open it up.
  722. $dir = dir($theme_dir);
  723. while ($entry = $dir->read())
  724. {
  725. // We're only after the files for this language.
  726. if (preg_match('~^([A-Za-z]+)\.' . $context['lang_id'] . '\.php$~', $entry, $matches) == 0)
  727. continue;
  728. /**
  729. * @todo Temp!
  730. */
  731. if ($matches[1] == 'EmailTemplates')
  732. continue;
  733. if (!isset($context['possible_files'][$theme]))
  734. $context['possible_files'][$theme] = array(
  735. 'id' => $theme,
  736. 'name' => $themes[$theme]['name'],
  737. 'files' => array(),
  738. );
  739. $context['possible_files'][$theme]['files'][] = array(
  740. 'id' => $matches[1],
  741. 'name' => isset($txt['lang_file_desc_' . $matches[1]]) ? $txt['lang_file_desc_' . $matches[1]] : $matches[1],
  742. 'selected' => $theme_id == $theme && $file_id == $matches[1],
  743. );
  744. }
  745. $dir->close();
  746. }
  747. // We no longer wish to speak this language.
  748. if (!empty($_POST['delete_main']) && $context['lang_id'] != 'english')
  749. {
  750. checkSession();
  751. /**
  752. * @todo FTP Controls?
  753. */
  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. /**
  969. * @todo Fix this properly.
  970. */
  971. if ($save_strings[$entryKey] == '')
  972. $save_strings[$entryKey] = '\'\'';
  973. // Set the new value.
  974. $entryValue['entry'] = $save_strings[$entryKey];
  975. // And we know what to save now!
  976. $final_saves[$entryKey] = array(
  977. 'find' => $entryValue['full'],
  978. 'replace' => '$' . $entryValue['type'] . '[\'' . $entryKey . '\'] = ' . $save_strings[$entryKey] . ';',
  979. );
  980. }
  981. $editing_string = cleanLangString($entryValue['entry'], true);
  982. $context['file_entries'][] = array(
  983. 'key' => $entryKey,
  984. 'value' => $editing_string,
  985. 'rows' => (int) (strlen($editing_string) / 38) + substr_count($editing_string, "\n") + 1,
  986. );
  987. }
  988. }
  989. // Any saves to make?
  990. if (!empty($final_saves))
  991. {
  992. checkSession();
  993. $file_contents = implode('', file($current_file));
  994. foreach ($final_saves as $save)
  995. $file_contents = strtr($file_contents, array($save['find'] => $save['replace']));
  996. // Save the actual changes.
  997. $fp = fopen($current_file, 'w+');
  998. fwrite($fp, $file_contents);
  999. fclose($fp);
  1000. $madeSave = true;
  1001. }
  1002. // Another restore.
  1003. $txt = $old_txt;
  1004. }
  1005. // If we saved, redirect.
  1006. if ($madeSave)
  1007. redirectexit('action=admin;area=languages;sa=editlang;lid=' . $context['lang_id']);
  1008. createToken('admin-mlang');
  1009. }
  1010. /**
  1011. * This function cleans language entries to/from display.
  1012. * @todo This function could be two functions?
  1013. *
  1014. * @param $string
  1015. * @param $to_display
  1016. */
  1017. function cleanLangString($string, $to_display = true)
  1018. {
  1019. global $smcFunc;
  1020. // If going to display we make sure it doesn't have any HTML in it - etc.
  1021. $new_string = '';
  1022. if ($to_display)
  1023. {
  1024. // Are we in a string (0 = no, 1 = single quote, 2 = parsed)
  1025. $in_string = 0;
  1026. $is_escape = false;
  1027. for ($i = 0; $i < strlen($string); $i++)
  1028. {
  1029. // Handle ecapes first.
  1030. if ($string{$i} == '\\')
  1031. {
  1032. // Toggle the escape.
  1033. $is_escape = !$is_escape;
  1034. // If we're now escaped don't add this string.
  1035. if ($is_escape)
  1036. continue;
  1037. }
  1038. // Special case - parsed string with line break etc?
  1039. elseif (($string{$i} == 'n' || $string{$i} == 't') && $in_string == 2 && $is_escape)
  1040. {
  1041. // Put the escape back...
  1042. $new_string .= $string{$i} == 'n' ? "\n" : "\t";
  1043. $is_escape = false;
  1044. continue;
  1045. }
  1046. // Have we got a single quote?
  1047. elseif ($string{$i} == '\'')
  1048. {
  1049. // Already in a parsed string, or escaped in a linear string, means we print it - otherwise something special.
  1050. if ($in_string != 2 && ($in_string != 1 || !$is_escape))
  1051. {
  1052. // Is it the end of a single quote string?
  1053. if ($in_string == 1)
  1054. $in_string = 0;
  1055. // Otherwise it's the start!
  1056. else
  1057. $in_string = 1;
  1058. // Don't actually include this character!
  1059. continue;
  1060. }
  1061. }
  1062. // Otherwise a double quote?
  1063. elseif ($string{$i} == '"')
  1064. {
  1065. // Already in a single quote string, or escaped in a parsed string, means we print it - otherwise something special.
  1066. if ($in_string != 1 && ($in_string != 2 || !$is_escape))
  1067. {
  1068. // Is it the end of a double quote string?
  1069. if ($in_string == 2)
  1070. $in_string = 0;
  1071. // Otherwise it's the start!
  1072. else
  1073. $in_string = 2;
  1074. // Don't actually include this character!
  1075. continue;
  1076. }
  1077. }
  1078. // A join/space outside of a string is simply removed.
  1079. elseif ($in_string == 0 && (empty($string{$i}) || $string{$i} == '.'))
  1080. continue;
  1081. // Start of a variable?
  1082. elseif ($in_string == 0 && $string{$i} == '$')
  1083. {
  1084. // Find the whole of it!
  1085. preg_match('~([\$A-Za-z0-9\'\[\]_-]+)~', substr($string, $i), $matches);
  1086. if (!empty($matches[1]))
  1087. {
  1088. // Come up with some pseudo thing to indicate this is a var.
  1089. /**
  1090. * @todo Do better than this, please!
  1091. */
  1092. $new_string .= '{%' . $matches[1] . '%}';
  1093. // We're not going to reparse this.
  1094. $i += strlen($matches[1]) - 1;
  1095. }
  1096. continue;
  1097. }
  1098. // Right, if we're outside of a string we have DANGER, DANGER!
  1099. elseif ($in_string == 0)
  1100. {
  1101. continue;
  1102. }
  1103. // Actually add the character to the string!
  1104. $new_string .= $string{$i};
  1105. // If anything was escaped it ain't any longer!
  1106. $is_escape = false;
  1107. }
  1108. // Unhtml then rehtml the whole thing!
  1109. $new_string = htmlspecialchars(un_htmlspecialchars($new_string));
  1110. }
  1111. else
  1112. {
  1113. // Keep track of what we're doing...
  1114. $in_string = 0;
  1115. // This is for deciding whether to HTML a quote.
  1116. $in_html = false;
  1117. for ($i = 0; $i < strlen($string); $i++)
  1118. {
  1119. // Handle line breaks!
  1120. if ($string{$i} == "\n" || $string{$i} == "\t")
  1121. {
  1122. // Are we in a string? Is it the right type?
  1123. if ($in_string == 1)
  1124. {
  1125. // Change type!
  1126. $new_string .= '\' . "\\' . ($string{$i} == "\n" ? 'n' : 't');
  1127. $in_string = 2;
  1128. }
  1129. elseif ($in_string == 2)
  1130. $new_string .= '\\' . ($string{$i} == "\n" ? 'n' : 't');
  1131. // Otherwise start one off - joining if required.
  1132. else
  1133. $new_string .= ($new_string ? ' . ' : '') . '"\\' . ($string{$i} == "\n" ? 'n' : 't');
  1134. continue;
  1135. }
  1136. // We don't do parsed strings apart from for breaks.
  1137. elseif ($in_string == 2)
  1138. {
  1139. $in_string = 0;
  1140. $new_string .= '"';
  1141. }
  1142. // Not in a string yet?
  1143. if ($in_string != 1)
  1144. {
  1145. $in_string = 1;
  1146. $new_string .= ($new_string ? ' . ' : '') . '\'';
  1147. }
  1148. // Is this a variable?
  1149. if ($string{$i} == '{' && $string{$i + 1} == '%' && $string{$i + 2} == '$')
  1150. {
  1151. // Grab the variable.
  1152. preg_match('~\{%([\$A-Za-z0-9\'\[\]_-]+)%\}~', substr($string, $i), $matches);
  1153. if (!empty($matches[1]))
  1154. {
  1155. if ($in_string == 1)
  1156. $new_string .= '\' . ';
  1157. elseif ($new_string)
  1158. $new_string .= ' . ';
  1159. $new_string .= $matches[1];
  1160. $i += strlen($matches[1]) + 3;
  1161. $in_string = 0;
  1162. }
  1163. continue;
  1164. }
  1165. // Is this a lt sign?
  1166. elseif ($string{$i} == '<')
  1167. {
  1168. // Probably HTML?
  1169. if ($string{$i + 1} != ' ')
  1170. $in_html = true;
  1171. // Assume we need an entity...
  1172. else
  1173. {
  1174. $new_string .= '&lt;';
  1175. continue;
  1176. }
  1177. }
  1178. // What about gt?
  1179. elseif ($string{$i} == '>')
  1180. {
  1181. // Will it be HTML?
  1182. if ($in_html)
  1183. $in_html = false;
  1184. // Otherwise we need an entity...
  1185. else
  1186. {
  1187. $new_string .= '&gt;';
  1188. continue;
  1189. }
  1190. }
  1191. // Is it a slash? If so escape it...
  1192. if ($string{$i} == '\\')
  1193. $new_string .= '\\';
  1194. // The infamous double quote?
  1195. elseif ($string{$i} == '"')
  1196. {
  1197. // If we're in HTML we leave it as a quote - otherwise we entity it.
  1198. if (!$in_html)
  1199. {
  1200. $new_string .= '&quot;';
  1201. continue;
  1202. }
  1203. }
  1204. // A single quote?
  1205. elseif ($string{$i} == '\'')
  1206. {
  1207. // Must be in a string so escape it.
  1208. $new_string .= '\\';
  1209. }
  1210. // Finally add the character to the string!
  1211. $new_string .= $string{$i};
  1212. }
  1213. // If we ended as a string then close it off.
  1214. if ($in_string == 1)
  1215. $new_string .= '\'';
  1216. elseif ($in_string == 2)
  1217. $new_string .= '"';
  1218. }
  1219. return $new_string;
  1220. }
  1221. ?>