Passed
Push — release-2.1 ( 12d126...77eee1 )
by Mathias
07:47 queued 16s
created

ModifyBasicSettings()   C

Complexity

Conditions 12
Paths 240

Size

Total Lines 125
Code Lines 74

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 74
c 0
b 0
f 0
nop 1
dl 0
loc 125
rs 5.0739
nc 240

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

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