Passed
Pull Request — release-2.1 (#6845)
by Jon
04:16
created

ModifyBasicSettings()   D

Complexity

Conditions 14
Paths 224

Size

Total Lines 146
Code Lines 90

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 14
eloc 90
c 1
b 0
f 0
nc 224
nop 1
dl 0
loc 146
rs 4.3248

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This file is here to make it easier for installed mods to have
5
 * settings and options.
6
 *
7
 * Simple Machines Forum (SMF)
8
 *
9
 * @package SMF
10
 * @author Simple Machines https://www.simplemachines.org
11
 * @copyright 2021 Simple Machines and individual contributors
12
 * @license https://www.simplemachines.org/about/smf/license.php BSD
13
 *
14
 * @version 2.1 RC4
15
 */
16
17
if (!defined('SMF'))
18
	die('No direct access...');
19
20
/**
21
 * This function makes sure the requested subaction does exists, if it doesn't, it sets a default action or.
22
 *
23
 * @param array $subActions An array containing all possible subactions.
24
 * @param string $defaultAction The default action to be called if no valid subaction was found.
25
 */
26
function loadGeneralSettingParameters($subActions = array(), $defaultAction = null)
27
{
28
	global $context, $sourcedir;
29
30
	// You need to be an admin to edit settings!
31
	isAllowedTo('admin_forum');
32
33
	// Will need the utility functions from here.
34
	require_once($sourcedir . '/ManageServer.php');
35
36
	$context['sub_template'] = 'show_settings';
37
38
	// If no fallback was specified, use the first subaction.
39
	$defaultAction = $defaultAction ?: key($subActions);
40
41
	// I want...
42
	$_REQUEST['sa'] = isset($_REQUEST['sa'], $subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : $defaultAction;
43
	$context['sub_action'] = $_REQUEST['sa'];
44
}
45
46
/**
47
 * This function passes control through to the relevant tab.
48
 */
49
function ModifyFeatureSettings()
50
{
51
	global $context, $txt, $settings, $scripturl, $modSettings, $language;
52
53
	loadLanguage('Help');
54
	loadLanguage('ManageSettings');
55
56
	$context['page_title'] = $txt['modSettings_title'];
57
	$context['show_privacy_policy_warning'] = empty($modSettings['policy_' . $language]);
58
59
	$subActions = array(
60
		'basic' => 'ModifyBasicSettings',
61
		'bbc' => 'ModifyBBCSettings',
62
		'layout' => 'ModifyLayoutSettings',
63
		'sig' => 'ModifySignatureSettings',
64
		'profile' => 'ShowCustomProfiles',
65
		'profileedit' => 'EditCustomProfiles',
66
		'likes' => 'ModifyLikesSettings',
67
		'mentions' => 'ModifyMentionsSettings',
68
		'alerts' => 'ModifyAlertsSettings',
69
	);
70
71
	// Load up all the tabs...
72
	$context[$context['admin_menu_name']]['tab_data'] = array(
73
		'title' => $txt['modSettings_title'],
74
		'help' => 'featuresettings',
75
		'description' => sprintf($txt['modSettings_desc'], $settings['theme_id'], $context['session_id'], $context['session_var'], $scripturl),
76
		'tabs' => array(
77
			'basic' => array(
78
			),
79
			'bbc' => array(
80
				'description' => $txt['manageposts_bbc_settings_description'],
81
			),
82
			'layout' => array(
83
			),
84
			'sig' => array(
85
				'description' => $txt['signature_settings_desc'],
86
			),
87
			'profile' => array(
88
				'description' => $txt['custom_profile_desc'],
89
			),
90
			'likes' => array(
91
			),
92
			'mentions' => array(
93
			),
94
			'alerts' => array(
95
				'description' => $txt['notifications_desc'],
96
			),
97
		),
98
	);
99
100
	call_integration_hook('integrate_modify_features', array(&$subActions));
101
102
	loadGeneralSettingParameters($subActions, 'basic');
103
104
	// Call the right function for this sub-action.
105
	call_helper($subActions[$_REQUEST['sa']]);
106
}
107
108
/**
109
 * This my friend, is for all the mod authors out there.
110
 */
111
function ModifyModSettings()
112
{
113
	global $context, $txt;
114
115
	loadLanguage('Help');
116
	loadLanguage('ManageSettings');
117
118
	$context['page_title'] = $txt['admin_modifications'];
119
120
	$subActions = array(
121
		'general' => 'ModifyGeneralModSettings',
122
		// Mod authors, once again, if you have a whole section to add do it AFTER this line, and keep a comma at the end.
123
	);
124
125
	// Load up all the tabs...
126
	$context[$context['admin_menu_name']]['tab_data'] = array(
127
		'title' => $txt['admin_modifications'],
128
		'help' => 'modsettings',
129
		'description' => $txt['modification_settings_desc'],
130
		'tabs' => array(
131
			'general' => array(
132
			),
133
		),
134
	);
135
136
	// Make it easier for mods to add new areas.
137
	call_integration_hook('integrate_modify_modifications', array(&$subActions));
138
139
	loadGeneralSettingParameters($subActions, 'general');
140
141
	// Call the right function for this sub-action.
142
	call_helper($subActions[$_REQUEST['sa']]);
143
}
144
145
/**
146
 * Config array for changing the basic forum settings
147
 * Accessed  from ?action=admin;area=featuresettings;sa=basic;
148
 *
149
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
150
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
151
 */
152
function ModifyBasicSettings($return_config = false)
153
{
154
	global $txt, $scripturl, $context, $modSettings;
155
156
	// We need to know if personal text is enabled, and if it's in the registration fields option.
157
	// If admins have set it up as an on-registration thing, they can't set a default value (because it'll never be used)
158
	$disabled_fields = isset($modSettings['disabled_profile_fields']) ? explode(',', $modSettings['disabled_profile_fields']) : array();
159
	$reg_fields = isset($modSettings['registration_fields']) ? explode(',', $modSettings['registration_fields']) : array();
160
	$can_personal_text = !in_array('personal_text', $disabled_fields) && !in_array('personal_text', $reg_fields);
161
162
	$config_vars = array(
163
		// Big Options... polls, sticky, bbc....
164
		array('select', 'pollMode', array($txt['disable_polls'], $txt['enable_polls'], $txt['polls_as_topics'])),
165
		'',
166
167
		// Basic stuff, titles, flash, permissions...
168
		array('check', 'allow_guestAccess'),
169
		array('check', 'enable_buddylist'),
170
		array('check', 'allow_hideOnline'),
171
		array('check', 'titlesEnable'),
172
		array('text', 'default_personal_text', 'subtext' => $txt['default_personal_text_note'], 'disabled' => !$can_personal_text),
173
		array('check', 'topic_move_any'),
174
		array('int', 'defaultMaxListItems', 'step' => 1, 'min' => 1, 'max' => 999),
175
		'',
176
177
		// Jquery source
178
		array(
179
			'select',
180
			'jquery_source',
181
			array(
182
				'auto' => $txt['jquery_auto'],
183
				'local' => $txt['jquery_local'],
184
				'cdn' => $txt['jquery_cdn'],
185
				'custom' => $txt['jquery_custom']
186
			),
187
			'onchange' => 'if (this.value == \'custom\'){document.getElementById(\'jquery_custom\').disabled = false; } else {document.getElementById(\'jquery_custom\').disabled = true;}'
188
		),
189
		array(
190
			'text',
191
			'jquery_custom',
192
			'disabled' => isset($modSettings['jquery_source']) && $modSettings['jquery_source'] != 'custom', 'size' => 75
193
		),
194
		'',
195
196
		// css and js minification.
197
		array('check', 'minimize_files'),
198
		'',
199
200
		// SEO stuff
201
		array('check', 'queryless_urls', 'subtext' => '<strong>' . $txt['queryless_urls_note'] . '</strong>'),
202
		array('text', 'meta_keywords', 'subtext' => $txt['meta_keywords_note'], 'size' => 50),
203
		'',
204
205
		// Number formatting, timezones.
206
		array('text', 'time_format'),
207
		array(
208
			'float',
209
			'time_offset',
210
			6,
211
			'postinput' => $txt['hours'],
212
			'step' => 0.25,
213
			'min' => -23.5,
214
			'max' => 23.5
215
		),
216
		array('select', 'default_timezone', array_filter(smf_list_timezones(), 'is_string', ARRAY_FILTER_USE_KEY)),
217
		array('text', 'timezone_priority_countries', 'subtext' => $txt['setting_timezone_priority_countries_note']),
218
		'',
219
220
		// Who's online?
221
		array('check', 'who_enabled'),
222
		array('int', 'lastActive', 6, 'postinput' => $txt['minutes']),
223
		'',
224
225
		// Statistics.
226
		array('check', 'trackStats'),
227
		array('check', 'hitStats'),
228
		'',
229
230
		// Option-ish things... miscellaneous sorta.
231
		array('check', 'disallow_sendBody'),
232
		'',
233
234
		// Alerts stuff
235
		array('check', 'enable_ajax_alerts'),
236
		array('select', 'alerts_auto_purge',
237
			array(
238
				'0' => $txt['alerts_auto_purge_0'],
239
				'7' => $txt['alerts_auto_purge_7'],
240
				'30' => $txt['alerts_auto_purge_30'],
241
				'90' => $txt['alerts_auto_purge_90'],
242
			),
243
		),
244
	);
245
246
	call_integration_hook('integrate_modify_basic_settings', array(&$config_vars));
247
248
	if ($return_config)
249
		return $config_vars;
250
251
	// Saving?
252
	if (isset($_GET['save']))
253
	{
254
		checkSession();
255
256
		// Make sure the country codes are valid.
257
		if (!empty($_POST['timezone_priority_countries']))
258
		{
259
			$country_codes = explode(',', $_POST['timezone_priority_countries']);
260
			foreach ($country_codes as $key => $country_code)
261
			{
262
				$country_code = substr(trim($country_code), 0, 2);
263
				$country_tzids = @timezone_identifiers_list(DateTimeZone::PER_COUNTRY, $country_code);
264
265
				if (empty($country_tzids))
266
					unset($country_codes[$key]);
267
				else
268
					$country_codes[$key] = $country_code;
269
			}
270
271
			if (empty($country_codes))
272
				unset($_POST['timezone_priority_countries']);
273
			else
274
				$_POST['timezone_priority_countries'] = implode(',', $country_codes);
275
		}
276
277
		// Prevent absurd boundaries here - make it a day tops.
278
		if (isset($_POST['lastActive']))
279
			$_POST['lastActive'] = min((int) $_POST['lastActive'], 1440);
280
281
		call_integration_hook('integrate_save_basic_settings');
282
283
		saveDBSettings($config_vars);
284
		$_SESSION['adm-save'] = true;
285
286
		// Do a bit of housekeeping
287
		if (empty($_POST['minimize_files']) || $_POST['minimize_files'] != $modSettings['minimize_files'])
288
			deleteAllMinified();
289
290
		writeLog();
291
		redirectexit('action=admin;area=featuresettings;sa=basic');
292
	}
293
294
	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=basic';
295
	$context['settings_title'] = $txt['mods_cat_features'];
296
297
	prepareDBSettingContext($config_vars);
298
}
299
300
/**
301
 * Set a few Bulletin Board Code settings. It loads a list of Bulletin Board Code tags to allow disabling tags.
302
 * Requires the admin_forum permission.
303
 * Accessed from ?action=admin;area=featuresettings;sa=bbc.
304
 * @uses template_show_settings()
305
 *
306
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
307
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
308
 */
309
function ModifyBBCSettings($return_config = false)
310
{
311
	global $context, $txt, $modSettings, $scripturl, $sourcedir;
312
313
	$config_vars = array(
314
		// Main tweaks
315
		array('check', 'enableBBC'),
316
		array('check', 'enableBBC', 0, 'onchange' => 'toggleBBCDisabled(\'disabledBBC\', !this.checked); toggleBBCDisabled(\'legacyBBC\', !this.checked);'),
317
		array('check', 'enablePostHTML'),
318
		array('check', 'autoLinkUrls'),
319
		'',
320
321
		array('bbc', 'disabledBBC'),
322
323
		// This one is actually pretend...
324
		array('bbc', 'legacyBBC', 'help' => 'legacy_bbc'),
325
	);
326
327
	// Permissions for restricted BBC
328
	if (!empty($context['restricted_bbc']))
329
		$config_vars[] = '';
330
331
	foreach ($context['restricted_bbc'] as $bbc)
332
		$config_vars[] = array('permissions', 'bbc_' . $bbc, 'text_label' => sprintf($txt['groups_can_use'], '[' . $bbc . ']'));
333
334
	$context['settings_post_javascript'] = '
335
		toggleBBCDisabled(\'disabledBBC\', ' . (empty($modSettings['enableBBC']) ? 'true' : 'false') . ');
336
		toggleBBCDisabled(\'legacyBBC\', ' . (empty($modSettings['enableBBC']) ? 'true' : 'false') . ');';
337
338
	call_integration_hook('integrate_modify_bbc_settings', array(&$config_vars));
339
340
	if ($return_config)
341
		return $config_vars;
342
343
	// Setup the template.
344
	require_once($sourcedir . '/ManageServer.php');
345
	$context['sub_template'] = 'show_settings';
346
	$context['page_title'] = $txt['manageposts_bbc_settings_title'];
347
348
	// Make sure we check the right tags!
349
	$modSettings['bbc_disabled_disabledBBC'] = empty($modSettings['disabledBBC']) ? array() : explode(',', $modSettings['disabledBBC']);
350
351
	// Legacy BBC are listed separately, but we use the same info in both cases
352
	$modSettings['bbc_disabled_legacyBBC'] = $modSettings['bbc_disabled_disabledBBC'];
353
354
	$extra = '';
355
	if (isset($_REQUEST['cowsay']))
356
	{
357
		$config_vars[] = array('permissions', 'bbc_cowsay', 'text_label' => sprintf($txt['groups_can_use'], '[cowsay]'));
358
		$extra = ';cowsay';
359
	}
360
361
	// Saving?
362
	if (isset($_GET['save']))
363
	{
364
		checkSession();
365
366
		// Clean up the tags.
367
		$bbcTags = array();
368
		$bbcTagsChildren = array();
369
		foreach (parse_bbc(false) as $tag)
370
		{
371
			$bbcTags[] = $tag['tag'];
372
			if (isset($tag['require_children']))
373
				$bbcTagsChildren[$tag['tag']] = !isset($bbcTagsChildren[$tag['tag']]) ? $tag['require_children'] : array_unique(array_merge($bbcTagsChildren[$tag['tag']], $tag['require_children']));
374
		}
375
376
		// Clean up tags with children
377
		foreach($bbcTagsChildren as $parent_tag => $children)
378
			foreach($children as $index => $child_tag)
379
			{
380
				// Remove entries where parent and child tag is the same
381
				if ($child_tag == $parent_tag)
382
				{
383
					unset($bbcTagsChildren[$parent_tag][$index]);
384
					continue;
385
				}
386
				// Combine chains of tags
387
				if (isset($bbcTagsChildren[$child_tag]))
388
				{
389
					$bbcTagsChildren[$parent_tag] = array_merge($bbcTagsChildren[$parent_tag], $bbcTagsChildren[$child_tag]);
390
					unset($bbcTagsChildren[$child_tag]);
391
				}
392
			}
393
394
		if (!isset($_POST['disabledBBC_enabledTags']))
395
			$_POST['disabledBBC_enabledTags'] = array();
396
		elseif (!is_array($_POST['disabledBBC_enabledTags']))
397
			$_POST['disabledBBC_enabledTags'] = array($_POST['disabledBBC_enabledTags']);
398
399
		if (!isset($_POST['legacyBBC_enabledTags']))
400
			$_POST['legacyBBC_enabledTags'] = array();
401
		elseif (!is_array($_POST['legacyBBC_enabledTags']))
402
			$_POST['legacyBBC_enabledTags'] = array($_POST['legacyBBC_enabledTags']);
403
404
		$_POST['disabledBBC_enabledTags'] = array_unique(array_merge($_POST['disabledBBC_enabledTags'], $_POST['legacyBBC_enabledTags']));
405
406
		// Enable all children if parent is enabled
407
		foreach ($bbcTagsChildren as $tag => $children)
408
			if (in_array($tag, $_POST['disabledBBC_enabledTags']))
409
				$_POST['disabledBBC_enabledTags'] = array_merge($_POST['disabledBBC_enabledTags'], $children);
410
411
		// Work out what is actually disabled!
412
		$_POST['disabledBBC'] = implode(',', array_diff($bbcTags, $_POST['disabledBBC_enabledTags']));
413
414
		// $modSettings['legacyBBC'] isn't really a thing...
415
		unset($_POST['legacyBBC_enabledTags']);
416
		$config_vars = array_filter($config_vars, function($config_var)
417
		{
418
			return !isset($config_var[1]) || $config_var[1] != 'legacyBBC';
419
		});
420
421
		call_integration_hook('integrate_save_bbc_settings', array($bbcTags));
422
423
		saveDBSettings($config_vars);
424
		$_SESSION['adm-save'] = true;
425
		redirectexit('action=admin;area=featuresettings;sa=bbc' . $extra);
426
	}
427
428
	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=bbc' . $extra;
429
	$context['settings_title'] = $txt['manageposts_bbc_settings_title'];
430
431
	prepareDBSettingContext($config_vars);
432
}
433
434
/**
435
 * Allows modifying the global layout settings in the forum
436
 * Accessed through ?action=admin;area=featuresettings;sa=layout;
437
 *
438
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
439
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
440
 */
441
function ModifyLayoutSettings($return_config = false)
442
{
443
	global $txt, $scripturl, $context;
444
445
	$config_vars = array(
446
		// Pagination stuff.
447
		array('check', 'compactTopicPagesEnable'),
448
		array(
449
			'int',
450
			'compactTopicPagesContiguous',
451
			null,
452
			$txt['contiguous_page_display'] . '<div class="smalltext">' . str_replace(' ', '&nbsp;', '"3" ' . $txt['to_display'] . ': <strong>1 ... 4 [5] 6 ... 9</strong>') . '<br>' . str_replace(' ', '&nbsp;', '"5" ' . $txt['to_display'] . ': <strong>1 ... 3 4 [5] 6 7 ... 9</strong>') . '</div>'
453
		),
454
		array('int', 'defaultMaxMembers'),
455
		'',
456
457
		// Stuff that just is everywhere - today, search, online, etc.
458
		array('select', 'todayMod', array($txt['today_disabled'], $txt['today_only'], $txt['yesterday_today'])),
459
		array('check', 'onlineEnable'),
460
		'',
461
462
		// This is like debugging sorta.
463
		array('check', 'timeLoadPageEnable'),
464
	);
465
466
	call_integration_hook('integrate_layout_settings', array(&$config_vars));
467
468
	if ($return_config)
469
		return $config_vars;
470
471
	// Saving?
472
	if (isset($_GET['save']))
473
	{
474
		checkSession();
475
476
		call_integration_hook('integrate_save_layout_settings');
477
478
		saveDBSettings($config_vars);
479
		$_SESSION['adm-save'] = true;
480
		writeLog();
481
482
		redirectexit('action=admin;area=featuresettings;sa=layout');
483
	}
484
485
	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=layout';
486
	$context['settings_title'] = $txt['mods_cat_layout'];
487
488
	prepareDBSettingContext($config_vars);
489
}
490
491
/**
492
 * Config array for changing like settings
493
 * Accessed  from ?action=admin;area=featuresettings;sa=likes;
494
 *
495
 * @param bool $return_config Whether or not to return the config_vars array
496
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
497
 */
498
function ModifyLikesSettings($return_config = false)
499
{
500
	global $txt, $scripturl, $context;
501
502
	$config_vars = array(
503
		array('check', 'enable_likes'),
504
		array('permissions', 'likes_like'),
505
	);
506
507
	call_integration_hook('integrate_likes_settings', array(&$config_vars));
508
509
	if ($return_config)
510
		return $config_vars;
511
512
	// Saving?
513
	if (isset($_GET['save']))
514
	{
515
		checkSession();
516
517
		call_integration_hook('integrate_save_likes_settings');
518
519
		saveDBSettings($config_vars);
520
		$_SESSION['adm-save'] = true;
521
		redirectexit('action=admin;area=featuresettings;sa=likes');
522
	}
523
524
	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=likes';
525
	$context['settings_title'] = $txt['likes'];
526
527
	prepareDBSettingContext($config_vars);
528
}
529
530
/**
531
 * Config array for changing like settings
532
 * Accessed  from ?action=admin;area=featuresettings;sa=mentions;
533
 *
534
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
535
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
536
 */
537
function ModifyMentionsSettings($return_config = false)
538
{
539
	global $txt, $scripturl, $context;
540
541
	$config_vars = array(
542
		array('check', 'enable_mentions'),
543
		array('permissions', 'mention'),
544
	);
545
546
	call_integration_hook('integrate_mentions_settings', array(&$config_vars));
547
548
	if ($return_config)
549
		return $config_vars;
550
551
	// Saving?
552
	if (isset($_GET['save']))
553
	{
554
		checkSession();
555
556
		call_integration_hook('integrate_save_mentions_settings');
557
558
		saveDBSettings($config_vars);
559
		$_SESSION['adm-save'] = true;
560
		redirectexit('action=admin;area=featuresettings;sa=mentions');
561
	}
562
563
	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=mentions';
564
	$context['settings_title'] = $txt['mentions'];
565
566
	prepareDBSettingContext($config_vars);
567
}
568
569
/**
570
 * Moderation type settings - although there are fewer than we have you believe ;)
571
 *
572
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
573
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
574
 */
575
function ModifyWarningSettings($return_config = false)
576
{
577
	global $txt, $scripturl, $context, $modSettings, $sourcedir;
578
579
	// You need to be an admin to edit settings!
580
	isAllowedTo('admin_forum');
581
582
	loadLanguage('Help');
583
	loadLanguage('ManageSettings');
584
585
	// We need the existing ones for this
586
	list ($currently_enabled, $modSettings['user_limit'], $modSettings['warning_decrement']) = explode(',', $modSettings['warning_settings']);
587
588
	$config_vars = array(
589
		// Warning system?
590
		'enable' => array('check', 'warning_enable'),
591
	);
592
593
	if (!empty($modSettings['warning_settings']) && $currently_enabled)
594
		$config_vars += array(
595
			'',
596
597
			array(
598
				'int',
599
				'warning_watch',
600
				'subtext' => $txt['setting_warning_watch_note'] . ' ' . $txt['zero_to_disable']
601
			),
602
			'moderate' => array(
603
				'int',
604
				'warning_moderate',
605
				'subtext' => $txt['setting_warning_moderate_note'] . ' ' . $txt['zero_to_disable']
606
			),
607
			array(
608
				'int',
609
				'warning_mute',
610
				'subtext' => $txt['setting_warning_mute_note'] . ' ' . $txt['zero_to_disable']
611
			),
612
			'rem1' => array(
613
				'int',
614
				'user_limit',
615
				'subtext' => $txt['setting_user_limit_note']
616
			),
617
			'rem2' => array(
618
				'int',
619
				'warning_decrement',
620
				'subtext' => $txt['setting_warning_decrement_note'] . ' ' . $txt['zero_to_disable']
621
			),
622
			array('permissions', 'view_warning_any'),
623
			array('permissions', 'view_warning_own'),
624
		);
625
626
	call_integration_hook('integrate_warning_settings', array(&$config_vars));
627
628
	if ($return_config)
629
		return $config_vars;
630
631
	// Cannot use moderation if post moderation is not enabled.
632
	if (!$modSettings['postmod_active'])
633
		unset($config_vars['moderate']);
634
635
	// Will need the utility functions from here.
636
	require_once($sourcedir . '/ManageServer.php');
637
638
	// Saving?
639
	if (isset($_GET['save']))
640
	{
641
		checkSession();
642
643
		// Make sure these don't have an effect.
644
		if (!$currently_enabled && empty($_POST['warning_enable']))
645
		{
646
			$_POST['warning_watch'] = 0;
647
			$_POST['warning_moderate'] = 0;
648
			$_POST['warning_mute'] = 0;
649
		}
650
		// If it was disabled and we're enabling it now, set some sane defaults.
651
		elseif (!$currently_enabled && !empty($_POST['warning_enable']))
652
		{
653
			// Need to add these, these weren't there before...
654
			$vars = array(
655
				'warning_watch' => 10,
656
				'warning_mute' => 60,
657
			);
658
			if ($modSettings['postmod_active'])
659
				$vars['warning_moderate'] = 35;
660
661
			foreach ($vars as $var => $value)
662
			{
663
				$config_vars[] = array('int', $var);
664
				$_POST[$var] = $value;
665
			}
666
		}
667
		else
668
		{
669
			$_POST['warning_watch'] = min($_POST['warning_watch'], 100);
670
			$_POST['warning_moderate'] = $modSettings['postmod_active'] ? min($_POST['warning_moderate'], 100) : 0;
671
			$_POST['warning_mute'] = min($_POST['warning_mute'], 100);
672
		}
673
674
		// We might not have these already depending on how we got here.
675
		$_POST['user_limit'] = isset($_POST['user_limit']) ? (int) $_POST['user_limit'] : $modSettings['user_limit'];
676
		$_POST['warning_decrement'] = isset($_POST['warning_decrement']) ? (int) $_POST['warning_decrement'] : $modSettings['warning_decrement'];
677
678
		// Fix the warning setting array!
679
		$_POST['warning_settings'] = (!empty($_POST['warning_enable']) ? 1 : 0) . ',' . min(100, $_POST['user_limit']) . ',' . min(100, $_POST['warning_decrement']);
680
		$save_vars = $config_vars;
681
		$save_vars[] = array('text', 'warning_settings');
682
		unset($save_vars['enable'], $save_vars['rem1'], $save_vars['rem2']);
683
684
		call_integration_hook('integrate_save_warning_settings', array(&$save_vars));
685
686
		saveDBSettings($save_vars);
687
		$_SESSION['adm-save'] = true;
688
		redirectexit('action=admin;area=warnings');
689
	}
690
691
	// We actually store lots of these together - for efficiency.
692
	list ($modSettings['warning_enable'], $modSettings['user_limit'], $modSettings['warning_decrement']) = explode(',', $modSettings['warning_settings']);
693
694
	$context['sub_template'] = 'show_settings';
695
	$context['post_url'] = $scripturl . '?action=admin;area=warnings;save';
696
	$context['settings_title'] = $txt['warnings'];
697
	$context['page_title'] = $txt['warnings'];
698
699
	$context[$context['admin_menu_name']]['tab_data'] = array(
700
		'title' => $txt['warnings'],
701
		'help' => '',
702
		'description' => $txt['warnings_desc'],
703
	);
704
705
	prepareDBSettingContext($config_vars);
706
}
707
708
/**
709
 * Let's try keep the spam to a minimum ah Thantos?
710
 *
711
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
712
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
713
 */
714
function ModifyAntispamSettings($return_config = false)
715
{
716
	global $txt, $scripturl, $context, $modSettings, $smcFunc, $language, $sourcedir;
717
718
	loadLanguage('Help');
719
	loadLanguage('ManageSettings');
720
721
	// Generate a sample registration image.
722
	$context['use_graphic_library'] = in_array('gd', get_loaded_extensions());
723
	$context['verification_image_href'] = $scripturl . '?action=verificationcode;rand=' . md5(mt_rand());
724
725
	$config_vars = array(
726
		array('check', 'reg_verification'),
727
		array('check', 'search_enable_captcha'),
728
		// This, my friend, is a cheat :p
729
		'guest_verify' => array(
730
			'check',
731
			'guests_require_captcha',
732
			'subtext' => $txt['setting_guests_require_captcha_desc']
733
		),
734
		array(
735
			'int',
736
			'posts_require_captcha',
737
			'subtext' => $txt['posts_require_captcha_desc'],
738
			'min' => -1,
739
			'onchange' => 'if (this.value > 0){ document.getElementById(\'guests_require_captcha\').checked = true; document.getElementById(\'guests_require_captcha\').disabled = true;} else {document.getElementById(\'guests_require_captcha\').disabled = false;}'
740
		),
741
		'',
742
743
		// PM Settings
744
		'pm1' => array('int', 'max_pm_recipients', 'subtext' => $txt['max_pm_recipients_note']),
745
		'pm2' => array('int', 'pm_posts_verification', 'subtext' => $txt['pm_posts_verification_note']),
746
		'pm3' => array('int', 'pm_posts_per_hour', 'subtext' => $txt['pm_posts_per_hour_note']),
747
		// Visual verification.
748
		array('title', 'configure_verification_means'),
749
		array('desc', 'configure_verification_means_desc'),
750
		'vv' => array(
751
			'select',
752
			'visual_verification_type',
753
			array(
754
				$txt['setting_image_verification_off'],
755
				$txt['setting_image_verification_vsimple'],
756
				$txt['setting_image_verification_simple'],
757
				$txt['setting_image_verification_medium'],
758
				$txt['setting_image_verification_high'],
759
				$txt['setting_image_verification_extreme']
760
			),
761
			'subtext' => $txt['setting_visual_verification_type_desc'],
762
			'onchange' => $context['use_graphic_library'] ? 'refreshImages();' : ''
763
		),
764
		// reCAPTCHA
765
		array('title', 'recaptcha_configure'),
766
		array('desc', 'recaptcha_configure_desc', 'class' => 'windowbg'),
767
		array('check', 'recaptcha_enabled', 'subtext' => $txt['recaptcha_enable_desc']),
768
		array('text', 'recaptcha_site_key', 'subtext' => $txt['recaptcha_site_key_desc']),
769
		array('text', 'recaptcha_secret_key', 'subtext' => $txt['recaptcha_secret_key_desc']),
770
		array('select', 'recaptcha_theme', array('light' => $txt['recaptcha_theme_light'], 'dark' => $txt['recaptcha_theme_dark'])),
771
		// Clever Thomas, who is looking sheepy now? Not I, the mighty sword swinger did say.
772
		array('title', 'setup_verification_questions'),
773
		array('desc', 'setup_verification_questions_desc'),
774
		array('int', 'qa_verification_number', 'subtext' => $txt['setting_qa_verification_number_desc']),
775
		array('callback', 'question_answer_list'),
776
	);
777
778
	call_integration_hook('integrate_spam_settings', array(&$config_vars));
779
780
	if ($return_config)
781
		return $config_vars;
782
783
	// You need to be an admin to edit settings!
784
	isAllowedTo('admin_forum');
785
786
	// Firstly, figure out what languages we're dealing with, and do a little processing for the form's benefit.
787
	getLanguages();
788
	$context['qa_languages'] = array();
789
	foreach ($context['languages'] as $lang_id => $lang)
790
	{
791
		$lang_id = strtr($lang_id, array('-utf8' => ''));
792
		$lang['name'] = strtr($lang['name'], array('-utf8' => ''));
793
		$context['qa_languages'][$lang_id] = $lang;
794
	}
795
796
	// Secondly, load any questions we currently have.
797
	$context['question_answers'] = array();
798
	$request = $smcFunc['db_query']('', '
799
		SELECT id_question, lngfile, question, answers
800
		FROM {db_prefix}qanda'
801
	);
802
	while ($row = $smcFunc['db_fetch_assoc']($request))
803
	{
804
		$lang = strtr($row['lngfile'], array('-utf8' => ''));
805
		$context['question_answers'][$row['id_question']] = array(
806
			'lngfile' => $lang,
807
			'question' => $row['question'],
808
			'answers' => $smcFunc['json_decode']($row['answers'], true),
809
		);
810
		$context['qa_by_lang'][$lang][] = $row['id_question'];
811
	}
812
813
	if (empty($context['qa_by_lang'][strtr($language, array('-utf8' => ''))]) && !empty($context['question_answers']))
814
	{
815
		if (empty($context['settings_insert_above']))
816
			$context['settings_insert_above'] = '';
817
818
		$context['settings_insert_above'] .= '<div class="noticebox">' . sprintf($txt['question_not_defined'], $context['languages'][$language]['name']) . '</div>';
819
	}
820
821
	// Thirdly, push some JavaScript for the form to make it work.
822
	addInlineJavaScript('
823
	var nextrow = ' . (!empty($context['question_answers']) ? max(array_keys($context['question_answers'])) + 1 : 1) . ';
824
	$(".qa_link a").click(function() {
825
		var id = $(this).parent().attr("id").substring(6);
826
		$("#qa_fs_" + id).show();
827
		$(this).parent().hide();
828
	});
829
	$(".qa_fieldset legend a").click(function() {
830
		var id = $(this).closest("fieldset").attr("id").substring(6);
831
		$("#qa_dt_" + id).show();
832
		$(this).closest("fieldset").hide();
833
	});
834
	$(".qa_add_question a").click(function() {
835
		var id = $(this).closest("fieldset").attr("id").substring(6);
836
		$(\'<dt><input type="text" name="question[\' + id + \'][\' + nextrow + \']" value="" size="50" class="verification_question"></dt><dd><input type="text" name="answer[\' + id + \'][\' + nextrow + \'][]" value="" size="50" class="verification_answer" / ><div class="qa_add_answer"><a href="javascript:void(0);">[ \' + ' . JavaScriptEscape($txt['setup_verification_add_answer']) . ' + \' ]</a></div></dd>\').insertBefore($(this).parent());
837
		nextrow++;
838
	});
839
	$(".qa_fieldset ").on("click", ".qa_add_answer a", function() {
840
		var attr = $(this).closest("dd").find(".verification_answer:last").attr("name");
841
		$(\'<input type="text" name="\' + attr + \'" value="" size="50" class="verification_answer">\').insertBefore($(this).closest("div"));
842
		return false;
843
	});
844
	$("#qa_dt_' . strtr($language, array('-utf8' => '')) . ' a").click();', true);
845
846
	// Will need the utility functions from here.
847
	require_once($sourcedir . '/ManageServer.php');
848
849
	// Saving?
850
	if (isset($_GET['save']))
851
	{
852
		checkSession();
853
854
		// Fix PM settings.
855
		$_POST['pm_spam_settings'] = (int) $_POST['max_pm_recipients'] . ',' . (int) $_POST['pm_posts_verification'] . ',' . (int) $_POST['pm_posts_per_hour'];
856
857
		// Hack in guest requiring verification!
858
		if (empty($_POST['posts_require_captcha']) && !empty($_POST['guests_require_captcha']))
859
			$_POST['posts_require_captcha'] = -1;
860
861
		$save_vars = $config_vars;
862
		unset($save_vars['pm1'], $save_vars['pm2'], $save_vars['pm3'], $save_vars['guest_verify']);
863
864
		$save_vars[] = array('text', 'pm_spam_settings');
865
866
		// Handle verification questions.
867
		$changes = array(
868
			'insert' => array(),
869
			'replace' => array(),
870
			'delete' => array(),
871
		);
872
		$qs_per_lang = array();
873
		foreach ($context['qa_languages'] as $lang_id => $dummy)
874
		{
875
			// If we had some questions for this language before, but don't now, delete everything from that language.
876
			if ((!isset($_POST['question'][$lang_id]) || !is_array($_POST['question'][$lang_id])) && !empty($context['qa_by_lang'][$lang_id]))
877
				$changes['delete'] = array_merge($changes['delete'], $context['qa_by_lang'][$lang_id]);
878
879
			// Now step through and see if any existing questions no longer exist.
880
			if (!empty($context['qa_by_lang'][$lang_id]))
881
				foreach ($context['qa_by_lang'][$lang_id] as $q_id)
882
					if (empty($_POST['question'][$lang_id][$q_id]))
883
						$changes['delete'][] = $q_id;
884
885
			// Now let's see if there are new questions or ones that need updating.
886
			if (isset($_POST['question'][$lang_id]))
887
			{
888
				foreach ($_POST['question'][$lang_id] as $q_id => $question)
889
				{
890
					// Ignore junky ids.
891
					$q_id = (int) $q_id;
892
					if ($q_id <= 0)
893
						continue;
894
895
					// Check the question isn't empty (because they want to delete it?)
896
					if (empty($question) || trim($question) == '')
897
					{
898
						if (isset($context['question_answers'][$q_id]))
899
							$changes['delete'][] = $q_id;
900
						continue;
901
					}
902
					$question = $smcFunc['htmlspecialchars'](trim($question));
903
904
					// Get the answers. Firstly check there actually might be some.
905
					if (!isset($_POST['answer'][$lang_id][$q_id]) || !is_array($_POST['answer'][$lang_id][$q_id]))
906
					{
907
						if (isset($context['question_answers'][$q_id]))
908
							$changes['delete'][] = $q_id;
909
						continue;
910
					}
911
					// Now get them and check that they might be viable.
912
					$answers = array();
913
					foreach ($_POST['answer'][$lang_id][$q_id] as $answer)
914
						if (!empty($answer) && trim($answer) !== '')
915
							$answers[] = $smcFunc['htmlspecialchars'](trim($answer));
916
					if (empty($answers))
917
					{
918
						if (isset($context['question_answers'][$q_id]))
919
							$changes['delete'][] = $q_id;
920
						continue;
921
					}
922
					$answers = $smcFunc['json_encode']($answers);
923
924
					// At this point we know we have a question and some answers. What are we doing with it?
925
					if (!isset($context['question_answers'][$q_id]))
926
					{
927
						// New question. Now, we don't want to randomly consume ids, so we'll set those, rather than trusting the browser's supplied ids.
928
						$changes['insert'][] = array($lang_id, $question, $answers);
929
					}
930
					else
931
					{
932
						// It's an existing question. Let's see what's changed, if anything.
933
						if ($lang_id != $context['question_answers'][$q_id]['lngfile'] || $question != $context['question_answers'][$q_id]['question'] || $answers != $context['question_answers'][$q_id]['answers'])
934
							$changes['replace'][$q_id] = array('lngfile' => $lang_id, 'question' => $question, 'answers' => $answers);
935
					}
936
937
					if (!isset($qs_per_lang[$lang_id]))
938
						$qs_per_lang[$lang_id] = 0;
939
					$qs_per_lang[$lang_id]++;
940
				}
941
			}
942
		}
943
944
		// OK, so changes?
945
		if (!empty($changes['delete']))
946
		{
947
			$smcFunc['db_query']('', '
948
				DELETE FROM {db_prefix}qanda
949
				WHERE id_question IN ({array_int:questions})',
950
				array(
951
					'questions' => $changes['delete'],
952
				)
953
			);
954
		}
955
956
		if (!empty($changes['replace']))
957
		{
958
			foreach ($changes['replace'] as $q_id => $question)
959
			{
960
				$smcFunc['db_query']('', '
961
					UPDATE {db_prefix}qanda
962
					SET lngfile = {string:lngfile},
963
						question = {string:question},
964
						answers = {string:answers}
965
					WHERE id_question = {int:id_question}',
966
					array(
967
						'id_question' => $q_id,
968
						'lngfile' => $question['lngfile'],
969
						'question' => $question['question'],
970
						'answers' => $question['answers'],
971
					)
972
				);
973
			}
974
		}
975
976
		if (!empty($changes['insert']))
977
		{
978
			$smcFunc['db_insert']('insert',
979
				'{db_prefix}qanda',
980
				array('lngfile' => 'string-50', 'question' => 'string-255', 'answers' => 'string-65534'),
981
				$changes['insert'],
982
				array('id_question')
983
			);
984
		}
985
986
		// Lastly, the count of messages needs to be no more than the lowest number of questions for any one language.
987
		$count_questions = empty($qs_per_lang) ? 0 : min($qs_per_lang);
988
		if (empty($count_questions) || $_POST['qa_verification_number'] > $count_questions)
989
			$_POST['qa_verification_number'] = $count_questions;
990
991
		call_integration_hook('integrate_save_spam_settings', array(&$save_vars));
992
993
		// Now save.
994
		saveDBSettings($save_vars);
995
		$_SESSION['adm-save'] = true;
996
997
		cache_put_data('verificationQuestions', null, 300);
998
999
		redirectexit('action=admin;area=antispam');
1000
	}
1001
1002
	$character_range = array_merge(range('A', 'H'), array('K', 'M', 'N', 'P', 'R'), range('T', 'Y'));
1003
	$_SESSION['visual_verification_code'] = '';
1004
	for ($i = 0; $i < 6; $i++)
1005
		$_SESSION['visual_verification_code'] .= $character_range[array_rand($character_range)];
1006
1007
	// Some javascript for CAPTCHA.
1008
	$context['settings_post_javascript'] = '';
1009
	if ($context['use_graphic_library'])
1010
		$context['settings_post_javascript'] .= '
1011
		function refreshImages()
1012
		{
1013
			var imageType = document.getElementById(\'visual_verification_type\').value;
1014
			document.getElementById(\'verification_image\').src = \'' . $context['verification_image_href'] . ';type=\' + imageType;
1015
		}';
1016
1017
	// Show the image itself, or text saying we can't.
1018
	if ($context['use_graphic_library'])
1019
		$config_vars['vv']['postinput'] = '<br><img src="' . $context['verification_image_href'] . ';type=' . (empty($modSettings['visual_verification_type']) ? 0 : $modSettings['visual_verification_type']) . '" alt="' . $txt['setting_image_verification_sample'] . '" id="verification_image"><br>';
1020
	else
1021
		$config_vars['vv']['postinput'] = '<br><span class="smalltext">' . $txt['setting_image_verification_nogd'] . '</span>';
1022
1023
	// Hack for PM spam settings.
1024
	list ($modSettings['max_pm_recipients'], $modSettings['pm_posts_verification'], $modSettings['pm_posts_per_hour']) = explode(',', $modSettings['pm_spam_settings']);
1025
1026
	// Hack for guests requiring verification.
1027
	$modSettings['guests_require_captcha'] = !empty($modSettings['posts_require_captcha']);
1028
	$modSettings['posts_require_captcha'] = !isset($modSettings['posts_require_captcha']) || $modSettings['posts_require_captcha'] == -1 ? 0 : $modSettings['posts_require_captcha'];
1029
1030
	// Some minor javascript for the guest post setting.
1031
	if ($modSettings['posts_require_captcha'])
1032
		$context['settings_post_javascript'] .= '
1033
		document.getElementById(\'guests_require_captcha\').disabled = true;';
1034
1035
	// And everything else.
1036
	$context['post_url'] = $scripturl . '?action=admin;area=antispam;save';
1037
	$context['settings_title'] = $txt['antispam_Settings'];
1038
	$context['page_title'] = $txt['antispam_title'];
1039
	$context['sub_template'] = 'show_settings';
1040
1041
	$context[$context['admin_menu_name']]['tab_data'] = array(
1042
		'title' => $txt['antispam_title'],
1043
		'description' => $txt['antispam_Settings_desc'],
1044
	);
1045
1046
	prepareDBSettingContext($config_vars);
1047
}
1048
1049
/**
1050
 * You'll never guess what this function does...
1051
 *
1052
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
1053
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
1054
 */
1055
function ModifySignatureSettings($return_config = false)
1056
{
1057
	global $context, $txt, $modSettings, $sig_start, $smcFunc, $scripturl;
1058
1059
	$config_vars = array(
1060
		// Are signatures even enabled?
1061
		array('check', 'signature_enable'),
1062
		'',
1063
1064
		// Tweaking settings!
1065
		array('int', 'signature_max_length', 'subtext' => $txt['zero_for_no_limit']),
1066
		array('int', 'signature_max_lines', 'subtext' => $txt['zero_for_no_limit']),
1067
		array('int', 'signature_max_font_size', 'subtext' => $txt['zero_for_no_limit']),
1068
		array('check', 'signature_allow_smileys', 'onclick' => 'document.getElementById(\'signature_max_smileys\').disabled = !this.checked;'),
1069
		array('int', 'signature_max_smileys', 'subtext' => $txt['zero_for_no_limit']),
1070
		'',
1071
1072
		// Image settings.
1073
		array('int', 'signature_max_images', 'subtext' => $txt['signature_max_images_note']),
1074
		array('int', 'signature_max_image_width', 'subtext' => $txt['zero_for_no_limit']),
1075
		array('int', 'signature_max_image_height', 'subtext' => $txt['zero_for_no_limit']),
1076
		'',
1077
1078
		array('bbc', 'signature_bbc'),
1079
	);
1080
1081
	call_integration_hook('integrate_signature_settings', array(&$config_vars));
1082
1083
	if ($return_config)
1084
		return $config_vars;
1085
1086
	// Setup the template.
1087
	$context['page_title'] = $txt['signature_settings'];
1088
	$context['sub_template'] = 'show_settings';
1089
1090
	// Disable the max smileys option if we don't allow smileys at all!
1091
	$context['settings_post_javascript'] = 'document.getElementById(\'signature_max_smileys\').disabled = !document.getElementById(\'signature_allow_smileys\').checked;';
1092
1093
	// Load all the signature settings.
1094
	list ($sig_limits, $sig_bbc) = explode(':', $modSettings['signature_settings']);
1095
	$sig_limits = explode(',', $sig_limits);
1096
	$disabledTags = !empty($sig_bbc) ? explode(',', $sig_bbc) : array();
1097
1098
	// Applying to ALL signatures?!!
1099
	if (isset($_GET['apply']))
1100
	{
1101
		// Security!
1102
		checkSession('get');
1103
1104
		$sig_start = time();
1105
		// This is horrid - but I suppose some people will want the option to do it.
1106
		$_GET['step'] = isset($_GET['step']) ? (int) $_GET['step'] : 0;
1107
		$done = false;
1108
1109
		$request = $smcFunc['db_query']('', '
1110
			SELECT MAX(id_member)
1111
			FROM {db_prefix}members',
1112
			array(
1113
			)
1114
		);
1115
		list ($context['max_member']) = $smcFunc['db_fetch_row']($request);
1116
		$smcFunc['db_free_result']($request);
1117
1118
		while (!$done)
1119
		{
1120
			$changes = array();
1121
1122
			$request = $smcFunc['db_query']('', '
1123
				SELECT id_member, signature
1124
				FROM {db_prefix}members
1125
				WHERE id_member BETWEEN {int:step} AND {int:step} + 49
1126
					AND id_group != {int:admin_group}
1127
					AND FIND_IN_SET({int:admin_group}, additional_groups) = 0',
1128
				array(
1129
					'admin_group' => 1,
1130
					'step' => $_GET['step'],
1131
				)
1132
			);
1133
			while ($row = $smcFunc['db_fetch_assoc']($request))
1134
			{
1135
				// Apply all the rules we can realistically do.
1136
				$sig = strtr($row['signature'], array('<br>' => "\n"));
1137
1138
				// Max characters...
1139
				if (!empty($sig_limits[1]))
1140
					$sig = $smcFunc['substr']($sig, 0, $sig_limits[1]);
1141
				// Max lines...
1142
				if (!empty($sig_limits[2]))
1143
				{
1144
					$count = 0;
1145
					for ($i = 0; $i < strlen($sig); $i++)
1146
					{
1147
						if ($sig[$i] == "\n")
1148
						{
1149
							$count++;
1150
							if ($count >= $sig_limits[2])
1151
								$sig = substr($sig, 0, $i) . strtr(substr($sig, $i), array("\n" => ' '));
1152
						}
1153
					}
1154
				}
1155
1156
				if (!empty($sig_limits[7]) && preg_match_all('~\[size=([\d\.]+)?(px|pt|em|x-large|larger)~i', $sig, $matches) !== false && isset($matches[2]))
1157
				{
1158
					foreach ($matches[1] as $ind => $size)
1159
					{
1160
						$limit_broke = 0;
1161
						// Attempt to allow all sizes of abuse, so to speak.
1162
						if ($matches[2][$ind] == 'px' && $size > $sig_limits[7])
1163
							$limit_broke = $sig_limits[7] . 'px';
1164
						elseif ($matches[2][$ind] == 'pt' && $size > ($sig_limits[7] * 0.75))
1165
							$limit_broke = ((int) $sig_limits[7] * 0.75) . 'pt';
1166
						elseif ($matches[2][$ind] == 'em' && $size > ((float) $sig_limits[7] / 16))
1167
							$limit_broke = ((float) $sig_limits[7] / 16) . 'em';
1168
						elseif ($matches[2][$ind] != 'px' && $matches[2][$ind] != 'pt' && $matches[2][$ind] != 'em' && $sig_limits[7] < 18)
1169
							$limit_broke = 'large';
1170
1171
						if ($limit_broke)
1172
							$sig = str_replace($matches[0][$ind], '[size=' . $sig_limits[7] . 'px', $sig);
1173
					}
1174
				}
1175
1176
				// Stupid images - this is stupidly, stupidly challenging.
1177
				if ((!empty($sig_limits[3]) || !empty($sig_limits[5]) || !empty($sig_limits[6])))
1178
				{
1179
					$replaces = array();
1180
					$img_count = 0;
1181
					// Get all BBC tags...
1182
					preg_match_all('~\[img(\s+width=([\d]+))?(\s+height=([\d]+))?(\s+width=([\d]+))?\s*\](?:<br>)*([^<">]+?)(?:<br>)*\[/img\]~i', $sig, $matches);
1183
					// ... and all HTML ones.
1184
					preg_match_all('~&lt;img\s+src=(?:&quot;)?((?:http://|ftp://|https://|ftps://).+?)(?:&quot;)?(?:\s+alt=(?:&quot;)?(.*?)(?:&quot;)?)?(?:\s?/)?&gt;~i', $sig, $matches2, PREG_PATTERN_ORDER);
1185
					// And stick the HTML in the BBC.
1186
					if (!empty($matches2))
1187
					{
1188
						foreach ($matches2[0] as $ind => $dummy)
1189
						{
1190
							$matches[0][] = $matches2[0][$ind];
1191
							$matches[1][] = '';
1192
							$matches[2][] = '';
1193
							$matches[3][] = '';
1194
							$matches[4][] = '';
1195
							$matches[5][] = '';
1196
							$matches[6][] = '';
1197
							$matches[7][] = $matches2[1][$ind];
1198
						}
1199
					}
1200
					// Try to find all the images!
1201
					if (!empty($matches))
1202
					{
1203
						$image_count_holder = array();
1204
						foreach ($matches[0] as $key => $image)
1205
						{
1206
							$width = -1;
1207
							$height = -1;
1208
							$img_count++;
1209
							// Too many images?
1210
							if (!empty($sig_limits[3]) && $img_count > $sig_limits[3])
1211
							{
1212
								// If we've already had this before we only want to remove the excess.
1213
								if (isset($image_count_holder[$image]))
1214
								{
1215
									$img_offset = -1;
1216
									$rep_img_count = 0;
1217
									while ($img_offset !== false)
1218
									{
1219
										$img_offset = strpos($sig, $image, $img_offset + 1);
1220
										$rep_img_count++;
1221
										if ($rep_img_count > $image_count_holder[$image])
1222
										{
1223
											// Only replace the excess.
1224
											$sig = substr($sig, 0, $img_offset) . str_replace($image, '', substr($sig, $img_offset));
1225
											// Stop looping.
1226
											$img_offset = false;
1227
										}
1228
									}
1229
								}
1230
								else
1231
									$replaces[$image] = '';
1232
1233
								continue;
1234
							}
1235
1236
							// Does it have predefined restraints? Width first.
1237
							if ($matches[6][$key])
1238
								$matches[2][$key] = $matches[6][$key];
1239
							if ($matches[2][$key] && $sig_limits[5] && $matches[2][$key] > $sig_limits[5])
1240
							{
1241
								$width = $sig_limits[5];
1242
								$matches[4][$key] = $matches[4][$key] * ($width / $matches[2][$key]);
1243
							}
1244
							elseif ($matches[2][$key])
1245
								$width = $matches[2][$key];
1246
							// ... and height.
1247
							if ($matches[4][$key] && $sig_limits[6] && $matches[4][$key] > $sig_limits[6])
1248
							{
1249
								$height = $sig_limits[6];
1250
								if ($width != -1)
1251
									$width = $width * ($height / $matches[4][$key]);
1252
							}
1253
							elseif ($matches[4][$key])
1254
								$height = $matches[4][$key];
1255
1256
							// If the dimensions are still not fixed - we need to check the actual image.
1257
							if (($width == -1 && $sig_limits[5]) || ($height == -1 && $sig_limits[6]))
1258
							{
1259
								$sizes = url_image_size($matches[7][$key]);
1260
								if (is_array($sizes))
1261
								{
1262
									// Too wide?
1263
									if ($sizes[0] > $sig_limits[5] && $sig_limits[5])
1264
									{
1265
										$width = $sig_limits[5];
1266
										$sizes[1] = $sizes[1] * ($width / $sizes[0]);
1267
									}
1268
									// Too high?
1269
									if ($sizes[1] > $sig_limits[6] && $sig_limits[6])
1270
									{
1271
										$height = $sig_limits[6];
1272
										if ($width == -1)
1273
											$width = $sizes[0];
1274
										$width = $width * ($height / $sizes[1]);
1275
									}
1276
									elseif ($width != -1)
1277
										$height = $sizes[1];
1278
								}
1279
							}
1280
1281
							// Did we come up with some changes? If so remake the string.
1282
							if ($width != -1 || $height != -1)
1283
							{
1284
								$replaces[$image] = '[img' . ($width != -1 ? ' width=' . round($width) : '') . ($height != -1 ? ' height=' . round($height) : '') . ']' . $matches[7][$key] . '[/img]';
1285
							}
1286
1287
							// Record that we got one.
1288
							$image_count_holder[$image] = isset($image_count_holder[$image]) ? $image_count_holder[$image] + 1 : 1;
1289
						}
1290
						if (!empty($replaces))
1291
							$sig = str_replace(array_keys($replaces), array_values($replaces), $sig);
1292
					}
1293
				}
1294
				// Try to fix disabled tags.
1295
				if (!empty($disabledTags))
1296
				{
1297
					$sig = preg_replace('~\[(?:' . implode('|', $disabledTags) . ').+?\]~i', '', $sig);
1298
					$sig = preg_replace('~\[/(?:' . implode('|', $disabledTags) . ')\]~i', '', $sig);
1299
				}
1300
1301
				$sig = strtr($sig, array("\n" => '<br>'));
1302
				call_integration_hook('integrate_apply_signature_settings', array(&$sig, $sig_limits, $disabledTags));
1303
				if ($sig != $row['signature'])
1304
					$changes[$row['id_member']] = $sig;
1305
			}
1306
			if ($smcFunc['db_num_rows']($request) == 0)
1307
				$done = true;
1308
			$smcFunc['db_free_result']($request);
1309
1310
			// Do we need to delete what we have?
1311
			if (!empty($changes))
1312
			{
1313
				foreach ($changes as $id => $sig)
1314
					$smcFunc['db_query']('', '
1315
						UPDATE {db_prefix}members
1316
						SET signature = {string:signature}
1317
						WHERE id_member = {int:id_member}',
1318
						array(
1319
							'id_member' => $id,
1320
							'signature' => $sig,
1321
						)
1322
					);
1323
			}
1324
1325
			$_GET['step'] += 50;
1326
			if (!$done)
1327
				pauseSignatureApplySettings();
1328
		}
1329
		$settings_applied = true;
1330
	}
1331
1332
	$context['signature_settings'] = array(
1333
		'enable' => isset($sig_limits[0]) ? $sig_limits[0] : 0,
1334
		'max_length' => isset($sig_limits[1]) ? $sig_limits[1] : 0,
1335
		'max_lines' => isset($sig_limits[2]) ? $sig_limits[2] : 0,
1336
		'max_images' => isset($sig_limits[3]) ? $sig_limits[3] : 0,
1337
		'allow_smileys' => isset($sig_limits[4]) && $sig_limits[4] == -1 ? 0 : 1,
1338
		'max_smileys' => isset($sig_limits[4]) && $sig_limits[4] != -1 ? $sig_limits[4] : 0,
1339
		'max_image_width' => isset($sig_limits[5]) ? $sig_limits[5] : 0,
1340
		'max_image_height' => isset($sig_limits[6]) ? $sig_limits[6] : 0,
1341
		'max_font_size' => isset($sig_limits[7]) ? $sig_limits[7] : 0,
1342
	);
1343
1344
	// Temporarily make each setting a modSetting!
1345
	foreach ($context['signature_settings'] as $key => $value)
1346
		$modSettings['signature_' . $key] = $value;
1347
1348
	// Make sure we check the right tags!
1349
	$modSettings['bbc_disabled_signature_bbc'] = $disabledTags;
1350
1351
	// Saving?
1352
	if (isset($_GET['save']))
1353
	{
1354
		checkSession();
1355
1356
		// Clean up the tag stuff!
1357
		$bbcTags = array();
1358
		foreach (parse_bbc(false) as $tag)
1359
			$bbcTags[] = $tag['tag'];
1360
1361
		if (!isset($_POST['signature_bbc_enabledTags']))
1362
			$_POST['signature_bbc_enabledTags'] = array();
1363
		elseif (!is_array($_POST['signature_bbc_enabledTags']))
1364
			$_POST['signature_bbc_enabledTags'] = array($_POST['signature_bbc_enabledTags']);
1365
1366
		$sig_limits = array();
1367
		foreach ($context['signature_settings'] as $key => $value)
1368
		{
1369
			if ($key == 'allow_smileys')
1370
				continue;
1371
			elseif ($key == 'max_smileys' && empty($_POST['signature_allow_smileys']))
1372
				$sig_limits[] = -1;
1373
			else
1374
				$sig_limits[] = !empty($_POST['signature_' . $key]) ? max(1, (int) $_POST['signature_' . $key]) : 0;
1375
		}
1376
1377
		call_integration_hook('integrate_save_signature_settings', array(&$sig_limits, &$bbcTags));
1378
1379
		$_POST['signature_settings'] = implode(',', $sig_limits) . ':' . implode(',', array_diff($bbcTags, $_POST['signature_bbc_enabledTags']));
1380
1381
		// Even though we have practically no settings let's keep the convention going!
1382
		$save_vars = array();
1383
		$save_vars[] = array('text', 'signature_settings');
1384
1385
		saveDBSettings($save_vars);
1386
		$_SESSION['adm-save'] = true;
1387
		redirectexit('action=admin;area=featuresettings;sa=sig');
1388
	}
1389
1390
	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=sig';
1391
	$context['settings_title'] = $txt['signature_settings'];
1392
1393
	if (!empty($settings_applied))
1394
		$context['settings_message'] = array(
1395
			'label' => $txt['signature_settings_applied'],
1396
			'tag' => 'div',
1397
			'class' => 'infobox'
1398
		);
1399
	else
1400
		$context['settings_message'] = array(
1401
			'label' => sprintf($txt['signature_settings_warning'], $context['session_id'], $context['session_var'], $scripturl),
1402
			'tag' => 'div',
1403
			'class' => 'centertext'
1404
		);
1405
1406
	prepareDBSettingContext($config_vars);
1407
}
1408
1409
/**
1410
 * Just pause the signature applying thing.
1411
 */
1412
function pauseSignatureApplySettings()
1413
{
1414
	global $context, $txt, $sig_start;
1415
1416
	// Try get more time...
1417
	@set_time_limit(600);
1418
	if (function_exists('apache_reset_timeout'))
1419
		@apache_reset_timeout();
1420
1421
	// Have we exhausted all the time we allowed?
1422
	if (time() - array_sum(explode(' ', $sig_start)) < 3)
1423
		return;
1424
1425
	$context['continue_get_data'] = '?action=admin;area=featuresettings;sa=sig;apply;step=' . $_GET['step'] . ';' . $context['session_var'] . '=' . $context['session_id'];
1426
	$context['page_title'] = $txt['not_done_title'];
1427
	$context['continue_post_data'] = '';
1428
	$context['continue_countdown'] = '2';
1429
	$context['sub_template'] = 'not_done';
1430
1431
	// Specific stuff to not break this template!
1432
	$context[$context['admin_menu_name']]['current_subsection'] = 'sig';
1433
1434
	// Get the right percent.
1435
	$context['continue_percent'] = round(($_GET['step'] / $context['max_member']) * 100);
1436
1437
	// Never more than 100%!
1438
	$context['continue_percent'] = min($context['continue_percent'], 100);
1439
1440
	obExit();
1441
}
1442
1443
/**
1444
 * Show all the custom profile fields available to the user.
1445
 */
1446
function ShowCustomProfiles()
1447
{
1448
	global $txt, $scripturl, $context;
1449
	global $sourcedir;
1450
1451
	$context['page_title'] = $txt['custom_profile_title'];
1452
	$context['sub_template'] = 'show_custom_profile';
1453
1454
	// What about standard fields they can tweak?
1455
	$standard_fields = array('website', 'personal_text', 'timezone', 'posts', 'warning_status');
1456
	// What fields can't you put on the registration page?
1457
	$context['fields_no_registration'] = array('posts', 'warning_status');
1458
1459
	// Are we saving any standard field changes?
1460
	if (isset($_POST['save']))
1461
	{
1462
		checkSession();
1463
		validateToken('admin-scp');
1464
1465
		// Do the active ones first.
1466
		$disable_fields = array_flip($standard_fields);
1467
		if (!empty($_POST['active']))
1468
		{
1469
			foreach ($_POST['active'] as $value)
1470
				if (isset($disable_fields[$value]))
1471
					unset($disable_fields[$value]);
1472
		}
1473
		// What we have left!
1474
		$changes['disabled_profile_fields'] = empty($disable_fields) ? '' : implode(',', array_keys($disable_fields));
0 ignored issues
show
Comprehensibility Best Practice introduced by
$changes was never initialized. Although not strictly required by PHP, it is generally a good practice to add $changes = array(); before regardless.
Loading history...
1475
1476
		// Things we want to show on registration?
1477
		$reg_fields = array();
1478
		if (!empty($_POST['reg']))
1479
		{
1480
			foreach ($_POST['reg'] as $value)
1481
				if (in_array($value, $standard_fields) && !isset($disable_fields[$value]))
1482
					$reg_fields[] = $value;
1483
		}
1484
		// What we have left!
1485
		$changes['registration_fields'] = empty($reg_fields) ? '' : implode(',', $reg_fields);
1486
1487
		$_SESSION['adm-save'] = true;
1488
		if (!empty($changes))
1489
			updateSettings($changes);
1490
	}
1491
1492
	createToken('admin-scp');
1493
1494
	// Need to know the max order for custom fields
1495
	$context['custFieldsMaxOrder'] = custFieldsMaxOrder();
1496
1497
	require_once($sourcedir . '/Subs-List.php');
1498
1499
	$listOptions = array(
1500
		'id' => 'standard_profile_fields',
1501
		'title' => $txt['standard_profile_title'],
1502
		'base_href' => $scripturl . '?action=admin;area=featuresettings;sa=profile',
1503
		'get_items' => array(
1504
			'function' => 'list_getProfileFields',
1505
			'params' => array(
1506
				true,
1507
			),
1508
		),
1509
		'columns' => array(
1510
			'field' => array(
1511
				'header' => array(
1512
					'value' => $txt['standard_profile_field'],
1513
				),
1514
				'data' => array(
1515
					'db' => 'label',
1516
					'style' => 'width: 60%;',
1517
				),
1518
			),
1519
			'active' => array(
1520
				'header' => array(
1521
					'value' => $txt['custom_edit_active'],
1522
					'class' => 'centercol',
1523
				),
1524
				'data' => array(
1525
					'function' => function($rowData)
1526
					{
1527
						$isChecked = $rowData['disabled'] ? '' : ' checked';
1528
						$onClickHandler = $rowData['can_show_register'] ? sprintf(' onclick="document.getElementById(\'reg_%1$s\').disabled = !this.checked;"', $rowData['id']) : '';
1529
						return sprintf('<input type="checkbox" name="active[]" id="active_%1$s" value="%1$s" %2$s%3$s>', $rowData['id'], $isChecked, $onClickHandler);
1530
					},
1531
					'style' => 'width: 20%;',
1532
					'class' => 'centercol',
1533
				),
1534
			),
1535
			'show_on_registration' => array(
1536
				'header' => array(
1537
					'value' => $txt['custom_edit_registration'],
1538
					'class' => 'centercol',
1539
				),
1540
				'data' => array(
1541
					'function' => function($rowData)
1542
					{
1543
						$isChecked = $rowData['on_register'] && !$rowData['disabled'] ? ' checked' : '';
1544
						$isDisabled = $rowData['can_show_register'] ? '' : ' disabled';
1545
						return sprintf('<input type="checkbox" name="reg[]" id="reg_%1$s" value="%1$s" %2$s%3$s>', $rowData['id'], $isChecked, $isDisabled);
1546
					},
1547
					'style' => 'width: 20%;',
1548
					'class' => 'centercol',
1549
				),
1550
			),
1551
		),
1552
		'form' => array(
1553
			'href' => $scripturl . '?action=admin;area=featuresettings;sa=profile',
1554
			'name' => 'standardProfileFields',
1555
			'token' => 'admin-scp',
1556
		),
1557
		'additional_rows' => array(
1558
			array(
1559
				'position' => 'below_table_data',
1560
				'value' => '<input type="submit" name="save" value="' . $txt['save'] . '" class="button">',
1561
			),
1562
		),
1563
	);
1564
	createList($listOptions);
1565
1566
	$listOptions = array(
1567
		'id' => 'custom_profile_fields',
1568
		'title' => $txt['custom_profile_title'],
1569
		'base_href' => $scripturl . '?action=admin;area=featuresettings;sa=profile',
1570
		'default_sort_col' => 'field_order',
1571
		'no_items_label' => $txt['custom_profile_none'],
1572
		'items_per_page' => 25,
1573
		'get_items' => array(
1574
			'function' => 'list_getProfileFields',
1575
			'params' => array(
1576
				false,
1577
			),
1578
		),
1579
		'get_count' => array(
1580
			'function' => 'list_getProfileFieldSize',
1581
		),
1582
		'columns' => array(
1583
			'field_order' => array(
1584
				'header' => array(
1585
					'value' => $txt['custom_profile_fieldorder'],
1586
				),
1587
				'data' => array(
1588
					'function' => function($rowData) use ($context, $txt, $scripturl)
1589
					{
1590
						$return = '<p class="centertext bold_text">';
1591
1592
						if ($rowData['field_order'] > 1)
1593
							$return .= '<a href="' . $scripturl . '?action=admin;area=featuresettings;sa=profileedit;fid=' . $rowData['id_field'] . ';move=up"><span class="toggle_up" title="' . $txt['custom_edit_order_move'] . ' ' . $txt['custom_edit_order_up'] . '"></span></a>';
1594
1595
						if ($rowData['field_order'] < $context['custFieldsMaxOrder'])
1596
							$return .= '<a href="' . $scripturl . '?action=admin;area=featuresettings;sa=profileedit;fid=' . $rowData['id_field'] . ';move=down"><span class="toggle_down" title="' . $txt['custom_edit_order_move'] . ' ' . $txt['custom_edit_order_down'] . '"></span></a>';
1597
1598
						$return .= '</p>';
1599
1600
						return $return;
1601
					},
1602
					'style' => 'width: 12%;',
1603
				),
1604
				'sort' => array(
1605
					'default' => 'field_order',
1606
					'reverse' => 'field_order DESC',
1607
				),
1608
			),
1609
			'field_name' => array(
1610
				'header' => array(
1611
					'value' => $txt['custom_profile_fieldname'],
1612
				),
1613
				'data' => array(
1614
					'function' => function($rowData) use ($scripturl)
1615
					{
1616
						return sprintf('<a href="%1$s?action=admin;area=featuresettings;sa=profileedit;fid=%2$d">%3$s</a><div class="smalltext">%4$s</div>', $scripturl, $rowData['id_field'], $rowData['field_name'], $rowData['field_desc']);
1617
					},
1618
					'style' => 'width: 62%;',
1619
				),
1620
				'sort' => array(
1621
					'default' => 'field_name',
1622
					'reverse' => 'field_name DESC',
1623
				),
1624
			),
1625
			'field_type' => array(
1626
				'header' => array(
1627
					'value' => $txt['custom_profile_fieldtype'],
1628
				),
1629
				'data' => array(
1630
					'function' => function($rowData) use ($txt)
1631
					{
1632
						$textKey = sprintf('custom_profile_type_%1$s', $rowData['field_type']);
1633
						return isset($txt[$textKey]) ? $txt[$textKey] : $textKey;
1634
					},
1635
					'style' => 'width: 15%;',
1636
				),
1637
				'sort' => array(
1638
					'default' => 'field_type',
1639
					'reverse' => 'field_type DESC',
1640
				),
1641
			),
1642
			'active' => array(
1643
				'header' => array(
1644
					'value' => $txt['custom_profile_active'],
1645
				),
1646
				'data' => array(
1647
					'function' => function($rowData) use ($txt)
1648
					{
1649
						return $rowData['active'] ? $txt['yes'] : $txt['no'];
1650
					},
1651
					'style' => 'width: 8%;',
1652
				),
1653
				'sort' => array(
1654
					'default' => 'active DESC',
1655
					'reverse' => 'active',
1656
				),
1657
			),
1658
			'placement' => array(
1659
				'header' => array(
1660
					'value' => $txt['custom_profile_placement'],
1661
				),
1662
				'data' => array(
1663
					'function' => function($rowData)
1664
					{
1665
						global $txt, $context;
1666
1667
						return $txt['custom_profile_placement_' . (empty($rowData['placement']) ? 'standard' : $context['cust_profile_fields_placement'][$rowData['placement']])];
1668
					},
1669
					'style' => 'width: 8%;',
1670
				),
1671
				'sort' => array(
1672
					'default' => 'placement DESC',
1673
					'reverse' => 'placement',
1674
				),
1675
			),
1676
			'show_on_registration' => array(
1677
				'data' => array(
1678
					'sprintf' => array(
1679
						'format' => '<a href="' . $scripturl . '?action=admin;area=featuresettings;sa=profileedit;fid=%1$s">' . $txt['modify'] . '</a>',
1680
						'params' => array(
1681
							'id_field' => false,
1682
						),
1683
					),
1684
					'style' => 'width: 15%;',
1685
				),
1686
			),
1687
		),
1688
		'form' => array(
1689
			'href' => $scripturl . '?action=admin;area=featuresettings;sa=profileedit',
1690
			'name' => 'customProfileFields',
1691
		),
1692
		'additional_rows' => array(
1693
			array(
1694
				'position' => 'below_table_data',
1695
				'value' => '<input type="submit" name="new" value="' . $txt['custom_profile_make_new'] . '" class="button">',
1696
			),
1697
		),
1698
	);
1699
	createList($listOptions);
1700
1701
	// There are two different ways we could get to this point. To keep it simple, they both do
1702
	// the same basic thing.
1703
	if (isset($_SESSION['adm-save']))
1704
	{
1705
		$context['saved_successful'] = true;
1706
		unset ($_SESSION['adm-save']);
1707
	}
1708
}
1709
1710
/**
1711
 * Callback for createList().
1712
 *
1713
 * @param int $start The item to start with (used for pagination purposes)
1714
 * @param int $items_per_page The number of items to display per page
1715
 * @param string $sort A string indicating how to sort the results
1716
 * @param bool $standardFields Whether or not to include standard fields as well
1717
 * @return array An array of info about the various profile fields
1718
 */
1719
function list_getProfileFields($start, $items_per_page, $sort, $standardFields)
1720
{
1721
	global $txt, $modSettings, $smcFunc;
1722
1723
	$list = array();
1724
1725
	if ($standardFields)
1726
	{
1727
		$standard_fields = array('website', 'personal_text', 'timezone', 'posts', 'warning_status');
1728
		$fields_no_registration = array('posts', 'warning_status');
1729
		$disabled_fields = isset($modSettings['disabled_profile_fields']) ? explode(',', $modSettings['disabled_profile_fields']) : array();
1730
		$registration_fields = isset($modSettings['registration_fields']) ? explode(',', $modSettings['registration_fields']) : array();
1731
1732
		foreach ($standard_fields as $field)
1733
			$list[] = array(
1734
				'id' => $field,
1735
				'label' => isset($txt['standard_profile_field_' . $field]) ? $txt['standard_profile_field_' . $field] : (isset($txt[$field]) ? $txt[$field] : $field),
1736
				'disabled' => in_array($field, $disabled_fields),
1737
				'on_register' => in_array($field, $registration_fields) && !in_array($field, $fields_no_registration),
1738
				'can_show_register' => !in_array($field, $fields_no_registration),
1739
			);
1740
	}
1741
	else
1742
	{
1743
		// Load all the fields.
1744
		$request = $smcFunc['db_query']('', '
1745
			SELECT id_field, col_name, field_name, field_desc, field_type, field_order, active, placement
1746
			FROM {db_prefix}custom_fields
1747
			ORDER BY {raw:sort}
1748
			LIMIT {int:start}, {int:items_per_page}',
1749
			array(
1750
				'sort' => $sort,
1751
				'start' => $start,
1752
				'items_per_page' => $items_per_page,
1753
			)
1754
		);
1755
		while ($row = $smcFunc['db_fetch_assoc']($request))
1756
			$list[] = $row;
1757
		$smcFunc['db_free_result']($request);
1758
	}
1759
1760
	return $list;
1761
}
1762
1763
/**
1764
 * Callback for createList().
1765
 *
1766
 * @return int The total number of custom profile fields
1767
 */
1768
function list_getProfileFieldSize()
1769
{
1770
	global $smcFunc;
1771
1772
	$request = $smcFunc['db_query']('', '
1773
		SELECT COUNT(*)
1774
		FROM {db_prefix}custom_fields',
1775
		array(
1776
		)
1777
	);
1778
1779
	list ($numProfileFields) = $smcFunc['db_fetch_row']($request);
1780
	$smcFunc['db_free_result']($request);
1781
1782
	return $numProfileFields;
1783
}
1784
1785
/**
1786
 * Edit some profile fields?
1787
 */
1788
function EditCustomProfiles()
1789
{
1790
	global $txt, $scripturl, $context, $smcFunc;
1791
1792
	// Sort out the context!
1793
	$context['fid'] = isset($_GET['fid']) ? (int) $_GET['fid'] : 0;
1794
	$context[$context['admin_menu_name']]['current_subsection'] = 'profile';
1795
	$context['page_title'] = $context['fid'] ? $txt['custom_edit_title'] : $txt['custom_add_title'];
1796
	$context['sub_template'] = 'edit_profile_field';
1797
1798
	// Load the profile language for section names.
1799
	loadLanguage('Profile');
1800
1801
	// There's really only a few places we can go...
1802
	$move_to = array('up', 'down');
1803
1804
	// We need this for both moving and saving so put it right here.
1805
	$order_count = custFieldsMaxOrder();
1806
1807
	if ($context['fid'] && !isset($_GET['move']))
1808
	{
1809
		$request = $smcFunc['db_query']('', '
1810
			SELECT
1811
				id_field, col_name, field_name, field_desc, field_type, field_order, field_length, field_options,
1812
				show_reg, show_display, show_mlist, show_profile, private, active, default_value, can_search,
1813
				bbc, mask, enclose, placement
1814
			FROM {db_prefix}custom_fields
1815
			WHERE id_field = {int:current_field}',
1816
			array(
1817
				'current_field' => $context['fid'],
1818
			)
1819
		);
1820
		$context['field'] = array();
1821
		while ($row = $smcFunc['db_fetch_assoc']($request))
1822
		{
1823
			if ($row['field_type'] == 'textarea')
1824
				@list ($rows, $cols) = @explode(',', $row['default_value']);
1825
			else
1826
			{
1827
				$rows = 3;
1828
				$cols = 30;
1829
			}
1830
1831
			$context['field'] = array(
1832
				'name' => $row['field_name'],
1833
				'desc' => $row['field_desc'],
1834
				'col_name' => $row['col_name'],
1835
				'profile_area' => $row['show_profile'],
1836
				'reg' => $row['show_reg'],
1837
				'display' => $row['show_display'],
1838
				'mlist' => $row['show_mlist'],
1839
				'type' => $row['field_type'],
1840
				'order' => $row['field_order'],
1841
				'max_length' => $row['field_length'],
1842
				'rows' => $rows,
1843
				'cols' => $cols,
1844
				'bbc' => $row['bbc'] ? true : false,
1845
				'default_check' => $row['field_type'] == 'check' && $row['default_value'] ? true : false,
1846
				'default_select' => $row['field_type'] == 'select' || $row['field_type'] == 'radio' ? $row['default_value'] : '',
1847
				'options' => strlen($row['field_options']) > 1 ? explode(',', $row['field_options']) : array('', '', ''),
1848
				'active' => $row['active'],
1849
				'private' => $row['private'],
1850
				'can_search' => $row['can_search'],
1851
				'mask' => $row['mask'],
1852
				'regex' => substr($row['mask'], 0, 5) == 'regex' ? substr($row['mask'], 5) : '',
1853
				'enclose' => $row['enclose'],
1854
				'placement' => $row['placement'],
1855
			);
1856
		}
1857
		$smcFunc['db_free_result']($request);
1858
	}
1859
1860
	// Setup the default values as needed.
1861
	if (empty($context['field']))
1862
		$context['field'] = array(
1863
			'name' => '',
1864
			'col_name' => '???',
1865
			'desc' => '',
1866
			'profile_area' => 'forumprofile',
1867
			'reg' => false,
1868
			'display' => false,
1869
			'mlist' => false,
1870
			'type' => 'text',
1871
			'order' => 0,
1872
			'max_length' => 255,
1873
			'rows' => 4,
1874
			'cols' => 30,
1875
			'bbc' => false,
1876
			'default_check' => false,
1877
			'default_select' => '',
1878
			'options' => array('', '', ''),
1879
			'active' => true,
1880
			'private' => false,
1881
			'can_search' => false,
1882
			'mask' => 'nohtml',
1883
			'regex' => '',
1884
			'enclose' => '',
1885
			'placement' => 0,
1886
		);
1887
1888
	// Are we moving it?
1889
	if ($context['fid'] && isset($_GET['move']) && in_array($smcFunc['htmlspecialchars']($_GET['move']), $move_to))
1890
	{
1891
		$request = $smcFunc['db_query']('', '
1892
			SELECT
1893
				id_field, field_order
1894
			FROM {db_prefix}custom_fields
1895
			ORDER BY field_order',
1896
				array()
1897
		);
1898
		$fields = array();
1899
		$new_sort = array();
1900
1901
		while($row = $smcFunc['db_fetch_assoc']($request))
1902
				$fields[] = $row['id_field'];
1903
		$smcFunc['db_free_result']($request);
1904
1905
		$idx = array_search($context['fid'], $fields);
1906
1907
		if ($_GET['move'] == 'down' && count($fields) - 1 > $idx )
1908
		{
1909
				$new_sort = array_slice($fields ,0 ,$idx ,true);
0 ignored issues
show
Bug introduced by
It seems like $idx can also be of type string; however, parameter $length of array_slice() does only seem to accept integer|null, maybe add an additional type check? ( Ignorable by Annotation )

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

1909
				$new_sort = array_slice($fields ,0 ,/** @scrutinizer ignore-type */ $idx ,true);
Loading history...
1910
				$new_sort[] = $fields[$idx + 1];
1911
				$new_sort[] = $fields[$idx];
1912
				$new_sort += array_slice($fields ,$idx + 2 ,count($fields) ,true);
1913
		}
1914
		elseif ($context['fid'] > 0 and $idx < count($fields))
1915
		{
1916
				$new_sort = array_slice($fields ,0 ,($idx - 1) ,true);
1917
				$new_sort[] = $fields[$idx];
1918
				$new_sort[] = $fields[$idx - 1];
1919
				$new_sort += array_slice($fields ,($idx + 1) ,count($fields) ,true);
1920
		}
1921
		else
1922
			redirectexit('action=admin;area=featuresettings;sa=profile'); // @todo implement an error handler
1923
1924
		$sql_update = 'CASE ';
1925
		foreach ($new_sort as $orderKey => $PKid)
1926
		{
1927
			$sql_update .= 'WHEN id_field = ' . $PKid . ' THEN ' . ($orderKey + 1) . ' ';
1928
		}
1929
		$sql_update .= 'END';
1930
1931
		$smcFunc['db_query']('', '
1932
			UPDATE {db_prefix}custom_fields
1933
			SET field_order = ' . $sql_update,
1934
				array()
1935
		);
1936
1937
		redirectexit('action=admin;area=featuresettings;sa=profile'); // @todo perhaps a nice confirmation message, dunno.
1938
	}
1939
1940
	// Are we saving?
1941
	if (isset($_POST['save']))
1942
	{
1943
		checkSession();
1944
		validateToken('admin-ecp');
1945
1946
		// Everyone needs a name - even the (bracket) unknown...
1947
		if (trim($_POST['field_name']) == '')
1948
			redirectexit($scripturl . '?action=admin;area=featuresettings;sa=profileedit;fid=' . $_GET['fid'] . ';msg=need_name');
1949
1950
		// Regex you say?  Do a very basic test to see if the pattern is valid
1951
		if (!empty($_POST['regex']) && @preg_match($_POST['regex'], 'dummy') === false)
1952
			redirectexit($scripturl . '?action=admin;area=featuresettings;sa=profileedit;fid=' . $_GET['fid'] . ';msg=regex_error');
1953
1954
		$_POST['field_name'] = $smcFunc['htmlspecialchars']($_POST['field_name']);
1955
		$_POST['field_desc'] = $smcFunc['htmlspecialchars']($_POST['field_desc']);
1956
1957
		// Checkboxes...
1958
		$show_reg = isset($_POST['reg']) ? (int) $_POST['reg'] : 0;
1959
		$show_display = isset($_POST['display']) ? 1 : 0;
1960
		$show_mlist = isset($_POST['mlist']) ? 1 : 0;
1961
		$bbc = isset($_POST['bbc']) ? 1 : 0;
1962
		$show_profile = $_POST['profile_area'];
1963
		$active = isset($_POST['active']) ? 1 : 0;
1964
		$private = isset($_POST['private']) ? (int) $_POST['private'] : 0;
1965
		$can_search = isset($_POST['can_search']) ? 1 : 0;
1966
1967
		// Some masking stuff...
1968
		$mask = isset($_POST['mask']) ? $_POST['mask'] : '';
1969
		if ($mask == 'regex' && isset($_POST['regex']))
1970
			$mask .= $_POST['regex'];
1971
1972
		$field_length = isset($_POST['max_length']) ? (int) $_POST['max_length'] : 255;
1973
		$enclose = isset($_POST['enclose']) ? $_POST['enclose'] : '';
1974
		$placement = isset($_POST['placement']) ? (int) $_POST['placement'] : 0;
1975
1976
		// Select options?
1977
		$field_options = '';
1978
		$newOptions = array();
1979
		$default = isset($_POST['default_check']) && $_POST['field_type'] == 'check' ? 1 : '';
1980
		if (!empty($_POST['select_option']) && ($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio'))
1981
		{
1982
			foreach ($_POST['select_option'] as $k => $v)
1983
			{
1984
				// Clean, clean, clean...
1985
				$v = $smcFunc['htmlspecialchars']($v);
1986
				$v = strtr($v, array(',' => ''));
1987
1988
				// Nada, zip, etc...
1989
				if (trim($v) == '')
1990
					continue;
1991
1992
				// Otherwise, save it boy.
1993
				$field_options .= $v . ',';
1994
				// This is just for working out what happened with old options...
1995
				$newOptions[$k] = $v;
1996
1997
				// Is it default?
1998
				if (isset($_POST['default_select']) && $_POST['default_select'] == $k)
1999
					$default = $v;
2000
			}
2001
			$field_options = substr($field_options, 0, -1);
2002
		}
2003
2004
		// Text area has default has dimensions
2005
		if ($_POST['field_type'] == 'textarea')
2006
			$default = (int) $_POST['rows'] . ',' . (int) $_POST['cols'];
2007
2008
		// Come up with the unique name?
2009
		if (empty($context['fid']))
2010
		{
2011
			$col_name = $smcFunc['substr'](strtr($_POST['field_name'], array(' ' => '')), 0, 6);
2012
			preg_match('~([\w\d_-]+)~', $col_name, $matches);
2013
2014
			// If there is nothing to the name, then let's start out own - for foreign languages etc.
2015
			if (isset($matches[1]))
2016
				$col_name = $initial_col_name = 'cust_' . strtolower($matches[1]);
2017
			else
2018
				$col_name = $initial_col_name = 'cust_' . mt_rand(1, 9999);
2019
2020
			// Make sure this is unique.
2021
			$current_fields = array();
2022
			$request = $smcFunc['db_query']('', '
2023
				SELECT id_field, col_name
2024
				FROM {db_prefix}custom_fields'
2025
			);
2026
			while ($row = $smcFunc['db_fetch_assoc']($request))
2027
				$current_fields[$row['id_field']] = $row['col_name'];
2028
2029
			$smcFunc['db_free_result']($request);
2030
2031
			$unique = false;
2032
			for ($i = 0; !$unique && $i < 9; $i++)
2033
			{
2034
				if (!in_array($col_name, $current_fields))
2035
					$unique = true;
2036
				else
2037
					$col_name = $initial_col_name . $i;
2038
			}
2039
2040
			// Still not a unique column name? Leave it up to the user, then.
2041
			if (!$unique)
2042
				fatal_lang_error('custom_option_not_unique');
2043
		}
2044
		// Work out what to do with the user data otherwise...
2045
		else
2046
		{
2047
			// Anything going to check or select is pointless keeping - as is anything coming from check!
2048
			if (($_POST['field_type'] == 'check' && $context['field']['type'] != 'check')
2049
				|| (($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio') && $context['field']['type'] != 'select' && $context['field']['type'] != 'radio')
2050
				|| ($context['field']['type'] == 'check' && $_POST['field_type'] != 'check'))
2051
			{
2052
				$smcFunc['db_query']('', '
2053
					DELETE FROM {db_prefix}themes
2054
					WHERE variable = {string:current_column}
2055
						AND id_member > {int:no_member}',
2056
					array(
2057
						'no_member' => 0,
2058
						'current_column' => $context['field']['col_name'],
2059
					)
2060
				);
2061
			}
2062
			// Otherwise - if the select is edited may need to adjust!
2063
			elseif ($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio')
2064
			{
2065
				$optionChanges = array();
2066
				$takenKeys = array();
2067
				// Work out what's changed!
2068
				foreach ($context['field']['options'] as $k => $option)
2069
				{
2070
					if (trim($option) == '')
2071
						continue;
2072
2073
					// Still exists?
2074
					if (in_array($option, $newOptions))
2075
					{
2076
						$takenKeys[] = $k;
2077
						continue;
2078
					}
2079
				}
2080
2081
				// Finally - have we renamed it - or is it really gone?
2082
				foreach ($optionChanges as $k => $option)
2083
				{
2084
					// Just been renamed?
2085
					if (!in_array($k, $takenKeys) && !empty($newOptions[$k]))
2086
						$smcFunc['db_query']('', '
2087
							UPDATE {db_prefix}themes
2088
							SET value = {string:new_value}
2089
							WHERE variable = {string:current_column}
2090
								AND value = {string:old_value}
2091
								AND id_member > {int:no_member}',
2092
							array(
2093
								'no_member' => 0,
2094
								'new_value' => $newOptions[$k],
2095
								'current_column' => $context['field']['col_name'],
2096
								'old_value' => $option,
2097
							)
2098
						);
2099
				}
2100
			}
2101
			// @todo Maybe we should adjust based on new text length limits?
2102
		}
2103
2104
		// Do the insertion/updates.
2105
		if ($context['fid'])
2106
		{
2107
			$smcFunc['db_query']('', '
2108
				UPDATE {db_prefix}custom_fields
2109
				SET
2110
					field_name = {string:field_name}, field_desc = {string:field_desc},
2111
					field_type = {string:field_type}, field_length = {int:field_length},
2112
					field_options = {string:field_options}, show_reg = {int:show_reg},
2113
					show_display = {int:show_display}, show_mlist = {int:show_mlist}, show_profile = {string:show_profile},
2114
					private = {int:private}, active = {int:active}, default_value = {string:default_value},
2115
					can_search = {int:can_search}, bbc = {int:bbc}, mask = {string:mask},
2116
					enclose = {string:enclose}, placement = {int:placement}
2117
				WHERE id_field = {int:current_field}',
2118
				array(
2119
					'field_length' => $field_length,
2120
					'show_reg' => $show_reg,
2121
					'show_display' => $show_display,
2122
					'show_mlist' => $show_mlist,
2123
					'private' => $private,
2124
					'active' => $active,
2125
					'can_search' => $can_search,
2126
					'bbc' => $bbc,
2127
					'current_field' => $context['fid'],
2128
					'field_name' => $_POST['field_name'],
2129
					'field_desc' => $_POST['field_desc'],
2130
					'field_type' => $_POST['field_type'],
2131
					'field_options' => $field_options,
2132
					'show_profile' => $show_profile,
2133
					'default_value' => $default,
2134
					'mask' => $mask,
2135
					'enclose' => $enclose,
2136
					'placement' => $placement,
2137
				)
2138
			);
2139
2140
			// Just clean up any old selects - these are a pain!
2141
			if (($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio') && !empty($newOptions))
2142
				$smcFunc['db_query']('', '
2143
					DELETE FROM {db_prefix}themes
2144
					WHERE variable = {string:current_column}
2145
						AND value NOT IN ({array_string:new_option_values})
2146
						AND id_member > {int:no_member}',
2147
					array(
2148
						'no_member' => 0,
2149
						'new_option_values' => $newOptions,
2150
						'current_column' => $context['field']['col_name'],
2151
					)
2152
				);
2153
		}
2154
		else
2155
		{
2156
			// Gotta figure it out the order.
2157
			$new_order = $order_count > 1 ? ($order_count + 1) : 1;
2158
2159
			$smcFunc['db_insert']('',
2160
				'{db_prefix}custom_fields',
2161
				array(
2162
					'col_name' => 'string', 'field_name' => 'string', 'field_desc' => 'string',
2163
					'field_type' => 'string', 'field_length' => 'string', 'field_options' => 'string', 'field_order' => 'int',
2164
					'show_reg' => 'int', 'show_display' => 'int', 'show_mlist' => 'int', 'show_profile' => 'string',
2165
					'private' => 'int', 'active' => 'int', 'default_value' => 'string', 'can_search' => 'int',
2166
					'bbc' => 'int', 'mask' => 'string', 'enclose' => 'string', 'placement' => 'int',
2167
				),
2168
				array(
2169
					$col_name, $_POST['field_name'], $_POST['field_desc'],
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $col_name does not seem to be defined for all execution paths leading up to this point.
Loading history...
2170
					$_POST['field_type'], $field_length, $field_options, $new_order,
2171
					$show_reg, $show_display, $show_mlist, $show_profile,
2172
					$private, $active, $default, $can_search,
2173
					$bbc, $mask, $enclose, $placement,
2174
				),
2175
				array('id_field')
2176
			);
2177
		}
2178
	}
2179
	// Deleting?
2180
	elseif (isset($_POST['delete']) && $context['field']['col_name'])
2181
	{
2182
		checkSession();
2183
		validateToken('admin-ecp');
2184
2185
		// Delete the user data first.
2186
		$smcFunc['db_query']('', '
2187
			DELETE FROM {db_prefix}themes
2188
			WHERE variable = {string:current_column}
2189
				AND id_member > {int:no_member}',
2190
			array(
2191
				'no_member' => 0,
2192
				'current_column' => $context['field']['col_name'],
2193
			)
2194
		);
2195
		// Finally - the field itself is gone!
2196
		$smcFunc['db_query']('', '
2197
			DELETE FROM {db_prefix}custom_fields
2198
			WHERE id_field = {int:current_field}',
2199
			array(
2200
				'current_field' => $context['fid'],
2201
			)
2202
		);
2203
2204
		// Re-arrange the order.
2205
		$smcFunc['db_query']('', '
2206
			UPDATE {db_prefix}custom_fields
2207
			SET field_order = field_order - 1
2208
			WHERE field_order > {int:current_order}',
2209
			array(
2210
				'current_order' => $context['field']['order'],
2211
			)
2212
		);
2213
	}
2214
2215
	// Rebuild display cache etc.
2216
	if (isset($_POST['delete']) || isset($_POST['save']))
2217
	{
2218
		checkSession();
2219
2220
		$request = $smcFunc['db_query']('', '
2221
			SELECT col_name, field_name, field_type, field_order, bbc, enclose, placement, show_mlist, field_options
2222
			FROM {db_prefix}custom_fields
2223
			WHERE show_display = {int:is_displayed}
2224
				AND active = {int:active}
2225
				AND private != {int:not_owner_only}
2226
				AND private != {int:not_admin_only}
2227
			ORDER BY field_order',
2228
			array(
2229
				'is_displayed' => 1,
2230
				'active' => 1,
2231
				'not_owner_only' => 2,
2232
				'not_admin_only' => 3,
2233
			)
2234
		);
2235
2236
		$fields = array();
2237
		while ($row = $smcFunc['db_fetch_assoc']($request))
2238
		{
2239
			$fields[] = array(
2240
				'col_name' => strtr($row['col_name'], array('|' => '', ';' => '')),
2241
				'title' => strtr($row['field_name'], array('|' => '', ';' => '')),
2242
				'type' => $row['field_type'],
2243
				'order' => $row['field_order'],
2244
				'bbc' => $row['bbc'] ? '1' : '0',
2245
				'placement' => !empty($row['placement']) ? $row['placement'] : '0',
2246
				'enclose' => !empty($row['enclose']) ? $row['enclose'] : '',
2247
				'mlist' => $row['show_mlist'],
2248
				'options' => (!empty($row['field_options']) ? explode(',', $row['field_options']) : array()),
2249
			);
2250
		}
2251
		$smcFunc['db_free_result']($request);
2252
2253
		updateSettings(array('displayFields' => $smcFunc['json_encode']($fields)));
2254
		$_SESSION['adm-save'] = true;
2255
		redirectexit('action=admin;area=featuresettings;sa=profile');
2256
	}
2257
2258
	createToken('admin-ecp');
2259
}
2260
2261
/**
2262
 * Returns the maximum field_order value for the custom fields
2263
 *
2264
 * @return int The maximum value of field_order from the custom_fields table
2265
 */
2266
function custFieldsMaxOrder()
2267
{
2268
	global $smcFunc;
2269
2270
	// Gotta know the order limit
2271
	$result = $smcFunc['db_query']('', '
2272
		SELECT MAX(field_order)
2273
		FROM {db_prefix}custom_fields',
2274
		array()
2275
	);
2276
2277
	list ($order_count) = $smcFunc['db_fetch_row']($result);
2278
	$smcFunc['db_free_result']($result);
2279
2280
	return (int) $order_count;
2281
}
2282
2283
/**
2284
 * Allow to edit the settings on the pruning screen.
2285
 *
2286
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
2287
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
2288
 */
2289
function ModifyLogSettings($return_config = false)
2290
{
2291
	global $txt, $scripturl, $sourcedir, $context, $modSettings;
2292
2293
	// Make sure we understand what's going on.
2294
	loadLanguage('ManageSettings');
2295
2296
	$context['page_title'] = $txt['log_settings'];
2297
2298
	$config_vars = array(
2299
		array('check', 'modlog_enabled', 'help' => 'modlog'),
2300
		array('check', 'adminlog_enabled', 'help' => 'adminlog'),
2301
		array('check', 'userlog_enabled', 'help' => 'userlog'),
2302
		// The error log is a wonderful thing.
2303
		array('title', 'errorlog', 'force_div_id' => 'errorlog'),
2304
		array('desc', 'error_log_desc'),
2305
		array('check', 'enableErrorLogging'),
2306
		array('check', 'enableErrorQueryLogging'),
2307
		// The 'mark read' log settings.
2308
		array('title', 'markread_title', 'force_div_id' => 'markread_title'),
2309
		array('desc', 'mark_read_desc'),
2310
		array('int', 'mark_read_beyond', 'step' => 1, 'min' => 0, 'max' => 18000, 'subtext' => $txt['zero_to_disable']),
2311
		array('int', 'mark_read_delete_beyond', 'step' => 1, 'min' => 0, 'max' => 18000, 'subtext' => $txt['zero_to_disable']),
2312
		array('int', 'mark_read_max_users', 'step' => 1, 'min' => 0, 'max' => 20000, 'subtext' => $txt['zero_to_disable']),
2313
		// Even do the pruning?
2314
		array('title', 'pruning_title', 'force_div_id' => 'pruning_title'),
2315
		array('desc', 'pruning_desc'),
2316
		// The array indexes are there so we can remove/change them before saving.
2317
		'pruningOptions' => array('check', 'pruningOptions'),
2318
		'',
2319
2320
		// Various logs that could be pruned.
2321
		array('int', 'pruneErrorLog', 'postinput' => $txt['days_word'], 'subtext' => $txt['zero_to_disable']), // Error log.
2322
		array('int', 'pruneModLog', 'postinput' => $txt['days_word'], 'subtext' => $txt['zero_to_disable']), // Moderation log.
2323
		array('int', 'pruneBanLog', 'postinput' => $txt['days_word'], 'subtext' => $txt['zero_to_disable']), // Ban hit log.
2324
		array('int', 'pruneReportLog', 'postinput' => $txt['days_word'], 'subtext' => $txt['zero_to_disable']), // Report to moderator log.
2325
		array('int', 'pruneScheduledTaskLog', 'postinput' => $txt['days_word'], 'subtext' => $txt['zero_to_disable']), // Log of the scheduled tasks and how long they ran.
2326
		array('int', 'pruneSpiderHitLog', 'postinput' => $txt['days_word'], 'subtext' => $txt['zero_to_disable']), // Log of the scheduled tasks and how long they ran.
2327
		// If you add any additional logs make sure to add them after this point.  Additionally, make sure you add them to the weekly scheduled task.
2328
		// Mod Developers: Do NOT use the pruningOptions master variable for this as SMF Core may overwrite your setting in the future!
2329
	);
2330
2331
	// We want to be toggling some of these for a nice user experience. If you want to add yours to the list of those magically hidden when the 'pruning' option is off, add to this.
2332
	$prune_toggle = array('pruneErrorLog', 'pruneModLog', 'pruneBanLog', 'pruneReportLog', 'pruneScheduledTaskLog', 'pruneSpiderHitLog');
2333
2334
	call_integration_hook('integrate_prune_settings', array(&$config_vars, &$prune_toggle, false));
2335
2336
	$prune_toggle_dt = array();
2337
	foreach ($prune_toggle as $item)
2338
		$prune_toggle_dt[] = 'setting_' . $item;
2339
2340
	if ($return_config)
2341
		return $config_vars;
2342
2343
	addInlineJavaScript('
2344
	function togglePruned()
2345
	{
2346
		var newval = $("#pruningOptions").prop("checked");
2347
		$("#' . implode(', #', $prune_toggle) . '").closest("dd").toggle(newval);
2348
		$("#' . implode(', #', $prune_toggle_dt) . '").closest("dt").toggle(newval);
2349
	};
2350
	togglePruned();
2351
	$("#pruningOptions").click(function() { togglePruned(); });', true);
2352
2353
	// We'll need this in a bit.
2354
	require_once($sourcedir . '/ManageServer.php');
2355
2356
	// Saving?
2357
	if (isset($_GET['save']))
2358
	{
2359
		checkSession();
2360
2361
		// Because of the excitement attached to combining pruning log items, we need to duplicate everything here.
2362
		$savevar = array(
2363
			array('check', 'modlog_enabled'),
2364
			array('check', 'adminlog_enabled'),
2365
			array('check', 'userlog_enabled'),
2366
			array('check', 'enableErrorLogging'),
2367
			array('check', 'enableErrorQueryLogging'),
2368
			array('int', 'mark_read_beyond'),
2369
			array('int', 'mark_read_delete_beyond'),
2370
			array('int', 'mark_read_max_users'),
2371
			array('text', 'pruningOptions')
2372
		);
2373
2374
		call_integration_hook('integrate_prune_settings', array(&$savevar, &$prune_toggle, true));
2375
2376
		if (!empty($_POST['pruningOptions']))
2377
		{
2378
			$vals = array();
2379
			foreach ($config_vars as $index => $dummy)
2380
			{
2381
				if (!is_array($dummy) || $index == 'pruningOptions' || !in_array($dummy[1], $prune_toggle))
2382
					continue;
2383
2384
				$vals[] = empty($_POST[$dummy[1]]) || $_POST[$dummy[1]] < 0 ? 0 : (int) $_POST[$dummy[1]];
2385
			}
2386
			$_POST['pruningOptions'] = implode(',', $vals);
2387
		}
2388
		else
2389
			$_POST['pruningOptions'] = '';
2390
2391
		saveDBSettings($savevar);
2392
		$_SESSION['adm-save'] = true;
2393
		redirectexit('action=admin;area=logs;sa=settings');
2394
	}
2395
2396
	$context['post_url'] = $scripturl . '?action=admin;area=logs;save;sa=settings';
2397
	$context['settings_title'] = $txt['log_settings'];
2398
	$context['sub_template'] = 'show_settings';
2399
2400
	// Get the actual values
2401
	if (!empty($modSettings['pruningOptions']))
2402
		@list ($modSettings['pruneErrorLog'], $modSettings['pruneModLog'], $modSettings['pruneBanLog'], $modSettings['pruneReportLog'], $modSettings['pruneScheduledTaskLog'], $modSettings['pruneSpiderHitLog']) = explode(',', $modSettings['pruningOptions']);
2403
	else
2404
		$modSettings['pruneErrorLog'] = $modSettings['pruneModLog'] = $modSettings['pruneBanLog'] = $modSettings['pruneReportLog'] = $modSettings['pruneScheduledTaskLog'] = $modSettings['pruneSpiderHitLog'] = 0;
2405
2406
	prepareDBSettingContext($config_vars);
2407
}
2408
2409
/**
2410
 * If you have a general mod setting to add stick it here.
2411
 *
2412
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
2413
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
2414
 */
2415
function ModifyGeneralModSettings($return_config = false)
2416
{
2417
	global $txt, $scripturl, $context;
2418
2419
	$config_vars = array(
2420
		// Mod authors, add any settings UNDER this line. Include a comma at the end of the line and don't remove this statement!!
2421
	);
2422
2423
	// Make it even easier to add new settings.
2424
	call_integration_hook('integrate_general_mod_settings', array(&$config_vars));
2425
2426
	if ($return_config)
2427
		return $config_vars;
2428
2429
	$context['post_url'] = $scripturl . '?action=admin;area=modsettings;save;sa=general';
2430
	$context['settings_title'] = $txt['mods_cat_modifications_misc'];
2431
2432
	// No removing this line you, dirty unwashed mod authors. :p
2433
	if (empty($config_vars))
2434
	{
2435
		$context['settings_save_dont_show'] = true;
2436
		$context['settings_message'] = array(
2437
			'label' => $txt['modification_no_misc_settings'],
2438
			'tag' => 'div',
2439
			'class' => 'centertext'
2440
		);
2441
2442
		return prepareDBSettingContext($config_vars);
0 ignored issues
show
Bug introduced by
Are you sure the usage of prepareDBSettingContext($config_vars) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2443
	}
2444
2445
	// Saving?
2446
	if (isset($_GET['save']))
2447
	{
2448
		checkSession();
2449
2450
		$save_vars = $config_vars;
2451
2452
		call_integration_hook('integrate_save_general_mod_settings', array(&$save_vars));
2453
2454
		// This line is to help mod authors do a search/add after if you want to add something here. Keyword: FOOT TAPPING SUCKS!
2455
		saveDBSettings($save_vars);
2456
2457
		// This line is to remind mod authors that it's nice to let the users know when something has been saved.
2458
		$_SESSION['adm-save'] = true;
2459
2460
		// This line is to help mod authors do a search/add after if you want to add something here. Keyword: I LOVE TEA!
2461
		redirectexit('action=admin;area=modsettings;sa=general');
2462
	}
2463
2464
	// This line is to help mod authors do a search/add after if you want to add something here. Keyword: RED INK IS FOR TEACHERS AND THOSE WHO LIKE PAIN!
2465
	prepareDBSettingContext($config_vars);
2466
}
2467
2468
/**
2469
 * Handles modifying the alerts settings
2470
 */
2471
function ModifyAlertsSettings()
2472
{
2473
	global $context, $modSettings, $sourcedir, $txt;
2474
2475
	// Dummy settings for the template...
2476
	$context['user']['is_owner'] = false;
2477
	$context['member'] = array();
2478
	$context['id_member'] = 0;
2479
	$context['menu_item_selected'] = 'alerts';
2480
	$context['token_check'] = 'noti-admin';
2481
2482
	// Specify our action since we'll want to post back here instead of the profile
2483
	$context['action'] = 'action=admin;area=featuresettings;sa=alerts;' . $context['session_var'] . '=' . $context['session_id'];
2484
2485
	loadTemplate('Profile');
2486
	loadLanguage('Profile');
2487
2488
	include_once($sourcedir . '/Profile-Modify.php');
2489
	alert_configuration(0, true);
2490
2491
	$context['page_title'] = $txt['notify_settings'];
2492
2493
	// Override the description
2494
	$context['description'] = $txt['notifications_desc'];
2495
	$context['sub_template'] = 'alert_configuration';
2496
}
2497
2498
?>