Completed
Pull Request — release-2.1 (#5969)
by John
04:27
created

loadCacheAPIs()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 12
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 23
rs 9.8666
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
	foreach ($detected as $api => $object)
689
		$detected[$api] = isset($txt[$api . '_cache']) ? $txt[$api . '_cache'] : $api;
690
691
	// set our values to show what, if anything, we found
692
	if (empty($detected))
693
	{
694
		$txt['cache_settings_message'] = '<strong class="alert">' . $txt['detected_no_caching'] . '</strong>';
695
		$cache_level = array($txt['cache_off']);
696
		$detected['none'] = $txt['cache_off'];
697
	}
698
	else
699
	{
700
		$txt['cache_settings_message'] = '<strong class="success">' . sprintf($txt['detected_accelerators'], implode(', ', $detected)) . '</strong>';
701
		$cache_level = array($txt['cache_off'], $txt['cache_level1'], $txt['cache_level2'], $txt['cache_level3']);
702
	}
703
704
	// Define the variables we want to edit.
705
	$config_vars = array(
706
		// Only a few settings, but they are important
707
		array('', $txt['cache_settings_message'], '', 'desc'),
708
		array('cache_enable', $txt['cache_enable'], 'file', 'select', $cache_level, 'cache_enable'),
709
		array('cache_accelerator', $txt['cache_accelerator'], 'file', 'select', $detected),
710
	);
711
712
	// some javascript to enable / disable certain settings if the option is not selected
713
	$context['settings_post_javascript'] = '
714
		$(document).ready(function() {
715
			$("#cache_accelerator").change();
716
		});';
717
718
	call_integration_hook('integrate_modify_cache_settings', array(&$config_vars));
719
720
	// Maybe we have some additional settings from the selected accelerator.
721
	if (!empty($detected))
722
	{
723
		foreach ($detected as $tryCache => $dummy)
724
		{
725
			$cache_class_name = $tryCache . '_cache';
726
727
			// loadCacheAPIs has already included the file, just see if we can't add the settings in.
728
			if (is_callable(array($cache_class_name, 'cacheSettings')))
729
			{
730
				$testAPI = new $cache_class_name();
731
				call_user_func_array(array($testAPI, 'cacheSettings'), array(&$config_vars));
732
			}
733
		}
734
	}
735
	if ($return_config)
736
		return $config_vars;
737
738
	// Saving again?
739
	if (isset($_GET['save']))
740
	{
741
		call_integration_hook('integrate_save_cache_settings');
742
743
		saveSettings($config_vars);
744
		$_SESSION['adm-save'] = true;
745
746
		// We need to save the $cache_enable to $modSettings as well
747
		updatesettings(array('cache_enable' => (int) $_POST['cache_enable']));
748
749
		// exit so we reload our new settings on the page
750
		redirectexit('action=admin;area=serversettings;sa=cache;' . $context['session_var'] . '=' . $context['session_id']);
751
	}
752
753
	loadLanguage('ManageMaintenance');
754
	createToken('admin-maint');
755
	$context['template_layers'][] = 'clean_cache_button';
756
757
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=cache;save';
758
	$context['settings_title'] = $txt['caching_settings'];
759
760
	// Changing cache settings won't have any effect if Settings.php is not writeable.
761
	$context['save_disabled'] = $context['settings_not_writable'];
762
763
	// Decide what message to show.
764
	if (!$context['save_disabled'])
765
		$context['settings_message'] = $txt['caching_information'];
766
767
	// Prepare the template.
768
	prepareServerSettingsContext($config_vars);
769
}
770
771
/**
772
 * Allows to edit load balancing settings.
773
 *
774
 * @param bool $return_config Whether or not to return the config_vars array
775
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
776
 */
777
function ModifyLoadBalancingSettings($return_config = false)
778
{
779
	global $txt, $scripturl, $context, $modSettings;
780
781
	// Setup a warning message, but disabled by default.
782
	$disabled = true;
783
	$context['settings_message'] = array('label' => $txt['loadavg_disabled_conf'], 'class' => 'error');
784
785
	if (DIRECTORY_SEPARATOR === '\\')
786
	{
787
		$context['settings_message']['label'] = $txt['loadavg_disabled_windows'];
788
		if (isset($_GET['save']))
789
			$_SESSION['adm-save'] = $context['settings_message']['label'];
790
	}
791
	elseif (stripos(PHP_OS, 'darwin') === 0)
792
	{
793
		$context['settings_message']['label'] = $txt['loadavg_disabled_osx'];
794
		if (isset($_GET['save']))
795
			$_SESSION['adm-save'] = $context['settings_message']['label'];
796
	}
797
	else
798
	{
799
		$modSettings['load_average'] = @file_get_contents('/proc/loadavg');
800
		if (!empty($modSettings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', $modSettings['load_average'], $matches) !== 0)
801
			$modSettings['load_average'] = (float) $matches[1];
802
		elseif (($modSettings['load_average'] = @`uptime`) !== null && preg_match('~load averages?: (\d+\.\d+), (\d+\.\d+), (\d+\.\d+)~i', $modSettings['load_average'], $matches) !== 0)
803
			$modSettings['load_average'] = (float) $matches[1];
804
		else
805
			unset($modSettings['load_average']);
806
807
		if (!empty($modSettings['load_average']) || (isset($modSettings['load_average']) && $modSettings['load_average'] === 0.0))
808
		{
809
			$context['settings_message']['label'] = sprintf($txt['loadavg_warning'], $modSettings['load_average']);
810
			$disabled = false;
811
		}
812
	}
813
814
	// Start with a simple checkbox.
815
	$config_vars = array(
816
		array('check', 'loadavg_enable', 'disabled' => $disabled),
817
	);
818
819
	// Set the default values for each option.
820
	$default_values = array(
821
		'loadavg_auto_opt' => 1.0,
822
		'loadavg_search' => 2.5,
823
		'loadavg_allunread' => 2.0,
824
		'loadavg_unreadreplies' => 3.5,
825
		'loadavg_show_posts' => 2.0,
826
		'loadavg_userstats' => 10.0,
827
		'loadavg_bbc' => 30.0,
828
		'loadavg_forum' => 40.0,
829
	);
830
831
	// Loop through the settings.
832
	foreach ($default_values as $name => $value)
833
	{
834
		// Use the default value if the setting isn't set yet.
835
		$value = !isset($modSettings[$name]) ? $value : $modSettings[$name];
836
		$config_vars[] = array('float', $name, 'value' => $value, 'disabled' => $disabled);
837
	}
838
839
	call_integration_hook('integrate_loadavg_settings', array(&$config_vars));
840
841
	if ($return_config)
842
		return $config_vars;
843
844
	$context['post_url'] = $scripturl . '?action=admin;area=serversettings;sa=loads;save';
845
	$context['settings_title'] = $txt['load_balancing_settings'];
846
847
	// Saving?
848
	if (isset($_GET['save']))
849
	{
850
		// Stupidity is not allowed.
851
		foreach ($_POST as $key => $value)
852
		{
853
			if (strpos($key, 'loadavg') === 0 || $key === 'loadavg_enable' || !in_array($key, array_keys($default_values)))
854
				continue;
855
			else
856
				$_POST[$key] = (float) $value;
857
858
			if ($key == 'loadavg_auto_opt' && $value <= 1)
859
				$_POST['loadavg_auto_opt'] = 1.0;
860
			elseif ($key == 'loadavg_forum' && $value < 10)
861
				$_POST['loadavg_forum'] = 10.0;
862
			elseif ($value < 2)
863
				$_POST[$key] = 2.0;
864
		}
865
866
		call_integration_hook('integrate_save_loadavg_settings');
867
868
		saveDBSettings($config_vars);
869
		if (!isset($_SESSION['adm-save']))
870
			$_SESSION['adm-save'] = true;
871
		redirectexit('action=admin;area=serversettings;sa=loads;' . $context['session_var'] . '=' . $context['session_id']);
872
	}
873
874
	prepareDBSettingContext($config_vars);
875
}
876
877
/**
878
 * Helper function, it sets up the context for the manage server settings.
879
 * - The basic usage of the six numbered key fields are
880
 * - array (0 ,1, 2, 3, 4, 5
881
 *		0 variable name - the name of the saved variable
882
 *		1 label - the text to show on the settings page
883
 *		2 saveto - file or db, where to save the variable name - value pair
884
 *		3 type - type of data to save, int, float, text, check
885
 *		4 size - false or field size
886
 *		5 help - '' or helptxt variable name
887
 *	)
888
 *
889
 * the following named keys are also permitted
890
 * 'disabled' => A string of code that will determine whether or not the setting should be disabled
891
 * 'postinput' => Text to display after the input field
892
 * 'preinput' => Text to display before the input field
893
 * 'subtext' => Additional descriptive text to display under the field's label
894
 * 'min' => minimum allowed value (for int/float). Defaults to 0 if not set.
895
 * 'max' => maximum allowed value (for int/float)
896
 * 'step' => how much to increment/decrement the value by (only for int/float - mostly used for float values).
897
 *
898
 * @param array $config_vars An array of configuration variables
899
 */
900
function prepareServerSettingsContext(&$config_vars)
901
{
902
	global $context, $modSettings, $smcFunc;
903
904
	if (isset($_SESSION['adm-save']))
905
	{
906
		if ($_SESSION['adm-save'] === true)
907
			$context['saved_successful'] = true;
908
		else
909
			$context['saved_failed'] = $_SESSION['adm-save'];
910
911
		unset($_SESSION['adm-save']);
912
	}
913
914
	$context['config_vars'] = array();
915
	foreach ($config_vars as $identifier => $config_var)
916
	{
917
		if (!is_array($config_var) || !isset($config_var[1]))
918
			$context['config_vars'][] = $config_var;
919
		else
920
		{
921
			$varname = $config_var[0];
922
			global $$varname;
923
924
			// Set the subtext in case it's part of the label.
925
			// @todo Temporary. Preventing divs inside label tags.
926
			$divPos = strpos($config_var[1], '<div');
927
			$subtext = '';
928
			if ($divPos !== false)
929
			{
930
				$subtext = preg_replace('~</?div[^>]*>~', '', substr($config_var[1], $divPos));
931
				$config_var[1] = substr($config_var[1], 0, $divPos);
932
			}
933
934
			$context['config_vars'][$config_var[0]] = array(
935
				'label' => $config_var[1],
936
				'help' => isset($config_var[5]) ? $config_var[5] : '',
937
				'type' => $config_var[3],
938
				'size' => empty($config_var[4]) ? 0 : $config_var[4],
939
				'data' => isset($config_var[4]) && is_array($config_var[4]) && $config_var[3] != 'select' ? $config_var[4] : array(),
940
				'name' => $config_var[0],
941
				'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 : '')),
942
				'disabled' => !empty($context['settings_not_writable']) || !empty($config_var['disabled']),
943
				'invalid' => false,
944
				'subtext' => !empty($config_var['subtext']) ? $config_var['subtext'] : $subtext,
945
				'javascript' => '',
946
				'preinput' => !empty($config_var['preinput']) ? $config_var['preinput'] : '',
947
				'postinput' => !empty($config_var['postinput']) ? $config_var['postinput'] : '',
948
			);
949
950
			// Handle min/max/step if necessary
951
			if ($config_var[3] == 'int' || $config_var[3] == 'float')
952
			{
953
				// Default to a min of 0 if one isn't set
954
				if (isset($config_var['min']))
955
					$context['config_vars'][$config_var[0]]['min'] = $config_var['min'];
956
				else
957
					$context['config_vars'][$config_var[0]]['min'] = 0;
958
959
				if (isset($config_var['max']))
960
					$context['config_vars'][$config_var[0]]['max'] = $config_var['max'];
961
962
				if (isset($config_var['step']))
963
					$context['config_vars'][$config_var[0]]['step'] = $config_var['step'];
964
			}
965
966
			// If this is a select box handle any data.
967
			if (!empty($config_var[4]) && is_array($config_var[4]))
968
			{
969
				// If it's associative
970
				$config_values = array_values($config_var[4]);
971
				if (isset($config_values[0]) && is_array($config_values[0]))
972
					$context['config_vars'][$config_var[0]]['data'] = $config_var[4];
973
				else
974
				{
975
					foreach ($config_var[4] as $key => $item)
976
						$context['config_vars'][$config_var[0]]['data'][] = array($key, $item);
977
				}
978
			}
979
		}
980
	}
981
982
	// Two tokens because saving these settings requires both saveSettings and saveDBSettings
983
	createToken('admin-ssc');
984
	createToken('admin-dbsc');
985
}
986
987
/**
988
 * Helper function, it sets up the context for database settings.
989
 *
990
 * @todo see rev. 10406 from 2.1-requests
991
 *
992
 * @param array $config_vars An array of configuration variables
993
 */
994
function prepareDBSettingContext(&$config_vars)
995
{
996
	global $txt, $helptxt, $context, $modSettings, $sourcedir, $smcFunc;
997
998
	loadLanguage('Help');
999
1000
	if (isset($_SESSION['adm-save']))
1001
	{
1002
		if ($_SESSION['adm-save'] === true)
1003
			$context['saved_successful'] = true;
1004
		else
1005
			$context['saved_failed'] = $_SESSION['adm-save'];
1006
1007
		unset($_SESSION['adm-save']);
1008
	}
1009
1010
	$context['config_vars'] = array();
1011
	$inlinePermissions = array();
1012
	$bbcChoice = array();
1013
	$board_list = false;
1014
	foreach ($config_vars as $config_var)
1015
	{
1016
		// HR?
1017
		if (!is_array($config_var))
1018
			$context['config_vars'][] = $config_var;
1019
		else
1020
		{
1021
			// If it has no name it doesn't have any purpose!
1022
			if (empty($config_var[1]))
1023
				continue;
1024
1025
			// Special case for inline permissions
1026
			if ($config_var[0] == 'permissions' && allowedTo('manage_permissions'))
1027
				$inlinePermissions[] = $config_var[1];
1028
1029
			elseif ($config_var[0] == 'permissions')
1030
				continue;
1031
1032
			if ($config_var[0] == 'boards')
1033
				$board_list = true;
1034
1035
			// Are we showing the BBC selection box?
1036
			if ($config_var[0] == 'bbc')
1037
				$bbcChoice[] = $config_var[1];
1038
1039
			// We need to do some parsing of the value before we pass it in.
1040
			if (isset($modSettings[$config_var[1]]))
1041
			{
1042
				switch ($config_var[0])
1043
				{
1044
					case 'select':
1045
						$value = $modSettings[$config_var[1]];
1046
						break;
1047
					case 'json':
1048
						$value = $smcFunc['htmlspecialchars']($smcFunc['json_encode']($modSettings[$config_var[1]]));
1049
						break;
1050
					case 'boards':
1051
						$value = explode(',', $modSettings[$config_var[1]]);
1052
						break;
1053
					default:
1054
						$value = $smcFunc['htmlspecialchars']($modSettings[$config_var[1]]);
1055
				}
1056
			}
1057
			else
1058
			{
1059
				// Darn, it's empty. What type is expected?
1060
				switch ($config_var[0])
1061
				{
1062
					case 'int':
1063
					case 'float':
1064
						$value = 0;
1065
						break;
1066
					case 'select':
1067
						$value = !empty($config_var['multiple']) ? $smcFunc['json_encode'](array()) : '';
1068
						break;
1069
					case 'boards':
1070
						$value = array();
1071
						break;
1072
					default:
1073
						$value = '';
1074
				}
1075
			}
1076
1077
			$context['config_vars'][$config_var[1]] = array(
1078
				'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] : '')),
1079
				'help' => isset($helptxt[$config_var[1]]) ? $config_var[1] : '',
1080
				'type' => $config_var[0],
1081
				'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)),
1082
				'data' => array(),
1083
				'name' => $config_var[1],
1084
				'value' => $value,
1085
				'disabled' => false,
1086
				'invalid' => !empty($config_var['invalid']),
1087
				'javascript' => '',
1088
				'var_message' => !empty($config_var['message']) && isset($txt[$config_var['message']]) ? $txt[$config_var['message']] : '',
1089
				'preinput' => isset($config_var['preinput']) ? $config_var['preinput'] : '',
1090
				'postinput' => isset($config_var['postinput']) ? $config_var['postinput'] : '',
1091
			);
1092
1093
			// Handle min/max/step if necessary
1094
			if ($config_var[0] == 'int' || $config_var[0] == 'float')
1095
			{
1096
				// Default to a min of 0 if one isn't set
1097
				if (isset($config_var['min']))
1098
					$context['config_vars'][$config_var[1]]['min'] = $config_var['min'];
1099
1100
				else
1101
					$context['config_vars'][$config_var[1]]['min'] = 0;
1102
1103
				if (isset($config_var['max']))
1104
					$context['config_vars'][$config_var[1]]['max'] = $config_var['max'];
1105
1106
				if (isset($config_var['step']))
1107
					$context['config_vars'][$config_var[1]]['step'] = $config_var['step'];
1108
			}
1109
1110
			// If this is a select box handle any data.
1111
			if (!empty($config_var[2]) && is_array($config_var[2]))
1112
			{
1113
				// If we allow multiple selections, we need to adjust a few things.
1114
				if ($config_var[0] == 'select' && !empty($config_var['multiple']))
1115
				{
1116
					$context['config_vars'][$config_var[1]]['name'] .= '[]';
1117
					$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();
1118
				}
1119
1120
				// If it's associative
1121
				if (isset($config_var[2][0]) && is_array($config_var[2][0]))
1122
					$context['config_vars'][$config_var[1]]['data'] = $config_var[2];
1123
1124
				else
1125
				{
1126
					foreach ($config_var[2] as $key => $item)
1127
						$context['config_vars'][$config_var[1]]['data'][] = array($key, $item);
1128
				}
1129
				if (empty($config_var['size']) && !empty($config_var['multiple']))
1130
					$context['config_vars'][$config_var[1]]['size'] = max(4, count($config_var[2]));
1131
			}
1132
1133
			// Finally allow overrides - and some final cleanups.
1134
			foreach ($config_var as $k => $v)
1135
			{
1136
				if (!is_numeric($k))
1137
				{
1138
					if (substr($k, 0, 2) == 'on')
1139
						$context['config_vars'][$config_var[1]]['javascript'] .= ' ' . $k . '="' . $v . '"';
1140
					else
1141
						$context['config_vars'][$config_var[1]][$k] = $v;
1142
				}
1143
1144
				// See if there are any other labels that might fit?
1145
				if (isset($txt['setting_' . $config_var[1]]))
1146
					$context['config_vars'][$config_var[1]]['label'] = $txt['setting_' . $config_var[1]];
1147
1148
				elseif (isset($txt['groups_' . $config_var[1]]))
1149
					$context['config_vars'][$config_var[1]]['label'] = $txt['groups_' . $config_var[1]];
1150
			}
1151
1152
			// Set the subtext in case it's part of the label.
1153
			// @todo Temporary. Preventing divs inside label tags.
1154
			$divPos = strpos($context['config_vars'][$config_var[1]]['label'], '<div');
1155
			if ($divPos !== false)
1156
			{
1157
				$context['config_vars'][$config_var[1]]['subtext'] = preg_replace('~</?div[^>]*>~', '', substr($context['config_vars'][$config_var[1]]['label'], $divPos));
1158
				$context['config_vars'][$config_var[1]]['label'] = substr($context['config_vars'][$config_var[1]]['label'], 0, $divPos);
1159
			}
1160
		}
1161
	}
1162
1163
	// If we have inline permissions we need to prep them.
1164
	if (!empty($inlinePermissions) && allowedTo('manage_permissions'))
1165
	{
1166
		require_once($sourcedir . '/ManagePermissions.php');
1167
		init_inline_permissions($inlinePermissions);
1168
	}
1169
1170
	if ($board_list)
1171
	{
1172
		require_once($sourcedir . '/Subs-MessageIndex.php');
1173
		$context['board_list'] = getBoardList();
1174
	}
1175
1176
	// What about any BBC selection boxes?
1177
	if (!empty($bbcChoice))
1178
	{
1179
		// What are the options, eh?
1180
		$temp = parse_bbc(false);
1181
		$bbcTags = array();
1182
		foreach ($temp as $tag)
0 ignored issues
show
Bug introduced by
The expression $temp of type string is not traversable.
Loading history...
1183
			$bbcTags[] = $tag['tag'];
1184
1185
		$bbcTags = array_unique($bbcTags);
1186
1187
		// The number of columns we want to show the BBC tags in.
1188
		$numColumns = isset($context['num_bbc_columns']) ? $context['num_bbc_columns'] : 3;
1189
1190
		// Now put whatever BBC options we may have into context too!
1191
		$context['bbc_sections'] = array();
1192
		foreach ($bbcChoice as $bbcSection)
1193
		{
1194
			$context['bbc_sections'][$bbcSection] = array(
1195
				'title' => isset($txt['bbc_title_' . $bbcSection]) ? $txt['bbc_title_' . $bbcSection] : $txt['enabled_bbc_select'],
1196
				'disabled' => empty($modSettings['bbc_disabled_' . $bbcSection]) ? array() : $modSettings['bbc_disabled_' . $bbcSection],
1197
				'all_selected' => empty($modSettings['bbc_disabled_' . $bbcSection]),
1198
				'columns' => array(),
1199
			);
1200
1201
			if ($bbcSection == 'legacyBBC')
1202
				$sectionTags = array_intersect($context['legacy_bbc'], $bbcTags);
1203
			else
1204
				$sectionTags = array_diff($bbcTags, $context['legacy_bbc']);
1205
1206
			$totalTags = count($sectionTags);
1207
			$tagsPerColumn = ceil($totalTags / $numColumns);
1208
1209
			$col = 0;
1210
			$i = 0;
1211
			foreach ($sectionTags as $tag)
1212
			{
1213
				if ($i % $tagsPerColumn == 0 && $i != 0)
1214
					$col++;
1215
1216
				$context['bbc_sections'][$bbcSection]['columns'][$col][] = array(
1217
					'tag' => $tag,
1218
					// @todo  'tag_' . ?
1219
					'show_help' => isset($helptxt[$tag]),
1220
				);
1221
1222
				$i++;
1223
			}
1224
		}
1225
	}
1226
1227
	call_integration_hook('integrate_prepare_db_settings', array(&$config_vars));
1228
	createToken('admin-dbsc');
1229
}
1230
1231
/**
1232
 * Helper function. Saves settings by putting them in Settings.php or saving them in the settings table.
1233
 *
1234
 * - Saves those settings set from ?action=admin;area=serversettings.
1235
 * - Requires the admin_forum permission.
1236
 * - Contains arrays of the types of data to save into Settings.php.
1237
 *
1238
 * @param array $config_vars An array of configuration variables
1239
 */
1240
function saveSettings(&$config_vars)
1241
{
1242
	global $sourcedir, $context;
1243
1244
	validateToken('admin-ssc');
1245
1246
	// Fix the darn stupid cookiename! (more may not be allowed, but these for sure!)
1247
	if (isset($_POST['cookiename']))
1248
		$_POST['cookiename'] = preg_replace('~[,;\s\.$]+~' . ($context['utf8'] ? 'u' : ''), '', $_POST['cookiename']);
1249
1250
	// Fix the forum's URL if necessary.
1251
	if (isset($_POST['boardurl']))
1252
	{
1253
		if (substr($_POST['boardurl'], -10) == '/index.php')
1254
			$_POST['boardurl'] = substr($_POST['boardurl'], 0, -10);
1255
		elseif (substr($_POST['boardurl'], -1) == '/')
1256
			$_POST['boardurl'] = substr($_POST['boardurl'], 0, -1);
1257
		if (substr($_POST['boardurl'], 0, 7) != 'http://' && substr($_POST['boardurl'], 0, 7) != 'file://' && substr($_POST['boardurl'], 0, 8) != 'https://')
1258
			$_POST['boardurl'] = 'http://' . $_POST['boardurl'];
1259
	}
1260
1261
	// Any passwords?
1262
	$config_passwords = array(
1263
		'db_passwd',
1264
		'ssi_db_passwd',
1265
	);
1266
1267
	// All the strings to write.
1268
	$config_strs = array(
1269
		'mtitle', 'mmessage',
1270
		'language', 'mbname', 'boardurl',
1271
		'cookiename',
1272
		'webmaster_email',
1273
		'db_name', 'db_user', 'db_server', 'db_prefix', 'ssi_db_user',
1274
		'boarddir', 'sourcedir',
1275
		'cachedir', 'cachedir_sqlite', 'cache_accelerator', 'cache_memcached',
1276
		'image_proxy_secret',
1277
	);
1278
1279
	// All the numeric variables.
1280
	$config_ints = array(
1281
		'db_port',
1282
		'cache_enable',
1283
		'image_proxy_maxsize',
1284
	);
1285
1286
	// All the checkboxes
1287
	$config_bools = array('db_persist', 'db_error_send', 'maintenance', 'image_proxy_enabled');
1288
1289
	// Now sort everything into a big array, and figure out arrays and etc.
1290
	$new_settings = array();
1291
	// Figure out which config vars we're saving here...
1292
	foreach ($config_vars as $var)
1293
	{
1294
		if (!is_array($var) || $var[2] != 'file' || (!in_array($var[0], $config_bools) && !isset($_POST[$var[0]])))
1295
			continue;
1296
1297
		$config_var = $var[0];
1298
1299
		if (in_array($config_var, $config_passwords))
1300
		{
1301
			if (isset($_POST[$config_var][1]) && $_POST[$config_var][0] == $_POST[$config_var][1])
1302
				$new_settings[$config_var] = $_POST[$config_var][0];
1303
		}
1304
		elseif (in_array($config_var, $config_strs))
1305
		{
1306
			$new_settings[$config_var] = $_POST[$config_var];
1307
		}
1308
		elseif (in_array($config_var, $config_ints))
1309
		{
1310
			$new_settings[$config_var] = (int) $_POST[$config_var];
1311
1312
			// 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...
1313
			$min = isset($var['min']) ? $var['min'] : 0;
1314
			$new_settings[$config_var] = max($min, $new_settings[$config_var]);
1315
1316
			// Is there a max value for this as well?
1317
			if (isset($var['max']))
1318
				$new_settings[$config_var] = min($var['max'], $new_settings[$config_var]);
1319
		}
1320
		elseif (in_array($config_var, $config_bools))
1321
		{
1322
			if (!empty($_POST[$config_var]))
1323
				$new_settings[$config_var] = 1;
1324
			else
1325
				$new_settings[$config_var] = 0;
1326
		}
1327
		else
1328
		{
1329
			// This shouldn't happen, but it might...
1330
			fatal_error('Unknown config_var \'' . $config_var . '\'');
1331
		}
1332
	}
1333
1334
	// Save the relevant settings in the Settings.php file.
1335
	require_once($sourcedir . '/Subs-Admin.php');
1336
	updateSettingsFile($new_settings);
1337
1338
	// Now loop through the remaining (database-based) settings.
1339
	$new_settings = array();
1340
	foreach ($config_vars as $config_var)
1341
	{
1342
		// We just saved the file-based settings, so skip their definitions.
1343
		if (!is_array($config_var) || $config_var[2] == 'file')
1344
			continue;
1345
1346
		$new_setting = array($config_var[3], $config_var[0]);
1347
1348
		// Select options need carried over, too.
1349
		if (isset($config_var[4]))
1350
			$new_setting[] = $config_var[4];
1351
1352
		// Include min and max if necessary
1353
		if (isset($config_var['min']))
1354
			$new_setting['min'] = $config_var['min'];
1355
1356
		if (isset($config_var['max']))
1357
			$new_setting['max'] = $config_var['max'];
1358
1359
		// Rewrite the definition a bit.
1360
		$new_settings[] = $new_setting;
1361
	}
1362
1363
	// Save the new database-based settings, if any.
1364
	if (!empty($new_settings))
1365
		saveDBSettings($new_settings);
1366
}
1367
1368
/**
1369
 * Helper function for saving database settings.
1370
 *
1371
 * @todo see rev. 10406 from 2.1-requests
1372
 *
1373
 * @param array $config_vars An array of configuration variables
1374
 */
1375
function saveDBSettings(&$config_vars)
1376
{
1377
	global $sourcedir, $smcFunc;
1378
	static $board_list = null;
1379
1380
	validateToken('admin-dbsc');
1381
1382
	$inlinePermissions = array();
1383
	foreach ($config_vars as $var)
1384
	{
1385
		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']))))
1386
			continue;
1387
1388
		// Checkboxes!
1389
		elseif ($var[0] == 'check')
1390
			$setArray[$var[1]] = !empty($_POST[$var[1]]) ? '1' : '0';
1391
		// Select boxes!
1392
		elseif ($var[0] == 'select' && in_array($_POST[$var[1]], array_keys($var[2])))
1393
			$setArray[$var[1]] = $_POST[$var[1]];
1394
		elseif ($var[0] == 'select' && !empty($var['multiple']) && array_intersect($_POST[$var[1]], array_keys($var[2])) != array())
1395
		{
1396
			// For security purposes we validate this line by line.
1397
			$lOptions = array();
1398
			foreach ($_POST[$var[1]] as $invar)
1399
				if (in_array($invar, array_keys($var[2])))
1400
					$lOptions[] = $invar;
1401
1402
			$setArray[$var[1]] = $smcFunc['json_encode']($lOptions);
1403
		}
1404
		// List of boards!
1405
		elseif ($var[0] == 'boards')
1406
		{
1407
			// We just need a simple list of valid boards, nothing more.
1408
			if ($board_list === null)
1409
			{
1410
				$board_list = array();
1411
				$request = $smcFunc['db_query']('', '
1412
					SELECT id_board
1413
					FROM {db_prefix}boards');
1414
1415
				while ($row = $smcFunc['db_fetch_row']($request))
1416
					$board_list[$row[0]] = true;
1417
1418
				$smcFunc['db_free_result']($request);
1419
			}
1420
1421
			$lOptions = array();
1422
1423
			if (!empty($_POST[$var[1]]))
1424
				foreach ($_POST[$var[1]] as $invar => $dummy)
1425
					if (isset($board_list[$invar]))
1426
						$lOptions[] = $invar;
1427
1428
			$setArray[$var[1]] = !empty($lOptions) ? implode(',', $lOptions) : '';
1429
		}
1430
		// Integers!
1431
		elseif ($var[0] == 'int')
1432
		{
1433
			$setArray[$var[1]] = (int) $_POST[$var[1]];
1434
1435
			// 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...
1436
			$min = isset($var['min']) ? $var['min'] : 0;
1437
			$setArray[$var[1]] = max($min, $setArray[$var[1]]);
1438
1439
			// Do we have a max value for this as well?
1440
			if (isset($var['max']))
1441
				$setArray[$var[1]] = min($var['max'], $setArray[$var[1]]);
1442
		}
1443
		// Floating point!
1444
		elseif ($var[0] == 'float')
1445
		{
1446
			$setArray[$var[1]] = (float) $_POST[$var[1]];
1447
1448
			// 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...
1449
			$min = isset($var['min']) ? $var['min'] : 0;
1450
			$setArray[$var[1]] = max($min, $setArray[$var[1]]);
1451
1452
			// Do we have a max value for this as well?
1453
			if (isset($var['max']))
1454
				$setArray[$var[1]] = min($var['max'], $setArray[$var[1]]);
1455
		}
1456
		// Text!
1457
		elseif (in_array($var[0], array('text', 'large_text', 'color', 'date', 'datetime', 'datetime-local', 'email', 'month', 'time')))
1458
			$setArray[$var[1]] = $_POST[$var[1]];
1459
		// Passwords!
1460
		elseif ($var[0] == 'password')
1461
		{
1462
			if (isset($_POST[$var[1]][1]) && $_POST[$var[1]][0] == $_POST[$var[1]][1])
1463
				$setArray[$var[1]] = $_POST[$var[1]][0];
1464
		}
1465
		// BBC.
1466
		elseif ($var[0] == 'bbc')
1467
		{
1468
			$bbcTags = array();
1469
			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...
1470
				$bbcTags[] = $tag['tag'];
1471
1472
			if (!isset($_POST[$var[1] . '_enabledTags']))
1473
				$_POST[$var[1] . '_enabledTags'] = array();
1474
			elseif (!is_array($_POST[$var[1] . '_enabledTags']))
1475
				$_POST[$var[1] . '_enabledTags'] = array($_POST[$var[1] . '_enabledTags']);
1476
1477
			$setArray[$var[1]] = implode(',', array_diff($bbcTags, $_POST[$var[1] . '_enabledTags']));
1478
		}
1479
		// Permissions?
1480
		elseif ($var[0] == 'permissions')
1481
			$inlinePermissions[] = $var[1];
1482
	}
1483
1484
	if (!empty($setArray))
1485
		updateSettings($setArray);
1486
1487
	// If we have inline permissions we need to save them.
1488
	if (!empty($inlinePermissions) && allowedTo('manage_permissions'))
1489
	{
1490
		require_once($sourcedir . '/ManagePermissions.php');
1491
		save_inline_permissions($inlinePermissions);
1492
	}
1493
}
1494
1495
/**
1496
 * Allows us to see the servers php settings
1497
 *
1498
 * - loads the settings into an array for display in a template
1499
 * - drops cookie values just in case
1500
 */
1501
function ShowPHPinfoSettings()
1502
{
1503
	global $context, $txt;
1504
1505
	$category = $txt['phpinfo_settings'];
1506
1507
	// get the data
1508
	ob_start();
1509
	phpinfo();
1510
1511
	// We only want it for its body, pigs that we are
1512
	$info_lines = preg_replace('~^.*<body>(.*)</body>.*$~', '$1', ob_get_contents());
1513
	$info_lines = explode("\n", strip_tags($info_lines, "<tr><td><h2>"));
1514
	ob_end_clean();
1515
1516
	// remove things that could be considered sensitive
1517
	$remove = '_COOKIE|Cookie|_GET|_REQUEST|REQUEST_URI|QUERY_STRING|REQUEST_URL|HTTP_REFERER';
1518
1519
	// put all of it into an array
1520
	foreach ($info_lines as $line)
1521
	{
1522
		if (preg_match('~(' . $remove . ')~', $line))
1523
			continue;
1524
1525
		// new category?
1526
		if (strpos($line, '<h2>') !== false)
1527
			$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...
1528
1529
		// load it as setting => value or the old setting local master
1530
		if (preg_match('~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~', $line, $val))
1531
			$pinfo[$category][$val[1]] = $val[2];
1532
		elseif (preg_match('~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~', $line, $val))
1533
			$pinfo[$category][$val[1]] = array($txt['phpinfo_localsettings'] => $val[2], $txt['phpinfo_defaultsettings'] => $val[3]);
1534
	}
1535
1536
	// load it in to context and display it
1537
	$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...
1538
	$context['page_title'] = $txt['admin_server_settings'];
1539
	$context['sub_template'] = 'php_info';
1540
	return;
1541
}
1542
1543
/**
1544
 * Get the installed Cache API implementations.
1545
 *
1546
 */
1547
function loadCacheAPIs()
1548
{
1549
	global $sourcedir;
1550
1551
	// Make sure our class is in session.
1552
	require_once($sourcedir . '/Class-CacheAPI.php');
1553
1554
	$apis = array();
1555
	$classes = new GlobIterator($sourcedir . '/CacheAPI-*.php', FilesystemIterator::NEW_CURRENT_AND_KEY);
1556
1557
	foreach ($classes as $file => $info)
1558
	{
1559
		$tryCache = strtolower(explode('-', $info->getBasename('.php'))[1]);
1560
1561
		require_once($sourcedir . '/' . $file);
1562
		$cache_class_name = $tryCache . '_cache';
1563
		$testAPI = new $cache_class_name();
1564
1565
		if ($testAPI->isSupported(true) && $testAPI->connect())
1566
			$apis[$tryCache] = $testAPI;
1567
	}
1568
1569
	return $apis;
1570
}
1571
1572
/**
1573
 * Registers the site with the Simple Machines Stat collection. This function
1574
 * purposely does not use updateSettings.php as it will be called shortly after
1575
 * this process completes by the saveSettings() function.
1576
 *
1577
 * @see Stats.php SMStats() for more information.
1578
 * @link https://www.simplemachines.org/about/stats.php for more info.
1579
 *
1580
 */
1581
function registerSMStats()
1582
{
1583
	global $modSettings, $boardurl, $smcFunc;
1584
1585
	// Already have a key?  Can't register again.
1586
	if (!empty($modSettings['sm_stats_key']))
1587
		return true;
1588
1589
	$fp = @fsockopen('www.simplemachines.org', 80, $errno, $errstr);
1590
	if ($fp)
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
1591
	{
1592
		$out = 'GET /smf/stats/register_stats.php?site=' . base64_encode($boardurl) . ' HTTP/1.1' . "\r\n";
1593
		$out .= 'Host: www.simplemachines.org' . "\r\n";
1594
		$out .= 'Connection: Close' . "\r\n\r\n";
1595
		fwrite($fp, $out);
1596
1597
		$return_data = '';
1598
		while (!feof($fp))
1599
			$return_data .= fgets($fp, 128);
1600
1601
		fclose($fp);
1602
1603
		// Get the unique site ID.
1604
		preg_match('~SITE-ID:\s(\w{10})~', $return_data, $ID);
1605
1606
		if (!empty($ID[1]))
1607
		{
1608
			$smcFunc['db_insert']('replace',
1609
				'{db_prefix}settings',
1610
				array('variable' => 'string', 'value' => 'string'),
1611
				array('sm_stats_key', $ID[1]),
1612
				array('variable')
1613
			);
1614
			return true;
1615
		}
1616
	}
1617
1618
	return false;
1619
}
1620
1621
?>