Passed
Push — release-2.1 ( 249e75...276738 )
by Mathias
39s queued 10s
created

saveDBSettings()   F

Complexity

Conditions 43
Paths 140

Size

Total Lines 117
Code Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 43
eloc 63
c 0
b 0
f 0
nc 140
nop 1
dl 0
loc 117
rs 3.8333

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 https://www.simplemachines.org
56
 * @copyright 2020 Simple Machines and individual contributors
57
 * @license https://www.simplemachines.org/about/smf/license.php BSD
58
 *
59
 * @version 2.1 RC2
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'] = array(
116
			'label' => $txt['settings_not_writable'],
117
			'tag' => 'div',
118
			'class' => 'centertext strong'
119
		);
120
	elseif ($settings_backup_fail)
121
		$context['settings_message'] = array(
122
			'label' => $txt['admin_backup_fail'],
123
			'tag' => 'div',
124
			'class' => 'centertext strong'
125
		);
126
127
	$context['settings_not_writable'] = $settings_not_writable;
128
129
	call_integration_hook('integrate_server_settings', array(&$subActions));
130
131
	// Call the right function for this sub-action.
132
	call_helper($subActions[$_REQUEST['sa']]);
133
}
134
135
/**
136
 * General forum settings - forum name, maintenance mode, etc.
137
 * Practically, this shows an interface for the settings in Settings.php to be changed.
138
 *
139
 * - Requires the admin_forum permission.
140
 * - Uses the edit_settings administration area.
141
 * - Contains the actual array of settings to show from Settings.php.
142
 * - Accessed from ?action=admin;area=serversettings;sa=general.
143
 *
144
 * @param bool $return_config Whether to return the $config_vars array (for pagination purposes)
145
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
146
 */
147
function ModifyGeneralSettings($return_config = false)
148
{
149
	global $scripturl, $context, $txt, $modSettings, $boardurl, $sourcedir;
150
151
	// If no cert, force_ssl must remain 0
152
	require_once($sourcedir . '/Subs.php');
153
	if (!ssl_cert_found($boardurl) && empty($modSettings['force_ssl']))
154
		$disable_force_ssl = true;
155
	else
156
		$disable_force_ssl = false;
157
158
	/* If you're writing a mod, it's a bad idea to add things here....
159
	For each option:
160
		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)
161
	OR	an empty string for a horizontal rule.
162
	OR	a string for a titled section. */
163
	$config_vars = array(
164
		array('mbname', $txt['admin_title'], 'file', 'text', 30),
165
		'',
166
		array('maintenance', $txt['admin_maintain'], 'file', 'check'),
167
		array('mtitle', $txt['maintenance_subject'], 'file', 'text', 36),
168
		array('mmessage', $txt['maintenance_message'], 'file', 'text', 36),
169
		'',
170
		array('webmaster_email', $txt['admin_webmaster_email'], 'file', 'text', 30),
171
		'',
172
		array('enableCompressedOutput', $txt['enableCompressedOutput'], 'db', 'check', null, 'enableCompressedOutput'),
173
		array('disableHostnameLookup', $txt['disableHostnameLookup'], 'db', 'check', null, 'disableHostnameLookup'),
174
		'',
175
		array('force_ssl', $txt['force_ssl'], 'db', 'select', array($txt['force_ssl_off'], $txt['force_ssl_complete']), 'force_ssl', 'disabled' => $disable_force_ssl),
176
		array('image_proxy_enabled', $txt['image_proxy_enabled'], 'file', 'check', null, 'image_proxy_enabled'),
177
		array('image_proxy_secret', $txt['image_proxy_secret'], 'file', 'text', 30, 'image_proxy_secret'),
178
		array('image_proxy_maxsize', $txt['image_proxy_maxsize'], 'file', 'int', null, 'image_proxy_maxsize'),
179
		'',
180
		array('enable_sm_stats', $txt['enable_sm_stats'], 'db', 'check', null, 'enable_sm_stats'),
181
	);
182
183
	call_integration_hook('integrate_general_settings', array(&$config_vars));
184
185
	if ($return_config)
186
		return $config_vars;
187
188
	// Setup the template stuff.
189
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=general;save';
190
	$context['settings_title'] = $txt['general_settings'];
191
192
	// Saving settings?
193
	if (isset($_REQUEST['save']))
194
	{
195
		call_integration_hook('integrate_save_general_settings');
196
197
		// Are we saving the stat collection?
198
		if (!empty($_POST['enable_sm_stats']) && empty($modSettings['sm_stats_key']))
199
		{
200
			$registerSMStats = registerSMStats();
201
202
			// Failed to register, disable it again.
203
			if (empty($registerSMStats))
204
				$_POST['enable_sm_stats'] = 0;
205
		}
206
207
		// Ensure all URLs are aligned with the new force_ssl setting
208
		// Treat unset like 0
209
		if (isset($_POST['force_ssl']))
210
			AlignURLsWithSSLSetting($_POST['force_ssl']);
211
		else
212
			AlignURLsWithSSLSetting(0);
213
214
		saveSettings($config_vars);
215
		$_SESSION['adm-save'] = true;
216
		redirectexit('action=admin;area=serversettings;sa=general;' . $context['session_var'] . '=' . $context['session_id']);
217
	}
218
219
	// Fill the config array.
220
	prepareServerSettingsContext($config_vars);
221
222
	// Some javascript for SSL
223
	addInlineJavaScript('
224
$(function()
225
{
226
	$("#force_ssl").change(function()
227
	{
228
		var mode = $(this).val() == 1 ? false : true;
229
		$("#image_proxy_enabled").prop("disabled", mode);
230
		$("#image_proxy_secret").prop("disabled", mode);
231
		$("#image_proxy_maxsize").prop("disabled", mode);
232
	}).change();
233
});', true);
234
}
235
236
/**
237
 * Align URLs with SSL Setting.
238
 *
239
 * If force_ssl has changed, ensure all URLs are aligned with the new setting.
240
 * This includes:
241
 *     - $boardurl
242
 *     - $modSettings['smileys_url']
243
 *     - $modSettings['avatar_url']
244
 *     - $modSettings['custom_avatar_url'] - if found
245
 *     - theme_url - all entries in the themes table
246
 *     - images_url - all entries in the themes table
247
 *
248
 * This function will NOT overwrite URLs that are not subfolders of $boardurl.
249
 * The admin must have pointed those somewhere else on purpose, so they must be updated manually.
250
 *
251
 * A word of caution: You can't trust the http/https scheme reflected for these URLs in $globals
252
 * (e.g., $boardurl) or in $modSettings.  This is because SMF may change them in memory to comply
253
 * with the force_ssl setting - a soft redirect may be in effect...  Thus, conditional updates
254
 * to these values do not work.  You gotta just brute force overwrite them based on force_ssl.
255
 *
256
 * @param int $new_force_ssl is the current force_ssl setting.
257
 * @return void Returns nothing, just does its job
258
 */
259
function AlignURLsWithSSLSetting($new_force_ssl = 0)
260
{
261
	global $boardurl, $modSettings, $sourcedir, $smcFunc;
262
	require_once($sourcedir . '/Subs-Admin.php');
263
264
	// Check $boardurl
265
	if (!empty($new_force_ssl))
266
		$newval = strtr($boardurl, array('http://' => 'https://'));
267
	else
268
		$newval = strtr($boardurl, array('https://' => 'http://'));
269
	updateSettingsFile(array('boardurl' => $newval));
270
271
	$new_settings = array();
272
273
	// Check $smileys_url, but only if it points to a subfolder of $boardurl
274
	if (BoardurlMatch($modSettings['smileys_url']))
275
	{
276
		if (!empty($new_force_ssl))
277
			$newval = strtr($modSettings['smileys_url'], array('http://' => 'https://'));
278
		else
279
			$newval = strtr($modSettings['smileys_url'], array('https://' => 'http://'));
280
		$new_settings['smileys_url'] = $newval;
281
	}
282
283
	// Check $avatar_url, but only if it points to a subfolder of $boardurl
284
	if (BoardurlMatch($modSettings['avatar_url']))
285
	{
286
		if (!empty($new_force_ssl))
287
			$newval = strtr($modSettings['avatar_url'], array('http://' => 'https://'));
288
		else
289
			$newval = strtr($modSettings['avatar_url'], array('https://' => 'http://'));
290
		$new_settings['avatar_url'] = $newval;
291
	}
292
293
	// Check $custom_avatar_url, but only if it points to a subfolder of $boardurl
294
	// This one had been optional in the past, make sure it is set first
295
	if (isset($modSettings['custom_avatar_url']) && BoardurlMatch($modSettings['custom_avatar_url']))
296
	{
297
		if (!empty($new_force_ssl))
298
			$newval = strtr($modSettings['custom_avatar_url'], array('http://' => 'https://'));
299
		else
300
			$newval = strtr($modSettings['custom_avatar_url'], array('https://' => 'http://'));
301
		$new_settings['custom_avatar_url'] = $newval;
302
	}
303
304
	// Save updates to the settings table
305
	if (!empty($new_settings))
306
		updateSettings($new_settings, true);
307
308
	// Now we move onto the themes.
309
	// First, get a list of theme URLs...
310
	$request = $smcFunc['db_query']('', '
311
		SELECT id_theme, variable, value
312
		FROM {db_prefix}themes
313
		WHERE variable in ({string:themeurl}, {string:imagesurl})
314
			AND id_member = {int:zero}',
315
		array(
316
			'themeurl' => 'theme_url',
317
			'imagesurl' => 'images_url',
318
			'zero' => 0,
319
		)
320
	);
321
322
	while ($row = $smcFunc['db_fetch_assoc']($request))
323
	{
324
		// First check to see if it points to a subfolder of $boardurl
325
		if (BoardurlMatch($row['value']))
326
		{
327
			if (!empty($new_force_ssl))
328
				$newval = strtr($row['value'], array('http://' => 'https://'));
329
			else
330
				$newval = strtr($row['value'], array('https://' => 'http://'));
331
332
			$smcFunc['db_query']('', '
333
				UPDATE {db_prefix}themes
334
				SET value = {string:theme_val}
335
				WHERE variable = {string:theme_var}
336
					AND id_theme = {string:theme_id}
337
					AND id_member = {int:zero}',
338
				array(
339
					'theme_val' => $newval,
340
					'theme_var' => $row['variable'],
341
					'theme_id' => $row['id_theme'],
342
					'zero' => 0,
343
				)
344
			);
345
		}
346
	}
347
	$smcFunc['db_free_result']($request);
348
}
349
350
/**
351
 * $boardurl Match.
352
 *
353
 * Helper function to see if the url being checked is based off of $boardurl.
354
 * If not, it was overridden by the admin to some other value on purpose, and should not
355
 * be stepped on by SMF when aligning URLs with the force_ssl setting.
356
 * The site admin must change URLs that are not aligned with $boardurl manually.
357
 *
358
 * @param string $url is the url to check.
359
 * @return bool Returns true if the url is based off of $boardurl (without the scheme), false if not
360
 */
361
function BoardurlMatch($url = '')
362
{
363
	global $boardurl;
364
365
	// Strip the schemes
366
	$urlpath = strtr($url, array('http://' => '', 'https://' => ''));
367
	$boardurlpath = strtr($boardurl, array('http://' => '', 'https://' => ''));
368
369
	// If leftmost portion of path matches boardurl, return true
370
	$result = strpos($urlpath, $boardurlpath);
371
	if ($result === false || $result != 0)
372
		return false;
373
	else
374
		return true;
375
}
376
377
/**
378
 * Basic database and paths settings - database name, host, etc.
379
 *
380
 * - It shows an interface for the settings in Settings.php to be changed.
381
 * - It contains the actual array of settings to show from Settings.php.
382
 * - Requires the admin_forum permission.
383
 * - Uses the edit_settings administration area.
384
 * - Accessed from ?action=admin;area=serversettings;sa=database.
385
 *
386
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
387
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
388
 */
389
function ModifyDatabaseSettings($return_config = false)
390
{
391
	global $scripturl, $context, $txt, $smcFunc;
392
	db_extend('extra');
393
394
	/* If you're writing a mod, it's a bad idea to add things here....
395
		For each option:
396
		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)
397
		OR an empty string for a horizontal rule.
398
		OR a string for a titled section. */
399
	$config_vars = array(
400
		array('db_persist', $txt['db_persist'], 'file', 'check', null, 'db_persist'),
401
		array('db_error_send', $txt['db_error_send'], 'file', 'check'),
402
		array('ssi_db_user', $txt['ssi_db_user'], 'file', 'text', null, 'ssi_db_user'),
403
		array('ssi_db_passwd', $txt['ssi_db_passwd'], 'file', 'password'),
404
		'',
405
		array('autoFixDatabase', $txt['autoFixDatabase'], 'db', 'check', false, 'autoFixDatabase')
406
	);
407
408
	// Add PG Stuff
409
	if ($smcFunc['db_title'] === POSTGRE_TITLE)
410
	{
411
		$request = $smcFunc['db_query']('', 'SELECT cfgname FROM pg_ts_config', array());
412
		$fts_language = array();
413
414
		while ($row = $smcFunc['db_fetch_assoc']($request))
415
			$fts_language[$row['cfgname']] = $row['cfgname'];
416
417
		$config_vars = array_merge($config_vars, array(
418
				'',
419
				array('search_language', $txt['search_language'], 'db', 'select', $fts_language, 'pgFulltextSearch')
420
			)
421
		);
422
	}
423
424
	call_integration_hook('integrate_database_settings', array(&$config_vars));
425
426
	if ($return_config)
427
		return $config_vars;
428
429
	// Setup the template stuff.
430
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=database;save';
431
	$context['settings_title'] = $txt['database_settings'];
432
	$context['save_disabled'] = $context['settings_not_writable'];
433
434
	if (!$smcFunc['db_allow_persistent']())
435
		addInlineJavaScript('
436
			$(function()
437
			{
438
				$("#db_persist").prop("disabled", true);
439
			});', true);
440
441
	// Saving settings?
442
	if (isset($_REQUEST['save']))
443
	{
444
		call_integration_hook('integrate_save_database_settings');
445
446
		saveSettings($config_vars);
447
		$_SESSION['adm-save'] = true;
448
		redirectexit('action=admin;area=serversettings;sa=database;' . $context['session_var'] . '=' . $context['session_id']);
449
	}
450
451
	// Fill the config array.
452
	prepareServerSettingsContext($config_vars);
453
}
454
455
/**
456
 * This function handles cookies settings modifications.
457
 *
458
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
459
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
460
 */
461
function ModifyCookieSettings($return_config = false)
462
{
463
	global $context, $scripturl, $txt, $sourcedir, $modSettings, $cookiename, $user_settings, $boardurl, $smcFunc;
464
465
	// Define the variables we want to edit.
466
	$config_vars = array(
467
		// Cookies...
468
		array('cookiename', $txt['cookie_name'], 'file', 'text', 20),
469
		array('cookieTime', $txt['cookieTime'], 'db', 'select', array(
470
			3153600 => $txt['always_logged_in'],
471
			60 => $txt['one_hour'],
472
			1440 => $txt['one_day'],
473
			10080 => $txt['one_week'],
474
			43200 => $txt['one_month'],
475
		)),
476
		array('localCookies', $txt['localCookies'], 'db', 'check', false, 'localCookies'),
477
		array('globalCookies', $txt['globalCookies'], 'db', 'check', false, 'globalCookies'),
478
		array('globalCookiesDomain', $txt['globalCookiesDomain'], 'db', 'text', false, 'globalCookiesDomain'),
479
		array('secureCookies', $txt['secureCookies'], 'db', 'check', false, 'secureCookies', 'disabled' => !httpsOn()),
480
		array('httponlyCookies', $txt['httponlyCookies'], 'db', 'check', false, 'httponlyCookies'),
481
		'',
482
		// Sessions
483
		array('databaseSession_enable', $txt['databaseSession_enable'], 'db', 'check', false, 'databaseSession_enable'),
484
		array('databaseSession_loose', $txt['databaseSession_loose'], 'db', 'check', false, 'databaseSession_loose'),
485
		array('databaseSession_lifetime', $txt['databaseSession_lifetime'], 'db', 'int', false, 'databaseSession_lifetime', 'postinput' => $txt['seconds']),
486
		'',
487
		// 2FA
488
		array('tfa_mode', $txt['tfa_mode'], 'db', 'select', array(
489
			0 => $txt['tfa_mode_disabled'],
490
			1 => $txt['tfa_mode_enabled'],
491
		) + (empty($user_settings['tfa_secret']) ? array() : array(
492
			2 => $txt['tfa_mode_forced'],
493
		)) + (empty($user_settings['tfa_secret']) ? array() : array(
494
			3 => $txt['tfa_mode_forcedall'],
495
		)), 'subtext' => $txt['tfa_mode_subtext'] . (empty($user_settings['tfa_secret']) ? '<br><strong>' . $txt['tfa_mode_forced_help'] . '</strong>' : ''), 'tfa_mode'),
496
	);
497
498
	addInlineJavaScript('
499
	function hideGlobalCookies()
500
	{
501
		var usingLocal = $("#localCookies").prop("checked");
502
		$("#setting_globalCookies").closest("dt").toggle(!usingLocal);
503
		$("#globalCookies").closest("dd").toggle(!usingLocal);
504
505
		var usingGlobal = !usingLocal && $("#globalCookies").prop("checked");
506
		$("#setting_globalCookiesDomain").closest("dt").toggle(usingGlobal);
507
		$("#globalCookiesDomain").closest("dd").toggle(usingGlobal);
508
	};
509
	hideGlobalCookies();
510
511
	$("#localCookies, #globalCookies").click(function() {
512
		hideGlobalCookies();
513
	});', true);
514
515
	if (empty($user_settings['tfa_secret']))
516
		addInlineJavaScript('');
517
518
	call_integration_hook('integrate_cookie_settings', array(&$config_vars));
519
520
	if ($return_config)
521
		return $config_vars;
522
523
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=cookie;save';
524
	$context['settings_title'] = $txt['cookies_sessions_settings'];
525
526
	// Saving settings?
527
	if (isset($_REQUEST['save']))
528
	{
529
		call_integration_hook('integrate_save_cookie_settings');
530
531
		// Local and global do not play nicely together.
532
		if (!empty($_POST['localCookies']) && empty($_POST['globalCookies']))
533
			unset ($_POST['globalCookies']);
534
535
		if (empty($modSettings['localCookies']) != empty($_POST['localCookies']) || empty($modSettings['globalCookies']) != empty($_POST['globalCookies']))
536
			$scope_changed = true;
537
538
		if (!empty($_POST['globalCookiesDomain']) && strpos($boardurl, $_POST['globalCookiesDomain']) === false)
539
			fatal_lang_error('invalid_cookie_domain', false);
540
541
		saveSettings($config_vars);
542
543
		// If the cookie name or scope were changed, reset the cookie.
544
		if ($cookiename != $_POST['cookiename'] || !empty($scope_changed))
545
		{
546
			$original_session_id = $context['session_id'];
547
			include_once($sourcedir . '/Subs-Auth.php');
548
549
			// Remove the old cookie.
550
			setLoginCookie(-3600, 0);
551
552
			// Set the new one.
553
			$cookiename = !empty($_POST['cookiename']) ? $_POST['cookiename'] : $cookiename;
554
			setLoginCookie(60 * $modSettings['cookieTime'], $user_settings['id_member'], hash_salt($user_settings['passwd'], $user_settings['password_salt']));
555
556
			redirectexit('action=admin;area=serversettings;sa=cookie;' . $context['session_var'] . '=' . $original_session_id, $context['server']['needs_login_fix']);
557
		}
558
559
		//If we disabled 2FA, reset all members and membergroups settings.
560
		if (isset($_POST['tfa_mode']) && empty($_POST['tfa_mode']))
561
		{
562
			$smcFunc['db_query']('', '
563
				UPDATE {db_prefix}membergroups
564
				SET tfa_required = {int:zero}',
565
				array(
566
					'zero' => 0,
567
				)
568
			);
569
			$smcFunc['db_query']('', '
570
				UPDATE {db_prefix}members
571
				SET tfa_secret = {string:empty}, tfa_backup = {string:empty}',
572
				array(
573
					'empty' => '',
574
				)
575
			);
576
		}
577
578
		$_SESSION['adm-save'] = true;
579
		redirectexit('action=admin;area=serversettings;sa=cookie;' . $context['session_var'] . '=' . $context['session_id']);
580
	}
581
582
	// Fill the config array.
583
	prepareServerSettingsContext($config_vars);
584
}
585
586
/**
587
 * Settings really associated with general security aspects.
588
 *
589
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
590
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
591
 */
592
function ModifyGeneralSecuritySettings($return_config = false)
593
{
594
	global $txt, $scripturl, $context;
595
596
	$config_vars = array(
597
		array('int', 'failed_login_threshold'),
598
		array('int', 'loginHistoryDays', 'subtext' => $txt['zero_to_disable']),
599
		'',
600
601
		array('check', 'securityDisable'),
602
		array('check', 'securityDisable_moderate'),
603
		'',
604
605
		// Reactive on email, and approve on delete
606
		array('check', 'send_validation_onChange'),
607
		array('check', 'approveAccountDeletion'),
608
		'',
609
610
		// Password strength.
611
		array(
612
			'select',
613
			'password_strength',
614
			array(
615
				$txt['setting_password_strength_low'],
616
				$txt['setting_password_strength_medium'],
617
				$txt['setting_password_strength_high']
618
			)
619
		),
620
		array('check', 'enable_password_conversion'),
621
		'',
622
623
		// Reporting of personal messages?
624
		array('check', 'enableReportPM'),
625
		'',
626
627
		array(
628
			'select',
629
			'frame_security',
630
			array(
631
				'SAMEORIGIN' => $txt['setting_frame_security_SAMEORIGIN'],
632
				'DENY' => $txt['setting_frame_security_DENY'],
633
				'DISABLE' => $txt['setting_frame_security_DISABLE']
634
			)
635
		),
636
		'',
637
638
		array(
639
			'select',
640
			'proxy_ip_header',
641
			array(
642
				'disabled' => $txt['setting_proxy_ip_header_disabled'],
643
				'autodetect' => $txt['setting_proxy_ip_header_autodetect'],
644
				'HTTP_X_FORWARDED_FOR' => 'HTTP_X_FORWARDED_FOR',
645
				'HTTP_CLIENT_IP' => 'HTTP_CLIENT_IP',
646
				'HTTP_X_REAL_IP' => 'HTTP_X_REAL_IP',
647
				'CF-Connecting-IP' => 'CF-Connecting-IP'
648
			)
649
		),
650
		array('text', 'proxy_ip_servers'),
651
	);
652
653
	call_integration_hook('integrate_general_security_settings', array(&$config_vars));
654
655
	if ($return_config)
656
		return $config_vars;
657
658
	// Saving?
659
	if (isset($_GET['save']))
660
	{
661
		saveDBSettings($config_vars);
662
		$_SESSION['adm-save'] = true;
663
664
		call_integration_hook('integrate_save_general_security_settings');
665
666
		writeLog();
667
		redirectexit('action=admin;area=serversettings;sa=security;' . $context['session_var'] . '=' . $context['session_id']);
668
	}
669
670
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;save;sa=security';
671
	$context['settings_title'] = $txt['security_settings'];
672
673
	prepareDBSettingContext($config_vars);
674
}
675
676
/**
677
 * Simply modifying cache functions
678
 *
679
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
680
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
681
 */
682
function ModifyCacheSettings($return_config = false)
683
{
684
	global $context, $scripturl, $txt;
685
686
	// Detect all available optimizers
687
	$detected = loadCacheAPIs();
688
689
	// set our values to show what, if anything, we found
690
	if (empty($detected))
691
	{
692
		$txt['cache_settings_message'] = '<strong class="alert">' . $txt['detected_no_caching'] . '</strong>';
693
		$cache_level = array($txt['cache_off']);
694
		$detected['none'] = $txt['cache_off'];
695
	}
696
	else
697
	{
698
		$txt['cache_settings_message'] = '<strong class="success">' . sprintf($txt['detected_accelerators'], implode(', ', $detected)) . '</strong>';
699
		$cache_level = array($txt['cache_off'], $txt['cache_level1'], $txt['cache_level2'], $txt['cache_level3']);
700
	}
701
702
	// Define the variables we want to edit.
703
	$config_vars = array(
704
		// Only a few settings, but they are important
705
		array('', $txt['cache_settings_message'], '', 'desc'),
706
		array('cache_enable', $txt['cache_enable'], 'file', 'select', $cache_level, 'cache_enable'),
707
		array('cache_accelerator', $txt['cache_accelerator'], 'file', 'select', $detected),
708
	);
709
710
	// some javascript to enable / disable certain settings if the option is not selected
711
	$context['settings_post_javascript'] = '
712
		$(document).ready(function() {
713
			$("#cache_accelerator").change();
714
		});';
715
716
	call_integration_hook('integrate_modify_cache_settings', array(&$config_vars));
717
718
	// Maybe we have some additional settings from the selected accelerator.
719
	if (!empty($detected))
720
	{
721
		foreach ($detected as $tryCache => $dummy)
722
		{
723
			$cache_class_name = $tryCache . '_cache';
724
725
			// loadCacheAPIs has already included the file, just see if we can't add the settings in.
726
			if (is_callable(array($cache_class_name, 'cacheSettings')))
727
			{
728
				$testAPI = new $cache_class_name();
729
				call_user_func_array(array($testAPI, 'cacheSettings'), array(&$config_vars));
730
			}
731
		}
732
	}
733
	if ($return_config)
734
		return $config_vars;
735
736
	// Saving again?
737
	if (isset($_GET['save']))
738
	{
739
		call_integration_hook('integrate_save_cache_settings');
740
741
		saveSettings($config_vars);
742
		$_SESSION['adm-save'] = true;
743
744
		// We need to save the $cache_enable to $modSettings as well
745
		updatesettings(array('cache_enable' => (int) $_POST['cache_enable']));
746
747
		// exit so we reload our new settings on the page
748
		redirectexit('action=admin;area=serversettings;sa=cache;' . $context['session_var'] . '=' . $context['session_id']);
749
	}
750
751
	loadLanguage('ManageMaintenance');
752
	createToken('admin-maint');
753
	$context['template_layers'][] = 'clean_cache_button';
754
755
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=cache;save';
756
	$context['settings_title'] = $txt['caching_settings'];
757
758
	// Changing cache settings won't have any effect if Settings.php is not writeable.
759
	$context['save_disabled'] = $context['settings_not_writable'];
760
761
	// Decide what message to show.
762
	if (!$context['save_disabled'])
763
		$context['settings_message'] = $txt['caching_information'];
764
765
	// Prepare the template.
766
	prepareServerSettingsContext($config_vars);
767
}
768
769
/**
770
 * Allows to edit load balancing settings.
771
 *
772
 * @param bool $return_config Whether or not to return the config_vars array
773
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
774
 */
775
function ModifyLoadBalancingSettings($return_config = false)
776
{
777
	global $txt, $scripturl, $context, $modSettings;
778
779
	// Setup a warning message, but disabled by default.
780
	$disabled = true;
781
	$context['settings_message'] = array('label' => $txt['loadavg_disabled_conf'], 'class' => 'error');
782
783
	if (DIRECTORY_SEPARATOR === '\\')
784
	{
785
		$context['settings_message']['label'] = $txt['loadavg_disabled_windows'];
786
		if (isset($_GET['save']))
787
			$_SESSION['adm-save'] = $context['settings_message']['label'];
788
	}
789
	elseif (stripos(PHP_OS, 'darwin') === 0)
790
	{
791
		$context['settings_message']['label'] = $txt['loadavg_disabled_osx'];
792
		if (isset($_GET['save']))
793
			$_SESSION['adm-save'] = $context['settings_message']['label'];
794
	}
795
	else
796
	{
797
		$modSettings['load_average'] = @file_get_contents('/proc/loadavg');
798
		if (!empty($modSettings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', $modSettings['load_average'], $matches) !== 0)
799
			$modSettings['load_average'] = (float) $matches[1];
800
		elseif (($modSettings['load_average'] = @`uptime`) !== null && preg_match('~load averages?: (\d+\.\d+), (\d+\.\d+), (\d+\.\d+)~i', $modSettings['load_average'], $matches) !== 0)
801
			$modSettings['load_average'] = (float) $matches[1];
802
		else
803
			unset($modSettings['load_average']);
804
805
		if (!empty($modSettings['load_average']) || (isset($modSettings['load_average']) && $modSettings['load_average'] === 0.0))
806
		{
807
			$context['settings_message']['label'] = sprintf($txt['loadavg_warning'], $modSettings['load_average']);
808
			$disabled = false;
809
		}
810
	}
811
812
	// Start with a simple checkbox.
813
	$config_vars = array(
814
		array('check', 'loadavg_enable', 'disabled' => $disabled),
815
	);
816
817
	// Set the default values for each option.
818
	$default_values = array(
819
		'loadavg_auto_opt' => 1.0,
820
		'loadavg_search' => 2.5,
821
		'loadavg_allunread' => 2.0,
822
		'loadavg_unreadreplies' => 3.5,
823
		'loadavg_show_posts' => 2.0,
824
		'loadavg_userstats' => 10.0,
825
		'loadavg_bbc' => 30.0,
826
		'loadavg_forum' => 40.0,
827
	);
828
829
	// Loop through the settings.
830
	foreach ($default_values as $name => $value)
831
	{
832
		// Use the default value if the setting isn't set yet.
833
		$value = !isset($modSettings[$name]) ? $value : $modSettings[$name];
834
		$config_vars[] = array('float', $name, 'value' => $value, 'disabled' => $disabled);
835
	}
836
837
	call_integration_hook('integrate_loadavg_settings', array(&$config_vars));
838
839
	if ($return_config)
840
		return $config_vars;
841
842
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=loads;save';
843
	$context['settings_title'] = $txt['load_balancing_settings'];
844
845
	// Saving?
846
	if (isset($_GET['save']))
847
	{
848
		// Stupidity is not allowed.
849
		foreach ($_POST as $key => $value)
850
		{
851
			if (strpos($key, 'loadavg') === 0 || $key === 'loadavg_enable' || !in_array($key, array_keys($default_values)))
852
				continue;
853
			else
854
				$_POST[$key] = (float) $value;
855
856
			if ($key == 'loadavg_auto_opt' && $value <= 1)
857
				$_POST['loadavg_auto_opt'] = 1.0;
858
			elseif ($key == 'loadavg_forum' && $value < 10)
859
				$_POST['loadavg_forum'] = 10.0;
860
			elseif ($value < 2)
861
				$_POST[$key] = 2.0;
862
		}
863
864
		call_integration_hook('integrate_save_loadavg_settings');
865
866
		saveDBSettings($config_vars);
867
		if (!isset($_SESSION['adm-save']))
868
			$_SESSION['adm-save'] = true;
869
		redirectexit('action=admin;area=serversettings;sa=loads;' . $context['session_var'] . '=' . $context['session_id']);
870
	}
871
872
	prepareDBSettingContext($config_vars);
873
}
874
875
/**
876
 * Helper function, it sets up the context for the manage server settings.
877
 * - The basic usage of the six numbered key fields are
878
 * - array (0 ,1, 2, 3, 4, 5
879
 *		0 variable name - the name of the saved variable
880
 *		1 label - the text to show on the settings page
881
 *		2 saveto - file or db, where to save the variable name - value pair
882
 *		3 type - type of data to save, int, float, text, check
883
 *		4 size - false or field size
884
 *		5 help - '' or helptxt variable name
885
 *	)
886
 *
887
 * the following named keys are also permitted
888
 * 'disabled' => A string of code that will determine whether or not the setting should be disabled
889
 * 'postinput' => Text to display after the input field
890
 * 'preinput' => Text to display before the input field
891
 * 'subtext' => Additional descriptive text to display under the field's label
892
 * 'min' => minimum allowed value (for int/float). Defaults to 0 if not set.
893
 * 'max' => maximum allowed value (for int/float)
894
 * 'step' => how much to increment/decrement the value by (only for int/float - mostly used for float values).
895
 *
896
 * @param array $config_vars An array of configuration variables
897
 */
898
function prepareServerSettingsContext(&$config_vars)
899
{
900
	global $context, $modSettings, $smcFunc;
901
902
	if (isset($_SESSION['adm-save']))
903
	{
904
		if ($_SESSION['adm-save'] === true)
905
			$context['saved_successful'] = true;
906
		else
907
			$context['saved_failed'] = $_SESSION['adm-save'];
908
909
		unset($_SESSION['adm-save']);
910
	}
911
912
	$context['config_vars'] = array();
913
	foreach ($config_vars as $identifier => $config_var)
914
	{
915
		if (!is_array($config_var) || !isset($config_var[1]))
916
			$context['config_vars'][] = $config_var;
917
		else
918
		{
919
			$varname = $config_var[0];
920
			global $$varname;
921
922
			// Set the subtext in case it's part of the label.
923
			// @todo Temporary. Preventing divs inside label tags.
924
			$divPos = strpos($config_var[1], '<div');
925
			$subtext = '';
926
			if ($divPos !== false)
927
			{
928
				$subtext = preg_replace('~</?div[^>]*>~', '', substr($config_var[1], $divPos));
929
				$config_var[1] = substr($config_var[1], 0, $divPos);
930
			}
931
932
			$context['config_vars'][$config_var[0]] = array(
933
				'label' => $config_var[1],
934
				'help' => isset($config_var[5]) ? $config_var[5] : '',
935
				'type' => $config_var[3],
936
				'size' => empty($config_var[4]) ? 0 : $config_var[4],
937
				'data' => isset($config_var[4]) && is_array($config_var[4]) && $config_var[3] != 'select' ? $config_var[4] : array(),
938
				'name' => $config_var[0],
939
				'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 : '')),
940
				'disabled' => !empty($context['settings_not_writable']) || !empty($config_var['disabled']),
941
				'invalid' => false,
942
				'subtext' => !empty($config_var['subtext']) ? $config_var['subtext'] : $subtext,
943
				'javascript' => '',
944
				'preinput' => !empty($config_var['preinput']) ? $config_var['preinput'] : '',
945
				'postinput' => !empty($config_var['postinput']) ? $config_var['postinput'] : '',
946
			);
947
948
			// Handle min/max/step if necessary
949
			if ($config_var[3] == 'int' || $config_var[3] == 'float')
950
			{
951
				// Default to a min of 0 if one isn't set
952
				if (isset($config_var['min']))
953
					$context['config_vars'][$config_var[0]]['min'] = $config_var['min'];
954
				else
955
					$context['config_vars'][$config_var[0]]['min'] = 0;
956
957
				if (isset($config_var['max']))
958
					$context['config_vars'][$config_var[0]]['max'] = $config_var['max'];
959
960
				if (isset($config_var['step']))
961
					$context['config_vars'][$config_var[0]]['step'] = $config_var['step'];
962
			}
963
964
			// If this is a select box handle any data.
965
			if (!empty($config_var[4]) && is_array($config_var[4]))
966
			{
967
				// If it's associative
968
				$config_values = array_values($config_var[4]);
969
				if (isset($config_values[0]) && is_array($config_values[0]))
970
					$context['config_vars'][$config_var[0]]['data'] = $config_var[4];
971
				else
972
				{
973
					foreach ($config_var[4] as $key => $item)
974
						$context['config_vars'][$config_var[0]]['data'][] = array($key, $item);
975
				}
976
			}
977
		}
978
	}
979
980
	// Two tokens because saving these settings requires both saveSettings and saveDBSettings
981
	createToken('admin-ssc');
982
	createToken('admin-dbsc');
983
}
984
985
/**
986
 * Helper function, it sets up the context for database settings.
987
 *
988
 * @todo see rev. 10406 from 2.1-requests
989
 *
990
 * @param array $config_vars An array of configuration variables
991
 */
992
function prepareDBSettingContext(&$config_vars)
993
{
994
	global $txt, $helptxt, $context, $modSettings, $sourcedir, $smcFunc;
995
996
	loadLanguage('Help');
997
998
	if (isset($_SESSION['adm-save']))
999
	{
1000
		if ($_SESSION['adm-save'] === true)
1001
			$context['saved_successful'] = true;
1002
		else
1003
			$context['saved_failed'] = $_SESSION['adm-save'];
1004
1005
		unset($_SESSION['adm-save']);
1006
	}
1007
1008
	$context['config_vars'] = array();
1009
	$inlinePermissions = array();
1010
	$bbcChoice = array();
1011
	$board_list = false;
1012
	foreach ($config_vars as $config_var)
1013
	{
1014
		// HR?
1015
		if (!is_array($config_var))
1016
			$context['config_vars'][] = $config_var;
1017
		else
1018
		{
1019
			// If it has no name it doesn't have any purpose!
1020
			if (empty($config_var[1]))
1021
				continue;
1022
1023
			// Special case for inline permissions
1024
			if ($config_var[0] == 'permissions' && allowedTo('manage_permissions'))
1025
				$inlinePermissions[] = $config_var[1];
1026
1027
			elseif ($config_var[0] == 'permissions')
1028
				continue;
1029
1030
			if ($config_var[0] == 'boards')
1031
				$board_list = true;
1032
1033
			// Are we showing the BBC selection box?
1034
			if ($config_var[0] == 'bbc')
1035
				$bbcChoice[] = $config_var[1];
1036
1037
			// We need to do some parsing of the value before we pass it in.
1038
			if (isset($modSettings[$config_var[1]]))
1039
			{
1040
				switch ($config_var[0])
1041
				{
1042
					case 'select':
1043
						$value = $modSettings[$config_var[1]];
1044
						break;
1045
					case 'json':
1046
						$value = $smcFunc['htmlspecialchars']($smcFunc['json_encode']($modSettings[$config_var[1]]));
1047
						break;
1048
					case 'boards':
1049
						$value = explode(',', $modSettings[$config_var[1]]);
1050
						break;
1051
					default:
1052
						$value = $smcFunc['htmlspecialchars']($modSettings[$config_var[1]]);
1053
				}
1054
			}
1055
			else
1056
			{
1057
				// Darn, it's empty. What type is expected?
1058
				switch ($config_var[0])
1059
				{
1060
					case 'int':
1061
					case 'float':
1062
						$value = 0;
1063
						break;
1064
					case 'select':
1065
						$value = !empty($config_var['multiple']) ? $smcFunc['json_encode'](array()) : '';
1066
						break;
1067
					case 'boards':
1068
						$value = array();
1069
						break;
1070
					default:
1071
						$value = '';
1072
				}
1073
			}
1074
1075
			$context['config_vars'][$config_var[1]] = array(
1076
				'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] : '')),
1077
				'help' => isset($helptxt[$config_var[1]]) ? $config_var[1] : '',
1078
				'type' => $config_var[0],
1079
				'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)),
1080
				'data' => array(),
1081
				'name' => $config_var[1],
1082
				'value' => $value,
1083
				'disabled' => false,
1084
				'invalid' => !empty($config_var['invalid']),
1085
				'javascript' => '',
1086
				'var_message' => !empty($config_var['message']) && isset($txt[$config_var['message']]) ? $txt[$config_var['message']] : '',
1087
				'preinput' => isset($config_var['preinput']) ? $config_var['preinput'] : '',
1088
				'postinput' => isset($config_var['postinput']) ? $config_var['postinput'] : '',
1089
			);
1090
1091
			// Handle min/max/step if necessary
1092
			if ($config_var[0] == 'int' || $config_var[0] == 'float')
1093
			{
1094
				// Default to a min of 0 if one isn't set
1095
				if (isset($config_var['min']))
1096
					$context['config_vars'][$config_var[1]]['min'] = $config_var['min'];
1097
1098
				else
1099
					$context['config_vars'][$config_var[1]]['min'] = 0;
1100
1101
				if (isset($config_var['max']))
1102
					$context['config_vars'][$config_var[1]]['max'] = $config_var['max'];
1103
1104
				if (isset($config_var['step']))
1105
					$context['config_vars'][$config_var[1]]['step'] = $config_var['step'];
1106
			}
1107
1108
			// If this is a select box handle any data.
1109
			if (!empty($config_var[2]) && is_array($config_var[2]))
1110
			{
1111
				// If we allow multiple selections, we need to adjust a few things.
1112
				if ($config_var[0] == 'select' && !empty($config_var['multiple']))
1113
				{
1114
					$context['config_vars'][$config_var[1]]['name'] .= '[]';
1115
					$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();
1116
				}
1117
1118
				// If it's associative
1119
				if (isset($config_var[2][0]) && is_array($config_var[2][0]))
1120
					$context['config_vars'][$config_var[1]]['data'] = $config_var[2];
1121
1122
				else
1123
				{
1124
					foreach ($config_var[2] as $key => $item)
1125
						$context['config_vars'][$config_var[1]]['data'][] = array($key, $item);
1126
				}
1127
				if (empty($config_var['size']) && !empty($config_var['multiple']))
1128
					$context['config_vars'][$config_var[1]]['size'] = max(4, count($config_var[2]));
1129
			}
1130
1131
			// Finally allow overrides - and some final cleanups.
1132
			foreach ($config_var as $k => $v)
1133
			{
1134
				if (!is_numeric($k))
1135
				{
1136
					if (substr($k, 0, 2) == 'on')
1137
						$context['config_vars'][$config_var[1]]['javascript'] .= ' ' . $k . '="' . $v . '"';
1138
					else
1139
						$context['config_vars'][$config_var[1]][$k] = $v;
1140
				}
1141
1142
				// See if there are any other labels that might fit?
1143
				if (isset($txt['setting_' . $config_var[1]]))
1144
					$context['config_vars'][$config_var[1]]['label'] = $txt['setting_' . $config_var[1]];
1145
1146
				elseif (isset($txt['groups_' . $config_var[1]]))
1147
					$context['config_vars'][$config_var[1]]['label'] = $txt['groups_' . $config_var[1]];
1148
			}
1149
1150
			// Set the subtext in case it's part of the label.
1151
			// @todo Temporary. Preventing divs inside label tags.
1152
			$divPos = strpos($context['config_vars'][$config_var[1]]['label'], '<div');
1153
			if ($divPos !== false)
1154
			{
1155
				$context['config_vars'][$config_var[1]]['subtext'] = preg_replace('~</?div[^>]*>~', '', substr($context['config_vars'][$config_var[1]]['label'], $divPos));
1156
				$context['config_vars'][$config_var[1]]['label'] = substr($context['config_vars'][$config_var[1]]['label'], 0, $divPos);
1157
			}
1158
		}
1159
	}
1160
1161
	// If we have inline permissions we need to prep them.
1162
	if (!empty($inlinePermissions) && allowedTo('manage_permissions'))
1163
	{
1164
		require_once($sourcedir . '/ManagePermissions.php');
1165
		init_inline_permissions($inlinePermissions);
1166
	}
1167
1168
	if ($board_list)
1169
	{
1170
		require_once($sourcedir . '/Subs-MessageIndex.php');
1171
		$context['board_list'] = getBoardList();
1172
	}
1173
1174
	// What about any BBC selection boxes?
1175
	if (!empty($bbcChoice))
1176
	{
1177
		// What are the options, eh?
1178
		$temp = parse_bbc(false);
1179
		$bbcTags = array();
1180
		foreach ($temp as $tag)
0 ignored issues
show
Bug introduced by
The expression $temp of type string is not traversable.
Loading history...
1181
			$bbcTags[] = $tag['tag'];
1182
1183
		$bbcTags = array_unique($bbcTags);
1184
1185
		// The number of columns we want to show the BBC tags in.
1186
		$numColumns = isset($context['num_bbc_columns']) ? $context['num_bbc_columns'] : 3;
1187
1188
		// Now put whatever BBC options we may have into context too!
1189
		$context['bbc_sections'] = array();
1190
		foreach ($bbcChoice as $bbcSection)
1191
		{
1192
			$context['bbc_sections'][$bbcSection] = array(
1193
				'title' => isset($txt['bbc_title_' . $bbcSection]) ? $txt['bbc_title_' . $bbcSection] : $txt['enabled_bbc_select'],
1194
				'disabled' => empty($modSettings['bbc_disabled_' . $bbcSection]) ? array() : $modSettings['bbc_disabled_' . $bbcSection],
1195
				'all_selected' => empty($modSettings['bbc_disabled_' . $bbcSection]),
1196
				'columns' => array(),
1197
			);
1198
1199
			if ($bbcSection == 'legacyBBC')
1200
				$sectionTags = array_intersect($context['legacy_bbc'], $bbcTags);
1201
			else
1202
				$sectionTags = array_diff($bbcTags, $context['legacy_bbc']);
1203
1204
			$totalTags = count($sectionTags);
1205
			$tagsPerColumn = ceil($totalTags / $numColumns);
1206
1207
			$col = 0;
1208
			$i = 0;
1209
			foreach ($sectionTags as $tag)
1210
			{
1211
				if ($i % $tagsPerColumn == 0 && $i != 0)
1212
					$col++;
1213
1214
				$context['bbc_sections'][$bbcSection]['columns'][$col][] = array(
1215
					'tag' => $tag,
1216
					// @todo  'tag_' . ?
1217
					'show_help' => isset($helptxt[$tag]),
1218
				);
1219
1220
				$i++;
1221
			}
1222
		}
1223
	}
1224
1225
	call_integration_hook('integrate_prepare_db_settings', array(&$config_vars));
1226
	createToken('admin-dbsc');
1227
}
1228
1229
/**
1230
 * Helper function. Saves settings by putting them in Settings.php or saving them in the settings table.
1231
 *
1232
 * - Saves those settings set from ?action=admin;area=serversettings.
1233
 * - Requires the admin_forum permission.
1234
 * - Contains arrays of the types of data to save into Settings.php.
1235
 *
1236
 * @param array $config_vars An array of configuration variables
1237
 */
1238
function saveSettings(&$config_vars)
1239
{
1240
	global $sourcedir, $context;
1241
1242
	validateToken('admin-ssc');
1243
1244
	// Fix the darn stupid cookiename! (more may not be allowed, but these for sure!)
1245
	if (isset($_POST['cookiename']))
1246
		$_POST['cookiename'] = preg_replace('~[,;\s\.$]+~' . ($context['utf8'] ? 'u' : ''), '', $_POST['cookiename']);
1247
1248
	// Fix the forum's URL if necessary.
1249
	if (isset($_POST['boardurl']))
1250
	{
1251
		if (substr($_POST['boardurl'], -10) == '/index.php')
1252
			$_POST['boardurl'] = substr($_POST['boardurl'], 0, -10);
1253
		elseif (substr($_POST['boardurl'], -1) == '/')
1254
			$_POST['boardurl'] = substr($_POST['boardurl'], 0, -1);
1255
		if (substr($_POST['boardurl'], 0, 7) != 'http://' && substr($_POST['boardurl'], 0, 7) != 'file://' && substr($_POST['boardurl'], 0, 8) != 'https://')
1256
			$_POST['boardurl'] = 'http://' . $_POST['boardurl'];
1257
	}
1258
1259
	// Any passwords?
1260
	$config_passwords = array(
1261
		'db_passwd',
1262
		'ssi_db_passwd',
1263
	);
1264
1265
	// All the strings to write.
1266
	$config_strs = array(
1267
		'mtitle', 'mmessage',
1268
		'language', 'mbname', 'boardurl',
1269
		'cookiename',
1270
		'webmaster_email',
1271
		'db_name', 'db_user', 'db_server', 'db_prefix', 'ssi_db_user',
1272
		'boarddir', 'sourcedir',
1273
		'cachedir', 'cachedir_sqlite', 'cache_accelerator', 'cache_memcached',
1274
		'image_proxy_secret',
1275
	);
1276
1277
	// All the numeric variables.
1278
	$config_ints = array(
1279
		'db_port',
1280
		'cache_enable',
1281
		'image_proxy_maxsize',
1282
	);
1283
1284
	// All the checkboxes
1285
	$config_bools = array('db_persist', 'db_error_send', 'maintenance', 'image_proxy_enabled');
1286
1287
	// Now sort everything into a big array, and figure out arrays and etc.
1288
	$new_settings = array();
1289
	// Figure out which config vars we're saving here...
1290
	foreach ($config_vars as $var)
1291
	{
1292
		if (!is_array($var) || $var[2] != 'file' || (!in_array($var[0], $config_bools) && !isset($_POST[$var[0]])))
1293
			continue;
1294
1295
		$config_var = $var[0];
1296
1297
		if (in_array($config_var, $config_passwords))
1298
		{
1299
			if (isset($_POST[$config_var][1]) && $_POST[$config_var][0] == $_POST[$config_var][1])
1300
				$new_settings[$config_var] = $_POST[$config_var][0];
1301
		}
1302
		elseif (in_array($config_var, $config_strs))
1303
		{
1304
			$new_settings[$config_var] = $_POST[$config_var];
1305
		}
1306
		elseif (in_array($config_var, $config_ints))
1307
		{
1308
			$new_settings[$config_var] = (int) $_POST[$config_var];
1309
1310
			// 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...
1311
			$min = isset($var['min']) ? $var['min'] : 0;
1312
			$new_settings[$config_var] = max($min, $new_settings[$config_var]);
1313
1314
			// Is there a max value for this as well?
1315
			if (isset($var['max']))
1316
				$new_settings[$config_var] = min($var['max'], $new_settings[$config_var]);
1317
		}
1318
		elseif (in_array($config_var, $config_bools))
1319
		{
1320
			if (!empty($_POST[$config_var]))
1321
				$new_settings[$config_var] = 1;
1322
			else
1323
				$new_settings[$config_var] = 0;
1324
		}
1325
		else
1326
		{
1327
			// This shouldn't happen, but it might...
1328
			fatal_error('Unknown config_var \'' . $config_var . '\'');
1329
		}
1330
	}
1331
1332
	// Save the relevant settings in the Settings.php file.
1333
	require_once($sourcedir . '/Subs-Admin.php');
1334
	updateSettingsFile($new_settings);
1335
1336
	// Now loop through the remaining (database-based) settings.
1337
	$new_settings = array();
1338
	foreach ($config_vars as $config_var)
1339
	{
1340
		// We just saved the file-based settings, so skip their definitions.
1341
		if (!is_array($config_var) || $config_var[2] == 'file')
1342
			continue;
1343
1344
		$new_setting = array($config_var[3], $config_var[0]);
1345
1346
		// Select options need carried over, too.
1347
		if (isset($config_var[4]))
1348
			$new_setting[] = $config_var[4];
1349
1350
		// Include min and max if necessary
1351
		if (isset($config_var['min']))
1352
			$new_setting['min'] = $config_var['min'];
1353
1354
		if (isset($config_var['max']))
1355
			$new_setting['max'] = $config_var['max'];
1356
1357
		// Rewrite the definition a bit.
1358
		$new_settings[] = $new_setting;
1359
	}
1360
1361
	// Save the new database-based settings, if any.
1362
	if (!empty($new_settings))
1363
		saveDBSettings($new_settings);
1364
}
1365
1366
/**
1367
 * Helper function for saving database settings.
1368
 *
1369
 * @todo see rev. 10406 from 2.1-requests
1370
 *
1371
 * @param array $config_vars An array of configuration variables
1372
 */
1373
function saveDBSettings(&$config_vars)
1374
{
1375
	global $sourcedir, $smcFunc;
1376
	static $board_list = null;
1377
1378
	validateToken('admin-dbsc');
1379
1380
	$inlinePermissions = array();
1381
	foreach ($config_vars as $var)
1382
	{
1383
		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']))))
1384
			continue;
1385
1386
		// Checkboxes!
1387
		elseif ($var[0] == 'check')
1388
			$setArray[$var[1]] = !empty($_POST[$var[1]]) ? '1' : '0';
1389
		// Select boxes!
1390
		elseif ($var[0] == 'select' && in_array($_POST[$var[1]], array_keys($var[2])))
1391
			$setArray[$var[1]] = $_POST[$var[1]];
1392
		elseif ($var[0] == 'select' && !empty($var['multiple']) && array_intersect($_POST[$var[1]], array_keys($var[2])) != array())
1393
		{
1394
			// For security purposes we validate this line by line.
1395
			$lOptions = array();
1396
			foreach ($_POST[$var[1]] as $invar)
1397
				if (in_array($invar, array_keys($var[2])))
1398
					$lOptions[] = $invar;
1399
1400
			$setArray[$var[1]] = $smcFunc['json_encode']($lOptions);
1401
		}
1402
		// List of boards!
1403
		elseif ($var[0] == 'boards')
1404
		{
1405
			// We just need a simple list of valid boards, nothing more.
1406
			if ($board_list === null)
1407
			{
1408
				$board_list = array();
1409
				$request = $smcFunc['db_query']('', '
1410
					SELECT id_board
1411
					FROM {db_prefix}boards');
1412
1413
				while ($row = $smcFunc['db_fetch_row']($request))
1414
					$board_list[$row[0]] = true;
1415
1416
				$smcFunc['db_free_result']($request);
1417
			}
1418
1419
			$lOptions = array();
1420
1421
			if (!empty($_POST[$var[1]]))
1422
				foreach ($_POST[$var[1]] as $invar => $dummy)
1423
					if (isset($board_list[$invar]))
1424
						$lOptions[] = $invar;
1425
1426
			$setArray[$var[1]] = !empty($lOptions) ? implode(',', $lOptions) : '';
1427
		}
1428
		// Integers!
1429
		elseif ($var[0] == 'int')
1430
		{
1431
			$setArray[$var[1]] = (int) $_POST[$var[1]];
1432
1433
			// 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...
1434
			$min = isset($var['min']) ? $var['min'] : 0;
1435
			$setArray[$var[1]] = max($min, $setArray[$var[1]]);
1436
1437
			// Do we have a max value for this as well?
1438
			if (isset($var['max']))
1439
				$setArray[$var[1]] = min($var['max'], $setArray[$var[1]]);
1440
		}
1441
		// Floating point!
1442
		elseif ($var[0] == 'float')
1443
		{
1444
			$setArray[$var[1]] = (float) $_POST[$var[1]];
1445
1446
			// 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...
1447
			$min = isset($var['min']) ? $var['min'] : 0;
1448
			$setArray[$var[1]] = max($min, $setArray[$var[1]]);
1449
1450
			// Do we have a max value for this as well?
1451
			if (isset($var['max']))
1452
				$setArray[$var[1]] = min($var['max'], $setArray[$var[1]]);
1453
		}
1454
		// Text!
1455
		elseif (in_array($var[0], array('text', 'large_text', 'color', 'date', 'datetime', 'datetime-local', 'email', 'month', 'time')))
1456
			$setArray[$var[1]] = $_POST[$var[1]];
1457
		// Passwords!
1458
		elseif ($var[0] == 'password')
1459
		{
1460
			if (isset($_POST[$var[1]][1]) && $_POST[$var[1]][0] == $_POST[$var[1]][1])
1461
				$setArray[$var[1]] = $_POST[$var[1]][0];
1462
		}
1463
		// BBC.
1464
		elseif ($var[0] == 'bbc')
1465
		{
1466
			$bbcTags = array();
1467
			foreach (parse_bbc(false) as $tag)
0 ignored issues
show
Bug introduced by
The expression parse_bbc(false) of type string is not traversable.
Loading history...
1468
				$bbcTags[] = $tag['tag'];
1469
1470
			if (!isset($_POST[$var[1] . '_enabledTags']))
1471
				$_POST[$var[1] . '_enabledTags'] = array();
1472
			elseif (!is_array($_POST[$var[1] . '_enabledTags']))
1473
				$_POST[$var[1] . '_enabledTags'] = array($_POST[$var[1] . '_enabledTags']);
1474
1475
			$setArray[$var[1]] = implode(',', array_diff($bbcTags, $_POST[$var[1] . '_enabledTags']));
1476
		}
1477
		// Permissions?
1478
		elseif ($var[0] == 'permissions')
1479
			$inlinePermissions[] = $var[1];
1480
	}
1481
1482
	if (!empty($setArray))
1483
		updateSettings($setArray);
1484
1485
	// If we have inline permissions we need to save them.
1486
	if (!empty($inlinePermissions) && allowedTo('manage_permissions'))
1487
	{
1488
		require_once($sourcedir . '/ManagePermissions.php');
1489
		save_inline_permissions($inlinePermissions);
1490
	}
1491
}
1492
1493
/**
1494
 * Allows us to see the servers php settings
1495
 *
1496
 * - loads the settings into an array for display in a template
1497
 * - drops cookie values just in case
1498
 */
1499
function ShowPHPinfoSettings()
1500
{
1501
	global $context, $txt;
1502
1503
	$category = $txt['phpinfo_settings'];
1504
1505
	// get the data
1506
	ob_start();
1507
	phpinfo();
1508
1509
	// We only want it for its body, pigs that we are
1510
	$info_lines = preg_replace('~^.*<body>(.*)</body>.*$~', '$1', ob_get_contents());
1511
	$info_lines = explode("\n", strip_tags($info_lines, "<tr><td><h2>"));
1512
	ob_end_clean();
1513
1514
	// remove things that could be considered sensitive
1515
	$remove = '_COOKIE|Cookie|_GET|_REQUEST|REQUEST_URI|QUERY_STRING|REQUEST_URL|HTTP_REFERER';
1516
1517
	// put all of it into an array
1518
	foreach ($info_lines as $line)
1519
	{
1520
		if (preg_match('~(' . $remove . ')~', $line))
1521
			continue;
1522
1523
		// new category?
1524
		if (strpos($line, '<h2>') !== false)
1525
			$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...
1526
1527
		// load it as setting => value or the old setting local master
1528
		if (preg_match('~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~', $line, $val))
1529
			$pinfo[$category][$val[1]] = $val[2];
1530
		elseif (preg_match('~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~', $line, $val))
1531
			$pinfo[$category][$val[1]] = array($txt['phpinfo_localsettings'] => $val[2], $txt['phpinfo_defaultsettings'] => $val[3]);
1532
	}
1533
1534
	// load it in to context and display it
1535
	$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...
1536
	$context['page_title'] = $txt['admin_server_settings'];
1537
	$context['sub_template'] = 'php_info';
1538
	return;
1539
}
1540
1541
/**
1542
 * Get the installed Cache API implementations.
1543
 *
1544
 */
1545
function loadCacheAPIs()
1546
{
1547
	global $sourcedir, $txt;
1548
1549
	// Make sure our class is in session.
1550
	require_once($sourcedir . '/Class-CacheAPI.php');
1551
1552
	$apis = array();
1553
	if ($dh = opendir($sourcedir))
1554
	{
1555
		while (($file = readdir($dh)) !== false)
1556
		{
1557
			if (is_file($sourcedir . '/' . $file) && preg_match('~^CacheAPI-([A-Za-z\d_]+)\.php$~', $file, $matches))
1558
			{
1559
				$tryCache = strtolower($matches[1]);
1560
1561
				require_once($sourcedir . '/' . $file);
1562
				$cache_class_name = $tryCache . '_cache';
1563
				$testAPI = new $cache_class_name();
1564
1565
				// No Support?  NEXT!
1566
				if (!$testAPI->isSupported(true))
1567
					continue;
1568
1569
				$apis[$tryCache] = isset($txt[$tryCache . '_cache']) ? $txt[$tryCache . '_cache'] : $tryCache;
1570
			}
1571
		}
1572
	}
1573
	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

1573
	closedir(/** @scrutinizer ignore-type */ $dh);
Loading history...
1574
1575
	return $apis;
1576
}
1577
1578
/**
1579
 * Registers the site with the Simple Machines Stat collection. This function
1580
 * purposely does not use updateSettings.php as it will be called shortly after
1581
 * this process completes by the saveSettings() function.
1582
 *
1583
 * @see Stats.php SMStats() for more information.
1584
 * @link https://www.simplemachines.org/about/stats.php for more info.
1585
 *
1586
 */
1587
function registerSMStats()
1588
{
1589
	global $modSettings, $boardurl, $smcFunc;
1590
1591
	// Already have a key?  Can't register again.
1592
	if (!empty($modSettings['sm_stats_key']))
1593
		return true;
1594
1595
	$fp = @fsockopen('www.simplemachines.org', 80, $errno, $errstr);
1596
	if ($fp)
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
1597
	{
1598
		$out = 'GET /smf/stats/register_stats.php?site=' . base64_encode($boardurl) . ' HTTP/1.1' . "\r\n";
1599
		$out .= 'Host: www.simplemachines.org' . "\r\n";
1600
		$out .= 'Connection: Close' . "\r\n\r\n";
1601
		fwrite($fp, $out);
1602
1603
		$return_data = '';
1604
		while (!feof($fp))
1605
			$return_data .= fgets($fp, 128);
1606
1607
		fclose($fp);
1608
1609
		// Get the unique site ID.
1610
		preg_match('~SITE-ID:\s(\w{10})~', $return_data, $ID);
1611
1612
		if (!empty($ID[1]))
1613
		{
1614
			$smcFunc['db_insert']('replace',
1615
				'{db_prefix}settings',
1616
				array('variable' => 'string', 'value' => 'string'),
1617
				array('sm_stats_key', $ID[1]),
1618
				array('variable')
1619
			);
1620
			return true;
1621
		}
1622
	}
1623
1624
	return false;
1625
}
1626
1627
?>