ManageLanguages.php 44 KB

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