PageRenderTime 61ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/php/Sources/ManageServer.php

https://github.com/dekoza/openshift-smf-2.0.7
PHP | 2135 lines | 1486 code | 243 blank | 406 comment | 306 complexity | aa00efa6940adad770b8a422ba9d9198 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2011 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.0.5
  11. */
  12. if (!defined('SMF'))
  13. die('Hacking attempt...');
  14. /* This file contains all the functionality required to be able to edit the
  15. core server settings. This includes anything from which an error may result
  16. in the forum destroying itself in a firey fury.
  17. void ModifySettings()
  18. - Sets up all the available sub-actions.
  19. - Requires the admin_forum permission.
  20. - Uses the edit_settings adminIndex.
  21. - Sets up all the tabs and selects the appropriate one based on the sub-action.
  22. - Redirects to the appropriate function based on the sub-action.
  23. void ModifyGeneralSettings()
  24. - shows an interface for the settings in Settings.php to be changed.
  25. - uses the rawdata sub template (not theme-able.)
  26. - requires the admin_forum permission.
  27. - uses the edit_settings administration area.
  28. - contains the actual array of settings to show from Settings.php.
  29. - accessed from ?action=admin;area=serversettings;sa=general.
  30. void ModifyDatabaseSettings()
  31. - shows an interface for the settings in Settings.php to be changed.
  32. - uses the rawdata sub template (not theme-able.)
  33. - requires the admin_forum permission.
  34. - uses the edit_settings administration area.
  35. - contains the actual array of settings to show from Settings.php.
  36. - accessed from ?action=admin;area=serversettings;sa=database.
  37. void ModifyCookieSettings()
  38. // !!!
  39. void ModifyCacheSettings()
  40. // !!!
  41. void ModifyLoadBalancingSettings()
  42. // !!!
  43. void AddLanguage()
  44. // !!!
  45. void DownloadLanguage()
  46. - Uses the ManageSettings template and the download_language sub-template.
  47. - Requires a valid download ID ("did") in the URL.
  48. - Also handles installing language files.
  49. - Attempts to chmod things as needed.
  50. - Uses a standard list to display information about all the files and where they'll be put.
  51. void ManageLanguages()
  52. // !!!
  53. void ModifyLanguages()
  54. // !!!
  55. int list_getNumLanguages()
  56. // !!!
  57. array list_getLanguages()
  58. - Callback for $listOptions['get_items']['function'] in ManageLanguageSettings.
  59. - Determines which languages are available by looking for the "index.{language}.php" file.
  60. - Also figures out how many users are using a particular language.
  61. void ModifyLanguageSettings()
  62. // !!!
  63. void ModifyLanguage()
  64. // !!!
  65. void prepareServerSettingsContext(array config_vars)
  66. // !!!
  67. void prepareDBSettingContext(array config_vars)
  68. // !!!
  69. void saveSettings(array config_vars)
  70. - saves those settings set from ?action=admin;area=serversettings to the
  71. Settings.php file and the database.
  72. - requires the admin_forum permission.
  73. - contains arrays of the types of data to save into Settings.php.
  74. void saveDBSettings(array config_vars)
  75. // !!!
  76. */
  77. /* Adding options to one of the setting screens isn't hard. Call prepareDBSettingsContext;
  78. The basic format for a checkbox is:
  79. array('check', 'nameInModSettingsAndSQL'),
  80. And for a text box:
  81. array('text', 'nameInModSettingsAndSQL')
  82. (NOTE: You have to add an entry for this at the bottom!)
  83. In these cases, it will look for $txt['nameInModSettingsAndSQL'] as the description,
  84. and $helptxt['nameInModSettingsAndSQL'] as the help popup description.
  85. Here's a quick explanation of how to add a new item:
  86. * A text input box. For textual values.
  87. ie. array('text', 'nameInModSettingsAndSQL', 'OptionalInputBoxWidth'),
  88. * A text input box. For numerical values.
  89. ie. array('int', 'nameInModSettingsAndSQL', 'OptionalInputBoxWidth'),
  90. * A text input box. For floating point values.
  91. ie. array('float', 'nameInModSettingsAndSQL', 'OptionalInputBoxWidth'),
  92. * A large text input box. Used for textual values spanning multiple lines.
  93. ie. array('large_text', 'nameInModSettingsAndSQL', 'OptionalNumberOfRows'),
  94. * A check box. Either one or zero. (boolean)
  95. ie. array('check', 'nameInModSettingsAndSQL'),
  96. * A selection box. Used for the selection of something from a list.
  97. ie. array('select', 'nameInModSettingsAndSQL', array('valueForSQL' => $txt['displayedValue'])),
  98. Note that just saying array('first', 'second') will put 0 in the SQL for 'first'.
  99. * A password input box. Used for passwords, no less!
  100. ie. array('password', 'nameInModSettingsAndSQL', 'OptionalInputBoxWidth'),
  101. * A permission - for picking groups who have a permission.
  102. ie. array('permissions', 'manage_groups'),
  103. * A BBC selection box.
  104. ie. array('bbc', 'sig_bbc'),
  105. For each option:
  106. type (see above), variable name, size/possible values.
  107. OR make type '' for an empty string for a horizontal rule.
  108. SET preinput - to put some HTML prior to the input box.
  109. SET postinput - to put some HTML following the input box.
  110. SET invalid - to mark the data as invalid.
  111. PLUS You can override label and help parameters by forcing their keys in the array, for example:
  112. array('text', 'invalidlabel', 3, 'label' => 'Actual Label') */
  113. // This is the main pass through function, it creates tabs and the like.
  114. function ModifySettings()
  115. {
  116. global $context, $txt, $scripturl, $boarddir;
  117. // This is just to keep the database password more secure.
  118. isAllowedTo('admin_forum');
  119. // Load up all the tabs...
  120. $context[$context['admin_menu_name']]['tab_data'] = array(
  121. 'title' => $txt['admin_server_settings'],
  122. 'help' => 'serversettings',
  123. 'description' => $txt['admin_basic_settings'],
  124. );
  125. checkSession('request');
  126. // The settings are in here, I swear!
  127. loadLanguage('ManageSettings');
  128. $context['page_title'] = $txt['admin_server_settings'];
  129. $context['sub_template'] = 'show_settings';
  130. $subActions = array(
  131. 'general' => 'ModifyGeneralSettings',
  132. 'database' => 'ModifyDatabaseSettings',
  133. 'cookie' => 'ModifyCookieSettings',
  134. 'cache' => 'ModifyCacheSettings',
  135. 'loads' => 'ModifyLoadBalancingSettings',
  136. );
  137. // By default we're editing the core settings
  138. $_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'general';
  139. $context['sub_action'] = $_REQUEST['sa'];
  140. // Warn the user if there's any relevant information regarding Settings.php.
  141. if ($_REQUEST['sa'] != 'cache')
  142. {
  143. // Warn the user if the backup of Settings.php failed.
  144. $settings_not_writable = !is_writable($boarddir . '/Settings.php');
  145. $settings_backup_fail = !@is_writable($boarddir . '/Settings_bak.php') || !@copy($boarddir . '/Settings.php', $boarddir . '/Settings_bak.php');
  146. if ($settings_not_writable)
  147. $context['settings_message'] = '<div class="centertext"><strong>' . $txt['settings_not_writable'] . '</strong></div><br />';
  148. elseif ($settings_backup_fail)
  149. $context['settings_message'] = '<div class="centertext"><strong>' . $txt['admin_backup_fail'] . '</strong></div><br />';
  150. $context['settings_not_writable'] = $settings_not_writable;
  151. }
  152. // Call the right function for this sub-action.
  153. $subActions[$_REQUEST['sa']]();
  154. }
  155. // General forum settings - forum name, maintenance mode, etc.
  156. function ModifyGeneralSettings($return_config = false)
  157. {
  158. global $scripturl, $context, $txt;
  159. /* If you're writing a mod, it's a bad idea to add things here....
  160. For each option:
  161. variable name, description, type (constant), size/possible values, helptext.
  162. OR an empty string for a horizontal rule.
  163. OR a string for a titled section. */
  164. $config_vars = array(
  165. array('mbname', $txt['admin_title'], 'file', 'text', 30),
  166. '',
  167. array('maintenance', $txt['admin_maintain'], 'file', 'check'),
  168. array('mtitle', $txt['maintenance_subject'], 'file', 'text', 36),
  169. array('mmessage', $txt['maintenance_message'], 'file', 'text', 36),
  170. '',
  171. array('webmaster_email', $txt['admin_webmaster_email'], 'file', 'text', 30),
  172. '',
  173. array('enableCompressedOutput', $txt['enableCompressedOutput'], 'db', 'check', null, 'enableCompressedOutput'),
  174. array('disableTemplateEval', $txt['disableTemplateEval'], 'db', 'check', null, 'disableTemplateEval'),
  175. array('disableHostnameLookup', $txt['disableHostnameLookup'], 'db', 'check', null, 'disableHostnameLookup'),
  176. );
  177. if ($return_config)
  178. return $config_vars;
  179. // Setup the template stuff.
  180. $context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=general;save';
  181. $context['settings_title'] = $txt['general_settings'];
  182. // Saving settings?
  183. if (isset($_REQUEST['save']))
  184. {
  185. saveSettings($config_vars);
  186. redirectexit('action=admin;area=serversettings;sa=general;' . $context['session_var'] . '=' . $context['session_id']);
  187. }
  188. // Fill the config array.
  189. prepareServerSettingsContext($config_vars);
  190. }
  191. // Basic database and paths settings - database name, host, etc.
  192. function ModifyDatabaseSettings($return_config = false)
  193. {
  194. global $scripturl, $context, $settings, $txt, $boarddir;
  195. /* If you're writing a mod, it's a bad idea to add things here....
  196. For each option:
  197. variable name, description, type (constant), size/possible values, helptext.
  198. OR an empty string for a horizontal rule.
  199. OR a string for a titled section. */
  200. $config_vars = array(
  201. array('db_server', $txt['database_server'], 'file', 'text'),
  202. array('db_user', $txt['database_user'], 'file', 'text'),
  203. array('db_passwd', $txt['database_password'], 'file', 'password'),
  204. array('db_name', $txt['database_name'], 'file', 'text'),
  205. array('db_prefix', $txt['database_prefix'], 'file', 'text'),
  206. array('db_persist', $txt['db_persist'], 'file', 'check', null, 'db_persist'),
  207. array('db_error_send', $txt['db_error_send'], 'file', 'check'),
  208. array('ssi_db_user', $txt['ssi_db_user'], 'file', 'text', null, 'ssi_db_user'),
  209. array('ssi_db_passwd', $txt['ssi_db_passwd'], 'file', 'password'),
  210. '',
  211. array('autoFixDatabase', $txt['autoFixDatabase'], 'db', 'check', false, 'autoFixDatabase'),
  212. array('autoOptMaxOnline', $txt['autoOptMaxOnline'], 'db', 'int'),
  213. '',
  214. array('boardurl', $txt['admin_url'], 'file', 'text', 36),
  215. array('boarddir', $txt['boarddir'], 'file', 'text', 36),
  216. array('sourcedir', $txt['sourcesdir'], 'file', 'text', 36),
  217. array('cachedir', $txt['cachedir'], 'file', 'text', 36),
  218. );
  219. if ($return_config)
  220. return $config_vars;
  221. // Setup the template stuff.
  222. $context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=database;save';
  223. $context['settings_title'] = $txt['database_paths_settings'];
  224. $context['save_disabled'] = $context['settings_not_writable'];
  225. // Saving settings?
  226. if (isset($_REQUEST['save']))
  227. {
  228. saveSettings($config_vars);
  229. redirectexit('action=admin;area=serversettings;sa=database;' . $context['session_var'] . '=' . $context['session_id']);
  230. }
  231. // Fill the config array.
  232. prepareServerSettingsContext($config_vars);
  233. }
  234. // This function basically edits anything which is configuration and stored in the database, except for caching.
  235. function ModifyCookieSettings($return_config = false)
  236. {
  237. global $context, $scripturl, $txt, $sourcedir, $modSettings, $cookiename, $user_settings;
  238. // Define the variables we want to edit.
  239. $config_vars = array(
  240. // Cookies...
  241. array('cookiename', $txt['cookie_name'], 'file', 'text', 20),
  242. array('cookieTime', $txt['cookieTime'], 'db', 'int'),
  243. array('localCookies', $txt['localCookies'], 'db', 'check', false, 'localCookies'),
  244. array('globalCookies', $txt['globalCookies'], 'db', 'check', false, 'globalCookies'),
  245. array('secureCookies', $txt['secureCookies'], 'db', 'check', false, 'secureCookies', 'disabled' => !isset($_SERVER['HTTPS']) || !(strtolower($_SERVER['HTTPS']) == 'on' || strtolower($_SERVER['HTTPS']) == '1')),
  246. '',
  247. // Sessions
  248. array('databaseSession_enable', $txt['databaseSession_enable'], 'db', 'check', false, 'databaseSession_enable'),
  249. array('databaseSession_loose', $txt['databaseSession_loose'], 'db', 'check', false, 'databaseSession_loose'),
  250. array('databaseSession_lifetime', $txt['databaseSession_lifetime'], 'db', 'int', false, 'databaseSession_lifetime'),
  251. );
  252. if ($return_config)
  253. return $config_vars;
  254. $context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=cookie;save';
  255. $context['settings_title'] = $txt['cookies_sessions_settings'];
  256. // Saving settings?
  257. if (isset($_REQUEST['save']))
  258. {
  259. saveSettings($config_vars);
  260. // If the cookie name was changed, reset the cookie.
  261. if ($cookiename != $_POST['cookiename'])
  262. {
  263. $original_session_id = $context['session_id'];
  264. include_once($sourcedir . '/Subs-Auth.php');
  265. // Remove the old cookie.
  266. setLoginCookie(-3600, 0);
  267. // Set the new one.
  268. $cookiename = $_POST['cookiename'];
  269. setLoginCookie(60 * $modSettings['cookieTime'], $user_settings['id_member'], sha1($user_settings['passwd'] . $user_settings['password_salt']));
  270. redirectexit('action=admin;area=serversettings;sa=cookie;' . $context['session_var'] . '=' . $original_session_id, $context['server']['needs_login_fix']);
  271. }
  272. redirectexit('action=admin;area=serversettings;sa=cookie;' . $context['session_var'] . '=' . $context['session_id']);
  273. }
  274. // Fill the config array.
  275. prepareServerSettingsContext($config_vars);
  276. }
  277. // Simply modifying cache functions
  278. function ModifyCacheSettings($return_config = false)
  279. {
  280. global $context, $scripturl, $txt, $helptxt, $modSettings;
  281. // Define the variables we want to edit.
  282. $config_vars = array(
  283. // Only a couple of settings, but they are important
  284. array('select', 'cache_enable', array($txt['cache_off'], $txt['cache_level1'], $txt['cache_level2'], $txt['cache_level3'])),
  285. array('text', 'cache_memcached'),
  286. );
  287. if ($return_config)
  288. return $config_vars;
  289. // Saving again?
  290. if (isset($_GET['save']))
  291. {
  292. saveDBSettings($config_vars);
  293. // We have to manually force the clearing of the cache otherwise the changed settings might not get noticed.
  294. $modSettings['cache_enable'] = 1;
  295. cache_put_data('modSettings', null, 90);
  296. redirectexit('action=admin;area=serversettings;sa=cache;' . $context['session_var'] . '=' . $context['session_id']);
  297. }
  298. $context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=cache;save';
  299. $context['settings_title'] = $txt['caching_settings'];
  300. $context['settings_message'] = $txt['caching_information'];
  301. // Detect an optimizer?
  302. if (function_exists('eaccelerator_put'))
  303. $detected = 'eAccelerator';
  304. elseif (function_exists('mmcache_put'))
  305. $detected = 'MMCache';
  306. elseif (function_exists('apc_store'))
  307. $detected = 'APC';
  308. elseif (function_exists('output_cache_put'))
  309. $detected = 'Zend';
  310. elseif (function_exists('memcache_set'))
  311. $detected = 'Memcached';
  312. elseif (function_exists('xcache_set'))
  313. $detected = 'XCache';
  314. else
  315. $detected = 'no_caching';
  316. $context['settings_message'] = sprintf($context['settings_message'], $txt['detected_' . $detected]);
  317. // Prepare the template.
  318. prepareDBSettingContext($config_vars);
  319. }
  320. function ModifyLoadBalancingSettings($return_config = false)
  321. {
  322. global $txt, $scripturl, $context, $settings, $modSettings;
  323. // Setup a warning message, but disabled by default.
  324. $disabled = true;
  325. $context['settings_message'] = $txt['loadavg_disabled_conf'];
  326. if (strpos(strtolower(PHP_OS), 'win') === 0)
  327. $context['settings_message'] = $txt['loadavg_disabled_windows'];
  328. else
  329. {
  330. $modSettings['load_average'] = @file_get_contents('/proc/loadavg');
  331. if (!empty($modSettings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', $modSettings['load_average'], $matches) !== 0)
  332. $modSettings['load_average'] = (float) $matches[1];
  333. elseif (($modSettings['load_average'] = @`uptime`) !== null && preg_match('~load averages?: (\d+\.\d+), (\d+\.\d+), (\d+\.\d+)~i', $modSettings['load_average'], $matches) !== 0)
  334. $modSettings['load_average'] = (float) $matches[1];
  335. else
  336. unset($modSettings['load_average']);
  337. if (!empty($modSettings['load_average']))
  338. {
  339. $context['settings_message'] = sprintf($txt['loadavg_warning'], $modSettings['load_average']);
  340. $disabled = false;
  341. }
  342. }
  343. // Start with a simple checkbox.
  344. $config_vars = array(
  345. array('check', 'loadavg_enable'),
  346. );
  347. // Set the default values for each option.
  348. $default_values = array(
  349. 'loadavg_auto_opt' => '1.0',
  350. 'loadavg_search' => '2.5',
  351. 'loadavg_allunread' => '2.0',
  352. 'loadavg_unreadreplies' => '3.5',
  353. 'loadavg_show_posts' => '2.0',
  354. 'loadavg_forum' => '40.0',
  355. );
  356. // Loop through the settings.
  357. foreach ($default_values as $name => $value)
  358. {
  359. // Use the default value if the setting isn't set yet.
  360. $value = !isset($modSettings[$name]) ? $value : $modSettings[$name];
  361. $config_vars[] = array('text', $name, 'value' => $value, 'disabled' => $disabled);
  362. }
  363. if ($return_config)
  364. return $config_vars;
  365. $context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=loads;save';
  366. $context['settings_title'] = $txt['load_balancing_settings'];
  367. // Saving?
  368. if (isset($_GET['save']))
  369. {
  370. // Stupidity is not allowed.
  371. foreach ($_POST as $key => $value)
  372. {
  373. if (strpos($key, 'loadavg') === 0 || $key === 'loadavg_enable')
  374. continue;
  375. elseif ($key == 'loadavg_auto_opt' && $value <= 1)
  376. $_POST['loadavg_auto_opt'] = '1.0';
  377. elseif ($key == 'loadavg_forum' && $value < 10)
  378. $_POST['loadavg_forum'] = '10.0';
  379. elseif ($value < 2)
  380. $_POST[$key] = '2.0';
  381. }
  382. saveDBSettings($config_vars);
  383. redirectexit('action=admin;area=serversettings;sa=loads;' . $context['session_var'] . '=' . $context['session_id']);
  384. }
  385. prepareDBSettingContext($config_vars);
  386. }
  387. // This is the main function for the language area.
  388. function ManageLanguages()
  389. {
  390. global $context, $txt, $scripturl, $modSettings;
  391. loadLanguage('ManageSettings');
  392. $context['page_title'] = $txt['edit_languages'];
  393. $context['sub_template'] = 'show_settings';
  394. $subActions = array(
  395. 'edit' => 'ModifyLanguages',
  396. 'add' => 'AddLanguage',
  397. 'settings' => 'ModifyLanguageSettings',
  398. 'downloadlang' => 'DownloadLanguage',
  399. 'editlang' => 'ModifyLanguage',
  400. );
  401. // By default we're managing languages.
  402. $_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'edit';
  403. $context['sub_action'] = $_REQUEST['sa'];
  404. // Load up all the tabs...
  405. $context[$context['admin_menu_name']]['tab_data'] = array(
  406. 'title' => $txt['language_configuration'],
  407. 'description' => $txt['language_description'],
  408. );
  409. // Call the right function for this sub-acton.
  410. $subActions[$_REQUEST['sa']]();
  411. }
  412. // Interface for adding a new language
  413. function AddLanguage()
  414. {
  415. global $context, $sourcedir, $forum_version, $boarddir, $txt, $smcFunc, $scripturl;
  416. // Are we searching for new languages courtesy of Simple Machines?
  417. if (!empty($_POST['smf_add_sub']))
  418. {
  419. // Need fetch_web_data.
  420. require_once($sourcedir . '/Subs-Package.php');
  421. $context['smf_search_term'] = htmlspecialchars(trim($_POST['smf_add']));
  422. // We're going to use this URL.
  423. $url = 'http://download.simplemachines.org/fetch_language.php?version=' . urlencode(strtr($forum_version, array('SMF ' => '')));
  424. // Load the class file and stick it into an array.
  425. loadClassFile('Class-Package.php');
  426. $language_list = new xmlArray(fetch_web_data($url), true);
  427. // Check it exists.
  428. if (!$language_list->exists('languages'))
  429. $context['smf_error'] = 'no_response';
  430. else
  431. {
  432. $language_list = $language_list->path('languages[0]');
  433. $lang_files = $language_list->set('language');
  434. $context['smf_languages'] = array();
  435. foreach ($lang_files as $file)
  436. {
  437. // Were we searching?
  438. if (!empty($context['smf_search_term']) && strpos($file->fetch('name'), $smcFunc['strtolower']($context['smf_search_term'])) === false)
  439. continue;
  440. $context['smf_languages'][] = array(
  441. 'id' => $file->fetch('id'),
  442. 'name' => $smcFunc['ucwords']($file->fetch('name')),
  443. 'version' => $file->fetch('version'),
  444. 'utf8' => $file->fetch('utf8'),
  445. 'description' => $file->fetch('description'),
  446. 'link' => $scripturl . '?action=admin;area=languages;sa=downloadlang;did=' . $file->fetch('id') . ';' . $context['session_var'] . '=' . $context['session_id'],
  447. );
  448. }
  449. if (empty($context['smf_languages']))
  450. $context['smf_error'] = 'no_files';
  451. }
  452. }
  453. $context['sub_template'] = 'add_language';
  454. }
  455. // Download a language file from the Simple Machines website.
  456. function DownloadLanguage()
  457. {
  458. global $context, $sourcedir, $forum_version, $boarddir, $txt, $smcFunc, $scripturl, $modSettings;
  459. loadLanguage('ManageSettings');
  460. require_once($sourcedir . '/Subs-Package.php');
  461. // Clearly we need to know what to request.
  462. if (!isset($_GET['did']))
  463. fatal_lang_error('no_access', false);
  464. // Some lovely context.
  465. $context['download_id'] = $_GET['did'];
  466. $context['sub_template'] = 'download_language';
  467. $context['menu_data_' . $context['admin_menu_id']]['current_subsection'] = 'add';
  468. // Can we actually do the installation - and do they want to?
  469. if (!empty($_POST['do_install']) && !empty($_POST['copy_file']))
  470. {
  471. checkSession('get');
  472. $chmod_files = array();
  473. $install_files = array();
  474. // Check writable status.
  475. foreach ($_POST['copy_file'] as $file)
  476. {
  477. // Check it's not very bad.
  478. if (strpos($file, '..') !== false || (substr($file, 0, 6) != 'Themes' && !preg_match('~agreement\.[A-Za-z-_0-9]+\.txt$~', $file)))
  479. fatal_error($txt['languages_download_illegal_paths']);
  480. $chmod_files[] = $boarddir . '/' . $file;
  481. $install_files[] = $file;
  482. }
  483. // Call this in case we have work to do.
  484. $file_status = create_chmod_control($chmod_files);
  485. $files_left = $file_status['files']['notwritable'];
  486. // Something not writable?
  487. if (!empty($files_left))
  488. $context['error_message'] = $txt['languages_download_not_chmod'];
  489. // Otherwise, go go go!
  490. elseif (!empty($install_files))
  491. {
  492. $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);
  493. // Make sure the files aren't stuck in the cache.
  494. package_flush_cache();
  495. $context['install_complete'] = sprintf($txt['languages_download_complete_desc'], $scripturl . '?action=admin;area=languages');
  496. return;
  497. }
  498. }
  499. // Open up the old china.
  500. if (!isset($archive_content))
  501. $archive_content = read_tgz_file('http://download.simplemachines.org/fetch_language.php?version=' . urlencode(strtr($forum_version, array('SMF ' => ''))) . ';fetch=' . urlencode($_GET['did']), null);
  502. if (empty($archive_content))
  503. fatal_error($txt['add_language_error_no_response']);
  504. // Now for each of the files, let's do some *stuff*
  505. $context['files'] = array(
  506. 'lang' => array(),
  507. 'other' => array(),
  508. );
  509. $context['make_writable'] = array();
  510. foreach ($archive_content as $file)
  511. {
  512. $dirname = dirname($file['filename']);
  513. $filename = basename($file['filename']);
  514. $extension = substr($filename, strrpos($filename, '.') + 1);
  515. // Don't do anything with files we don't understand.
  516. if (!in_array($extension, array('php', 'jpg', 'gif', 'jpeg', 'png', 'txt')))
  517. continue;
  518. // Basic data.
  519. $context_data = array(
  520. 'name' => $filename,
  521. 'destination' => $boarddir . '/' . $file['filename'],
  522. 'generaldest' => $file['filename'],
  523. 'size' => $file['size'],
  524. // Does chmod status allow the copy?
  525. 'writable' => false,
  526. // Should we suggest they copy this file?
  527. 'default_copy' => true,
  528. // Does the file already exist, if so is it same or different?
  529. 'exists' => false,
  530. );
  531. // Does the file exist, is it different and can we overwrite?
  532. if (file_exists($boarddir . '/' . $file['filename']))
  533. {
  534. if (is_writable($boarddir . '/' . $file['filename']))
  535. $context_data['writable'] = true;
  536. // Finally, do we actually think the content has changed?
  537. if ($file['size'] == filesize($boarddir . '/' . $file['filename']) && $file['md5'] == md5_file($boarddir . '/' . $file['filename']))
  538. {
  539. $context_data['exists'] = 'same';
  540. $context_data['default_copy'] = false;
  541. }
  542. // Attempt to discover newline character differences.
  543. elseif ($file['md5'] == md5(preg_replace("~[\r]?\n~", "\r\n", file_get_contents($boarddir . '/' . $file['filename']))))
  544. {
  545. $context_data['exists'] = 'same';
  546. $context_data['default_copy'] = false;
  547. }
  548. else
  549. $context_data['exists'] = 'different';
  550. }
  551. // No overwrite?
  552. else
  553. {
  554. // Can we at least stick it in the directory...
  555. if (is_writable($boarddir . '/' . $dirname))
  556. $context_data['writable'] = true;
  557. }
  558. // 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...
  559. if ($extension == 'php' && preg_match('~\w+\.\w+(?:-utf8)?\.php~', $filename))
  560. {
  561. $context_data += array(
  562. 'version' => '??',
  563. 'cur_version' => false,
  564. 'version_compare' => 'newer',
  565. );
  566. list ($name, $language) = explode('.', $filename);
  567. // Let's get the new version, I like versions, they tell me that I'm up to date.
  568. if (preg_match('~\s*Version:\s+(.+?);\s*' . preg_quote($name, '~') . '~i', $file['preview'], $match) == 1)
  569. $context_data['version'] = $match[1];
  570. // Now does the old file exist - if so what is it's version?
  571. if (file_exists($boarddir . '/' . $file['filename']))
  572. {
  573. // OK - what is the current version?
  574. $fp = fopen($boarddir . '/' . $file['filename'], 'rb');
  575. $header = fread($fp, 768);
  576. fclose($fp);
  577. // Find the version.
  578. if (preg_match('~(?://|/\*)\s*Version:\s+(.+?);\s*' . preg_quote($name, '~') . '(?:[\s]{2}|\*/)~i', $header, $match) == 1)
  579. {
  580. $context_data['cur_version'] = $match[1];
  581. // How does this compare?
  582. if ($context_data['cur_version'] == $context_data['version'])
  583. $context_data['version_compare'] = 'same';
  584. elseif ($context_data['cur_version'] > $context_data['version'])
  585. $context_data['version_compare'] = 'older';
  586. // Don't recommend copying if the version is the same.
  587. if ($context_data['version_compare'] != 'newer')
  588. $context_data['default_copy'] = false;
  589. }
  590. }
  591. // Add the context data to the main set.
  592. $context['files']['lang'][] = $context_data;
  593. }
  594. else
  595. {
  596. // If we think it's a theme thing, work out what the theme is.
  597. if (substr($dirname, 0, 6) == 'Themes' && preg_match('~Themes[\\/]([^\\/]+)[\\/]~', $dirname, $match))
  598. $theme_name = $match[1];
  599. else
  600. $theme_name = 'misc';
  601. // Assume it's an image, could be an acceptance note etc but rare.
  602. $context['files']['images'][$theme_name][] = $context_data;
  603. }
  604. // Collect together all non-writable areas.
  605. if (!$context_data['writable'])
  606. $context['make_writable'][] = $context_data['destination'];
  607. }
  608. // So, I'm a perfectionist - let's get the theme names.
  609. $theme_indexes = array();
  610. foreach ($context['files']['images'] as $k => $dummy)
  611. $indexes[] = $k;
  612. $context['theme_names'] = array();
  613. if (!empty($indexes))
  614. {
  615. $value_data = array(
  616. 'query' => array(),
  617. 'params' => array(),
  618. );
  619. foreach ($indexes as $k => $index)
  620. {
  621. $value_data['query'][] = 'value LIKE {string:value_' . $k . '}';
  622. $value_data['params']['value_' . $k] = '%' . $index;
  623. }
  624. $request = $smcFunc['db_query']('', '
  625. SELECT id_theme, value
  626. FROM {db_prefix}themes
  627. WHERE id_member = {int:no_member}
  628. AND variable = {string:theme_dir}
  629. AND (' . implode(' OR ', $value_data['query']) . ')',
  630. array_merge($value_data['params'], array(
  631. 'no_member' => 0,
  632. 'theme_dir' => 'theme_dir',
  633. 'index_compare_explode' => 'value LIKE \'%' . implode('\' OR value LIKE \'%', $indexes) . '\'',
  634. ))
  635. );
  636. $themes = array();
  637. while ($row = $smcFunc['db_fetch_assoc']($request))
  638. {
  639. // Find the right one.
  640. foreach ($indexes as $index)
  641. if (strpos($row['value'], $index) !== false)
  642. $themes[$row['id_theme']] = $index;
  643. }
  644. $smcFunc['db_free_result']($request);
  645. if (!empty($themes))
  646. {
  647. // Now we have the id_theme we can get the pretty description.
  648. $request = $smcFunc['db_query']('', '
  649. SELECT id_theme, value
  650. FROM {db_prefix}themes
  651. WHERE id_member = {int:no_member}
  652. AND variable = {string:name}
  653. AND id_theme IN ({array_int:theme_list})',
  654. array(
  655. 'theme_list' => array_keys($themes),
  656. 'no_member' => 0,
  657. 'name' => 'name',
  658. )
  659. );
  660. while ($row = $smcFunc['db_fetch_assoc']($request))
  661. {
  662. // Now we have it...
  663. $context['theme_names'][$themes[$row['id_theme']]] = $row['value'];
  664. }
  665. $smcFunc['db_free_result']($request);
  666. }
  667. }
  668. // Before we go to far can we make anything writable, eh, eh?
  669. if (!empty($context['make_writable']))
  670. {
  671. // What is left to be made writable?
  672. $file_status = create_chmod_control($context['make_writable']);
  673. $context['still_not_writable'] = $file_status['files']['notwritable'];
  674. // Mark those which are now writable as such.
  675. foreach ($context['files'] as $type => $data)
  676. {
  677. if ($type == 'lang')
  678. {
  679. foreach ($data as $k => $file)
  680. if (!$file['writable'] && !in_array($file['destination'], $context['still_not_writable']))
  681. $context['files'][$type][$k]['writable'] = true;
  682. }
  683. else
  684. {
  685. foreach ($data as $theme => $files)
  686. foreach ($files as $k => $file)
  687. if (!$file['writable'] && !in_array($file['destination'], $context['still_not_writable']))
  688. $context['files'][$type][$theme][$k]['writable'] = true;
  689. }
  690. }
  691. // Are we going to need more language stuff?
  692. if (!empty($context['still_not_writable']))
  693. loadLanguage('Packages');
  694. }
  695. // This is the list for the main files.
  696. $listOptions = array(
  697. 'id' => 'lang_main_files_list',
  698. 'title' => $txt['languages_download_main_files'],
  699. 'get_items' => array(
  700. 'function' => create_function('', '
  701. global $context;
  702. return $context[\'files\'][\'lang\'];
  703. '),
  704. ),
  705. 'columns' => array(
  706. 'name' => array(
  707. 'header' => array(
  708. 'value' => $txt['languages_download_filename'],
  709. ),
  710. 'data' => array(
  711. 'function' => create_function('$rowData', '
  712. global $context, $txt;
  713. 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\'] : \'\');
  714. '),
  715. ),
  716. ),
  717. 'writable' => array(
  718. 'header' => array(
  719. 'value' => $txt['languages_download_writable'],
  720. ),
  721. 'data' => array(
  722. 'function' => create_function('$rowData', '
  723. global $txt;
  724. return \'<span style="color: \' . ($rowData[\'writable\'] ? \'green\' : \'red\') . \';">\' . ($rowData[\'writable\'] ? $txt[\'yes\'] : $txt[\'no\']) . \'</span>\';
  725. '),
  726. 'style' => 'text-align: center',
  727. ),
  728. ),
  729. 'version' => array(
  730. 'header' => array(
  731. 'value' => $txt['languages_download_version'],
  732. ),
  733. 'data' => array(
  734. 'function' => create_function('$rowData', '
  735. global $txt;
  736. return \'<span style="color: \' . ($rowData[\'version_compare\'] == \'older\' ? \'red\' : ($rowData[\'version_compare\'] == \'same\' ? \'orange\' : \'green\')) . \';">\' . $rowData[\'version\'] . \'</span>\';
  737. '),
  738. ),
  739. ),
  740. 'exists' => array(
  741. 'header' => array(
  742. 'value' => $txt['languages_download_exists'],
  743. ),
  744. 'data' => array(
  745. 'function' => create_function('$rowData', '
  746. global $txt;
  747. return $rowData[\'exists\'] ? ($rowData[\'exists\'] == \'same\' ? $txt[\'languages_download_exists_same\'] : $txt[\'languages_download_exists_different\']) : $txt[\'no\'];
  748. '),
  749. ),
  750. ),
  751. 'copy' => array(
  752. 'header' => array(
  753. 'value' => $txt['languages_download_copy'],
  754. ),
  755. 'data' => array(
  756. 'function' => create_function('$rowData', '
  757. return \'<input type="checkbox" name="copy_file[]" value="\' . $rowData[\'generaldest\'] . \'" \' . ($rowData[\'default_copy\'] ? \'checked="checked"\' : \'\') . \' class="input_check" />\';
  758. '),
  759. 'style' => 'text-align: center; width: 4%;',
  760. ),
  761. ),
  762. ),
  763. );
  764. // Kill the cache, as it is now invalid..
  765. if (!empty($modSettings['cache_enable']))
  766. {
  767. cache_put_data('known_languages', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  768. cache_put_data('known_languages_all', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  769. }
  770. require_once($sourcedir . '/Subs-List.php');
  771. createList($listOptions);
  772. $context['default_list'] = 'lang_main_files_list';
  773. }
  774. // This lists all the current languages and allows editing of them.
  775. function ModifyLanguages()
  776. {
  777. global $txt, $context, $scripturl;
  778. global $user_info, $smcFunc, $sourcedir, $language, $boarddir, $forum_version;
  779. // Setting a new default?
  780. if (!empty($_POST['set_default']) && !empty($_POST['def_language']))
  781. {
  782. checkSession();
  783. getLanguages(true, false);
  784. $lang_exists = false;
  785. foreach ($context['languages'] as $lang)
  786. {
  787. if ($_POST['def_language'] == $lang['filename'])
  788. {
  789. $lang_exists = true;
  790. break;
  791. }
  792. }
  793. if ($_POST['def_language'] != $language && $lang_exists)
  794. {
  795. require_once($sourcedir . '/Subs-Admin.php');
  796. updateSettingsFile(array('language' => '\'' . $_POST['def_language'] . '\''));
  797. $language = $_POST['def_language'];
  798. }
  799. }
  800. $listOptions = array(
  801. 'id' => 'language_list',
  802. 'items_per_page' => 20,
  803. 'base_href' => $scripturl . '?action=admin;area=languages',
  804. 'title' => $txt['edit_languages'],
  805. 'get_items' => array(
  806. 'function' => 'list_getLanguages',
  807. ),
  808. 'get_count' => array(
  809. 'function' => 'list_getNumLanguages',
  810. ),
  811. 'columns' => array(
  812. 'default' => array(
  813. 'header' => array(
  814. 'value' => $txt['languages_default'],
  815. ),
  816. 'data' => array(
  817. 'function' => create_function('$rowData', '
  818. return \'<input type="radio" name="def_language" value="\' . $rowData[\'id\'] . \'" \' . ($rowData[\'default\'] ? \'checked="checked"\' : \'\') . \' onclick="highlightSelected(\\\'list_language_list_\' . $rowData[\'id\'] . \'\\\');" class="input_radio" />\';
  819. '),
  820. 'style' => 'text-align: center; width: 8%;',
  821. ),
  822. ),
  823. 'name' => array(
  824. 'header' => array(
  825. 'value' => $txt['languages_lang_name'],
  826. ),
  827. 'data' => array(
  828. 'function' => create_function('$rowData', '
  829. global $scripturl, $context;
  830. return sprintf(\'<a href="%1$s?action=admin;area=languages;sa=editlang;lid=%2$s">%3$s</a>\', $scripturl, $rowData[\'id\'], $rowData[\'name\']);
  831. '),
  832. ),
  833. ),
  834. 'character_set' => array(
  835. 'header' => array(
  836. 'value' => $txt['languages_character_set'],
  837. ),
  838. 'data' => array(
  839. 'db_htmlsafe' => 'char_set',
  840. ),
  841. ),
  842. 'count' => array(
  843. 'header' => array(
  844. 'value' => $txt['languages_users'],
  845. ),
  846. 'data' => array(
  847. 'db_htmlsafe' => 'count',
  848. 'style' => 'text-align: center',
  849. ),
  850. ),
  851. 'locale' => array(
  852. 'header' => array(
  853. 'value' => $txt['languages_locale'],
  854. ),
  855. 'data' => array(
  856. 'db_htmlsafe' => 'locale',
  857. ),
  858. ),
  859. ),
  860. 'form' => array(
  861. 'href' => $scripturl . '?action=admin;area=languages',
  862. ),
  863. 'additional_rows' => array(
  864. array(
  865. 'position' => 'below_table_data',
  866. '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" />',
  867. 'style' => 'text-align: right;',
  868. ),
  869. ),
  870. // For highlighting the default.
  871. 'javascript' => '
  872. var prevClass = "";
  873. var prevDiv = "";
  874. function highlightSelected(box)
  875. {
  876. if (prevClass != "")
  877. prevDiv.className = prevClass;
  878. prevDiv = document.getElementById(box);
  879. prevClass = prevDiv.className;
  880. prevDiv.className = "highlight2";
  881. }
  882. highlightSelected("list_language_list_' . ($language == '' ? 'english' : $language). '");
  883. ',
  884. );
  885. // Display a warning if we cannot edit the default setting.
  886. if (!is_writable($boarddir . '/Settings.php'))
  887. $listOptions['additional_rows'][] = array(
  888. 'position' => 'after_title',
  889. 'value' => $txt['language_settings_writable'],
  890. 'class' => 'smalltext alert',
  891. );
  892. require_once($sourcedir . '/Subs-List.php');
  893. createList($listOptions);
  894. $context['sub_template'] = 'show_list';
  895. $context['default_list'] = 'language_list';
  896. }
  897. // How many languages?
  898. function list_getNumLanguages()
  899. {
  900. global $settings;
  901. // Return how many we have.
  902. return count(getLanguages(true, false));
  903. }
  904. // Fetch the actual language information.
  905. function list_getLanguages()
  906. {
  907. global $settings, $smcFunc, $language, $context, $txt;
  908. $languages = array();
  909. // Keep our old entries.
  910. $old_txt = $txt;
  911. $backup_actual_theme_dir = $settings['actual_theme_dir'];
  912. $backup_base_theme_dir = !empty($settings['base_theme_dir']) ? $settings['base_theme_dir'] : '';
  913. // Override these for now.
  914. $settings['actual_theme_dir'] = $settings['base_theme_dir'] = $settings['default_theme_dir'];
  915. getLanguages(true, false);
  916. // Put them back.
  917. $settings['actual_theme_dir'] = $backup_actual_theme_dir;
  918. if (!empty($backup_base_theme_dir))
  919. $settings['base_theme_dir'] = $backup_base_theme_dir;
  920. else
  921. unset($settings['base_theme_dir']);
  922. // Get the language files and data...
  923. foreach ($context['languages'] as $lang)
  924. {
  925. // Load the file to get the character set.
  926. require($settings['default_theme_dir'] . '/languages/index.' . $lang['filename'] . '.php');
  927. $languages[$lang['filename']] = array(
  928. 'id' => $lang['filename'],
  929. 'count' => 0,
  930. 'char_set' => $txt['lang_character_set'],
  931. 'default' => $language == $lang['filename'] || ($language == '' && $lang['filename'] == 'english'),
  932. 'locale' => $txt['lang_locale'],
  933. 'name' => $smcFunc['ucwords'](strtr($lang['filename'], array('_' => ' ', '-utf8' => ''))),
  934. );
  935. }
  936. // Work out how many people are using each language.
  937. $request = $smcFunc['db_query']('', '
  938. SELECT lngfile, COUNT(*) AS num_users
  939. FROM {db_prefix}members
  940. GROUP BY lngfile',
  941. array(
  942. )
  943. );
  944. while ($row = $smcFunc['db_fetch_assoc']($request))
  945. {
  946. // Default?
  947. if (empty($row['lngfile']) || !isset($languages[$row['lngfile']]))
  948. $row['lngfile'] = $language;
  949. if (!isset($languages[$row['lngfile']]) && isset($languages['english']))
  950. $languages['english']['count'] += $row['num_users'];
  951. elseif (isset($languages[$row['lngfile']]))
  952. $languages[$row['lngfile']]['count'] += $row['num_users'];
  953. }
  954. $smcFunc['db_free_result']($request);
  955. // Restore the current users language.
  956. $txt = $old_txt;
  957. // Return how many we have.
  958. return $languages;
  959. }
  960. // Edit language related settings.
  961. function ModifyLanguageSettings($return_config = false)
  962. {
  963. global $scripturl, $context, $txt, $boarddir, $settings, $smcFunc;
  964. // Warn the user if the backup of Settings.php failed.
  965. $settings_not_writable = !is_writable($boarddir . '/Settings.php');
  966. $settings_backup_fail = !@is_writable($boarddir . '/Settings_bak.php') || !@copy($boarddir . '/Settings.php', $boarddir . '/Settings_bak.php');
  967. /* If you're writing a mod, it's a bad idea to add things here....
  968. For each option:
  969. variable name, description, type (constant), size/possible values, helptext.
  970. OR an empty string for a horizontal rule.
  971. OR a string for a titled section. */
  972. $config_vars = array(
  973. 'language' => array('language', $txt['default_language'], 'file', 'select', array(), null, 'disabled' => $settings_not_writable),
  974. array('userLanguage', $txt['userLanguage'], 'db', 'check', null, 'userLanguage'),
  975. );
  976. if ($return_config)
  977. return $config_vars;
  978. // Get our languages. No cache and use utf8.
  979. getLanguages(false, false);
  980. foreach ($context['languages'] as $lang)
  981. $config_vars['language'][4][$lang['filename']] = array($lang['filename'], strtr($lang['name'], array('-utf8' => ' (UTF-8)')));
  982. // Saving settings?
  983. if (isset($_REQUEST['save']))
  984. {
  985. checkSession();
  986. saveSettings($config_vars);
  987. redirectexit('action=admin;area=languages;sa=settings');
  988. }
  989. // Setup the template stuff.
  990. $context['post_url'] = $scripturl . '?action=admin;area=languages;sa=settings;save';
  991. $context['settings_title'] = $txt['language_settings'];
  992. $context['save_disabled'] = $settings_not_writable;
  993. if ($settings_not_writable)
  994. $context['settings_message'] = '<div class="centertext"><strong>' . $txt['settings_not_writable'] . '</strong></div><br />';
  995. elseif ($settings_backup_fail)
  996. $context['settings_message'] = '<div class="centertext"><strong>' . $txt['admin_backup_fail'] . '</strong></div><br />';
  997. // Fill the config array.
  998. prepareServerSettingsContext($config_vars);
  999. }
  1000. // Edit a particular set of language entries.
  1001. function ModifyLanguage()
  1002. {
  1003. global $settings, $context, $smcFunc, $txt, $modSettings, $boarddir, $sourcedir, $language;
  1004. loadLanguage('ManageSettings');
  1005. // Select the languages tab.
  1006. $context['menu_data_' . $context['admin_menu_id']]['current_subsection'] = 'edit';
  1007. $context['page_title'] = $txt['edit_languages'];
  1008. $context['sub_template'] = 'modify_language_entries';
  1009. $context['lang_id'] = $_GET['lid'];
  1010. list($theme_id, $file_id) = empty($_REQUEST['tfid']) || strpos($_REQUEST['tfid'], '+') === false ? array(1, '') : explode('+', $_REQUEST['tfid']);
  1011. // Clean the ID - just in case.
  1012. preg_match('~([A-Za-z0-9_-]+)~', $context['lang_id'], $matches);
  1013. $context['lang_id'] = $matches[1];
  1014. // Get all the theme data.
  1015. $request = $smcFunc['db_query']('', '
  1016. SELECT id_theme, variable, value
  1017. FROM {db_prefix}themes
  1018. WHERE id_theme != {int:default_theme}
  1019. AND id_member = {int:no_member}
  1020. AND variable IN ({string:name}, {string:theme_dir})',
  1021. array(
  1022. 'default_theme' => 1,
  1023. 'no_member' => 0,
  1024. 'name' => 'name',
  1025. 'theme_dir' => 'theme_dir',
  1026. )
  1027. );
  1028. $themes = array(
  1029. 1 => array(
  1030. 'name' => $txt['dvc_default'],
  1031. 'theme_dir' => $settings['default_theme_dir'],
  1032. ),
  1033. );
  1034. while ($row = $smcFunc['db_fetch_assoc']($request))
  1035. $themes[$row['id_theme']][$row['variable']] = $row['value'];
  1036. $smcFunc['db_free_result']($request);
  1037. // This will be where we look
  1038. $lang_dirs = array();
  1039. // Check we have themes with a path and a name - just in case - and add the path.
  1040. foreach ($themes as $id => $data)
  1041. {
  1042. if (count($data) != 2)
  1043. unset($themes[$id]);
  1044. elseif (is_dir($data['theme_dir'] . '/languages'))
  1045. $lang_dirs[$id] = $data['theme_dir'] . '/languages';
  1046. // How about image directories?
  1047. if (is_dir($data['theme_dir'] . '/images/' . $context['lang_id']))
  1048. $images_dirs[$id] = $data['theme_dir'] . '/images/' . $context['lang_id'];
  1049. }
  1050. $current_file = $file_id ? $lang_dirs[$theme_id] . '/' . $file_id . '.' . $context['lang_id'] . '.php' : '';
  1051. // Now for every theme get all the files and stick them in context!
  1052. $context['possible_files'] = array();
  1053. foreach ($lang_dirs as $theme => $theme_dir)
  1054. {
  1055. // Open it up.
  1056. $dir = dir($theme_dir);
  1057. while ($entry = $dir->read())
  1058. {
  1059. // We're only after the files for this language.
  1060. if (preg_match('~^([A-Za-z]+)\.' . $context['lang_id'] . '\.php$~', $entry, $matches) == 0)
  1061. continue;
  1062. //!!! Temp!
  1063. if ($matches[1] == 'EmailTemplates')
  1064. continue;
  1065. if (!isset($context['possible_files'][$theme]))
  1066. $context['possible_files'][$theme] = array(
  1067. 'id' => $theme,
  1068. 'name' => $themes[$theme]['name'],
  1069. 'files' => array(),
  1070. );
  1071. $context['possible_files'][$theme]['files'][] = array(
  1072. 'id' => $matches[1],
  1073. 'name' => isset($txt['lang_file_desc_' . $matches[1]]) ? $txt['lang_file_desc_' . $matches[1]] : $matches[1],
  1074. 'selected' => $theme_id == $theme && $file_id == $matches[1],
  1075. );
  1076. }
  1077. $dir->close();
  1078. }
  1079. // We no longer wish to speak this language.
  1080. if (!empty($_POST['delete_main']) && $context['lang_id'] != 'english')
  1081. {
  1082. checkSession();
  1083. // !!! Todo: FTP Controls?
  1084. require_once($sourcedir . '/Subs-Package.php');
  1085. // First, Make a backup?
  1086. if (!empty($modSettings['package_make_backups']) && (!isset($_SESSION['last_backup_for']) || $_SESSION['last_backup_for'] != $context['lang_id'] . '$$$'))
  1087. {
  1088. $_SESSION['last_backup_for'] = $context['lang_id'] . '$$$';
  1089. package_create_backup('backup_lang_' . $context['lang_id']);
  1090. }
  1091. // Second, loop through the array to remove the files.
  1092. foreach ($lang_dirs as $curPath)
  1093. {
  1094. foreach ($context['possible_files'][1]['files'] as $lang)
  1095. if (file_exists($curPath . '/' . $lang['id'] . '.' . $context['lang_id'] . '.php'))
  1096. unlink($curPath . '/' . $lang['id'] . '.' . $context['lang_id'] . '.php');
  1097. // Check for the email template.
  1098. if (file_exists($curPath . '/EmailTemplates.' . $context['lang_id'] . '.php'))
  1099. unlink($curPath . '/EmailTemplates.' . $context['lang_id'] . '.php');
  1100. }
  1101. // Third, the agreement file.
  1102. if (file_exists($boarddir . '/agreement.' . $context['lang_id'] . '.txt'))
  1103. unlink($boarddir . '/agreement.' . $context['lang_id'] . '.txt');
  1104. // Fourth, a related images folder?
  1105. foreach ($images_dirs as $curPath)
  1106. if (is_dir($curPath))
  1107. deltree($curPath);
  1108. // Members can no longer use this language.
  1109. $smcFunc['db_query']('', '
  1110. UPDATE {db_prefix}members
  1111. SET lngfile = {string:empty_string}
  1112. WHERE lngfile = {string:current_language}',
  1113. array(
  1114. 'empty_string' => '',
  1115. 'current_language' => $context['lang_id'],
  1116. )
  1117. );
  1118. // Fifth, update getLanguages() cache.
  1119. if (!empty($modSettings['cache_enable']))
  1120. {
  1121. cache_put_data('known_languages', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  1122. cache_put_data('known_languages_all', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  1123. }
  1124. // Sixth, if we deleted the default language, set us back to english?
  1125. if ($context['lang_id'] == $language)
  1126. {
  1127. require_once($sourcedir . '/Subs-Admin.php');
  1128. $language = 'english';
  1129. updateSettingsFile(array('language' => '\'' . $language . '\''));
  1130. }
  1131. // Seventh, get out of here.
  1132. redirectexit('action=admin;area=languages;sa=edit;' . $context['session_var'] . '=' . $context['session_id']);
  1133. }
  1134. // Saving primary settings?
  1135. $madeSave = false;
  1136. if (!empty($_POST['save_main']) && !$current_file)
  1137. {
  1138. checkSession();
  1139. // Read in the current file.
  1140. $current_data = implode('', file($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php'));
  1141. // These are the replacements. old => new
  1142. $replace_array = array(
  1143. '~\$txt\[\'lang_character_set\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_character_set\'] = \'' . preg_replace('~[^\w-]~i', '', $_POST['character_set']) . '\';',
  1144. '~\$txt\[\'lang_locale\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_locale\'] = \'' . preg_replace('~[^\w-]~i', '', $_POST['locale']) . '\';',
  1145. '~\$txt\[\'lang_dictionary\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_dictionary\'] = \'' . preg_replace('~[^\w-]~i', '', $_POST['dictionary']) . '\';',
  1146. '~\$txt\[\'lang_spelling\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_spelling\'] = \'' . preg_replace('~[^\w-]~i', '', $_POST['spelling']) . '\';',
  1147. '~\$txt\[\'lang_rtl\'\]\s=\s[A-Za-z0-9]+;~' => '$txt[\'lang_rtl\'] = ' . (!empty($_POST['rtl']) ? 'true' : 'false') . ';',
  1148. );
  1149. $current_data = preg_replace(array_keys($replace_array), array_values($replace_array), $current_data);
  1150. $fp = fopen($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php', 'w+');
  1151. fwrite($fp, $current_data);
  1152. fclose($fp);
  1153. $madeSave = true;
  1154. }
  1155. // Quickly load index language entries.
  1156. $old_txt = $txt;
  1157. require($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php');
  1158. $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');
  1159. // Setup the primary settings context.
  1160. $context['primary_settings'] = array(
  1161. 'name' => $smcFunc['ucwords'](strtr($context['lang_id'], array('_' => ' ', '-utf8' => ''))),
  1162. 'character_set' => $txt['lang_character_set'],
  1163. 'locale' => $txt['lang_locale'],
  1164. 'dictionary' => $txt['lang_dictionary'],
  1165. 'spelling' => $txt['lang_spelling'],
  1166. 'rtl' => $txt['lang_rtl'],
  1167. );
  1168. // Restore normal service.
  1169. $txt = $old_txt;
  1170. // Are we saving?
  1171. $save_strings = array();
  1172. if (isset($_POST['save_entries']) && !empty($_POST['entry']))
  1173. {
  1174. checkSession();
  1175. // Clean each entry!
  1176. foreach ($_POST['entry'] as $k => $v)
  1177. {
  1178. // Only try to save if it's changed!
  1179. if ($_POST['entry'][$k] != $_POST['comp'][$k])
  1180. $save_strings[$k] = cleanLangString($v, false);
  1181. }
  1182. }
  1183. // If we are editing a file work away at that.
  1184. if ($current_file)
  1185. {
  1186. $context['entries_not_writable_message'] = is_writable($current_file) ? '' : sprintf($txt['lang_entries_not_writable'], $current_file);
  1187. $entries = array();
  1188. // We can't just require it I'm afraid - otherwise we pass in all kinds of variables!
  1189. $multiline_cache = '';
  1190. foreach (file($current_file) as $line)
  1191. {
  1192. // Got a new entry?
  1193. if ($line[0] == '$' && !empty($multiline_cache))
  1194. {
  1195. preg_match('~\$(helptxt|txt)\[\'(.+)\'\]\s=\s(.+);~', strtr($multiline_cache, array("\n" => '', "\t" => '')), $matches);
  1196. if (!empty($matches[3]))
  1197. {
  1198. $entries[$matches[2]] = array(
  1199. 'type' => $matches[1],
  1200. 'full' => $matches[0],
  1201. 'entry' => $matches[3],
  1202. );
  1203. $multiline_cache = '';
  1204. }
  1205. }
  1206. $multiline_cache .= $line . "\n";
  1207. }
  1208. // Last entry to add?
  1209. if ($multiline_cache)
  1210. {
  1211. preg_match('~\$(helptxt|txt)\[\'(.+)\'\]\s=\s(.+);~', strtr($multiline_cache, array("\n" => '', "\t" => '')), $matches);
  1212. if (!empty($matches[3]))
  1213. $entries[$matches[2]] = array(
  1214. 'type' => $matches[1],
  1215. 'full' => $matches[0],
  1216. 'entry' => $matches[3],
  1217. );
  1218. }
  1219. // These are the entries we can definitely save.
  1220. $final_saves = array();
  1221. $context['file_entries'] = array();
  1222. foreach ($entries as $entryKey => $entryValue)
  1223. {
  1224. // Ignore some things we set separately.
  1225. $ignore_files = array('lang_character_set', 'lang_locale', 'lang_dictionary', 'lang_spelling', 'lang_rtl');
  1226. if (in_array($entryKey, $ignore_files))
  1227. continue;
  1228. // These are arrays that need breaking out.
  1229. $arrays = array('days', 'days_short', 'months', 'months_titles', 'months_short');
  1230. if (in_array($entryKey, $arrays))
  1231. {
  1232. // Get off the first bits.
  1233. $entryValue['entry'] = substr($entryValue['entry'], strpos($entryValue['entry'], '(') + 1, strrpos($entryValue['entry'], ')') - strpos($entryValue['entry'], '('));
  1234. $entryValue['entry'] = explode(',', strtr($entryValue['entry'], array(' ' => '')));
  1235. // Now create an entry for each item.
  1236. $cur_index = 0;
  1237. $save_cache = array(
  1238. 'enabled' => false,
  1239. 'entries' => array(),
  1240. );
  1241. foreach ($entryValue['entry'] as $id => $subValue)
  1242. {
  1243. // Is this a new index?
  1244. if (preg_match('~^(\d+)~', $subValue, $matches))
  1245. {
  1246. $cur_index = $matches[1];
  1247. $subValue = substr($subValue, strpos($subValue, '\''));
  1248. }
  1249. // Clean up some bits.
  1250. $subValue = strtr($subValue, array('"' => '', '\'' => '', ')' => ''));
  1251. // Can we save?
  1252. if (isset($save_strings[$entryKey . '-+- ' . $cur_index]))
  1253. {
  1254. $save_cache['entries'][$cur_index] = strtr($save_strings[$entryKey . '-+- ' . $cur_index], array('\'' => ''));
  1255. $save_cache['enabled'] = true;
  1256. }
  1257. else
  1258. $save_cache['entries'][$cur_index] = $subValue;
  1259. $context['file_entries'][] = array(
  1260. 'key' => $entryKey . '-+- ' . $cur_index,
  1261. 'value' => $subValue,
  1262. 'rows' => 1,
  1263. );
  1264. $cur_index++;
  1265. }
  1266. // Do we need to save?
  1267. if ($save_cache['enabled'])
  1268. {
  1269. // Format the string, checking the indexes first.
  1270. $items = array();
  1271. $cur_index = 0;
  1272. foreach ($save_cache['entries'] as $k2 => $v2)
  1273. {
  1274. // Manually show the custom index.
  1275. if ($k2 != $cur_index)
  1276. {
  1277. $items[] = $k2 . ' => \'' . $v2 . '\'';
  1278. $cur_index = $k2;
  1279. }
  1280. else
  1281. $items[] = '\'' . $v2 . '\'';
  1282. $cur_index++;
  1283. }
  1284. // Now create the string!
  1285. $final_saves[$entryKey] = array(
  1286. 'find' => $entryValue['full'],
  1287. 'replace' => '$' . $entryValue['type'] . '[\'' . $entryKey . '\'] = array(' . implode(', ', $items) . ');',
  1288. );
  1289. }
  1290. }
  1291. else
  1292. {
  1293. // Saving?
  1294. if (isset($save_strings[$entryKey]) && $save_strings[$entryKey] != $entryValue['entry'])
  1295. {
  1296. // !!! Fix this properly.
  1297. if ($save_strings[$entryKey] == '')
  1298. $save_strings[$entryKey] = '\'\'';
  1299. // Set the new value.
  1300. $entryValue['entry'] = $save_strings[$entryKey];
  1301. // And we know what to save now!
  1302. $final_saves[$entryKey] = array(
  1303. 'find' => $entryValue['full'],
  1304. 'replace' => '$' . $entryValue['type'] . '[\'' . $entryKey . '\'] = ' . $save_strings[$entryKey] . ';',
  1305. );
  1306. }
  1307. $editing_string = cleanLangString($entryValue['entry'], true);
  1308. $context['file_entries'][] = array(
  1309. 'key' => $entryKey,
  1310. 'value' => $editing_string,
  1311. 'rows' => (int) (strlen($editing_string) / 38) + substr_count($editing_string, "\n") + 1,
  1312. );
  1313. }
  1314. }
  1315. // Any saves to make?
  1316. if (!empty($final_saves))
  1317. {
  1318. checkSession();
  1319. $file_contents = implode('', file($current_file));
  1320. foreach ($final_saves as $save)
  1321. $file_contents = strtr($file_contents, array($save['find'] => $save['replace']));
  1322. // Save the actual changes.
  1323. $fp = fopen($current_file, 'w+');
  1324. fwrite($fp, $file_contents);
  1325. fclose($fp);
  1326. $madeSave = true;
  1327. }
  1328. // Another restore.
  1329. $txt = $old_txt;
  1330. }
  1331. // If we saved, redirect.
  1332. if ($madeSave)
  1333. redirectexit('action=admin;area=languages;sa=editlang;lid=' . $context['lang_id']);
  1334. }
  1335. // This function could be two functions - either way it cleans language entries to/from display.
  1336. function cleanLangString($string, $to_display = true)
  1337. {
  1338. global $smcFunc;
  1339. // If going to display we make sure it doesn't have any HTML in it - etc.
  1340. $new_string = '';
  1341. if ($to_display)
  1342. {
  1343. // Are we in a string (0 = no, 1 = single quote, 2 = parsed)
  1344. $in_string = 0;
  1345. $is_escape = false;
  1346. for ($i = 0; $i < strlen($string); $i++)
  1347. {
  1348. // Handle ecapes first.
  1349. if ($string{$i} == '\\')
  1350. {
  1351. // Toggle the escape.
  1352. $is_escape = !$is_escape;
  1353. // If we're now escaped don't add this string.
  1354. if ($is_escape)
  1355. continue;
  1356. }
  1357. // Special case - parsed string with line break etc?
  1358. elseif (($string{$i} == 'n' || $string{$i} == 't') && $in_string == 2 && $is_escape)
  1359. {
  1360. // Put the escape back...
  1361. $new_string .= $string{$i} == 'n' ? "\n" : "\t";
  1362. $is_escape = false;
  1363. continue;
  1364. }
  1365. // Have we got a single quote?
  1366. elseif ($string{$i} == '\'')
  1367. {
  1368. // Already in a parsed string, or escaped in a linear string, means we print it - otherwise something special.
  1369. if ($in_string != 2 && ($in_string != 1 || !$is_escape))
  1370. {
  1371. // Is it the end of a single quote string?
  1372. if ($in_string == 1)
  1373. $in_string = 0;
  1374. // Otherwise it's the start!
  1375. else
  1376. $in_string = 1;
  1377. // Don't actually include this character!
  1378. continue;
  1379. }
  1380. }
  1381. // Otherwise a double quote?
  1382. elseif ($string{$i} == '"')
  1383. {
  1384. // Already in a single quote string, or escaped in a parsed string, means we print it - otherwise something special.
  1385. if ($in_string != 1 && ($in_string != 2 || !$is_escape))
  1386. {
  1387. // Is it the end of a double quote string?
  1388. if ($in_string == 2)
  1389. $in_string = 0;
  1390. // Otherwise it's the start!
  1391. else
  1392. $in_string = 2;
  1393. // Don't actually include this character!
  1394. continue;
  1395. }
  1396. }
  1397. // A join/space outside of a string is simply removed.
  1398. elseif ($in_string == 0 && (empty($string{$i}) || $string{$i} == '.'))
  1399. continue;
  1400. // Start of a variable?
  1401. elseif ($in_string == 0 && $string{$i} == '$')
  1402. {
  1403. // Find the whole of it!
  1404. preg_match('~([\$A-Za-z0-9\'\[\]_-]+)~', substr($string, $i), $matches);
  1405. if (!empty($matches[1]))
  1406. {
  1407. // Come up with some pseudo thing to indicate this is a var.
  1408. //!!! Do better than this, please!
  1409. $new_string .= '{%' . $matches[1] . '%}';
  1410. // We're not going to reparse this.
  1411. $i += strlen($matches[1]) - 1;
  1412. }
  1413. continue;
  1414. }
  1415. // Right, if we're outside of a string we have DANGER, DANGER!
  1416. elseif ($in_string == 0)
  1417. {
  1418. continue;
  1419. }
  1420. // Actually add the character to the string!
  1421. $new_string .= $string{$i};
  1422. // If anything was escaped it ain't any longer!
  1423. $is_escape = false;
  1424. }
  1425. // Unhtml then rehtml the whole thing!
  1426. $new_string = htmlspecialchars(un_htmlspecialchars($new_string));
  1427. }
  1428. else
  1429. {
  1430. // Keep track of what we're doing...
  1431. $in_string = 0;
  1432. // This is for deciding whether to HTML a quote.
  1433. $in_html = false;
  1434. for ($i = 0; $i < strlen($string); $i++)
  1435. {
  1436. // Handle line breaks!
  1437. if ($string{$i} == "\n" || $string{$i} == "\t")
  1438. {
  1439. // Are we in a string? Is it the right type?
  1440. if ($in_string == 1)
  1441. {
  1442. // Change type!
  1443. $new_string .= '\' . "\\' . ($string{$i} == "\n" ? 'n' : 't');
  1444. $in_string = 2;
  1445. }
  1446. elseif ($in_string == 2)
  1447. $new_string .= '\\' . ($string{$i} == "\n" ? 'n' : 't');
  1448. // Otherwise start one off - joining if required.
  1449. else
  1450. $new_string .= ($new_string ? ' . ' : '') . '"\\' . ($string{$i} == "\n" ? 'n' : 't');
  1451. continue;
  1452. }
  1453. // We don't do parsed strings apart from for breaks.
  1454. elseif ($in_string == 2)
  1455. {
  1456. $in_string = 0;
  1457. $new_string .= '"';
  1458. }
  1459. // Not in a string yet?
  1460. if ($in_string != 1)
  1461. {
  1462. $in_string = 1;
  1463. $new_string .= ($new_string ? ' . ' : '') . '\'';
  1464. }
  1465. // Is this a variable?
  1466. if ($string{$i} == '{' && $string{$i + 1} == '%' && $string{$i + 2} == '$')
  1467. {
  1468. // Grab the variable.
  1469. preg_match('~\{%([\$A-Za-z0-9\'\[\]_-]+)%\}~', substr($string, $i), $matches);
  1470. if (!empty($matches[1]))
  1471. {
  1472. if ($in_string == 1)
  1473. $new_string .= '\' . ';
  1474. elseif ($new_string)
  1475. $new_string .= ' . ';
  1476. $new_string .= $matches[1];
  1477. $i += strlen($matches[1]) + 3;
  1478. $in_string = 0;
  1479. }
  1480. continue;
  1481. }
  1482. // Is this a lt sign?
  1483. elseif ($string{$i} == '<')
  1484. {
  1485. // Probably HTML?
  1486. if ($string{$i + 1} != ' ')
  1487. $in_html = true;
  1488. // Assume we need an entity...
  1489. else
  1490. {
  1491. $new_string .= '&lt;';
  1492. continue;
  1493. }
  1494. }
  1495. // What about gt?
  1496. elseif ($string{$i} == '>')
  1497. {
  1498. // Will it be HTML?
  1499. if ($in_html)
  1500. $in_html = false;
  1501. // Otherwise we need an entity...
  1502. else
  1503. {
  1504. $new_string .= '&gt;';
  1505. continue;
  1506. }
  1507. }
  1508. // Is it a slash? If so escape it...
  1509. if ($string{$i} == '\\')
  1510. $new_string .= '\\';
  1511. // The infamous double quote?
  1512. elseif ($string{$i} == '"')
  1513. {
  1514. // If we're in HTML we leave it as a quote - otherwise we entity it.
  1515. if (!$in_html)
  1516. {
  1517. $new_string .= '&quot;';
  1518. continue;
  1519. }
  1520. }
  1521. // A single quote?
  1522. elseif ($string{$i} == '\'')
  1523. {
  1524. // Must be in a string so escape it.
  1525. $new_string .= '\\';
  1526. }
  1527. // Finally add the character to the string!
  1528. $new_string .= $string{$i};
  1529. }
  1530. // If we ended as a string then close it off.
  1531. if ($in_string == 1)
  1532. $new_string .= '\'';
  1533. elseif ($in_string == 2)
  1534. $new_string .= '"';
  1535. }
  1536. return $new_string;
  1537. }
  1538. // Helper function, it sets up the context for the manage server settings.
  1539. function prepareServerSettingsContext(&$config_vars)
  1540. {
  1541. global $context, $modSettings;
  1542. $context['config_vars'] = array();
  1543. foreach ($config_vars as $identifier => $config_var)
  1544. {
  1545. if (!is_array($config_var) || !isset($config_var[1]))
  1546. $context['config_vars'][] = $config_var;
  1547. else
  1548. {
  1549. $varname = $config_var[0];
  1550. global $$varname;
  1551. $context['config_vars'][] = array(
  1552. 'label' => $config_var[1],
  1553. 'help' => isset($config_var[5]) ? $config_var[5] : '',
  1554. 'type' => $config_var[3],
  1555. 'size' => empty($config_var[4]) ? 0 : $config_var[4],
  1556. 'data' => isset($config_var[4]) && is_array($config_var[4]) ? $config_var[4] : array(),
  1557. 'name' => $config_var[0],
  1558. 'value' => $config_var[2] == 'file' ? htmlspecialchars($$varname) : (isset($modSettings[$config_var[0]]) ? htmlspecialchars($modSettings[$config_var[0]]) : (in_array($config_var[3], array('int', 'float')) ? 0 : '')),
  1559. 'disabled' => !empty($context['settings_not_writable']) || !empty($config_var['disabled']),
  1560. 'invalid' => false,
  1561. 'javascript' => '',
  1562. 'preinput' => '',
  1563. 'postinput' => '',
  1564. );
  1565. }
  1566. }
  1567. }
  1568. // Helper function, it sets up the context for database settings.
  1569. function prepareDBSettingContext(&$config_vars)
  1570. {
  1571. global $txt, $helptxt, $context, $modSettings, $sourcedir;
  1572. loadLanguage('Help');
  1573. $context['config_vars'] = array();
  1574. $inlinePermissions = array();
  1575. $bbcChoice = array();
  1576. foreach ($config_vars as $config_var)
  1577. {
  1578. // HR?
  1579. if (!is_array($config_var))
  1580. $context['config_vars'][] = $config_var;
  1581. else
  1582. {
  1583. // If it has no name it doesn't have any purpose!
  1584. if (empty($config_var[1]))
  1585. continue;
  1586. // Special case for inline permissions
  1587. if ($config_var[0] == 'permissions' && allowedTo('manage_permissions'))
  1588. $inlinePermissions[] = $config_var[1];
  1589. elseif ($config_var[0] == 'permissions')
  1590. continue;
  1591. // Are we showing the BBC selection box?
  1592. if ($config_var[0] == 'bbc')
  1593. $bbcChoice[] = $config_var[1];
  1594. $context['config_vars'][$config_var[1]] = array(
  1595. 'label' => isset($config_var['text_label']) ? $config_var['text_label'] : (isset($txt[$config_var[1]]) ? $txt[$config_var[1]] : (isset($config_var[3]) && !is_array($config_var[3]) ? $config_var[3] : '')),
  1596. 'help' => isset($helptxt[$config_var[1]]) ? $config_var[1] : '',
  1597. 'type' => $config_var[0],
  1598. 'size' => !empty($config_var[2]) && !is_array($config_var[2]) ? $config_var[2] : (in_array($config_var[0], array('int', 'float')) ? 6 : 0),
  1599. 'data' => array(),
  1600. 'name' => $config_var[1],
  1601. 'value' => isset($modSettings[$config_var[1]]) ? ($config_var[0] == 'select' ? $modSettings[$config_var[1]] : htmlspecialchars($modSettings[$config_var[1]])) : (in_array($config_var[0], array('int', 'float')) ? 0 : ''),
  1602. 'disabled' => false,
  1603. 'invalid' => !empty($config_var['invalid']),
  1604. 'javascript' => '',
  1605. 'var_message' => !empty($config_var['message']) && isset($txt[$config_var['message']]) ? $txt[$config_var['message']] : '',
  1606. 'preinput' => isset($config_var['preinput']) ? $config_var['preinput'] : '',
  1607. 'postinput' => isset($config_var['postinput']) ? $config_var['postinput'] : '',
  1608. );
  1609. // If this is a select box handle any data.
  1610. if (!empty($config_var[2]) && is_array($config_var[2]))
  1611. {
  1612. // If we allow multiple selections, we need to adjust a few things.
  1613. if ($config_var[0] == 'select' && !empty($config_var['multiple']))
  1614. {
  1615. $context['config_vars'][$config_var[1]]['name'] .= '[]';
  1616. $context['config_vars'][$config_var[1]]['value'] = unserialize($context['config_vars'][$config_var[1]]['value']);
  1617. }
  1618. // If it's associative
  1619. if (isset($config_var[2][0]) && is_array($config_var[2][0]))
  1620. $context['config_vars'][$config_var[1]]['data'] = $config_var[2];
  1621. else
  1622. {
  1623. foreach ($config_var[2] as $key => $item)
  1624. $context['config_vars'][$config_var[1]]['data'][] = array($key, $item);
  1625. }
  1626. }
  1627. // Finally allow overrides - and some final cleanups.
  1628. foreach ($config_var as $k => $v)
  1629. {
  1630. if (!is_numeric($k))
  1631. {
  1632. if (substr($k, 0, 2) == 'on')
  1633. $context['config_vars'][$config_var[1]]['javascript'] .= ' ' . $k . '="' . $v . '"';
  1634. else
  1635. $context['config_vars'][$config_var[1]][$k] = $v;
  1636. }
  1637. // See if there are any other labels that might fit?
  1638. if (isset($txt['setting_' . $config_var[1]]))
  1639. $context['config_vars'][$config_var[1]]['label'] = $txt['setting_' . $config_var[1]];
  1640. elseif (isset($txt['groups_' . $config_var[1]]))
  1641. $context['config_vars'][$config_var[1]]['label'] = $txt['groups_' . $config_var[1]];
  1642. }
  1643. // Set the subtext in case it's part of the label.
  1644. // !!! Temporary. Preventing divs inside label tags.
  1645. $divPos = strpos($context['config_vars'][$config_var[1]]['label'], '<div');
  1646. if ($divPos !== false)
  1647. {
  1648. $context['config_vars'][$config_var[1]]['subtext'] = preg_replace('~</?div[^>]*>~', '', substr($context['config_vars'][$config_var[1]]['label'], $divPos));
  1649. $context['config_vars'][$config_var[1]]['label'] = substr($context['config_vars'][$config_var[1]]['label'], 0, $divPos);
  1650. }
  1651. }
  1652. }
  1653. // If we have inline permissions we need to prep them.
  1654. if (!empty($inlinePermissions) && allowedTo('manage_permissions'))
  1655. {
  1656. require_once($sourcedir . '/ManagePermissions.php');
  1657. init_inline_permissions($inlinePermissions, isset($context['permissions_excluded']) ? $context['permissions_excluded'] : array());
  1658. }
  1659. // What about any BBC selection boxes?
  1660. if (!empty($bbcChoice))
  1661. {
  1662. // What are the options, eh?
  1663. $temp = parse_bbc(false);
  1664. $bbcTags = array();
  1665. foreach ($temp as $tag)
  1666. $bbcTags[] = $tag['tag'];
  1667. $bbcTags = array_unique($bbcTags);
  1668. $totalTags = count($bbcTags);
  1669. // The number of columns we want to show the BBC tags in.
  1670. $numColumns = isset($context['num_bbc_columns']) ? $context['num_bbc_columns'] : 3;
  1671. // Start working out the context stuff.
  1672. $context['bbc_columns'] = array();
  1673. $tagsPerColumn = ceil($totalTags / $numColumns);
  1674. $col = 0; $i = 0;
  1675. foreach ($bbcTags as $tag)
  1676. {
  1677. if ($i % $tagsPerColumn == 0 && $i != 0)
  1678. $col++;
  1679. $context['bbc_columns'][$col][] = array(
  1680. 'tag' => $tag,
  1681. // !!! 'tag_' . ?
  1682. 'show_help' => isset($helptxt[$tag]),
  1683. );
  1684. $i++;
  1685. }
  1686. // Now put whatever BBC options we may have into context too!
  1687. $context['bbc_sections'] = array();
  1688. foreach ($bbcChoice as $bbc)
  1689. {
  1690. $context['bbc_sections'][$bbc] = array(
  1691. 'title' => isset($txt['bbc_title_' . $bbc]) ? $txt['bbc_title_' . $bbc] : $txt['bbcTagsToUse_select'],
  1692. 'disabled' => empty($modSettings['bbc_disabled_' . $bbc]) ? array() : $modSettings['bbc_disabled_' . $bbc],
  1693. 'all_selected' => empty($modSettings['bbc_disabled_' . $bbc]),
  1694. );
  1695. }
  1696. }
  1697. }
  1698. // Helper function. Saves settings by putting them in Settings.php or saving them in the settings table.
  1699. function saveSettings(&$config_vars)
  1700. {
  1701. global $boarddir, $sc, $cookiename, $modSettings, $user_settings;
  1702. global $sourcedir, $context, $cachedir;
  1703. // Fix the darn stupid cookiename! (more may not be allowed, but these for sure!)
  1704. if (isset($_POST['cookiename']))
  1705. $_POST['cookiename'] = preg_replace('~[,;\s\.$]+~' . ($context['utf8'] ? 'u' : ''), '', $_POST['cookiename']);
  1706. // Fix the forum's URL if necessary.
  1707. if (isset($_POST['boardurl']))
  1708. {
  1709. if (substr($_POST['boardurl'], -10) == '/index.php')
  1710. $_POST['boardurl'] = substr($_POST['boardurl'], 0, -10);
  1711. elseif (substr($_POST['boardurl'], -1) == '/')
  1712. $_POST['boardurl'] = substr($_POST['boardurl'], 0, -1);
  1713. if (substr($_POST['boardurl'], 0, 7) != 'http://' && substr($_POST['boardurl'], 0, 7) != 'file://' && substr($_POST['boardurl'], 0, 8) != 'https://')
  1714. $_POST['boardurl'] = 'http://' . $_POST['boardurl'];
  1715. }
  1716. // Any passwords?
  1717. $config_passwords = array(
  1718. 'db_passwd',
  1719. 'ssi_db_passwd',
  1720. );
  1721. // All the strings to write.
  1722. $config_strs = array(
  1723. 'mtitle', 'mmessage',
  1724. 'language', 'mbname', 'boardurl',
  1725. 'cookiename',
  1726. 'webmaster_email',
  1727. 'db_name', 'db_user', 'db_server', 'db_prefix', 'ssi_db_user',
  1728. 'boarddir', 'sourcedir', 'cachedir',
  1729. );
  1730. // All the numeric variables.
  1731. $config_ints = array(
  1732. );
  1733. // All the checkboxes.
  1734. $config_bools = array(
  1735. 'db_persist', 'db_error_send',
  1736. 'maintenance',
  1737. );
  1738. // Now sort everything into a big array, and figure out arrays and etc.
  1739. $new_settings = array();
  1740. foreach ($config_passwords as $config_var)
  1741. {
  1742. if (isset($_POST[$config_var][1]) && $_POST[$config_var][0] == $_POST[$config_var][1])
  1743. $new_settings[$config_var] = '\'' . addcslashes($_POST[$config_var][0], '\'\\') . '\'';
  1744. }
  1745. foreach ($config_strs as $config_var)
  1746. {
  1747. if (isset($_POST[$config_var]))
  1748. $new_settings[$config_var] = '\'' . addcslashes($_POST[$config_var], '\'\\') . '\'';
  1749. }
  1750. foreach ($config_ints as $config_var)
  1751. {
  1752. if (isset($_POST[$config_var]))
  1753. $new_settings[$config_var] = (int) $_POST[$config_var];
  1754. }
  1755. foreach ($config_bools as $key)
  1756. {
  1757. if (!empty($_POST[$key]))
  1758. $new_settings[$key] = '1';
  1759. else
  1760. $new_settings[$key] = '0';
  1761. }
  1762. // Save the relevant settings in the Settings.php file.
  1763. require_once($sourcedir . '/Subs-Admin.php');
  1764. updateSettingsFile($new_settings);
  1765. // Now loopt through the remaining (database-based) settings.
  1766. $new_settings = array();
  1767. foreach ($config_vars as $config_var)
  1768. {
  1769. // We just saved the file-based settings, so skip their definitions.
  1770. if (!is_array($config_var) || $config_var[2] == 'file')
  1771. continue;
  1772. // Rewrite the definition a bit.
  1773. $new_settings[] = array($config_var[3], $config_var[0]);
  1774. }
  1775. // Save the new database-based settings, if any.
  1776. if (!empty($new_settings))
  1777. saveDBSettings($new_settings);
  1778. }
  1779. // Helper function for saving database settings.
  1780. function saveDBSettings(&$config_vars)
  1781. {
  1782. global $sourcedir, $context;
  1783. $inlinePermissions = array();
  1784. foreach ($config_vars as $var)
  1785. {
  1786. if (!isset($var[1]) || (!isset($_POST[$var[1]]) && $var[0] != 'check' && $var[0] != 'permissions' && ($var[0] != 'bbc' || !isset($_POST[$var[1] . '_enabledTags']))))
  1787. continue;
  1788. // Checkboxes!
  1789. elseif ($var[0] == 'check')
  1790. $setArray[$var[1]] = !empty($_POST[$var[1]]) ? '1' : '0';
  1791. // Select boxes!
  1792. elseif ($var[0] == 'select' && in_array($_POST[$var[1]], array_keys($var[2])))
  1793. $setArray[$var[1]] = $_POST[$var[1]];
  1794. elseif ($var[0] == 'select' && !empty($var['multiple']) && array_intersect($_POST[$var[1]], array_keys($var[2])) != array())
  1795. {
  1796. // For security purposes we validate this line by line.
  1797. $options = array();
  1798. foreach ($_POST[$var[1]] as $invar)
  1799. if (in_array($invar, array_keys($var[2])))
  1800. $options[] = $invar;
  1801. $setArray[$var[1]] = serialize($options);
  1802. }
  1803. // Integers!
  1804. elseif ($var[0] == 'int')
  1805. $setArray[$var[1]] = (int) $_POST[$var[1]];
  1806. // Floating point!
  1807. elseif ($var[0] == 'float')
  1808. $setArray[$var[1]] = (float) $_POST[$var[1]];
  1809. // Text!
  1810. elseif ($var[0] == 'text' || $var[0] == 'large_text')
  1811. $setArray[$var[1]] = $_POST[$var[1]];
  1812. // Passwords!
  1813. elseif ($var[0] == 'password')
  1814. {
  1815. if (isset($_POST[$var[1]][1]) && $_POST[$var[1]][0] == $_POST[$var[1]][1])
  1816. $setArray[$var[1]] = $_POST[$var[1]][0];
  1817. }
  1818. // BBC.
  1819. elseif ($var[0] == 'bbc')
  1820. {
  1821. $bbcTags = array();
  1822. foreach (parse_bbc(false) as $tag)
  1823. $bbcTags[] = $tag['tag'];
  1824. if (!isset($_POST[$var[1] . '_enabledTags']))
  1825. $_POST[$var[1] . '_enabledTags'] = array();
  1826. elseif (!is_array($_POST[$var[1] . '_enabledTags']))
  1827. $_POST[$var[1] . '_enabledTags'] = array($_POST[$var[1] . '_enabledTags']);
  1828. $setArray[$var[1]] = implode(',', array_diff($bbcTags, $_POST[$var[1] . '_enabledTags']));
  1829. }
  1830. // Permissions?
  1831. elseif ($var[0] == 'permissions')
  1832. $inlinePermissions[] = $var[1];
  1833. }
  1834. if (!empty($setArray))
  1835. updateSettings($setArray);
  1836. // If we have inline permissions we need to save them.
  1837. if (!empty($inlinePermissions) && allowedTo('manage_permissions'))
  1838. {
  1839. require_once($sourcedir . '/ManagePermissions.php');
  1840. save_inline_permissions($inlinePermissions);
  1841. }
  1842. }
  1843. ?>