ManageLanguages.php 44 KB

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