ModifyCookieSettings()   F
last analyzed

Complexity

Conditions 18
Paths 800

Size

Total Lines 117
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 18
eloc 57
nop 1
dl 0
loc 117
rs 0.9777
c 0
b 0
f 0
nc 800

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 2019 Simple Machines and individual contributors
57
 * @license http://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'] = '<div class="centertext"><strong>' . $txt['settings_not_writable'] . '</strong></div>';
116
	elseif ($settings_backup_fail)
117
		$context['settings_message'] = '<div class="centertext"><strong>' . $txt['admin_backup_fail'] . '</strong></div>';
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['enable_sm_stats'], '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
324
			$smcFunc['db_query']('', '
325
				UPDATE {db_prefix}themes
326
				SET value = {string:theme_val}
327
				WHERE variable = {string:theme_var}
328
					AND id_theme = {string:theme_id}
329
					AND id_member = {int:zero}',
330
				array(
331
					'theme_val' => $newval,
332
					'theme_var' => $row['variable'],
333
					'theme_id' => $row['id_theme'],
334
					'zero' => 0,
335
				)
336
			);
337
		}
338
	}
339
	$smcFunc['db_free_result']($request);
340
}
341
342
/**
343
 * $boardurl Match.
344
 *
345
 * Helper function to see if the url being checked is based off of $boardurl.
346
 * If not, it was overridden by the admin to some other value on purpose, and should not
347
 * be stepped on by SMF when aligning URLs with the force_ssl setting.
348
 * The site admin must change URLs that are not aligned with $boardurl manually.
349
 *
350
 * @param string $url is the url to check.
351
 * @return bool Returns true if the url is based off of $boardurl (without the scheme), false if not
352
 */
353
function BoardurlMatch($url = '')
354
{
355
	global $boardurl;
356
357
	// Strip the schemes
358
	$urlpath = strtr($url, array('http://' => '', 'https://' => ''));
359
	$boardurlpath = strtr($boardurl, array('http://' => '', 'https://' => ''));
360
361
	// If leftmost portion of path matches boardurl, return true
362
	$result = strpos($urlpath, $boardurlpath);
363
	if ($result === false || $result != 0)
364
		return false;
365
	else
366
		return true;
367
}
368
369
/**
370
 * Basic database and paths settings - database name, host, etc.
371
 *
372
 * - It shows an interface for the settings in Settings.php to be changed.
373
 * - It contains the actual array of settings to show from Settings.php.
374
 * - Requires the admin_forum permission.
375
 * - Uses the edit_settings administration area.
376
 * - Accessed from ?action=admin;area=serversettings;sa=database.
377
 *
378
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
379
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
380
 */
381
function ModifyDatabaseSettings($return_config = false)
382
{
383
	global $scripturl, $context, $txt, $smcFunc;
384
	db_extend('extra');
385
386
	/* If you're writing a mod, it's a bad idea to add things here....
387
		For each option:
388
		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)
389
		OR an empty string for a horizontal rule.
390
		OR a string for a titled section. */
391
	$config_vars = array(
392
		array('db_persist', $txt['db_persist'], 'file', 'check', null, 'db_persist'),
393
		array('db_error_send', $txt['db_error_send'], 'file', 'check'),
394
		array('ssi_db_user', $txt['ssi_db_user'], 'file', 'text', null, 'ssi_db_user'),
395
		array('ssi_db_passwd', $txt['ssi_db_passwd'], 'file', 'password'),
396
		'',
397
		array('autoFixDatabase', $txt['autoFixDatabase'], 'db', 'check', false, 'autoFixDatabase')
398
	);
399
400
	// Add PG Stuff
401
	if ($smcFunc['db_title'] == "PostgreSQL")
402
	{
403
		$request = $smcFunc['db_query']('', 'SELECT cfgname FROM pg_ts_config', array());
404
		$fts_language = array();
405
406
		while ($row = $smcFunc['db_fetch_assoc']($request))
407
			$fts_language[$row['cfgname']] = $row['cfgname'];
408
409
		$config_vars = array_merge($config_vars, array(
410
				'',
411
				array('search_language', $txt['search_language'], 'db', 'select', $fts_language, 'pgFulltextSearch')
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
587
		array('check', 'securityDisable'),
588
		array('check', 'securityDisable_moderate'),
589
		'',
590
591
		// Reactive on email, and approve on delete
592
		array('check', 'send_validation_onChange'),
593
		array('check', 'approveAccountDeletion'),
594
		'',
595
596
		// Password strength.
597
		array(
598
			'select',
599
			'password_strength',
600
			array(
601
				$txt['setting_password_strength_low'],
602
				$txt['setting_password_strength_medium'],
603
				$txt['setting_password_strength_high']
604
			)
605
		),
606
		array('check', 'enable_password_conversion'),
607
		'',
608
609
		// Reporting of personal messages?
610
		array('check', 'enableReportPM'),
611
		'',
612
613
		array(
614
			'select',
615
			'frame_security',
616
			array(
617
				'SAMEORIGIN' => $txt['setting_frame_security_SAMEORIGIN'],
618
				'DENY' => $txt['setting_frame_security_DENY'],
619
				'DISABLE' => $txt['setting_frame_security_DISABLE']
620
			)
621
		),
622
		'',
623
624
		array(
625
			'select',
626
			'proxy_ip_header',
627
			array(
628
				'disabled' => $txt['setting_proxy_ip_header_disabled'],
629
				'autodetect' => $txt['setting_proxy_ip_header_autodetect'],
630
				'HTTP_X_FORWARDED_FOR' => 'HTTP_X_FORWARDED_FOR',
631
				'HTTP_CLIENT_IP' => 'HTTP_CLIENT_IP',
632
				'HTTP_X_REAL_IP' => 'HTTP_X_REAL_IP',
633
				'CF-Connecting-IP' => 'CF-Connecting-IP'
634
			)
635
		),
636
		array('text', 'proxy_ip_servers'),
637
	);
638
639
	call_integration_hook('integrate_general_security_settings', array(&$config_vars));
640
641
	if ($return_config)
642
		return $config_vars;
643
644
	// Saving?
645
	if (isset($_GET['save']))
646
	{
647
		saveDBSettings($config_vars);
648
		$_SESSION['adm-save'] = true;
649
650
		call_integration_hook('integrate_save_general_security_settings');
651
652
		writeLog();
653
		redirectexit('action=admin;area=serversettings;sa=security;' . $context['session_var'] . '=' . $context['session_id']);
654
	}
655
656
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;save;sa=security';
657
	$context['settings_title'] = $txt['security_settings'];
658
659
	prepareDBSettingContext($config_vars);
660
}
661
662
/**
663
 * Simply modifying cache functions
664
 *
665
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
666
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
667
 */
668
function ModifyCacheSettings($return_config = false)
669
{
670
	global $context, $scripturl, $txt;
671
672
	// Detect all available optimizers
673
	$detected = loadCacheAPIs();
674
675
	// set our values to show what, if anything, we found
676
	if (empty($detected))
677
	{
678
		$txt['cache_settings_message'] = $txt['detected_no_caching'];
679
		$cache_level = array($txt['cache_off']);
680
		$detected['none'] = $txt['cache_off'];
681
	}
682
	else
683
	{
684
		$txt['cache_settings_message'] = sprintf($txt['detected_accelerators'], implode(', ', $detected));
685
		$cache_level = array($txt['cache_off'], $txt['cache_level1'], $txt['cache_level2'], $txt['cache_level3']);
686
	}
687
688
	// Define the variables we want to edit.
689
	$config_vars = array(
690
		// Only a few settings, but they are important
691
		array('', $txt['cache_settings_message'], '', 'desc'),
692
		array('cache_enable', $txt['cache_enable'], 'file', 'select', $cache_level, 'cache_enable'),
693
		array('cache_accelerator', $txt['cache_accelerator'], 'file', 'select', $detected),
694
	);
695
696
	// some javascript to enable / disable certain settings if the option is not selected
697
	$context['settings_post_javascript'] = '
698
		$(document).ready(function() {
699
			$("#cache_accelerator").change();
700
		});';
701
702
	call_integration_hook('integrate_modify_cache_settings', array(&$config_vars));
703
704
	// Maybe we have some additional settings from the selected accelerator.
705
	if (!empty($detected))
706
	{
707
		foreach ($detected as $tryCache => $dummy)
708
		{
709
			$cache_class_name = $tryCache . '_cache';
710
711
			// loadCacheAPIs has already included the file, just see if we can't add the settings in.
712
			if (is_callable(array($cache_class_name, 'cacheSettings')))
713
			{
714
				$testAPI = new $cache_class_name();
715
				call_user_func_array(array($testAPI, 'cacheSettings'), array(&$config_vars));
716
			}
717
		}
718
	}
719
	if ($return_config)
720
		return $config_vars;
721
722
	// Saving again?
723
	if (isset($_GET['save']))
724
	{
725
		call_integration_hook('integrate_save_cache_settings');
726
727
		saveSettings($config_vars);
728
		$_SESSION['adm-save'] = true;
729
730
		// We need to save the $cache_enable to $modSettings as well
731
		updatesettings(array('cache_enable' => (int) $_POST['cache_enable']));
732
733
		// exit so we reload our new settings on the page
734
		redirectexit('action=admin;area=serversettings;sa=cache;' . $context['session_var'] . '=' . $context['session_id']);
735
	}
736
737
	loadLanguage('ManageMaintenance');
738
	createToken('admin-maint');
739
	$context['template_layers'][] = 'clean_cache_button';
740
741
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=cache;save';
742
	$context['settings_title'] = $txt['caching_settings'];
743
744
	// Changing cache settings won't have any effect if Settings.php is not writeable.
745
	$context['save_disabled'] = $context['settings_not_writable'];
746
747
	// Decide what message to show.
748
	if (!$context['save_disabled'])
749
		$context['settings_message'] = $txt['caching_information'];
750
751
	// Prepare the template.
752
	prepareServerSettingsContext($config_vars);
753
}
754
755
/**
756
 * Allows to edit load balancing settings.
757
 *
758
 * @param bool $return_config Whether or not to return the config_vars array
759
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
760
 */
761
function ModifyLoadBalancingSettings($return_config = false)
762
{
763
	global $txt, $scripturl, $context, $modSettings;
764
765
	// Setup a warning message, but disabled by default.
766
	$disabled = true;
767
	$context['settings_message'] = $txt['loadavg_disabled_conf'];
768
769
	if (DIRECTORY_SEPARATOR === '\\')
770
	{
771
		$context['settings_message'] = $txt['loadavg_disabled_windows'];
772
		if (isset($_GET['save']))
773
			$_SESSION['adm-save'] = $txt['loadavg_disabled_windows'];
774
	}
775
	elseif (stripos(PHP_OS, 'darwin') === 0)
776
	{
777
		$context['settings_message'] = $txt['loadavg_disabled_osx'];
778
		if (isset($_GET['save']))
779
			$_SESSION['adm-save'] = $txt['loadavg_disabled_osx'];
780
	}
781
	else
782
	{
783
		$modSettings['load_average'] = @file_get_contents('/proc/loadavg');
784
		if (!empty($modSettings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', $modSettings['load_average'], $matches) !== 0)
785
			$modSettings['load_average'] = (float) $matches[1];
786
		elseif (($modSettings['load_average'] = @`uptime`) !== null && preg_match('~load averages?: (\d+\.\d+), (\d+\.\d+), (\d+\.\d+)~i', $modSettings['load_average'], $matches) !== 0)
787
			$modSettings['load_average'] = (float) $matches[1];
788
		else
789
			unset($modSettings['load_average']);
790
791
		if (!empty($modSettings['load_average']) || (isset($modSettings['load_average']) && $modSettings['load_average'] === 0.0))
792
		{
793
			$context['settings_message'] = sprintf($txt['loadavg_warning'], $modSettings['load_average']);
794
			$disabled = false;
795
		}
796
	}
797
798
	// Start with a simple checkbox.
799
	$config_vars = array(
800
		array('check', 'loadavg_enable', 'disabled' => $disabled),
801
	);
802
803
	// Set the default values for each option.
804
	$default_values = array(
805
		'loadavg_auto_opt' => 1.0,
806
		'loadavg_search' => 2.5,
807
		'loadavg_allunread' => 2.0,
808
		'loadavg_unreadreplies' => 3.5,
809
		'loadavg_show_posts' => 2.0,
810
		'loadavg_userstats' => 10.0,
811
		'loadavg_bbc' => 30.0,
812
		'loadavg_forum' => 40.0,
813
	);
814
815
	// Loop through the settings.
816
	foreach ($default_values as $name => $value)
817
	{
818
		// Use the default value if the setting isn't set yet.
819
		$value = !isset($modSettings[$name]) ? $value : $modSettings[$name];
820
		$config_vars[] = array('float', $name, 'value' => $value, 'disabled' => $disabled);
821
	}
822
823
	call_integration_hook('integrate_loadavg_settings', array(&$config_vars));
824
825
	if ($return_config)
826
		return $config_vars;
827
828
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=loads;save';
829
	$context['settings_title'] = $txt['load_balancing_settings'];
830
831
	// Saving?
832
	if (isset($_GET['save']))
833
	{
834
		// Stupidity is not allowed.
835
		foreach ($_POST as $key => $value)
836
		{
837
			if (strpos($key, 'loadavg') === 0 || $key === 'loadavg_enable' || !in_array($key, array_keys($default_values)))
838
				continue;
839
			else
840
				$_POST[$key] = (float) $value;
841
842
			if ($key == 'loadavg_auto_opt' && $value <= 1)
843
				$_POST['loadavg_auto_opt'] = 1.0;
844
			elseif ($key == 'loadavg_forum' && $value < 10)
845
				$_POST['loadavg_forum'] = 10.0;
846
			elseif ($value < 2)
847
				$_POST[$key] = 2.0;
848
		}
849
850
		call_integration_hook('integrate_save_loadavg_settings');
851
852
		saveDBSettings($config_vars);
853
		if (!isset($_SESSION['adm-save']))
854
			$_SESSION['adm-save'] = true;
855
		redirectexit('action=admin;area=serversettings;sa=loads;' . $context['session_var'] . '=' . $context['session_id']);
856
	}
857
858
	prepareDBSettingContext($config_vars);
859
}
860
861
/**
862
 * Helper function, it sets up the context for the manage server settings.
863
 * - The basic usage of the six numbered key fields are
864
 * - array (0 ,1, 2, 3, 4, 5
865
 *		0 variable name - the name of the saved variable
866
 *		1 label - the text to show on the settings page
867
 *		2 saveto - file or db, where to save the variable name - value pair
868
 *		3 type - type of data to save, int, float, text, check
869
 *		4 size - false or field size
870
 *		5 help - '' or helptxt variable name
871
 *	)
872
 *
873
 * the following named keys are also permitted
874
 * 'disabled' => A string of code that will determine whether or not the setting should be disabled
875
 * 'postinput' => Text to display after the input field
876
 * 'preinput' => Text to display before the input field
877
 * 'subtext' => Additional descriptive text to display under the field's label
878
 * 'min' => minimum allowed value (for int/float). Defaults to 0 if not set.
879
 * 'max' => maximum allowed value (for int/float)
880
 * 'step' => how much to increment/decrement the value by (only for int/float - mostly used for float values).
881
 *
882
 * @param array $config_vars An array of configuration variables
883
 */
884
function prepareServerSettingsContext(&$config_vars)
885
{
886
	global $context, $modSettings, $smcFunc;
887
888
	if (isset($_SESSION['adm-save']))
889
	{
890
		if ($_SESSION['adm-save'] === true)
891
			$context['saved_successful'] = true;
892
		else
893
			$context['saved_failed'] = $_SESSION['adm-save'];
894
895
		unset($_SESSION['adm-save']);
896
	}
897
898
	$context['config_vars'] = array();
899
	foreach ($config_vars as $identifier => $config_var)
900
	{
901
		if (!is_array($config_var) || !isset($config_var[1]))
902
			$context['config_vars'][] = $config_var;
903
		else
904
		{
905
			$varname = $config_var[0];
906
			global $$varname;
907
908
			// Set the subtext in case it's part of the label.
909
			// @todo Temporary. Preventing divs inside label tags.
910
			$divPos = strpos($config_var[1], '<div');
911
			$subtext = '';
912
			if ($divPos !== false)
913
			{
914
				$subtext = preg_replace('~</?div[^>]*>~', '', substr($config_var[1], $divPos));
915
				$config_var[1] = substr($config_var[1], 0, $divPos);
916
			}
917
918
			$context['config_vars'][$config_var[0]] = array(
919
				'label' => $config_var[1],
920
				'help' => isset($config_var[5]) ? $config_var[5] : '',
921
				'type' => $config_var[3],
922
				'size' => empty($config_var[4]) ? 0 : $config_var[4],
923
				'data' => isset($config_var[4]) && is_array($config_var[4]) && $config_var[3] != 'select' ? $config_var[4] : array(),
924
				'name' => $config_var[0],
925
				'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 : '')),
926
				'disabled' => !empty($context['settings_not_writable']) || !empty($config_var['disabled']),
927
				'invalid' => false,
928
				'subtext' => !empty($config_var['subtext']) ? $config_var['subtext'] : $subtext,
929
				'javascript' => '',
930
				'preinput' => !empty($config_var['preinput']) ? $config_var['preinput'] : '',
931
				'postinput' => !empty($config_var['postinput']) ? $config_var['postinput'] : '',
932
			);
933
934
			// Handle min/max/step if necessary
935
			if ($config_var[3] == 'int' || $config_var[3] == 'float')
936
			{
937
				// Default to a min of 0 if one isn't set
938
				if (isset($config_var['min']))
939
					$context['config_vars'][$config_var[0]]['min'] = $config_var['min'];
940
				else
941
					$context['config_vars'][$config_var[0]]['min'] = 0;
942
943
				if (isset($config_var['max']))
944
					$context['config_vars'][$config_var[0]]['max'] = $config_var['max'];
945
946
				if (isset($config_var['step']))
947
					$context['config_vars'][$config_var[0]]['step'] = $config_var['step'];
948
			}
949
950
			// If this is a select box handle any data.
951
			if (!empty($config_var[4]) && is_array($config_var[4]))
952
			{
953
				// If it's associative
954
				$config_values = array_values($config_var[4]);
955
				if (isset($config_values[0]) && is_array($config_values[0]))
956
					$context['config_vars'][$config_var[0]]['data'] = $config_var[4];
957
				else
958
				{
959
					foreach ($config_var[4] as $key => $item)
960
						$context['config_vars'][$config_var[0]]['data'][] = array($key, $item);
961
				}
962
			}
963
		}
964
	}
965
966
	// Two tokens because saving these settings requires both saveSettings and saveDBSettings
967
	createToken('admin-ssc');
968
	createToken('admin-dbsc');
969
}
970
971
/**
972
 * Helper function, it sets up the context for database settings.
973
 *
974
 * @todo see rev. 10406 from 2.1-requests
975
 *
976
 * @param array $config_vars An array of configuration variables
977
 */
978
function prepareDBSettingContext(&$config_vars)
979
{
980
	global $txt, $helptxt, $context, $modSettings, $sourcedir, $smcFunc;
981
982
	loadLanguage('Help');
983
984
	if (isset($_SESSION['adm-save']))
985
	{
986
		if ($_SESSION['adm-save'] === true)
987
			$context['saved_successful'] = true;
988
		else
989
			$context['saved_failed'] = $_SESSION['adm-save'];
990
991
		unset($_SESSION['adm-save']);
992
	}
993
994
	$context['config_vars'] = array();
995
	$inlinePermissions = array();
996
	$bbcChoice = array();
997
	$board_list = false;
998
	foreach ($config_vars as $config_var)
999
	{
1000
		// HR?
1001
		if (!is_array($config_var))
1002
			$context['config_vars'][] = $config_var;
1003
		else
1004
		{
1005
			// If it has no name it doesn't have any purpose!
1006
			if (empty($config_var[1]))
1007
				continue;
1008
1009
			// Special case for inline permissions
1010
			if ($config_var[0] == 'permissions' && allowedTo('manage_permissions'))
1011
				$inlinePermissions[] = $config_var[1];
1012
			elseif ($config_var[0] == 'permissions')
1013
				continue;
1014
1015
			if ($config_var[0] == 'boards')
1016
				$board_list = true;
1017
1018
			// Are we showing the BBC selection box?
1019
			if ($config_var[0] == 'bbc')
1020
				$bbcChoice[] = $config_var[1];
1021
1022
			// We need to do some parsing of the value before we pass it in.
1023
			if (isset($modSettings[$config_var[1]]))
1024
			{
1025
				switch ($config_var[0])
1026
				{
1027
					case 'select':
1028
						$value = $modSettings[$config_var[1]];
1029
						break;
1030
					case 'json':
1031
						$value = $smcFunc['htmlspecialchars']($smcFunc['json_encode']($modSettings[$config_var[1]]));
1032
						break;
1033
					case 'boards':
1034
						$value = explode(',', $modSettings[$config_var[1]]);
1035
						break;
1036
					default:
1037
						$value = $smcFunc['htmlspecialchars']($modSettings[$config_var[1]]);
1038
				}
1039
			}
1040
			else
1041
			{
1042
				// Darn, it's empty. What type is expected?
1043
				switch ($config_var[0])
1044
				{
1045
					case 'int':
1046
					case 'float':
1047
						$value = 0;
1048
						break;
1049
					case 'select':
1050
						$value = !empty($config_var['multiple']) ? $smcFunc['json_encode'](array()) : '';
1051
						break;
1052
					case 'boards':
1053
						$value = array();
1054
						break;
1055
					default:
1056
						$value = '';
1057
				}
1058
			}
1059
1060
			$context['config_vars'][$config_var[1]] = array(
1061
				'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] : '')),
1062
				'help' => isset($helptxt[$config_var[1]]) ? $config_var[1] : '',
1063
				'type' => $config_var[0],
1064
				'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)),
1065
				'data' => array(),
1066
				'name' => $config_var[1],
1067
				'value' => $value,
1068
				'disabled' => false,
1069
				'invalid' => !empty($config_var['invalid']),
1070
				'javascript' => '',
1071
				'var_message' => !empty($config_var['message']) && isset($txt[$config_var['message']]) ? $txt[$config_var['message']] : '',
1072
				'preinput' => isset($config_var['preinput']) ? $config_var['preinput'] : '',
1073
				'postinput' => isset($config_var['postinput']) ? $config_var['postinput'] : '',
1074
			);
1075
1076
			// Handle min/max/step if necessary
1077
			if ($config_var[0] == 'int' || $config_var[0] == 'float')
1078
			{
1079
				// Default to a min of 0 if one isn't set
1080
				if (isset($config_var['min']))
1081
					$context['config_vars'][$config_var[1]]['min'] = $config_var['min'];
1082
				else
1083
					$context['config_vars'][$config_var[1]]['min'] = 0;
1084
1085
				if (isset($config_var['max']))
1086
					$context['config_vars'][$config_var[1]]['max'] = $config_var['max'];
1087
1088
				if (isset($config_var['step']))
1089
					$context['config_vars'][$config_var[1]]['step'] = $config_var['step'];
1090
			}
1091
1092
			// If this is a select box handle any data.
1093
			if (!empty($config_var[2]) && is_array($config_var[2]))
1094
			{
1095
				// If we allow multiple selections, we need to adjust a few things.
1096
				if ($config_var[0] == 'select' && !empty($config_var['multiple']))
1097
				{
1098
					$context['config_vars'][$config_var[1]]['name'] .= '[]';
1099
					$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();
1100
				}
1101
1102
				// If it's associative
1103
				if (isset($config_var[2][0]) && is_array($config_var[2][0]))
1104
					$context['config_vars'][$config_var[1]]['data'] = $config_var[2];
1105
				else
1106
				{
1107
					foreach ($config_var[2] as $key => $item)
1108
						$context['config_vars'][$config_var[1]]['data'][] = array($key, $item);
1109
				}
1110
			}
1111
1112
			// Finally allow overrides - and some final cleanups.
1113
			foreach ($config_var as $k => $v)
1114
			{
1115
				if (!is_numeric($k))
1116
				{
1117
					if (substr($k, 0, 2) == 'on')
1118
						$context['config_vars'][$config_var[1]]['javascript'] .= ' ' . $k . '="' . $v . '"';
1119
					else
1120
						$context['config_vars'][$config_var[1]][$k] = $v;
1121
				}
1122
1123
				// See if there are any other labels that might fit?
1124
				if (isset($txt['setting_' . $config_var[1]]))
1125
					$context['config_vars'][$config_var[1]]['label'] = $txt['setting_' . $config_var[1]];
1126
				elseif (isset($txt['groups_' . $config_var[1]]))
1127
					$context['config_vars'][$config_var[1]]['label'] = $txt['groups_' . $config_var[1]];
1128
			}
1129
1130
			// Set the subtext in case it's part of the label.
1131
			// @todo Temporary. Preventing divs inside label tags.
1132
			$divPos = strpos($context['config_vars'][$config_var[1]]['label'], '<div');
1133
			if ($divPos !== false)
1134
			{
1135
				$context['config_vars'][$config_var[1]]['subtext'] = preg_replace('~</?div[^>]*>~', '', substr($context['config_vars'][$config_var[1]]['label'], $divPos));
1136
				$context['config_vars'][$config_var[1]]['label'] = substr($context['config_vars'][$config_var[1]]['label'], 0, $divPos);
1137
			}
1138
		}
1139
	}
1140
1141
	// If we have inline permissions we need to prep them.
1142
	if (!empty($inlinePermissions) && allowedTo('manage_permissions'))
1143
	{
1144
		require_once($sourcedir . '/ManagePermissions.php');
1145
		init_inline_permissions($inlinePermissions);
1146
	}
1147
1148
	if ($board_list)
1149
	{
1150
		require_once($sourcedir . '/Subs-MessageIndex.php');
1151
		$context['board_list'] = getBoardList();
1152
	}
1153
1154
	// What about any BBC selection boxes?
1155
	if (!empty($bbcChoice))
1156
	{
1157
		// What are the options, eh?
1158
		$temp = parse_bbc(false);
1159
		$bbcTags = array();
1160
		foreach ($temp as $tag)
0 ignored issues
show
Bug introduced by
The expression $temp of type string is not traversable.
Loading history...
1161
			$bbcTags[] = $tag['tag'];
1162
1163
		$bbcTags = array_unique($bbcTags);
1164
1165
		// The number of columns we want to show the BBC tags in.
1166
		$numColumns = isset($context['num_bbc_columns']) ? $context['num_bbc_columns'] : 3;
1167
1168
		// Now put whatever BBC options we may have into context too!
1169
		$context['bbc_sections'] = array();
1170
		foreach ($bbcChoice as $bbcSection)
1171
		{
1172
			$context['bbc_sections'][$bbcSection] = array(
1173
				'title' => isset($txt['bbc_title_' . $bbcSection]) ? $txt['bbc_title_' . $bbcSection] : $txt['enabled_bbc_select'],
1174
				'disabled' => empty($modSettings['bbc_disabled_' . $bbcSection]) ? array() : $modSettings['bbc_disabled_' . $bbcSection],
1175
				'all_selected' => empty($modSettings['bbc_disabled_' . $bbcSection]),
1176
				'columns' => array(),
1177
			);
1178
1179
			if ($bbcSection == 'legacyBBC')
1180
				$sectionTags = array_intersect($context['legacy_bbc'], $bbcTags);
1181
			else
1182
				$sectionTags = array_diff($bbcTags, $context['legacy_bbc']);
1183
1184
			$totalTags = count($sectionTags);
1185
			$tagsPerColumn = ceil($totalTags / $numColumns);
1186
1187
			$col = 0;
1188
			$i = 0;
1189
			foreach ($sectionTags as $tag)
1190
			{
1191
				if ($i % $tagsPerColumn == 0 && $i != 0)
1192
					$col++;
1193
1194
				$context['bbc_sections'][$bbcSection]['columns'][$col][] = array(
1195
					'tag' => $tag,
1196
					// @todo  'tag_' . ?
1197
					'show_help' => isset($helptxt[$tag]),
1198
				);
1199
1200
				$i++;
1201
			}
1202
		}
1203
	}
1204
1205
	call_integration_hook('integrate_prepare_db_settings', array(&$config_vars));
1206
	createToken('admin-dbsc');
1207
}
1208
1209
/**
1210
 * Helper function. Saves settings by putting them in Settings.php or saving them in the settings table.
1211
 *
1212
 * - Saves those settings set from ?action=admin;area=serversettings.
1213
 * - Requires the admin_forum permission.
1214
 * - Contains arrays of the types of data to save into Settings.php.
1215
 *
1216
 * @param array $config_vars An array of configuration variables
1217
 */
1218
function saveSettings(&$config_vars)
1219
{
1220
	global $sourcedir, $context;
1221
1222
	validateToken('admin-ssc');
1223
1224
	// Fix the darn stupid cookiename! (more may not be allowed, but these for sure!)
1225
	if (isset($_POST['cookiename']))
1226
		$_POST['cookiename'] = preg_replace('~[,;\s\.$]+~' . ($context['utf8'] ? 'u' : ''), '', $_POST['cookiename']);
1227
1228
	// Fix the forum's URL if necessary.
1229
	if (isset($_POST['boardurl']))
1230
	{
1231
		if (substr($_POST['boardurl'], -10) == '/index.php')
1232
			$_POST['boardurl'] = substr($_POST['boardurl'], 0, -10);
1233
		elseif (substr($_POST['boardurl'], -1) == '/')
1234
			$_POST['boardurl'] = substr($_POST['boardurl'], 0, -1);
1235
		if (substr($_POST['boardurl'], 0, 7) != 'http://' && substr($_POST['boardurl'], 0, 7) != 'file://' && substr($_POST['boardurl'], 0, 8) != 'https://')
1236
			$_POST['boardurl'] = 'http://' . $_POST['boardurl'];
1237
	}
1238
1239
	// Any passwords?
1240
	$config_passwords = array(
1241
		'db_passwd',
1242
		'ssi_db_passwd',
1243
	);
1244
1245
	// All the strings to write.
1246
	$config_strs = array(
1247
		'mtitle', 'mmessage',
1248
		'language', 'mbname', 'boardurl',
1249
		'cookiename',
1250
		'webmaster_email',
1251
		'db_name', 'db_user', 'db_server', 'db_prefix', 'ssi_db_user',
1252
		'boarddir', 'sourcedir',
1253
		'cachedir', 'cachedir_sqlite', 'cache_accelerator', 'cache_memcached',
1254
		'image_proxy_secret',
1255
	);
1256
1257
	// All the numeric variables.
1258
	$config_ints = array(
1259
		'cache_enable',
1260
		'image_proxy_maxsize',
1261
	);
1262
1263
	// All the checkboxes
1264
	$config_bools = array('db_persist', 'db_error_send', 'maintenance', 'image_proxy_enabled');
1265
1266
	// Now sort everything into a big array, and figure out arrays and etc.
1267
	$new_settings = array();
1268
	// Figure out which config vars we're saving here...
1269
	foreach ($config_vars as $var)
1270
	{
1271
		if (!is_array($var) || $var[2] != 'file' || (!in_array($var[0], $config_bools) && !isset($_POST[$var[0]])))
1272
			continue;
1273
1274
		$config_var = $var[0];
1275
1276
		if (in_array($config_var, $config_passwords))
1277
		{
1278
			if (isset($_POST[$config_var][1]) && $_POST[$config_var][0] == $_POST[$config_var][1])
1279
				$new_settings[$config_var] = '\'' . addcslashes($_POST[$config_var][0], '\'\\') . '\'';
1280
		}
1281
		elseif (in_array($config_var, $config_strs))
1282
		{
1283
			$new_settings[$config_var] = '\'' . addcslashes($_POST[$config_var], '\'\\') . '\'';
1284
		}
1285
		elseif (in_array($config_var, $config_ints))
1286
		{
1287
			$new_settings[$config_var] = (int) $_POST[$config_var];
1288
1289
			// 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...
1290
			$min = isset($var['min']) ? $var['min'] : 0;
1291
			$new_settings[$config_var] = max($min, $new_settings[$config_var]);
1292
1293
			// Is there a max value for this as well?
1294
			if (isset($var['max']))
1295
				$new_settings[$config_var] = min($var['max'], $new_settings[$config_var]);
1296
		}
1297
		elseif (in_array($config_var, $config_bools))
1298
		{
1299
			if (!empty($_POST[$config_var]))
1300
				$new_settings[$config_var] = '1';
1301
			else
1302
				$new_settings[$config_var] = '0';
1303
		}
1304
		else
1305
		{
1306
			// This shouldn't happen, but it might...
1307
			fatal_error('Unknown config_var \'' . $config_var . '\'');
1308
		}
1309
	}
1310
1311
	// Save the relevant settings in the Settings.php file.
1312
	require_once($sourcedir . '/Subs-Admin.php');
1313
	updateSettingsFile($new_settings);
1314
1315
	// Now loop through the remaining (database-based) settings.
1316
	$new_settings = array();
1317
	foreach ($config_vars as $config_var)
1318
	{
1319
		// We just saved the file-based settings, so skip their definitions.
1320
		if (!is_array($config_var) || $config_var[2] == 'file')
1321
			continue;
1322
1323
		$new_setting = array($config_var[3], $config_var[0]);
1324
1325
		// Select options need carried over, too.
1326
		if (isset($config_var[4]))
1327
			$new_setting[] = $config_var[4];
1328
1329
		// Include min and max if necessary
1330
		if (isset($config_var['min']))
1331
			$new_setting['min'] = $config_var['min'];
1332
1333
		if (isset($config_var['max']))
1334
			$new_setting['max'] = $config_var['max'];
1335
1336
		// Rewrite the definition a bit.
1337
		$new_settings[] = $new_setting;
1338
	}
1339
1340
	// Save the new database-based settings, if any.
1341
	if (!empty($new_settings))
1342
		saveDBSettings($new_settings);
1343
}
1344
1345
/**
1346
 * Helper function for saving database settings.
1347
 *
1348
 * @todo see rev. 10406 from 2.1-requests
1349
 *
1350
 * @param array $config_vars An array of configuration variables
1351
 */
1352
function saveDBSettings(&$config_vars)
1353
{
1354
	global $sourcedir, $smcFunc;
1355
	static $board_list = null;
1356
1357
	validateToken('admin-dbsc');
1358
1359
	$inlinePermissions = array();
1360
	foreach ($config_vars as $var)
1361
	{
1362
		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']))))
1363
			continue;
1364
1365
		// Checkboxes!
1366
		elseif ($var[0] == 'check')
1367
			$setArray[$var[1]] = !empty($_POST[$var[1]]) ? '1' : '0';
1368
		// Select boxes!
1369
		elseif ($var[0] == 'select' && in_array($_POST[$var[1]], array_keys($var[2])))
1370
			$setArray[$var[1]] = $_POST[$var[1]];
1371
		elseif ($var[0] == 'select' && !empty($var['multiple']) && array_intersect($_POST[$var[1]], array_keys($var[2])) != array())
1372
		{
1373
			// For security purposes we validate this line by line.
1374
			$lOptions = array();
1375
			foreach ($_POST[$var[1]] as $invar)
1376
				if (in_array($invar, array_keys($var[2])))
1377
					$lOptions[] = $invar;
1378
1379
			$setArray[$var[1]] = $smcFunc['json_encode']($lOptions);
1380
		}
1381
		// List of boards!
1382
		elseif ($var[0] == 'boards')
1383
		{
1384
			// We just need a simple list of valid boards, nothing more.
1385
			if ($board_list === null)
1386
			{
1387
				$board_list = array();
1388
				$request = $smcFunc['db_query']('', '
1389
					SELECT id_board
1390
					FROM {db_prefix}boards');
1391
1392
				while ($row = $smcFunc['db_fetch_row']($request))
1393
					$board_list[$row[0]] = true;
1394
1395
				$smcFunc['db_free_result']($request);
1396
			}
1397
1398
			$lOptions = array();
1399
1400
			if (!empty($_POST[$var[1]]))
1401
				foreach ($_POST[$var[1]] as $invar => $dummy)
1402
					if (isset($board_list[$invar]))
1403
						$lOptions[] = $invar;
1404
1405
			$setArray[$var[1]] = !empty($lOptions) ? implode(',', $lOptions) : '';
1406
		}
1407
		// Integers!
1408
		elseif ($var[0] == 'int')
1409
		{
1410
			$setArray[$var[1]] = (int) $_POST[$var[1]];
1411
1412
			// 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...
1413
			$min = isset($var['min']) ? $var['min'] : 0;
1414
			$setArray[$var[1]] = max($min, $setArray[$var[1]]);
1415
1416
			// Do we have a max value for this as well?
1417
			if (isset($var['max']))
1418
				$setArray[$var[1]] = min($var['max'], $setArray[$var[1]]);
1419
		}
1420
		// Floating point!
1421
		elseif ($var[0] == 'float')
1422
		{
1423
			$setArray[$var[1]] = (float) $_POST[$var[1]];
1424
1425
			// 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...
1426
			$min = isset($var['min']) ? $var['min'] : 0;
1427
			$setArray[$var[1]] = max($min, $setArray[$var[1]]);
1428
1429
			// Do we have a max value for this as well?
1430
			if (isset($var['max']))
1431
				$setArray[$var[1]] = min($var['max'], $setArray[$var[1]]);
1432
		}
1433
		// Text!
1434
		elseif (in_array($var[0], array('text', 'large_text', 'color', 'date', 'datetime', 'datetime-local', 'email', 'month', 'time')))
1435
			$setArray[$var[1]] = $_POST[$var[1]];
1436
		// Passwords!
1437
		elseif ($var[0] == 'password')
1438
		{
1439
			if (isset($_POST[$var[1]][1]) && $_POST[$var[1]][0] == $_POST[$var[1]][1])
1440
				$setArray[$var[1]] = $_POST[$var[1]][0];
1441
		}
1442
		// BBC.
1443
		elseif ($var[0] == 'bbc')
1444
		{
1445
			$bbcTags = array();
1446
			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...
1447
				$bbcTags[] = $tag['tag'];
1448
1449
			if (!isset($_POST[$var[1] . '_enabledTags']))
1450
				$_POST[$var[1] . '_enabledTags'] = array();
1451
			elseif (!is_array($_POST[$var[1] . '_enabledTags']))
1452
				$_POST[$var[1] . '_enabledTags'] = array($_POST[$var[1] . '_enabledTags']);
1453
1454
			$setArray[$var[1]] = implode(',', array_diff($bbcTags, $_POST[$var[1] . '_enabledTags']));
1455
		}
1456
		// Permissions?
1457
		elseif ($var[0] == 'permissions')
1458
			$inlinePermissions[] = $var[1];
1459
	}
1460
1461
	if (!empty($setArray))
1462
		updateSettings($setArray);
1463
1464
	// If we have inline permissions we need to save them.
1465
	if (!empty($inlinePermissions) && allowedTo('manage_permissions'))
1466
	{
1467
		require_once($sourcedir . '/ManagePermissions.php');
1468
		save_inline_permissions($inlinePermissions);
1469
	}
1470
}
1471
1472
/**
1473
 * Allows us to see the servers php settings
1474
 *
1475
 * - loads the settings into an array for display in a template
1476
 * - drops cookie values just in case
1477
 */
1478
function ShowPHPinfoSettings()
1479
{
1480
	global $context, $txt;
1481
1482
	$category = $txt['phpinfo_settings'];
1483
1484
	// get the data
1485
	ob_start();
1486
	phpinfo();
1487
1488
	// We only want it for its body, pigs that we are
1489
	$info_lines = preg_replace('~^.*<body>(.*)</body>.*$~', '$1', ob_get_contents());
1490
	$info_lines = explode("\n", strip_tags($info_lines, "<tr><td><h2>"));
1491
	ob_end_clean();
1492
1493
	// remove things that could be considered sensitive
1494
	$remove = '_COOKIE|Cookie|_GET|_REQUEST|REQUEST_URI|QUERY_STRING|REQUEST_URL|HTTP_REFERER';
1495
1496
	// put all of it into an array
1497
	foreach ($info_lines as $line)
1498
	{
1499
		if (preg_match('~(' . $remove . ')~', $line))
1500
			continue;
1501
1502
		// new category?
1503
		if (strpos($line, '<h2>') !== false)
1504
			$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...
1505
1506
		// load it as setting => value or the old setting local master
1507
		if (preg_match('~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~', $line, $val))
1508
			$pinfo[$category][$val[1]] = $val[2];
1509
		elseif (preg_match('~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~', $line, $val))
1510
			$pinfo[$category][$val[1]] = array($txt['phpinfo_localsettings'] => $val[2], $txt['phpinfo_defaultsettings'] => $val[3]);
1511
	}
1512
1513
	// load it in to context and display it
1514
	$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...
1515
	$context['page_title'] = $txt['admin_server_settings'];
1516
	$context['sub_template'] = 'php_info';
1517
	return;
1518
}
1519
1520
/**
1521
 * Get the installed Cache API implementations.
1522
 *
1523
 */
1524
function loadCacheAPIs()
1525
{
1526
	global $sourcedir, $txt;
1527
1528
	// Make sure our class is in session.
1529
	require_once($sourcedir . '/Class-CacheAPI.php');
1530
1531
	$apis = array();
1532
	if ($dh = opendir($sourcedir))
1533
	{
1534
		while (($file = readdir($dh)) !== false)
1535
		{
1536
			if (is_file($sourcedir . '/' . $file) && preg_match('~^CacheAPI-([A-Za-z\d_]+)\.php$~', $file, $matches))
1537
			{
1538
				$tryCache = strtolower($matches[1]);
1539
1540
				require_once($sourcedir . '/' . $file);
1541
				$cache_class_name = $tryCache . '_cache';
1542
				$testAPI = new $cache_class_name();
1543
1544
				// No Support?  NEXT!
1545
				if (!$testAPI->isSupported(true))
1546
					continue;
1547
1548
				$apis[$tryCache] = isset($txt[$tryCache . '_cache']) ? $txt[$tryCache . '_cache'] : $tryCache;
1549
			}
1550
		}
1551
	}
1552
	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

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