Passed
Push — release-2.1 ( 0c2197...207d2d )
by Jeremy
05:47
created

ManageServer.php ➔ prepareDBSettingContext()   F

Complexity

Conditions 65
Paths > 20000

Size

Total Lines 225

Duplication

Lines 30
Ratio 13.33 %

Importance

Changes 0
Metric Value
cc 65
nc 429496.7295
nop 1
dl 30
loc 225
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Contains all the functionality required to be able to edit the core server
5
 * settings. This includes anything from which an error may result in the forum
6
 * destroying itself in a firey fury.
7
 *
8
 * Adding options to one of the setting screens isn't hard. Call prepareDBSettingsContext;
9
 * The basic format for a checkbox is:
10
 * 		array('check', 'nameInModSettingsAndSQL'),
11
 * And for a text box:
12
 * 		array('text', 'nameInModSettingsAndSQL')
13
 * (NOTE: You have to add an entry for this at the bottom!)
14
 *
15
 * In these cases, it will look for $txt['nameInModSettingsAndSQL'] as the description,
16
 * and $helptxt['nameInModSettingsAndSQL'] as the help popup description.
17
 *
18
 * Here's a quick explanation of how to add a new item:
19
 *
20
 * - A text input box.  For textual values.
21
 * 		array('text', 'nameInModSettingsAndSQL', 'OptionalInputBoxWidth'),
22
 * - A text input box.  For numerical values.
23
 * 		array('int', 'nameInModSettingsAndSQL', 'OptionalInputBoxWidth'),
24
 * - A text input box.  For floating point values.
25
 * 		array('float', 'nameInModSettingsAndSQL', 'OptionalInputBoxWidth'),
26
 * - A large text input box. Used for textual values spanning multiple lines.
27
 * 		array('large_text', 'nameInModSettingsAndSQL', 'OptionalNumberOfRows'),
28
 * - A check box.  Either one or zero. (boolean)
29
 * 		array('check', 'nameInModSettingsAndSQL'),
30
 * - A selection box.  Used for the selection of something from a list.
31
 * 		array('select', 'nameInModSettingsAndSQL', array('valueForSQL' => $txt['displayedValue'])),
32
 * 		Note that just saying array('first', 'second') will put 0 in the SQL for 'first'.
33
 * - A password input box. Used for passwords, no less!
34
 * 		array('password', 'nameInModSettingsAndSQL', 'OptionalInputBoxWidth'),
35
 * - A permission - for picking groups who have a permission.
36
 * 		array('permissions', 'manage_groups'),
37
 * - A BBC selection box.
38
 * 		array('bbc', 'sig_bbc'),
39
 * - A list of boards to choose from
40
 *  	array('boards', 'likes_boards'),
41
 *  	Note that the storage in the database is as 1,2,3,4
42
 *
43
 * For each option:
44
 * 	- type (see above), variable name, size/possible values.
45
 * 	  OR make type '' for an empty string for a horizontal rule.
46
 *  - SET preinput - to put some HTML prior to the input box.
47
 *  - SET postinput - to put some HTML following the input box.
48
 *  - SET invalid - to mark the data as invalid.
49
 *  - PLUS you can override label and help parameters by forcing their keys in the array, for example:
50
 *  	array('text', 'invalidlabel', 3, 'label' => 'Actual Label')
51
 *
52
 * Simple Machines Forum (SMF)
53
 *
54
 * @package SMF
55
 * @author Simple Machines http://www.simplemachines.org
56
 * @copyright 2018 Simple Machines and individual contributors
57
 * @license http://www.simplemachines.org/about/smf/license.php BSD
58
 *
59
 * @version 2.1 Beta 4
60
 */
61
62
if (!defined('SMF'))
63
	die('No direct access...');
64
65
/**
66
 * This is the main dispatcher. Sets up all the available sub-actions, all the tabs and selects
67
 * the appropriate one based on the sub-action.
68
 *
69
 * Requires the admin_forum permission.
70
 * Redirects to the appropriate function based on the sub-action.
71
 *
72
 * @uses edit_settings adminIndex.
73
 */
74
function ModifySettings()
75
{
76
	global $context, $txt, $boarddir;
77
78
	// This is just to keep the database password more secure.
79
	isAllowedTo('admin_forum');
80
81
	// Load up all the tabs...
82
	$context[$context['admin_menu_name']]['tab_data'] = array(
83
		'title' => $txt['admin_server_settings'],
84
		'help' => 'serversettings',
85
		'description' => $txt['admin_basic_settings'],
86
	);
87
88
	checkSession('request');
89
90
	// The settings are in here, I swear!
91
	loadLanguage('ManageSettings');
92
93
	$context['page_title'] = $txt['admin_server_settings'];
94
	$context['sub_template'] = 'show_settings';
95
96
	$subActions = array(
97
		'general' => 'ModifyGeneralSettings',
98
		'database' => 'ModifyDatabaseSettings',
99
		'cookie' => 'ModifyCookieSettings',
100
		'security' => 'ModifyGeneralSecuritySettings',
101
		'cache' => 'ModifyCacheSettings',
102
		'loads' => 'ModifyLoadBalancingSettings',
103
		'phpinfo' => 'ShowPHPinfoSettings',
104
	);
105
106
	// By default we're editing the core settings
107
	$_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'general';
108
	$context['sub_action'] = $_REQUEST['sa'];
109
110
	// Warn the user if there's any relevant information regarding Settings.php.
111
	$settings_not_writable = !is_writable($boarddir . '/Settings.php');
112
	$settings_backup_fail = !@is_writable($boarddir . '/Settings_bak.php') || !@copy($boarddir . '/Settings.php', $boarddir . '/Settings_bak.php');
113
114
	if ($settings_not_writable)
115
		$context['settings_message'] = '<div class="centertext"><strong>' . $txt['settings_not_writable'] . '</strong></div><br>';
116
	elseif ($settings_backup_fail)
117
		$context['settings_message'] = '<div class="centertext"><strong>' . $txt['admin_backup_fail'] . '</strong></div><br>';
118
119
	$context['settings_not_writable'] = $settings_not_writable;
120
121
	call_integration_hook('integrate_server_settings', array(&$subActions));
122
123
	// Call the right function for this sub-action.
124
	call_helper($subActions[$_REQUEST['sa']]);
125
}
126
127
/**
128
 * General forum settings - forum name, maintenance mode, etc.
129
 * Practically, this shows an interface for the settings in Settings.php to be changed.
130
 *
131
 * - Requires the admin_forum permission.
132
 * - Uses the edit_settings administration area.
133
 * - Contains the actual array of settings to show from Settings.php.
134
 * - Accessed from ?action=admin;area=serversettings;sa=general.
135
 *
136
 * @param bool $return_config Whether to return the $config_vars array (for pagination purposes)
137
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
138
 */
139
function ModifyGeneralSettings($return_config = false)
140
{
141
	global $scripturl, $context, $txt, $modSettings, $boardurl, $sourcedir;
142
143
	// If no cert, force_ssl must remain 0
144
	require_once($sourcedir . '/Subs.php');
145
	if (!ssl_cert_found($boardurl) && empty($modSettings['force_ssl']))
146
		$disable_force_ssl = true;
147
	else
148
		$disable_force_ssl = false;
149
150
	/* If you're writing a mod, it's a bad idea to add things here....
151
	For each option:
152
		variable name, description, type (constant), size/possible values, helptext, optional 'min' (minimum value for float/int, defaults to 0), optional 'max' (maximum value for float/int), optional 'step' (amount to increment/decrement value for float/int)
153
	OR	an empty string for a horizontal rule.
154
	OR	a string for a titled section. */
155
	$config_vars = array(
156
		array('mbname', $txt['admin_title'], 'file', 'text', 30),
157
		'',
158
		array('maintenance', $txt['admin_maintain'], 'file', 'check'),
159
		array('mtitle', $txt['maintenance_subject'], 'file', 'text', 36),
160
		array('mmessage', $txt['maintenance_message'], 'file', 'text', 36),
161
		'',
162
		array('webmaster_email', $txt['admin_webmaster_email'], 'file', 'text', 30),
163
		'',
164
		array('enableCompressedOutput', $txt['enableCompressedOutput'], 'db', 'check', null, 'enableCompressedOutput'),
165
		array('disableHostnameLookup', $txt['disableHostnameLookup'], 'db', 'check', null, 'disableHostnameLookup'),
166
		'',
167
		array('force_ssl', $txt['force_ssl'], 'db', 'select', array($txt['force_ssl_off'], $txt['force_ssl_complete']), 'force_ssl', 'disabled' => $disable_force_ssl),
168
		array('image_proxy_enabled', $txt['image_proxy_enabled'], 'file', 'check', null, 'image_proxy_enabled'),
169
		array('image_proxy_secret', $txt['image_proxy_secret'], 'file', 'text', 30, 'image_proxy_secret'),
170
		array('image_proxy_maxsize', $txt['image_proxy_maxsize'], 'file', 'int', null, 'image_proxy_maxsize'),
171
		'',
172
		array('enable_sm_stats', $txt['sm_state_setting'], 'db', 'check', null, 'enable_sm_stats'),
173
	);
174
175
	call_integration_hook('integrate_general_settings', array(&$config_vars));
176
177
	if ($return_config)
178
		return $config_vars;
179
180
	// Setup the template stuff.
181
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=general;save';
182
	$context['settings_title'] = $txt['general_settings'];
183
184
	// Saving settings?
185
	if (isset($_REQUEST['save']))
186
	{
187
		call_integration_hook('integrate_save_general_settings');
188
189
		// Are we saving the stat collection?
190
		if (!empty($_POST['enable_sm_stats']) && empty($modSettings['sm_stats_key']))
191
		{
192
			$registerSMStats = registerSMStats();
193
194
			// Failed to register, disable it again.
195
			if (empty($registerSMStats))
196
				$_POST['enable_sm_stats'] = 0;
197
		}
198
199
		// Ensure all URLs are aligned with the new force_ssl setting
200
		// Treat unset like 0
201
		if (isset($_POST['force_ssl']))
202
			AlignURLsWithSSLSetting($_POST['force_ssl']);
203
		else
204
			AlignURLsWithSSLSetting(0);
205
206
		saveSettings($config_vars);
207
		$_SESSION['adm-save'] = true;
208
		redirectexit('action=admin;area=serversettings;sa=general;' . $context['session_var'] . '=' . $context['session_id']);
209
	}
210
211
	// Fill the config array.
212
	prepareServerSettingsContext($config_vars);
213
214
	// Some javascript for SSL
215
	addInlineJavaScript('
216
$(function()
217
{
218
	$("#force_ssl").change(function()
219
	{
220
		var mode = $(this).val() == 1 ? false : true;
221
		$("#image_proxy_enabled").prop("disabled", mode);
222
		$("#image_proxy_secret").prop("disabled", mode);
223
		$("#image_proxy_maxsize").prop("disabled", mode);
224
	}).change();
225
});', true);
226
}
227
228
/**
229
 * Align URLs with SSL Setting.
230
 *
231
 * If force_ssl has changed, ensure all URLs are aligned with the new setting.
232
 * This includes:
233
 *     - $boardurl
234
 *     - $modSettings['smileys_url']
235
 *     - $modSettings['avatar_url']
236
 *     - $modSettings['custom_avatar_url'] - if found
237
 *     - theme_url - all entries in the themes table
238
 *     - images_url - all entries in the themes table
239
 *
240
 * This function will NOT overwrite URLs that are not subfolders of $boardurl.
241
 * The admin must have pointed those somewhere else on purpose, so they must be updated manually.
242
 *
243
 * A word of caution: You can't trust the http/https scheme reflected for these URLs in $globals
244
 * (e.g., $boardurl) or in $modSettings.  This is because SMF may change them in memory to comply
245
 * with the force_ssl setting - a soft redirect may be in effect...  Thus, conditional updates
246
 * to these values do not work.  You gotta just brute force overwrite them based on force_ssl.
247
 *
248
 * @param int $new_force_ssl is the current force_ssl setting.
249
 * @return void Returns nothing, just does its job
250
 */
251
function AlignURLsWithSSLSetting($new_force_ssl = 0)
252
{
253
	global $boardurl, $modSettings, $sourcedir, $smcFunc;
254
	require_once($sourcedir . '/Subs-Admin.php');
255
256
	// Check $boardurl
257
	if (!empty($new_force_ssl))
258
		$newval = strtr($boardurl, array('http://' => 'https://'));
259
	else
260
		$newval = strtr($boardurl, array('https://' => 'http://'));
261
	updateSettingsFile(array('boardurl' => '\'' . addslashes($newval) . '\''));
262
263
	$new_settings = array();
264
265
	// Check $smileys_url, but only if it points to a subfolder of $boardurl
266
	if (BoardurlMatch($modSettings['smileys_url']))
267
	{
268
		if (!empty($new_force_ssl))
269
			$newval = strtr($modSettings['smileys_url'], array('http://' => 'https://'));
270
		else
271
			$newval = strtr($modSettings['smileys_url'], array('https://' => 'http://'));
272
		$new_settings['smileys_url'] = $newval;
273
	}
274
275
	// Check $avatar_url, but only if it points to a subfolder of $boardurl
276
	if (BoardurlMatch($modSettings['avatar_url']))
277
	{
278
		if (!empty($new_force_ssl))
279
			$newval = strtr($modSettings['avatar_url'], array('http://' => 'https://'));
280
		else
281
			$newval = strtr($modSettings['avatar_url'], array('https://' => 'http://'));
282
		$new_settings['avatar_url'] = $newval;
283
	}
284
285
	// Check $custom_avatar_url, but only if it points to a subfolder of $boardurl
286
	// This one had been optional in the past, make sure it is set first
287
	if (isset($modSettings['custom_avatar_url']) && BoardurlMatch($modSettings['custom_avatar_url']))
288
	{
289
		if (!empty($new_force_ssl))
290
			$newval = strtr($modSettings['custom_avatar_url'], array('http://' => 'https://'));
291
		else
292
			$newval = strtr($modSettings['custom_avatar_url'], array('https://' => 'http://'));
293
		$new_settings['custom_avatar_url'] = $newval;
294
	}
295
296
	// Save updates to the settings table
297
	if (!empty($new_settings))
298
		updateSettings($new_settings, true);
299
300
	// Now we move onto the themes.
301
	// First, get a list of theme URLs...
302
	$request = $smcFunc['db_query']('', '
303
		SELECT id_theme, variable, value
304
		  FROM {db_prefix}themes
305
		 WHERE variable in ({string:themeurl}, {string:imagesurl})
306
		   AND id_member = {int:zero}',
307
		array(
308
			'themeurl' => 'theme_url',
309
			'imagesurl' => 'images_url',
310
			'zero' => 0,
311
		)
312
	);
313
314
	while ($row = $smcFunc['db_fetch_assoc']($request))
315
	{
316
		// First check to see if it points to a subfolder of $boardurl
317
		if (BoardurlMatch($row['value']))
318
		{
319
			if (!empty($new_force_ssl))
320
				$newval = strtr($row['value'], array('http://' => 'https://'));
321
			else
322
				$newval = strtr($row['value'], array('https://' => 'http://'));
323
			$smcFunc['db_query']('', '
324
				UPDATE {db_prefix}themes
325
				   SET value = {string:theme_val}
326
				 WHERE variable = {string:theme_var}
327
				   AND id_theme = {string:theme_id}
328
				   AND id_member = {int:zero}',
329
				array(
330
					'theme_val' => $newval,
331
					'theme_var' => $row['variable'],
332
					'theme_id' => $row['id_theme'],
333
					'zero' => 0,
334
				)
335
			);
336
		}
337
	}
338
	$smcFunc['db_free_result']($request);
339
}
340
341
/**
342
 * $boardurl Match.
343
 *
344
 * Helper function to see if the url being checked is based off of $boardurl.
345
 * If not, it was overridden by the admin to some other value on purpose, and should not
346
 * be stepped on by SMF when aligning URLs with the force_ssl setting.
347
 * The site admin must change URLs that are not aligned with $boardurl manually.
348
 *
349
 * @param string $url is the url to check.
350
 * @return bool Returns true if the url is based off of $boardurl (without the scheme), false if not
351
 */
352
function BoardurlMatch($url = '')
353
{
354
	global $boardurl;
355
356
	// Strip the schemes
357
	$urlpath = strtr($url, array('http://' => '', 'https://' => ''));
358
	$boardurlpath = strtr($boardurl, array('http://' => '', 'https://' => ''));
359
360
	// If leftmost portion of path matches boardurl, return true
361
	$result = strpos($urlpath, $boardurlpath);
362
	if ($result === false || $result != 0)
363
		return false;
364
	else
365
		return true;
366
}
367
368
/**
369
 * Basic database and paths settings - database name, host, etc.
370
 *
371
 * - It shows an interface for the settings in Settings.php to be changed.
372
 * - It contains the actual array of settings to show from Settings.php.
373
 * - Requires the admin_forum permission.
374
 * - Uses the edit_settings administration area.
375
 * - Accessed from ?action=admin;area=serversettings;sa=database.
376
 *
377
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
378
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
379
 */
380
function ModifyDatabaseSettings($return_config = false)
381
{
382
	global $scripturl, $context, $txt, $smcFunc;
383
	db_extend('extra');
384
385
	/* If you're writing a mod, it's a bad idea to add things here....
386
		For each option:
387
		variable name, description, type (constant), size/possible values, helptext, optional 'min' (minimum value for float/int, defaults to 0), optional 'max' (maximum value for float/int), optional 'step' (amount to increment/decrement value for float/int)
388
		OR an empty string for a horizontal rule.
389
		OR a string for a titled section. */
390
	$config_vars = array(
391
		array('db_persist', $txt['db_persist'], 'file', 'check', null, 'db_persist'),
392
		array('db_error_send', $txt['db_error_send'], 'file', 'check'),
393
		array('ssi_db_user', $txt['ssi_db_user'], 'file', 'text', null, 'ssi_db_user'),
394
		array('ssi_db_passwd', $txt['ssi_db_passwd'], 'file', 'password'),
395
		'',
396
		array('autoFixDatabase', $txt['autoFixDatabase'], 'db', 'check', false, 'autoFixDatabase')
397
	);
398
399
	// Add PG Stuff
400
	if ($smcFunc['db_title'] == "PostgreSQL")
401
	{
402
		$request = $smcFunc['db_query']('', 'SELECT cfgname FROM pg_ts_config', array());
403
		$fts_language = array();
404
405
		while ($row = $smcFunc['db_fetch_assoc']($request))
406
			$fts_language[$row['cfgname']] = $row['cfgname'];
407
408
		$config_vars = array_merge ($config_vars, array(
409
				'',
410
				array('search_language', $txt['search_language'], 'db', 'select', $fts_language, 'pgFulltextSearch')
411
			)
412
		);
413
	}
414
415
416
	call_integration_hook('integrate_database_settings', array(&$config_vars));
417
418
	if ($return_config)
419
		return $config_vars;
420
421
	// Setup the template stuff.
422
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=database;save';
423
	$context['settings_title'] = $txt['database_settings'];
424
	$context['save_disabled'] = $context['settings_not_writable'];
425
426
	if (!$smcFunc['db_allow_persistent']())
427
		addInlineJavaScript('
428
			$(function()
429
			{
430
				$("#db_persist").prop("disabled", true);
431
			});', true);
432
433
	// Saving settings?
434
	if (isset($_REQUEST['save']))
435
	{
436
		call_integration_hook('integrate_save_database_settings');
437
438
		saveSettings($config_vars);
439
		$_SESSION['adm-save'] = true;
440
		redirectexit('action=admin;area=serversettings;sa=database;' . $context['session_var'] . '=' . $context['session_id']);
441
	}
442
443
	// Fill the config array.
444
	prepareServerSettingsContext($config_vars);
445
}
446
447
/**
448
 * This function handles cookies settings modifications.
449
 *
450
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
451
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
452
 */
453
function ModifyCookieSettings($return_config = false)
454
{
455
	global $context, $scripturl, $txt, $sourcedir, $modSettings, $cookiename, $user_settings, $boardurl, $smcFunc;
456
457
	// Define the variables we want to edit.
458
	$config_vars = array(
459
		// Cookies...
460
		array('cookiename', $txt['cookie_name'], 'file', 'text', 20),
461
		array('cookieTime', $txt['cookieTime'], 'db', 'int', 'postinput' => $txt['minutes']),
462
		array('localCookies', $txt['localCookies'], 'db', 'check', false, 'localCookies'),
463
		array('globalCookies', $txt['globalCookies'], 'db', 'check', false, 'globalCookies'),
464
		array('globalCookiesDomain', $txt['globalCookiesDomain'], 'db', 'text', false, 'globalCookiesDomain'),
465
		array('secureCookies', $txt['secureCookies'], 'db', 'check', false, 'secureCookies', 'disabled' => !httpsOn()),
466
		array('httponlyCookies', $txt['httponlyCookies'], 'db', 'check', false, 'httponlyCookies'),
467
		'',
468
		// Sessions
469
		array('databaseSession_enable', $txt['databaseSession_enable'], 'db', 'check', false, 'databaseSession_enable'),
470
		array('databaseSession_loose', $txt['databaseSession_loose'], 'db', 'check', false, 'databaseSession_loose'),
471
		array('databaseSession_lifetime', $txt['databaseSession_lifetime'], 'db', 'int', false, 'databaseSession_lifetime', 'postinput' => $txt['seconds']),
472
		'',
473
		// 2FA
474
		array('tfa_mode', $txt['tfa_mode'], 'db', 'select', array(
475
			0 => $txt['tfa_mode_disabled'],
476
			1 => $txt['tfa_mode_enabled'],
477
		) + (empty($user_settings['tfa_secret']) ? array() : array(
478
			2 => $txt['tfa_mode_forced'],
479
		)) + (empty($user_settings['tfa_secret']) ? array() : array(
480
			3 => $txt['tfa_mode_forcedall'],
481
		)), 'subtext' => $txt['tfa_mode_subtext'] . (empty($user_settings['tfa_secret']) ? '<br><strong>' . $txt['tfa_mode_forced_help'] . '</strong>' : ''), 'tfa_mode'),
482
	);
483
484
	addInlineJavaScript('
485
	function hideGlobalCookies()
486
	{
487
		var usingLocal = $("#localCookies").prop("checked");
488
		$("#setting_globalCookies").closest("dt").toggle(!usingLocal);
489
		$("#globalCookies").closest("dd").toggle(!usingLocal);
490
491
		var usingGlobal = !usingLocal && $("#globalCookies").prop("checked");
492
		$("#setting_globalCookiesDomain").closest("dt").toggle(usingGlobal);
493
		$("#globalCookiesDomain").closest("dd").toggle(usingGlobal);
494
	};
495
	hideGlobalCookies();
496
497
	$("#localCookies, #globalCookies").click(function() {
498
		hideGlobalCookies();
499
	});', true);
500
501
	if (empty($user_settings['tfa_secret']))
502
		addInlineJavaScript('');
503
504
	call_integration_hook('integrate_cookie_settings', array(&$config_vars));
505
506
	if ($return_config)
507
		return $config_vars;
508
509
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=cookie;save';
510
	$context['settings_title'] = $txt['cookies_sessions_settings'];
511
512
	// Saving settings?
513
	if (isset($_REQUEST['save']))
514
	{
515
		call_integration_hook('integrate_save_cookie_settings');
516
517
		// Local and global do not play nicely together.
518
		if (!empty($_POST['localCookies']) && empty($_POST['globalCookies']))
519
			unset ($_POST['globalCookies']);
520
521
		if (empty($modSettings['localCookies']) != empty($_POST['localCookies']) || empty($modSettings['globalCookies']) != empty($_POST['globalCookies']))
522
			$scope_changed = true;
523
524
		if (!empty($_POST['globalCookiesDomain']) && strpos($boardurl, $_POST['globalCookiesDomain']) === false)
525
			fatal_lang_error('invalid_cookie_domain', false);
526
527
		saveSettings($config_vars);
528
529
		// If the cookie name or scope were changed, reset the cookie.
530
		if ($cookiename != $_POST['cookiename'] || !empty($scope_changed))
531
		{
532
			$original_session_id = $context['session_id'];
533
			include_once($sourcedir . '/Subs-Auth.php');
534
535
			// Remove the old cookie.
536
			setLoginCookie(-3600, 0);
537
538
			// Set the new one.
539
			$cookiename = !empty($_POST['cookiename']) ? $_POST['cookiename'] : $cookiename;
540
			setLoginCookie(60 * $modSettings['cookieTime'], $user_settings['id_member'], hash_salt($user_settings['passwd'], $user_settings['password_salt']));
541
542
			redirectexit('action=admin;area=serversettings;sa=cookie;' . $context['session_var'] . '=' . $original_session_id, $context['server']['needs_login_fix']);
543
		}
544
545
		//If we disabled 2FA, reset all members and membergroups settings.
546
		if (isset($_POST['tfa_mode']) && empty($_POST['tfa_mode']))
547
		{
548
			$smcFunc['db_query']('', '
549
				UPDATE {db_prefix}membergroups
550
				SET tfa_required = {int:zero}',
551
				array(
552
					'zero' => 0,
553
				)
554
			);
555
			$smcFunc['db_query']('', '
556
				UPDATE {db_prefix}members
557
				SET tfa_secret = {string:empty}, tfa_backup = {string:empty}',
558
				array(
559
					'empty' => '',
560
				)
561
			);
562
		}
563
564
		$_SESSION['adm-save'] = true;
565
		redirectexit('action=admin;area=serversettings;sa=cookie;' . $context['session_var'] . '=' . $context['session_id']);
566
	}
567
568
	// Fill the config array.
569
	prepareServerSettingsContext($config_vars);
570
}
571
572
/**
573
 * Settings really associated with general security aspects.
574
 *
575
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
576
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
577
 */
578
function ModifyGeneralSecuritySettings($return_config = false)
579
{
580
	global $txt, $scripturl, $context;
581
582
	$config_vars = array(
583
			array('int', 'failed_login_threshold'),
584
			array('int', 'loginHistoryDays', 'subtext' => $txt['zero_to_disable']),
585
		'',
586
			array('check', 'securityDisable'),
587
			array('check', 'securityDisable_moderate'),
588
		'',
589
			// Reactive on email, and approve on delete
590
			array('check', 'send_validation_onChange'),
591
			array('check', 'approveAccountDeletion'),
592
		'',
593
			// Password strength.
594
			array('select', 'password_strength', array($txt['setting_password_strength_low'], $txt['setting_password_strength_medium'], $txt['setting_password_strength_high'])),
595
			array('check', 'enable_password_conversion'),
596
		'',
597
			// Reporting of personal messages?
598
			array('check', 'enableReportPM'),
599
		'',
600
			array('select', 'frame_security', array('SAMEORIGIN' => $txt['setting_frame_security_SAMEORIGIN'], 'DENY' => $txt['setting_frame_security_DENY'], 'DISABLE' => $txt['setting_frame_security_DISABLE'])),
601
		'',
602
			array('select', 'proxy_ip_header', array('disabled' => $txt['setting_proxy_ip_header_disabled'], 'autodetect' => $txt['setting_proxy_ip_header_autodetect'], 'HTTP_X_FORWARDED_FOR' => 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP' => 'HTTP_CLIENT_IP', 'HTTP_X_REAL_IP' => 'HTTP_X_REAL_IP', 'CF-Connecting-IP' => 'CF-Connecting-IP')),
603
			array('text', 'proxy_ip_servers'),
604
	);
605
606
	call_integration_hook('integrate_general_security_settings', array(&$config_vars));
607
608
	if ($return_config)
609
		return $config_vars;
610
611
	// Saving?
612
	if (isset($_GET['save']))
613
	{
614
		saveDBSettings($config_vars);
615
		$_SESSION['adm-save'] = true;
616
617
		call_integration_hook('integrate_save_general_security_settings');
618
619
		writeLog();
620
		redirectexit('action=admin;area=serversettings;sa=security;' . $context['session_var'] . '=' . $context['session_id']);
621
	}
622
623
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;save;sa=security';
624
	$context['settings_title'] = $txt['security_settings'];
625
626
	prepareDBSettingContext($config_vars);
627
}
628
629
/**
630
 * Simply modifying cache functions
631
 *
632
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
633
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
634
 */
635
function ModifyCacheSettings($return_config = false)
636
{
637
	global $context, $scripturl, $txt;
638
639
	// Detect all available optimizers
640
	$detected = loadCacheAPIs();
641
642
	// set our values to show what, if anything, we found
643
	if (empty($detected))
644
	{
645
		$txt['cache_settings_message'] = $txt['detected_no_caching'];
646
		$cache_level = array($txt['cache_off']);
647
		$detected['none'] = $txt['cache_off'];
648
	}
649
	else
650
	{
651
		$txt['cache_settings_message'] = sprintf($txt['detected_accelerators'], implode(', ', $detected));
652
		$cache_level = array($txt['cache_off'], $txt['cache_level1'], $txt['cache_level2'], $txt['cache_level3']);
653
	}
654
655
	// Define the variables we want to edit.
656
	$config_vars = array(
657
		// Only a few settings, but they are important
658
		array('', $txt['cache_settings_message'], '', 'desc'),
659
		array('cache_enable', $txt['cache_enable'], 'file', 'select', $cache_level, 'cache_enable'),
660
		array('cache_accelerator', $txt['cache_accelerator'], 'file', 'select', $detected),
661
	);
662
663
	// some javascript to enable / disable certain settings if the option is not selected
664
	$context['settings_post_javascript'] = '
665
		$(document).ready(function() {
666
			$("#cache_accelerator").change();
667
		});';
668
669
	call_integration_hook('integrate_modify_cache_settings', array(&$config_vars));
670
671
	// Maybe we have some additional settings from the selected accelerator.
672
	if (!empty($detected))
673
	{
674
		foreach ($detected as $tryCache => $dummy)
675
		{
676
			$cache_class_name = $tryCache . '_cache';
677
678
			// loadCacheAPIs has already included the file, just see if we can't add the settings in.
679
			if (is_callable(array($cache_class_name, 'cacheSettings')))
680
			{
681
				$testAPI = new $cache_class_name();
682
				call_user_func_array(array($testAPI, 'cacheSettings'), array(&$config_vars));
683
			}
684
		}
685
	}
686
	if ($return_config)
687
		return $config_vars;
688
689
	// Saving again?
690
	if (isset($_GET['save']))
691
	{
692
		call_integration_hook('integrate_save_cache_settings');
693
694
		saveSettings($config_vars);
695
		$_SESSION['adm-save'] = true;
696
697
		// We need to save the $cache_enable to $modSettings as well
698
		updatesettings(array('cache_enable' => (int) $_POST['cache_enable']));
699
700
		// exit so we reload our new settings on the page
701
		redirectexit('action=admin;area=serversettings;sa=cache;' . $context['session_var'] . '=' . $context['session_id']);
702
	}
703
704
	loadLanguage('ManageMaintenance');
705
	createToken('admin-maint');
706
	$context['template_layers'][] = 'clean_cache_button';
707
708
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=cache;save';
709
	$context['settings_title'] = $txt['caching_settings'];
710
711
	// Changing cache settings won't have any effect if Settings.php is not writeable.
712
	$context['save_disabled'] = $context['settings_not_writable'];
713
714
	// Decide what message to show.
715
	if (!$context['save_disabled'])
716
		$context['settings_message'] = $txt['caching_information'];
717
718
	// Prepare the template.
719
	prepareServerSettingsContext($config_vars);
720
}
721
722
/**
723
 * Allows to edit load balancing settings.
724
 *
725
 * @param bool $return_config Whether or not to return the config_vars array
726
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
727
 */
728
function ModifyLoadBalancingSettings($return_config = false)
729
{
730
	global $txt, $scripturl, $context, $modSettings;
731
732
	// Setup a warning message, but disabled by default.
733
	$disabled = true;
734
	$context['settings_message'] = $txt['loadavg_disabled_conf'];
735
736
	if (DIRECTORY_SEPARATOR === '\\')
737
	{
738
		$context['settings_message'] = $txt['loadavg_disabled_windows'];
739
		if (isset($_GET['save']))
740
			$_SESSION['adm-save'] = $txt['loadavg_disabled_windows'];
741
	}
742
	elseif (stripos(PHP_OS, 'darwin') === 0)
743
	{
744
		$context['settings_message'] = $txt['loadavg_disabled_osx'];
745
		if (isset($_GET['save']))
746
			$_SESSION['adm-save'] = $txt['loadavg_disabled_osx'];
747
	}
748
	else
749
	{
750
		$modSettings['load_average'] = @file_get_contents('/proc/loadavg');
751
		if (!empty($modSettings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', $modSettings['load_average'], $matches) !== 0)
752
			$modSettings['load_average'] = (float) $matches[1];
753
		elseif (($modSettings['load_average'] = @`uptime`) !== null && preg_match('~load averages?: (\d+\.\d+), (\d+\.\d+), (\d+\.\d+)~i', $modSettings['load_average'], $matches) !== 0)
754
			$modSettings['load_average'] = (float) $matches[1];
755
		else
756
			unset($modSettings['load_average']);
757
758
		if (!empty($modSettings['load_average']) || (isset($modSettings['load_average']) && $modSettings['load_average'] === 0.0))
759
		{
760
			$context['settings_message'] = sprintf($txt['loadavg_warning'], $modSettings['load_average']);
761
			$disabled = false;
762
		}
763
	}
764
765
	// Start with a simple checkbox.
766
	$config_vars = array(
767
		array('check', 'loadavg_enable', 'disabled' => $disabled),
768
	);
769
770
	// Set the default values for each option.
771
	$default_values = array(
772
		'loadavg_auto_opt' => 1.0,
773
		'loadavg_search' => 2.5,
774
		'loadavg_allunread' => 2.0,
775
		'loadavg_unreadreplies' => 3.5,
776
		'loadavg_show_posts' => 2.0,
777
		'loadavg_userstats' => 10.0,
778
		'loadavg_bbc' => 30.0,
779
		'loadavg_forum' => 40.0,
780
	);
781
782
	// Loop through the settings.
783
	foreach ($default_values as $name => $value)
784
	{
785
		// Use the default value if the setting isn't set yet.
786
		$value = !isset($modSettings[$name]) ? $value : $modSettings[$name];
787
		$config_vars[] = array('float', $name, 'value' => $value, 'disabled' => $disabled);
788
	}
789
790
	call_integration_hook('integrate_loadavg_settings', array(&$config_vars));
791
792
	if ($return_config)
793
		return $config_vars;
794
795
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=loads;save';
796
	$context['settings_title'] = $txt['load_balancing_settings'];
797
798
	// Saving?
799
	if (isset($_GET['save']))
800
	{
801
		// Stupidity is not allowed.
802
		foreach ($_POST as $key => $value)
803
		{
804
			if (strpos($key, 'loadavg') === 0 || $key === 'loadavg_enable' || !in_array($key, array_keys($default_values)))
805
				continue;
806
			else
807
				$_POST[$key] = (float) $value;
808
809
			if ($key == 'loadavg_auto_opt' && $value <= 1)
810
				$_POST['loadavg_auto_opt'] = 1.0;
811
			elseif ($key == 'loadavg_forum' && $value < 10)
812
				$_POST['loadavg_forum'] = 10.0;
813
			elseif ($value < 2)
814
				$_POST[$key] = 2.0;
815
		}
816
817
		call_integration_hook('integrate_save_loadavg_settings');
818
819
		saveDBSettings($config_vars);
820
		if (!isset($_SESSION['adm-save']))
821
			$_SESSION['adm-save'] = true;
822
		redirectexit('action=admin;area=serversettings;sa=loads;' . $context['session_var'] . '=' . $context['session_id']);
823
	}
824
825
	prepareDBSettingContext($config_vars);
826
}
827
828
/**
829
 * Helper function, it sets up the context for the manage server settings.
830
 * - The basic usage of the six numbered key fields are
831
 * - array (0 ,1, 2, 3, 4, 5
832
 *		0 variable name - the name of the saved variable
833
 *		1 label - the text to show on the settings page
834
 *		2 saveto - file or db, where to save the variable name - value pair
835
 *		3 type - type of data to save, int, float, text, check
836
 *		4 size - false or field size
837
 *		5 help - '' or helptxt variable name
838
 *	)
839
 *
840
 * the following named keys are also permitted
841
 * 'disabled' => A string of code that will determine whether or not the setting should be disabled
842
 * 'postinput' => Text to display after the input field
843
 * 'preinput' => Text to display before the input field
844
 * 'subtext' => Additional descriptive text to display under the field's label
845
 * 'min' => minimum allowed value (for int/float). Defaults to 0 if not set.
846
 * 'max' => maximum allowed value (for int/float)
847
 * 'step' => how much to increment/decrement the value by (only for int/float - mostly used for float values).
848
 *
849
 * @param array $config_vars An array of configuration variables
850
 */
851
function prepareServerSettingsContext(&$config_vars)
852
{
853
	global $context, $modSettings, $smcFunc;
854
855
	if (isset($_SESSION['adm-save']))
856
	{
857
		if ($_SESSION['adm-save'] === true)
858
			$context['saved_successful'] = true;
859
		else
860
			$context['saved_failed'] = $_SESSION['adm-save'];
861
862
		unset($_SESSION['adm-save']);
863
	}
864
865
	$context['config_vars'] = array();
866
	foreach ($config_vars as $identifier => $config_var)
867
	{
868
		if (!is_array($config_var) || !isset($config_var[1]))
869
			$context['config_vars'][] = $config_var;
870
		else
871
		{
872
			$varname = $config_var[0];
873
			global $$varname;
874
875
			// Set the subtext in case it's part of the label.
876
			// @todo Temporary. Preventing divs inside label tags.
877
			$divPos = strpos($config_var[1], '<div');
878
			$subtext = '';
879
			if ($divPos !== false)
880
			{
881
				$subtext = preg_replace('~</?div[^>]*>~', '', substr($config_var[1], $divPos));
882
				$config_var[1] = substr($config_var[1], 0, $divPos);
883
			}
884
885
			$context['config_vars'][$config_var[0]] = array(
886
				'label' => $config_var[1],
887
				'help' => isset($config_var[5]) ? $config_var[5] : '',
888
				'type' => $config_var[3],
889
				'size' => empty($config_var[4]) ? 0 : $config_var[4],
890
				'data' => isset($config_var[4]) && is_array($config_var[4]) && $config_var[3] != 'select' ? $config_var[4] : array(),
891
				'name' => $config_var[0],
892
				'value' => $config_var[2] == 'file' ? $smcFunc['htmlspecialchars']($$varname) : (isset($modSettings[$config_var[0]]) ? $smcFunc['htmlspecialchars']($modSettings[$config_var[0]]) : (in_array($config_var[3], array('int', 'float')) ? 0 : '')),
893
				'disabled' => !empty($context['settings_not_writable']) || !empty($config_var['disabled']),
894
				'invalid' => false,
895
				'subtext' => !empty($config_var['subtext']) ? $config_var['subtext'] : $subtext,
896
				'javascript' => '',
897
				'preinput' => !empty($config_var['preinput']) ? $config_var['preinput'] : '',
898
				'postinput' => !empty($config_var['postinput']) ? $config_var['postinput'] : '',
899
			);
900
901
			// Handle min/max/step if necessary
902
			if ($config_var[3] == 'int' || $config_var[3] == 'float')
903
			{
904
				// Default to a min of 0 if one isn't set
905
				if (isset($config_var['min']))
906
					$context['config_vars'][$config_var[0]]['min'] = $config_var['min'];
907
				else
908
					$context['config_vars'][$config_var[0]]['min'] = 0;
909
910
				if (isset($config_var['max']))
911
					$context['config_vars'][$config_var[0]]['max'] = $config_var['max'];
912
913
				if (isset($config_var['step']))
914
					$context['config_vars'][$config_var[0]]['step'] = $config_var['step'];
915
			}
916
917
			// If this is a select box handle any data.
918
			if (!empty($config_var[4]) && is_array($config_var[4]))
919
			{
920
				// If it's associative
921
				$config_values = array_values($config_var[4]);
922
				if (isset($config_values[0]) && is_array($config_values[0]))
923
					$context['config_vars'][$config_var[0]]['data'] = $config_var[4];
924
				else
925
				{
926
					foreach ($config_var[4] as $key => $item)
927
						$context['config_vars'][$config_var[0]]['data'][] = array($key, $item);
928
				}
929
			}
930
		}
931
	}
932
933
	// Two tokens because saving these settings requires both saveSettings and saveDBSettings
934
	createToken('admin-ssc');
935
	createToken('admin-dbsc');
936
}
937
938
/**
939
 * Helper function, it sets up the context for database settings.
940
 * @todo see rev. 10406 from 2.1-requests
941
 *
942
 * @param array $config_vars An array of configuration variables
943
 */
944
function prepareDBSettingContext(&$config_vars)
945
{
946
	global $txt, $helptxt, $context, $modSettings, $sourcedir, $smcFunc;
947
948
	loadLanguage('Help');
949
950
	if (isset($_SESSION['adm-save']))
951
	{
952
		if ($_SESSION['adm-save'] === true)
953
			$context['saved_successful'] = true;
954
		else
955
			$context['saved_failed'] = $_SESSION['adm-save'];
956
957
		unset($_SESSION['adm-save']);
958
	}
959
960
	$context['config_vars'] = array();
961
	$inlinePermissions = array();
962
	$bbcChoice = array();
963
	$board_list = false;
964
	foreach ($config_vars as $config_var)
965
	{
966
		// HR?
967
		if (!is_array($config_var))
968
			$context['config_vars'][] = $config_var;
969
		else
970
		{
971
			// If it has no name it doesn't have any purpose!
972
			if (empty($config_var[1]))
973
				continue;
974
975
			// Special case for inline permissions
976
			if ($config_var[0] == 'permissions' && allowedTo('manage_permissions'))
977
				$inlinePermissions[] = $config_var[1];
978
			elseif ($config_var[0] == 'permissions')
979
				continue;
980
981
			if ($config_var[0] == 'boards')
982
				$board_list = true;
983
984
			// Are we showing the BBC selection box?
985
			if ($config_var[0] == 'bbc')
986
				$bbcChoice[] = $config_var[1];
987
988
			// We need to do some parsing of the value before we pass it in.
989
			if (isset($modSettings[$config_var[1]]))
990
			{
991
				switch ($config_var[0])
992
				{
993
					case 'select':
994
						$value = $modSettings[$config_var[1]];
995
						break;
996
					case 'json':
997
						$value = $smcFunc['htmlspecialchars']($smcFunc['json_encode']($modSettings[$config_var[1]]));
998
						break;
999
					case 'boards':
1000
						$value = explode(',', $modSettings[$config_var[1]]);
1001
						break;
1002
					default:
1003
						$value = $smcFunc['htmlspecialchars']($modSettings[$config_var[1]]);
1004
				}
1005
			}
1006
			else
1007
			{
1008
				// Darn, it's empty. What type is expected?
1009
				switch ($config_var[0])
1010
				{
1011
					case 'int':
1012
					case 'float':
1013
						$value = 0;
1014
						break;
1015
					case 'select':
1016
						$value = !empty($config_var['multiple']) ? $smcFunc['json_encode'](array()) : '';
1017
						break;
1018
					case 'boards':
1019
						$value = array();
1020
						break;
1021
					default:
1022
						$value = '';
1023
				}
1024
			}
1025
1026
			$context['config_vars'][$config_var[1]] = array(
1027
				'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] : '')),
1028
				'help' => isset($helptxt[$config_var[1]]) ? $config_var[1] : '',
1029
				'type' => $config_var[0],
1030
				'size' => !empty($config_var['size']) ? $config_var['size'] : (!empty($config_var[2]) && !is_array($config_var[2]) ? $config_var[2] : (in_array($config_var[0], array('int', 'float')) ? 6 : 0)),
1031
				'data' => array(),
1032
				'name' => $config_var[1],
1033
				'value' => $value,
1034
				'disabled' => false,
1035
				'invalid' => !empty($config_var['invalid']),
1036
				'javascript' => '',
1037
				'var_message' => !empty($config_var['message']) && isset($txt[$config_var['message']]) ? $txt[$config_var['message']] : '',
1038
				'preinput' => isset($config_var['preinput']) ? $config_var['preinput'] : '',
1039
				'postinput' => isset($config_var['postinput']) ? $config_var['postinput'] : '',
1040
			);
1041
1042
			// Handle min/max/step if necessary
1043
			if ($config_var[0] == 'int' || $config_var[0] == 'float')
1044
			{
1045
				// Default to a min of 0 if one isn't set
1046
				if (isset($config_var['min']))
1047
					$context['config_vars'][$config_var[1]]['min'] = $config_var['min'];
1048
				else
1049
					$context['config_vars'][$config_var[1]]['min'] = 0;
1050
1051
				if (isset($config_var['max']))
1052
					$context['config_vars'][$config_var[1]]['max'] = $config_var['max'];
1053
1054
				if (isset($config_var['step']))
1055
					$context['config_vars'][$config_var[1]]['step'] = $config_var['step'];
1056
			}
1057
1058
			// If this is a select box handle any data.
1059
			if (!empty($config_var[2]) && is_array($config_var[2]))
1060
			{
1061
				// If we allow multiple selections, we need to adjust a few things.
1062
				if ($config_var[0] == 'select' && !empty($config_var['multiple']))
1063
				{
1064
					$context['config_vars'][$config_var[1]]['name'] .= '[]';
1065
					$context['config_vars'][$config_var[1]]['value'] = !empty($context['config_vars'][$config_var[1]]['value']) ? $smcFunc['json_decode']($context['config_vars'][$config_var[1]]['value'], true) : array();
1066
				}
1067
1068
				// If it's associative
1069
				if (isset($config_var[2][0]) && is_array($config_var[2][0]))
1070
					$context['config_vars'][$config_var[1]]['data'] = $config_var[2];
1071
				else
1072
				{
1073
					foreach ($config_var[2] as $key => $item)
1074
						$context['config_vars'][$config_var[1]]['data'][] = array($key, $item);
1075
				}
1076
			}
1077
1078
			// Finally allow overrides - and some final cleanups.
1079
			foreach ($config_var as $k => $v)
1080
			{
1081
				if (!is_numeric($k))
1082
				{
1083
					if (substr($k, 0, 2) == 'on')
1084
						$context['config_vars'][$config_var[1]]['javascript'] .= ' ' . $k . '="' . $v . '"';
1085
					else
1086
						$context['config_vars'][$config_var[1]][$k] = $v;
1087
				}
1088
1089
				// See if there are any other labels that might fit?
1090
				if (isset($txt['setting_' . $config_var[1]]))
1091
					$context['config_vars'][$config_var[1]]['label'] = $txt['setting_' . $config_var[1]];
1092
				elseif (isset($txt['groups_' . $config_var[1]]))
1093
					$context['config_vars'][$config_var[1]]['label'] = $txt['groups_' . $config_var[1]];
1094
			}
1095
1096
			// Set the subtext in case it's part of the label.
1097
			// @todo Temporary. Preventing divs inside label tags.
1098
			$divPos = strpos($context['config_vars'][$config_var[1]]['label'], '<div');
1099
			if ($divPos !== false)
1100
			{
1101
				$context['config_vars'][$config_var[1]]['subtext'] = preg_replace('~</?div[^>]*>~', '', substr($context['config_vars'][$config_var[1]]['label'], $divPos));
1102
				$context['config_vars'][$config_var[1]]['label'] = substr($context['config_vars'][$config_var[1]]['label'], 0, $divPos);
1103
			}
1104
		}
1105
	}
1106
1107
	// If we have inline permissions we need to prep them.
1108
	if (!empty($inlinePermissions) && allowedTo('manage_permissions'))
1109
	{
1110
		require_once($sourcedir . '/ManagePermissions.php');
1111
		init_inline_permissions($inlinePermissions, isset($context['permissions_excluded']) ? $context['permissions_excluded'] : array());
1112
	}
1113
1114
	if ($board_list)
1115
	{
1116
		require_once($sourcedir . '/Subs-MessageIndex.php');
1117
		$context['board_list'] = getBoardList();
1118
	}
1119
1120
	// What about any BBC selection boxes?
1121
	if (!empty($bbcChoice))
1122
	{
1123
		// What are the options, eh?
1124
		$temp = parse_bbc(false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $message of parse_bbc(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1124
		$temp = parse_bbc(/** @scrutinizer ignore-type */ false);
Loading history...
1125
		$bbcTags = array();
1126
		foreach ($temp as $tag)
0 ignored issues
show
Bug introduced by
The expression $temp of type string is not traversable.
Loading history...
1127
			$bbcTags[] = $tag['tag'];
1128
1129
		$bbcTags = array_unique($bbcTags);
1130
		$totalTags = count($bbcTags);
1131
1132
		// The number of columns we want to show the BBC tags in.
1133
		$numColumns = isset($context['num_bbc_columns']) ? $context['num_bbc_columns'] : 3;
1134
1135
		// Start working out the context stuff.
1136
		$context['bbc_columns'] = array();
1137
		$tagsPerColumn = ceil($totalTags / $numColumns);
1138
1139
		$col = 0; $i = 0;
1140
		foreach ($bbcTags as $tag)
1141
		{
1142
			if ($i % $tagsPerColumn == 0 && $i != 0)
1143
				$col++;
1144
1145
			$context['bbc_columns'][$col][] = array(
1146
				'tag' => $tag,
1147
				// @todo  'tag_' . ?
1148
				'show_help' => isset($helptxt[$tag]),
1149
			);
1150
1151
			$i++;
1152
		}
1153
1154
		// Now put whatever BBC options we may have into context too!
1155
		$context['bbc_sections'] = array();
1156
		foreach ($bbcChoice as $bbc)
1157
		{
1158
			$context['bbc_sections'][$bbc] = array(
1159
				'title' => isset($txt['bbc_title_' . $bbc]) ? $txt['bbc_title_' . $bbc] : $txt['bbcTagsToUse_select'],
1160
				'disabled' => empty($modSettings['bbc_disabled_' . $bbc]) ? array() : $modSettings['bbc_disabled_' . $bbc],
1161
				'all_selected' => empty($modSettings['bbc_disabled_' . $bbc]),
1162
			);
1163
		}
1164
	}
1165
1166
	call_integration_hook('integrate_prepare_db_settings', array(&$config_vars));
1167
	createToken('admin-dbsc');
1168
}
1169
1170
/**
1171
 * Helper function. Saves settings by putting them in Settings.php or saving them in the settings table.
1172
 *
1173
 * - Saves those settings set from ?action=admin;area=serversettings.
1174
 * - Requires the admin_forum permission.
1175
 * - Contains arrays of the types of data to save into Settings.php.
1176
 *
1177
 * @param array $config_vars An array of configuration variables
1178
 */
1179
function saveSettings(&$config_vars)
1180
{
1181
	global $sourcedir, $context;
1182
1183
	validateToken('admin-ssc');
1184
1185
	// Fix the darn stupid cookiename! (more may not be allowed, but these for sure!)
1186
	if (isset($_POST['cookiename']))
1187
		$_POST['cookiename'] = preg_replace('~[,;\s\.$]+~' . ($context['utf8'] ? 'u' : ''), '', $_POST['cookiename']);
1188
1189
	// Fix the forum's URL if necessary.
1190
	if (isset($_POST['boardurl']))
1191
	{
1192
		if (substr($_POST['boardurl'], -10) == '/index.php')
1193
			$_POST['boardurl'] = substr($_POST['boardurl'], 0, -10);
1194
		elseif (substr($_POST['boardurl'], -1) == '/')
1195
			$_POST['boardurl'] = substr($_POST['boardurl'], 0, -1);
1196
		if (substr($_POST['boardurl'], 0, 7) != 'http://' && substr($_POST['boardurl'], 0, 7) != 'file://' && substr($_POST['boardurl'], 0, 8) != 'https://')
1197
			$_POST['boardurl'] = 'http://' . $_POST['boardurl'];
1198
	}
1199
1200
	// Any passwords?
1201
	$config_passwords = array(
1202
		'db_passwd',
1203
		'ssi_db_passwd',
1204
	);
1205
1206
	// All the strings to write.
1207
	$config_strs = array(
1208
		'mtitle', 'mmessage',
1209
		'language', 'mbname', 'boardurl',
1210
		'cookiename',
1211
		'webmaster_email',
1212
		'db_name', 'db_user', 'db_server', 'db_prefix', 'ssi_db_user',
1213
		'boarddir', 'sourcedir',
1214
		'cachedir', 'cachedir_sqlite', 'cache_accelerator', 'cache_memcached',
1215
		'image_proxy_secret',
1216
	);
1217
1218
	// All the numeric variables.
1219
	$config_ints = array(
1220
		'cache_enable',
1221
		'image_proxy_maxsize',
1222
	);
1223
1224
	// All the checkboxes
1225
	$config_bools = array('db_persist', 'db_error_send', 'maintenance', 'image_proxy_enabled');
1226
1227
	// Now sort everything into a big array, and figure out arrays and etc.
1228
	$new_settings = array();
1229
	// Figure out which config vars we're saving here...
1230
	foreach ($config_vars as $var)
1231
	{
1232
		if (!is_array($var) || $var[2] != 'file' || (!in_array($var[0], $config_bools) && !isset($_POST[$var[0]])))
1233
			continue;
1234
1235
		$config_var = $var[0];
1236
1237
		if (in_array($config_var, $config_passwords))
1238
		{
1239
			if (isset($_POST[$config_var][1]) && $_POST[$config_var][0] == $_POST[$config_var][1])
1240
				$new_settings[$config_var] = '\'' . addcslashes($_POST[$config_var][0], '\'\\') . '\'';
1241
		}
1242
		elseif (in_array($config_var, $config_strs))
1243
		{
1244
			$new_settings[$config_var] = '\'' . addcslashes($_POST[$config_var], '\'\\') . '\'';
1245
		}
1246
		elseif (in_array($config_var, $config_ints))
1247
		{
1248
			$new_settings[$config_var] = (int) $_POST[$config_var];
1249
1250
			// If no min is specified, assume 0. This is done to avoid having to specify 'min => 0' for all settings where 0 is the min...
1251
			$min = isset($var['min']) ? $var['min'] : 0;
1252
			$new_settings[$config_var] = max($min, $new_settings[$config_var]);
1253
1254
			// Is there a max value for this as well?
1255
			if (isset($var['max']))
1256
				$new_settings[$config_var] = min($var['max'], $new_settings[$config_var]);
1257
		}
1258
		elseif (in_array($config_var, $config_bools))
1259
		{
1260
			if (!empty($_POST[$config_var]))
1261
				$new_settings[$config_var] = '1';
1262
			else
1263
				$new_settings[$config_var] = '0';
1264
		}
1265
		else
1266
		{
1267
			// This shouldn't happen, but it might...
1268
			fatal_error('Unknown config_var \'' . $config_var . '\'');
1269
		}
1270
	}
1271
1272
	// Save the relevant settings in the Settings.php file.
1273
	require_once($sourcedir . '/Subs-Admin.php');
1274
	updateSettingsFile($new_settings);
1275
1276
	// Now loop through the remaining (database-based) settings.
1277
	$new_settings = array();
1278
	foreach ($config_vars as $config_var)
1279
	{
1280
		// We just saved the file-based settings, so skip their definitions.
1281
		if (!is_array($config_var) || $config_var[2] == 'file')
1282
			continue;
1283
1284
		$new_setting = array($config_var[3], $config_var[0]);
1285
1286
		// Select options need carried over, too.
1287
		if (isset($config_var[4]))
1288
			$new_setting[] = $config_var[4];
1289
1290
		// Include min and max if necessary
1291
		if (isset($config_var['min']))
1292
			$new_setting['min'] = $config_var['min'];
1293
1294
		if (isset($config_var['max']))
1295
			$new_setting['max'] = $config_var['max'];
1296
1297
		// Rewrite the definition a bit.
1298
		$new_settings[] = $new_setting;
1299
	}
1300
1301
	// Save the new database-based settings, if any.
1302
	if (!empty($new_settings))
1303
		saveDBSettings($new_settings);
1304
}
1305
1306
/**
1307
 * Helper function for saving database settings.
1308
 * @todo see rev. 10406 from 2.1-requests
1309
 *
1310
 * @param array $config_vars An array of configuration variables
1311
 */
1312
function saveDBSettings(&$config_vars)
1313
{
1314
	global $sourcedir, $smcFunc;
1315
	static $board_list = null;
1316
1317
	validateToken('admin-dbsc');
1318
1319
	$inlinePermissions = array();
1320
	foreach ($config_vars as $var)
1321
	{
1322
		if (!isset($var[1]) || (!isset($_POST[$var[1]]) && $var[0] != 'check' && $var[0] != 'permissions' && $var[0] != 'boards' && ($var[0] != 'bbc' || !isset($_POST[$var[1] . '_enabledTags']))))
1323
			continue;
1324
1325
		// Checkboxes!
1326
		elseif ($var[0] == 'check')
1327
			$setArray[$var[1]] = !empty($_POST[$var[1]]) ? '1' : '0';
1328
		// Select boxes!
1329
		elseif ($var[0] == 'select' && in_array($_POST[$var[1]], array_keys($var[2])))
1330
			$setArray[$var[1]] = $_POST[$var[1]];
1331
		elseif ($var[0] == 'select' && !empty($var['multiple']) && array_intersect($_POST[$var[1]], array_keys($var[2])) != array())
1332
		{
1333
			// For security purposes we validate this line by line.
1334
			$lOptions = array();
1335
			foreach ($_POST[$var[1]] as $invar)
1336
				if (in_array($invar, array_keys($var[2])))
1337
					$lOptions[] = $invar;
1338
1339
			$setArray[$var[1]] = $smcFunc['json_encode']($lOptions);
1340
		}
1341
		// List of boards!
1342
		elseif ($var[0] == 'boards')
1343
		{
1344
			// We just need a simple list of valid boards, nothing more.
1345
			if ($board_list === null)
1346
			{
1347
				$board_list = array();
1348
				$request = $smcFunc['db_query']('', '
1349
					SELECT id_board
1350
					FROM {db_prefix}boards');
1351
				while ($row = $smcFunc['db_fetch_row']($request))
1352
					$board_list[$row[0]] = true;
1353
1354
				$smcFunc['db_free_result']($request);
1355
			}
1356
1357
			$lOptions = array();
1358
1359
			if (!empty($_POST[$var[1]]))
1360
				foreach ($_POST[$var[1]] as $invar => $dummy)
1361
					if (isset($board_list[$invar]))
1362
						$lOptions[] = $invar;
1363
1364
			$setArray[$var[1]] = !empty($lOptions) ? implode(',', $lOptions) : '';
1365
		}
1366
		// Integers!
1367
		elseif ($var[0] == 'int')
1368
		{
1369
			$setArray[$var[1]] = (int) $_POST[$var[1]];
1370
1371
			// If no min is specified, assume 0. This is done to avoid having to specify 'min => 0' for all settings where 0 is the min...
1372
			$min = isset($var['min']) ? $var['min'] : 0;
1373
			$setArray[$var[1]] = max($min, $setArray[$var[1]]);
1374
1375
			// Do we have a max value for this as well?
1376
			if (isset($var['max']))
1377
				$setArray[$var[1]] = min($var['max'], $setArray[$var[1]]);
1378
		}
1379
		// Floating point!
1380
		elseif ($var[0] == 'float')
1381
		{
1382
			$setArray[$var[1]] = (float) $_POST[$var[1]];
1383
1384
			// If no min is specified, assume 0. This is done to avoid having to specify 'min => 0' for all settings where 0 is the min...
1385
			$min = isset($var['min']) ? $var['min'] : 0;
1386
			$setArray[$var[1]] = max($min, $setArray[$var[1]]);
1387
1388
			// Do we have a max value for this as well?
1389
			if (isset($var['max']))
1390
				$setArray[$var[1]] = min($var['max'], $setArray[$var[1]]);
1391
		}
1392
		// Text!
1393
		elseif (in_array($var[0], array('text', 'large_text', 'color', 'date', 'datetime', 'datetime-local', 'email', 'month', 'time')))
1394
			$setArray[$var[1]] = $_POST[$var[1]];
1395
		// Passwords!
1396
		elseif ($var[0] == 'password')
1397
		{
1398
			if (isset($_POST[$var[1]][1]) && $_POST[$var[1]][0] == $_POST[$var[1]][1])
1399
				$setArray[$var[1]] = $_POST[$var[1]][0];
1400
		}
1401
		// BBC.
1402
		elseif ($var[0] == 'bbc')
1403
		{
1404
			$bbcTags = array();
1405
			foreach (parse_bbc(false) as $tag)
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $message of parse_bbc(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1405
			foreach (parse_bbc(/** @scrutinizer ignore-type */ false) as $tag)
Loading history...
Bug introduced by
The expression parse_bbc(false) of type string is not traversable.
Loading history...
1406
				$bbcTags[] = $tag['tag'];
1407
1408
			if (!isset($_POST[$var[1] . '_enabledTags']))
1409
				$_POST[$var[1] . '_enabledTags'] = array();
1410
			elseif (!is_array($_POST[$var[1] . '_enabledTags']))
1411
				$_POST[$var[1] . '_enabledTags'] = array($_POST[$var[1] . '_enabledTags']);
1412
1413
			$setArray[$var[1]] = implode(',', array_diff($bbcTags, $_POST[$var[1] . '_enabledTags']));
1414
		}
1415
		// Permissions?
1416
		elseif ($var[0] == 'permissions')
1417
			$inlinePermissions[] = $var[1];
1418
	}
1419
1420
	if (!empty($setArray))
1421
		updateSettings($setArray);
1422
1423
	// If we have inline permissions we need to save them.
1424
	if (!empty($inlinePermissions) && allowedTo('manage_permissions'))
1425
	{
1426
		require_once($sourcedir . '/ManagePermissions.php');
1427
		save_inline_permissions($inlinePermissions);
1428
	}
1429
}
1430
1431
/**
1432
 * Allows us to see the servers php settings
1433
 *
1434
 * - loads the settings into an array for display in a template
1435
 * - drops cookie values just in case
1436
 */
1437
function ShowPHPinfoSettings()
1438
{
1439
	global $context, $txt;
1440
1441
	$category = $txt['phpinfo_settings'];
1442
1443
	// get the data
1444
	ob_start();
1445
	phpinfo();
1446
1447
	// We only want it for its body, pigs that we are
1448
	$info_lines = preg_replace('~^.*<body>(.*)</body>.*$~', '$1', ob_get_contents());
1449
	$info_lines = explode("\n", strip_tags($info_lines, "<tr><td><h2>"));
1450
	ob_end_clean();
1451
1452
	// remove things that could be considered sensitive
1453
	$remove = '_COOKIE|Cookie|_GET|_REQUEST|REQUEST_URI|QUERY_STRING|REQUEST_URL|HTTP_REFERER';
1454
1455
	// put all of it into an array
1456
	foreach ($info_lines as $line)
1457
	{
1458
		if (preg_match('~(' . $remove . ')~', $line))
1459
			continue;
1460
1461
		// new category?
1462
		if (strpos($line, '<h2>') !== false)
1463
			$category = preg_match('~<h2>(.*)</h2>~', $line, $title) ? $category = $title[1] : $category;
0 ignored issues
show
Unused Code introduced by
The assignment to $category is dead and can be removed.
Loading history...
1464
1465
		// load it as setting => value or the old setting local master
1466
		if (preg_match('~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~', $line, $val))
1467
			$pinfo[$category][$val[1]] = $val[2];
1468
		elseif (preg_match('~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~', $line, $val))
1469
			$pinfo[$category][$val[1]] = array($txt['phpinfo_localsettings'] => $val[2], $txt['phpinfo_defaultsettings'] => $val[3]);
1470
	}
1471
1472
	// load it in to context and display it
1473
	$context['pinfo'] = $pinfo;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $pinfo does not seem to be defined for all execution paths leading up to this point.
Loading history...
1474
	$context['page_title'] = $txt['admin_server_settings'];
1475
	$context['sub_template'] = 'php_info';
1476
	return;
1477
}
1478
1479
/**
1480
 * Get the installed Cache API implementations.
1481
 *
1482
 */
1483
function loadCacheAPIs()
1484
{
1485
	global $sourcedir, $txt;
1486
1487
	// Make sure our class is in session.
1488
	require_once($sourcedir . '/Class-CacheAPI.php');
1489
1490
	$apis = array();
1491
	if ($dh = opendir($sourcedir))
1492
	{
1493
		while (($file = readdir($dh)) !== false)
1494
		{
1495
			if (is_file($sourcedir . '/' . $file) && preg_match('~^CacheAPI-([A-Za-z\d_]+)\.php$~', $file, $matches))
1496
			{
1497
				$tryCache = strtolower($matches[1]);
1498
1499
				require_once($sourcedir . '/' . $file);
1500
				$cache_class_name = $tryCache . '_cache';
1501
				$testAPI = new $cache_class_name();
1502
1503
				// No Support?  NEXT!
1504
				if (!$testAPI->isSupported(true))
1505
					continue;
1506
1507
				$apis[$tryCache] = isset($txt[$tryCache . '_cache']) ? $txt[$tryCache . '_cache'] : $tryCache;
1508
			}
1509
		}
1510
	}
1511
	closedir($dh);
0 ignored issues
show
Bug introduced by
It seems like $dh can also be of type false; however, parameter $dir_handle of closedir() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1511
	closedir(/** @scrutinizer ignore-type */ $dh);
Loading history...
1512
1513
	return $apis;
1514
}
1515
1516
/**
1517
 * Registers the site with the Simple Machines Stat collection. This function
1518
 * purposely does not use updateSettings.php as it will be called shortly after
1519
 * this process completes by the saveSettings() function.
1520
 *
1521
 * @see Stats.php SMStats() for more information.
1522
 * @link https://www.simplemachines.org/about/stats.php for more info.
1523
 *
1524
 */
1525
function registerSMStats()
1526
{
1527
	global $modSettings, $boardurl, $smcFunc;
1528
1529
	// Already have a key?  Can't register again.
1530
	if (!empty($modSettings['sm_stats_key']))
1531
		return true;
1532
1533
	$fp = @fsockopen('www.simplemachines.org', 80, $errno, $errstr);
1534
	if ($fp)
0 ignored issues
show
introduced by
$fp is of type resource, thus it always evaluated to false.
Loading history...
1535
	{
1536
		$out = 'GET /smf/stats/register_stats.php?site=' . base64_encode($boardurl) . ' HTTP/1.1' . "\r\n";
1537
		$out .= 'Host: www.simplemachines.org' . "\r\n";
1538
		$out .= 'Connection: Close' . "\r\n\r\n";
1539
		fwrite($fp, $out);
1540
1541
		$return_data = '';
1542
		while (!feof($fp))
1543
			$return_data .= fgets($fp, 128);
1544
1545
		fclose($fp);
1546
1547
		// Get the unique site ID.
1548
		preg_match('~SITE-ID:\s(\w{10})~', $return_data, $ID);
1549
1550
		if (!empty($ID[1]))
1551
		{
1552
			$smcFunc['db_insert']('replace',
1553
				'{db_prefix}settings',
1554
				array('variable' => 'string', 'value' => 'string'),
1555
				array('sm_stats_key', $ID[1]),
1556
				array('variable')
1557
			);
1558
			return true;
1559
		}
1560
	}
1561
1562
	return false;
1563
}
1564
1565
?>