ManageLanguages.php 44 KB

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