Issues (1061)

Sources/ManageServer.php (5 issues)

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