Passed
Pull Request — release-2.1 (#4892)
by Mathias
06:47 queued 57s
created

ModifyPolicySettings()   C

Complexity

Conditions 13
Paths 96

Size

Total Lines 201
Code Lines 95

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
cc 13
eloc 95
c 6
b 0
f 0
nc 96
nop 1
dl 0
loc 201
rs 5.4024

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 http://www.simplemachines.org
11
 * @copyright 2018 Simple Machines and individual contributors
12
 * @license http://www.simplemachines.org/about/smf/license.php BSD
13
 *
14
 * @version 2.1 Beta 4
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;
52
53
	loadLanguage('Help');
54
	loadLanguage('ManageSettings');
55
56
	$context['page_title'] = $txt['modSettings_title'];
57
58
	$subActions = array(
59
		'basic' => 'ModifyBasicSettings',
60
		'bbc' => 'ModifyBBCSettings',
61
		'layout' => 'ModifyLayoutSettings',
62
		'sig' => 'ModifySignatureSettings',
63
		'profile' => 'ShowCustomProfiles',
64
		'profileedit' => 'EditCustomProfiles',
65
		'likes' => 'ModifyLikesSettings',
66
		'mentions' => 'ModifyMentionsSettings',
67
		'alerts' => 'ModifyAlertsSettings',
68
		'privacy' => 'ModifyPrivacySettings',
69
		'policy' => 'ModifyPolicySettings',
70
	);
71
72
	// Load up all the tabs...
73
	$context[$context['admin_menu_name']]['tab_data'] = array(
74
		'title' => $txt['modSettings_title'],
75
		'help' => 'featuresettings',
76
		'description' => sprintf($txt['modSettings_desc'], $settings['theme_id'], $context['session_id'], $context['session_var']),
77
		'tabs' => array(
78
			'basic' => array(
79
			),
80
			'bbc' => array(
81
				'description' => $txt['manageposts_bbc_settings_description'],
82
			),
83
			'layout' => array(
84
			),
85
			'sig' => array(
86
				'description' => $txt['signature_settings_desc'],
87
			),
88
			'profile' => array(
89
				'description' => $txt['custom_profile_desc'],
90
			),
91
			'likes' => array(
92
			),
93
			'mentions' => array(
94
			),
95
			'alerts' => array(
96
				'description' => $txt['notifications_desc'],
97
			),
98
			'privacy' => array(
99
			),
100
			'policy' => array(
101
			),
102
		),
103
	);
104
105
	call_integration_hook('integrate_modify_features', array(&$subActions));
106
107
	loadGeneralSettingParameters($subActions, 'basic');
108
109
	// Call the right function for this sub-action.
110
	call_helper($subActions[$_REQUEST['sa']]);
111
}
112
113
/**
114
 * This my friend, is for all the mod authors out there.
115
 */
116
function ModifyModSettings()
117
{
118
	global $context, $txt;
119
120
	loadLanguage('Help');
121
	loadLanguage('ManageSettings');
122
123
	$context['page_title'] = $txt['admin_modifications'];
124
125
	$subActions = array(
126
		'general' => 'ModifyGeneralModSettings',
127
		// Mod authors, once again, if you have a whole section to add do it AFTER this line, and keep a comma at the end.
128
	);
129
130
	// Load up all the tabs...
131
	$context[$context['admin_menu_name']]['tab_data'] = array(
132
		'title' => $txt['admin_modifications'],
133
		'help' => 'modsettings',
134
		'description' => $txt['modification_settings_desc'],
135
		'tabs' => array(
136
			'general' => array(
137
			),
138
		),
139
	);
140
141
	// Make it easier for mods to add new areas.
142
	call_integration_hook('integrate_modify_modifications', array(&$subActions));
143
144
	loadGeneralSettingParameters($subActions, 'general');
145
146
	// Call the right function for this sub-action.
147
	call_helper($subActions[$_REQUEST['sa']]);
148
}
149
150
/**
151
 * Config array for changing the basic forum settings
152
 * Accessed  from ?action=admin;area=featuresettings;sa=basic;
153
 *
154
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
155
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
156
 */
157
function ModifyBasicSettings($return_config = false)
158
{
159
	global $txt, $scripturl, $context, $modSettings;
160
161
	// We need to know if personal text is enabled, and if it's in the registration fields option.
162
	// If admins have set it up as an on-registration thing, they can't set a default value (because it'll never be used)
163
	$disabled_fields = isset($modSettings['disabled_profile_fields']) ? explode(',', $modSettings['disabled_profile_fields']) : array();
164
	$reg_fields = isset($modSettings['registration_fields']) ? explode(',', $modSettings['registration_fields']) : array();
165
	$can_personal_text = !in_array('personal_text', $disabled_fields) && !in_array('personal_text', $reg_fields);
166
167
	$config_vars = array(
168
			// Big Options... polls, sticky, bbc....
169
			array('select', 'pollMode', array($txt['disable_polls'], $txt['enable_polls'], $txt['polls_as_topics'])),
170
		'',
171
			// Basic stuff, titles, flash, permissions...
172
			array('check', 'allow_guestAccess'),
173
			array('check', 'enable_buddylist'),
174
			array('check', 'allow_hideOnline'),
175
			array('check', 'titlesEnable'),
176
			array('text', 'default_personal_text', 'subtext' => $txt['default_personal_text_note'], 'disabled' => !$can_personal_text),
177
			array('check', 'topic_move_any'),
178
			array('int', 'defaultMaxListItems', 'step' => 1, 'min' => 1, 'max' => 999),
179
		'',
180
			// Jquery source
181
			array('select', 'jquery_source', array('auto' => $txt['jquery_auto'], 'local' => $txt['jquery_local'], 'cdn' => $txt['jquery_cdn'], 'custom' => $txt['jquery_custom']), 'onchange' => 'if (this.value == \'custom\'){document.getElementById(\'jquery_custom\').disabled = false; } else {document.getElementById(\'jquery_custom\').disabled = true;}'),
182
			array('text', 'jquery_custom', 'disabled' => isset($modSettings['jquery_source']) && $modSettings['jquery_source'] != 'custom', 'size' => 75),
183
		'',
184
			// css and js minification.
185
			array('check', 'minimize_files'),
186
		'',
187
			// SEO stuff
188
			array('check', 'queryless_urls', 'subtext' => '<strong>' . $txt['queryless_urls_note'] . '</strong>'),
189
			array('text', 'meta_keywords', 'subtext' => $txt['meta_keywords_note'], 'size' => 50),
190
		'',
191
			// Number formatting, timezones.
192
			array('text', 'time_format'),
193
			array('float', 'time_offset', 'subtext' => $txt['setting_time_offset_note'], 6, 'postinput' => $txt['hours'], 'step' => 0.25, 'min' => -23.5, 'max' => 23.5),
194
			'default_timezone' => array('select', 'default_timezone', array()),
195
			array('text', 'timezone_priority_countries', 'subtext' => $txt['setting_timezone_priority_countries_note']),
196
		'',
197
			// Who's online?
198
			array('check', 'who_enabled'),
199
			array('int', 'lastActive', 6, 'postinput' => $txt['minutes']),
200
		'',
201
			// Statistics.
202
			array('check', 'trackStats'),
203
			array('check', 'hitStats'),
204
		'',
205
			// Option-ish things... miscellaneous sorta.
206
			array('check', 'allow_disableAnnounce'),
207
			array('check', 'disallow_sendBody'),
208
		'',
209
			// Alerts stuff
210
			array('check', 'enable_ajax_alerts'),
211
	);
212
213
	// Get all the time zones.
214
	if (function_exists('timezone_identifiers_list') && function_exists('date_default_timezone_set'))
215
	{
216
		$all_zones = timezone_identifiers_list();
217
		// Make sure we set the value to the same as the printed value.
218
		foreach ($all_zones as $zone)
219
			$config_vars['default_timezone'][2][$zone] = $zone;
220
	}
221
	else
222
		unset($config_vars['default_timezone']);
223
224
	call_integration_hook('integrate_modify_basic_settings', array(&$config_vars));
225
226
	if ($return_config)
227
		return $config_vars;
228
229
	// Saving?
230
	if (isset($_GET['save']))
231
	{
232
		checkSession();
233
234
		// Prevent absurd boundaries here - make it a day tops.
235
		if (isset($_POST['lastActive']))
236
			$_POST['lastActive'] = min((int) $_POST['lastActive'], 1440);
237
238
		call_integration_hook('integrate_save_basic_settings');
239
240
		saveDBSettings($config_vars);
241
		$_SESSION['adm-save'] = true;
242
243
		// Do a bit of housekeeping
244
		if (empty($_POST['minimize_files']))
245
			deleteAllMinified();
246
247
		writeLog();
248
		redirectexit('action=admin;area=featuresettings;sa=basic');
249
	}
250
251
	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=basic';
252
	$context['settings_title'] = $txt['mods_cat_features'];
253
254
	prepareDBSettingContext($config_vars);
255
}
256
257
/**
258
 * Set a few Bulletin Board Code settings. It loads a list of Bulletin Board Code tags to allow disabling tags.
259
 * Requires the admin_forum permission.
260
 * Accessed from ?action=admin;area=featuresettings;sa=bbc.
261
 *
262
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
263
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
264
 * @uses Admin template, edit_bbc_settings sub-template.
265
 */
266
function ModifyBBCSettings($return_config = false)
267
{
268
	global $context, $txt, $modSettings, $scripturl, $sourcedir;
269
270
	$config_vars = array(
271
			// Main tweaks
272
			array('check', 'enableBBC'),
273
			array('check', 'enableBBC', 0, 'onchange' => 'toggleBBCDisabled(\'disabledBBC\', !this.checked);'),
274
			array('check', 'enablePostHTML'),
275
			array('check', 'autoLinkUrls'),
276
		'',
277
			array('bbc', 'disabledBBC'),
278
	);
279
280
	$context['settings_post_javascript'] = '
281
		toggleBBCDisabled(\'disabledBBC\', ' . (empty($modSettings['enableBBC']) ? 'true' : 'false') . ');';
282
283
	call_integration_hook('integrate_modify_bbc_settings', array(&$config_vars));
284
285
	if ($return_config)
286
		return $config_vars;
287
288
	// Setup the template.
289
	require_once($sourcedir . '/ManageServer.php');
290
	$context['sub_template'] = 'show_settings';
291
	$context['page_title'] = $txt['manageposts_bbc_settings_title'];
292
293
	// Make sure we check the right tags!
294
	$modSettings['bbc_disabled_disabledBBC'] = empty($modSettings['disabledBBC']) ? array() : explode(',', $modSettings['disabledBBC']);
295
296
	// Saving?
297
	if (isset($_GET['save']))
298
	{
299
		checkSession();
300
301
		// Clean up the tags.
302
		$bbcTags = array();
303
		foreach (parse_bbc(false) as $tag)
304
			$bbcTags[] = $tag['tag'];
305
306
		if (!isset($_POST['disabledBBC_enabledTags']))
307
			$_POST['disabledBBC_enabledTags'] = array();
308
		elseif (!is_array($_POST['disabledBBC_enabledTags']))
309
			$_POST['disabledBBC_enabledTags'] = array($_POST['disabledBBC_enabledTags']);
310
		// Work out what is actually disabled!
311
		$_POST['disabledBBC'] = implode(',', array_diff($bbcTags, $_POST['disabledBBC_enabledTags']));
312
313
		call_integration_hook('integrate_save_bbc_settings', array($bbcTags));
314
315
		saveDBSettings($config_vars);
316
		$_SESSION['adm-save'] = true;
317
		redirectexit('action=admin;area=featuresettings;sa=bbc');
318
	}
319
320
	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=bbc';
321
	$context['settings_title'] = $txt['manageposts_bbc_settings_title'];
322
323
	prepareDBSettingContext($config_vars);
324
}
325
326
/**
327
 * Allows modifying the global layout settings in the forum
328
 * Accessed through ?action=admin;area=featuresettings;sa=layout;
329
 *
330
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
331
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
332
 */
333
function ModifyLayoutSettings($return_config = false)
334
{
335
	global $txt, $scripturl, $context;
336
337
	$config_vars = array(
338
			// Pagination stuff.
339
			array('check', 'compactTopicPagesEnable'),
340
			array('int', 'compactTopicPagesContiguous', null, $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>'),
341
			array('int', 'defaultMaxMembers'),
342
		'',
343
			// Stuff that just is everywhere - today, search, online, etc.
344
			array('select', 'todayMod', array($txt['today_disabled'], $txt['today_only'], $txt['yesterday_today'])),
345
			array('check', 'onlineEnable'),
346
		'',
347
			// This is like debugging sorta.
348
			array('check', 'timeLoadPageEnable'),
349
	);
350
351
	call_integration_hook('integrate_layout_settings', array(&$config_vars));
352
353
	if ($return_config)
354
		return $config_vars;
355
356
	// Saving?
357
	if (isset($_GET['save']))
358
	{
359
		checkSession();
360
361
		call_integration_hook('integrate_save_layout_settings');
362
363
		saveDBSettings($config_vars);
364
		$_SESSION['adm-save'] = true;
365
		writeLog();
366
367
		redirectexit('action=admin;area=featuresettings;sa=layout');
368
	}
369
370
	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=layout';
371
	$context['settings_title'] = $txt['mods_cat_layout'];
372
373
	prepareDBSettingContext($config_vars);
374
}
375
376
/**
377
 * Config array for changing like settings
378
 * Accessed  from ?action=admin;area=featuresettings;sa=likes;
379
 *
380
 * @param bool $return_config Whether or not to return the config_vars array
381
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
382
 */
383
function ModifyLikesSettings($return_config = false)
384
{
385
	global $txt, $scripturl, $context;
386
387
	$config_vars = array(
388
		array('check', 'enable_likes'),
389
		array('permissions', 'likes_like'),
390
	);
391
392
	call_integration_hook('integrate_likes_settings', array(&$config_vars));
393
394
	if ($return_config)
395
		return $config_vars;
396
397
	// Saving?
398
	if (isset($_GET['save']))
399
	{
400
		checkSession();
401
402
		call_integration_hook('integrate_save_likes_settings');
403
404
		saveDBSettings($config_vars);
405
		$_SESSION['adm-save'] = true;
406
		redirectexit('action=admin;area=featuresettings;sa=likes');
407
	}
408
409
	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=likes';
410
	$context['settings_title'] = $txt['likes'];
411
412
	prepareDBSettingContext($config_vars);
413
}
414
415
/**
416
 * Config array for changing like settings
417
 * Accessed  from ?action=admin;area=featuresettings;sa=mentions;
418
 *
419
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
420
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
421
 */
422
function ModifyMentionsSettings($return_config = false)
423
{
424
	global $txt, $scripturl, $context;
425
426
	$config_vars = array(
427
		array('check', 'enable_mentions'),
428
		array('permissions', 'mention'),
429
	);
430
431
	call_integration_hook('integrate_mentions_settings', array(&$config_vars));
432
433
	if ($return_config)
434
		return $config_vars;
435
436
	// Saving?
437
	if (isset($_GET['save']))
438
	{
439
		checkSession();
440
441
		call_integration_hook('integrate_save_mentions_settings');
442
443
		saveDBSettings($config_vars);
444
		$_SESSION['adm-save'] = true;
445
		redirectexit('action=admin;area=featuresettings;sa=mentions');
446
	}
447
448
	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=mentions';
449
	$context['settings_title'] = $txt['mentions'];
450
451
	prepareDBSettingContext($config_vars);
452
}
453
454
/**
455
 * Moderation type settings - although there are fewer than we have you believe ;)
456
 *
457
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
458
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
459
 */
460
function ModifyWarningSettings($return_config = false)
461
{
462
	global $txt, $scripturl, $context, $modSettings, $sourcedir;
463
464
	// You need to be an admin to edit settings!
465
	isAllowedTo('admin_forum');
466
467
	loadLanguage('Help');
468
	loadLanguage('ManageSettings');
469
470
	// We need the existing ones for this
471
	list ($currently_enabled, $modSettings['user_limit'], $modSettings['warning_decrement']) = explode(',', $modSettings['warning_settings']);
472
473
	$config_vars = array(
474
			// Warning system?
475
			'enable' => array('check', 'warning_enable'),
476
	);
477
478
	if (!empty($modSettings['warning_settings']) && $currently_enabled)
479
		$config_vars += array(
480
			'',
481
				array('int', 'warning_watch', 'subtext' => $txt['setting_warning_watch_note'] . ' ' . $txt['zero_to_disable']),
482
				'moderate' => array('int', 'warning_moderate', 'subtext' => $txt['setting_warning_moderate_note'] . ' ' . $txt['zero_to_disable']),
483
				array('int', 'warning_mute', 'subtext' => $txt['setting_warning_mute_note'] . ' ' . $txt['zero_to_disable']),
484
				'rem1' => array('int', 'user_limit', 'subtext' => $txt['setting_user_limit_note']),
485
				'rem2' => array('int', 'warning_decrement', 'subtext' => $txt['setting_warning_decrement_note'] . ' ' . $txt['zero_to_disable']),
486
				array('permissions', 'view_warning'),
487
		);
488
489
	call_integration_hook('integrate_warning_settings', array(&$config_vars));
490
491
	if ($return_config)
492
		return $config_vars;
493
494
	// Cannot use moderation if post moderation is not enabled.
495
	if (!$modSettings['postmod_active'])
496
		unset($config_vars['moderate']);
497
498
	// Will need the utility functions from here.
499
	require_once($sourcedir . '/ManageServer.php');
500
501
	// Saving?
502
	if (isset($_GET['save']))
503
	{
504
		checkSession();
505
506
		// Make sure these don't have an effect.
507
		if (!$currently_enabled && empty($_POST['warning_enable']))
508
		{
509
			$_POST['warning_watch'] = 0;
510
			$_POST['warning_moderate'] = 0;
511
			$_POST['warning_mute'] = 0;
512
		}
513
		// If it was disabled and we're enabling it now, set some sane defaults.
514
		elseif (!$currently_enabled && !empty($_POST['warning_enable']))
515
		{
516
			// Need to add these, these weren't there before...
517
			$vars = array(
518
				'warning_watch' => 10,
519
				'warning_mute' => 60,
520
			);
521
			if ($modSettings['postmod_active'])
522
				$vars['warning_moderate'] = 35;
523
524
			foreach ($vars as $var => $value)
525
			{
526
				$config_vars[] = array('int', $var);
527
				$_POST[$var] = $value;
528
			}
529
		}
530
		else
531
		{
532
			$_POST['warning_watch'] = min($_POST['warning_watch'], 100);
533
			$_POST['warning_moderate'] = $modSettings['postmod_active'] ? min($_POST['warning_moderate'], 100) : 0;
534
			$_POST['warning_mute'] = min($_POST['warning_mute'], 100);
535
		}
536
537
		// We might not have these already depending on how we got here.
538
		$_POST['user_limit'] = isset($_POST['user_limit']) ? (int) $_POST['user_limit'] : $modSettings['user_limit'];
539
		$_POST['warning_decrement'] = isset($_POST['warning_decrement']) ? (int) $_POST['warning_decrement'] : $modSettings['warning_decrement'];
540
541
		// Fix the warning setting array!
542
		$_POST['warning_settings'] = (!empty($_POST['warning_enable']) ? 1 : 0) . ',' . min(100, $_POST['user_limit']) . ',' . min(100, $_POST['warning_decrement']);
543
		$save_vars = $config_vars;
544
		$save_vars[] = array('text', 'warning_settings');
545
		unset($save_vars['enable'], $save_vars['rem1'], $save_vars['rem2']);
546
547
		call_integration_hook('integrate_save_warning_settings', array(&$save_vars));
548
549
		saveDBSettings($save_vars);
550
		$_SESSION['adm-save'] = true;
551
		redirectexit('action=admin;area=warnings');
552
	}
553
554
	// We actually store lots of these together - for efficiency.
555
	list ($modSettings['warning_enable'], $modSettings['user_limit'], $modSettings['warning_decrement']) = explode(',', $modSettings['warning_settings']);
556
557
	$context['sub_template'] = 'show_settings';
558
	$context['post_url'] = $scripturl . '?action=admin;area=warnings;save';
559
	$context['settings_title'] = $txt['warnings'];
560
	$context['page_title'] = $txt['warnings'];
561
562
	$context[$context['admin_menu_name']]['tab_data'] = array(
563
		'title' => $txt['warnings'],
564
		'help' => '',
565
		'description' => $txt['warnings_desc'],
566
	);
567
568
	prepareDBSettingContext($config_vars);
569
}
570
571
/**
572
 * Let's try keep the spam to a minimum ah Thantos?
573
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
574
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
575
 */
576
function ModifyAntispamSettings($return_config = false)
577
{
578
	global $txt, $scripturl, $context, $modSettings, $smcFunc, $language, $sourcedir;
579
580
	loadLanguage('Help');
581
	loadLanguage('ManageSettings');
582
583
	// Generate a sample registration image.
584
	$context['use_graphic_library'] = in_array('gd', get_loaded_extensions());
585
	$context['verification_image_href'] = $scripturl . '?action=verificationcode;rand=' . md5(mt_rand());
586
587
	$config_vars = array(
588
				array('check', 'reg_verification'),
589
				array('check', 'search_enable_captcha'),
590
				// This, my friend, is a cheat :p
591
				'guest_verify' => array('check', 'guests_require_captcha', 'subtext' => $txt['setting_guests_require_captcha_desc']),
592
				array('int', 'posts_require_captcha', 'subtext' => $txt['posts_require_captcha_desc'], '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;}'),
593
			'',
594
			// PM Settings
595
				'pm1' => array('int', 'max_pm_recipients', 'subtext' => $txt['max_pm_recipients_note']),
596
				'pm2' => array('int', 'pm_posts_verification', 'subtext' => $txt['pm_posts_verification_note']),
597
				'pm3' => array('int', 'pm_posts_per_hour', 'subtext' => $txt['pm_posts_per_hour_note']),
598
			// Visual verification.
599
			array('title', 'configure_verification_means'),
600
			array('desc', 'configure_verification_means_desc'),
601
				'vv' => array('select', 'visual_verification_type', array($txt['setting_image_verification_off'], $txt['setting_image_verification_vsimple'], $txt['setting_image_verification_simple'], $txt['setting_image_verification_medium'], $txt['setting_image_verification_high'], $txt['setting_image_verification_extreme']), 'subtext' => $txt['setting_visual_verification_type_desc'], 'onchange' => $context['use_graphic_library'] ? 'refreshImages();' : ''),
602
			// reCAPTCHA
603
			array('title', 'recaptcha_configure'),
604
			array('desc', 'recaptcha_configure_desc', 'class' => 'windowbg'),
605
				array('check', 'recaptcha_enabled', 'subtext' => $txt['recaptcha_enable_desc']),
606
				array('text', 'recaptcha_site_key', 'subtext' => $txt['recaptcha_site_key_desc']),
607
				array('text', 'recaptcha_secret_key', 'subtext' => $txt['recaptcha_secret_key_desc']),
608
				array('select', 'recaptcha_theme', array('light' => $txt['recaptcha_theme_light'], 'dark' => $txt['recaptcha_theme_dark'])),
609
			// Clever Thomas, who is looking sheepy now? Not I, the mighty sword swinger did say.
610
			array('title', 'setup_verification_questions'),
611
			array('desc', 'setup_verification_questions_desc'),
612
				array('int', 'qa_verification_number', 'subtext' => $txt['setting_qa_verification_number_desc']),
613
				array('callback', 'question_answer_list'),
614
	);
615
616
	call_integration_hook('integrate_spam_settings', array(&$config_vars));
617
618
	if ($return_config)
619
		return $config_vars;
620
621
	// You need to be an admin to edit settings!
622
	isAllowedTo('admin_forum');
623
624
	// Firstly, figure out what languages we're dealing with, and do a little processing for the form's benefit.
625
	getLanguages();
626
	$context['qa_languages'] = array();
627
	foreach ($context['languages'] as $lang_id => $lang)
628
	{
629
		$lang_id = strtr($lang_id, array('-utf8' => ''));
630
		$lang['name'] = strtr($lang['name'], array('-utf8' => ''));
631
		$context['qa_languages'][$lang_id] = $lang;
632
	}
633
634
	// Secondly, load any questions we currently have.
635
	$context['question_answers'] = array();
636
	$request = $smcFunc['db_query']('', '
637
		SELECT id_question, lngfile, question, answers
638
		FROM {db_prefix}qanda'
639
	);
640
	while ($row = $smcFunc['db_fetch_assoc']($request))
641
	{
642
		$lang = strtr($row['lngfile'], array('-utf8' => ''));
643
		$context['question_answers'][$row['id_question']] = array(
644
			'lngfile' => $lang,
645
			'question' => $row['question'],
646
			'answers' => $smcFunc['json_decode']($row['answers'], true),
647
		);
648
		$context['qa_by_lang'][$lang][] = $row['id_question'];
649
	}
650
651
	if (empty($context['qa_by_lang'][strtr($language, array('-utf8' => ''))]) && !empty($context['question_answers']))
652
	{
653
		if (empty($context['settings_insert_above']))
654
			$context['settings_insert_above'] = '';
655
656
		$context['settings_insert_above'] .= '<div class="noticebox">' . sprintf($txt['question_not_defined'], $context['languages'][$language]['name']) . '</div>';
657
	}
658
659
	// Thirdly, push some JavaScript for the form to make it work.
660
	addInlineJavaScript('
661
	var nextrow = ' . (!empty($context['question_answers']) ? max(array_keys($context['question_answers'])) + 1 : 1) . ';
662
	$(".qa_link a").click(function() {
663
		var id = $(this).parent().attr("id").substring(6);
664
		$("#qa_fs_" + id).show();
665
		$(this).parent().hide();
666
	});
667
	$(".qa_fieldset legend a").click(function() {
668
		var id = $(this).closest("fieldset").attr("id").substring(6);
669
		$("#qa_dt_" + id).show();
670
		$(this).closest("fieldset").hide();
671
	});
672
	$(".qa_add_question a").click(function() {
673
		var id = $(this).closest("fieldset").attr("id").substring(6);
674
		$(\'<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());
675
		nextrow++;
676
	});
677
	$(".qa_add_answer a").click(function() {
678
		var attr = $(this).closest("dd").find(".verification_answer:last").attr("name");
679
		$(\'<input type="text" name="\' + attr + \'" value="" size="50" class="verification_answer">\').insertBefore($(this).closest("div"));
680
		return false;
681
	});
682
	$("#qa_dt_' . strtr($language, array('-utf8' => '')) . ' a").click();', true);
683
684
	// Will need the utility functions from here.
685
	require_once($sourcedir . '/ManageServer.php');
686
687
	// Saving?
688
	if (isset($_GET['save']))
689
	{
690
		checkSession();
691
692
		// Fix PM settings.
693
		$_POST['pm_spam_settings'] = (int) $_POST['max_pm_recipients'] . ',' . (int) $_POST['pm_posts_verification'] . ',' . (int) $_POST['pm_posts_per_hour'];
694
695
		// Hack in guest requiring verification!
696
		if (empty($_POST['posts_require_captcha']) && !empty($_POST['guests_require_captcha']))
697
			$_POST['posts_require_captcha'] = -1;
698
699
		$save_vars = $config_vars;
700
		unset($save_vars['pm1'], $save_vars['pm2'], $save_vars['pm3'], $save_vars['guest_verify']);
701
702
		$save_vars[] = array('text', 'pm_spam_settings');
703
704
		// Handle verification questions.
705
		$changes = array(
706
			'insert' => array(),
707
			'replace' => array(),
708
			'delete' => array(),
709
		);
710
		$qs_per_lang = array();
711
		foreach ($context['qa_languages'] as $lang_id => $dummy)
712
		{
713
			// If we had some questions for this language before, but don't now, delete everything from that language.
714
			if ((!isset($_POST['question'][$lang_id]) || !is_array($_POST['question'][$lang_id])) && !empty($context['qa_by_lang'][$lang_id]))
715
				$changes['delete'] = array_merge($questions['delete'], $context['qa_by_lang'][$lang_id]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $questions does not exist. Did you maybe mean $question?
Loading history...
716
717
			// Now step through and see if any existing questions no longer exist.
718
			if (!empty($context['qa_by_lang'][$lang_id]))
719
				foreach ($context['qa_by_lang'][$lang_id] as $q_id)
720
					if (empty($_POST['question'][$lang_id][$q_id]))
721
						$changes['delete'][] = $q_id;
722
723
			// Now let's see if there are new questions or ones that need updating.
724
			if (isset($_POST['question'][$lang_id]))
725
			{
726
				foreach ($_POST['question'][$lang_id] as $q_id => $question)
727
				{
728
					// Ignore junky ids.
729
					$q_id = (int) $q_id;
730
					if ($q_id <= 0)
731
						continue;
732
733
					// Check the question isn't empty (because they want to delete it?)
734
					if (empty($question) || trim($question) == '')
735
					{
736
						if (isset($context['question_answers'][$q_id]))
737
							$changes['delete'][] = $q_id;
738
						continue;
739
					}
740
					$question = $smcFunc['htmlspecialchars'](trim($question));
741
742
					// Get the answers. Firstly check there actually might be some.
743
					if (!isset($_POST['answer'][$lang_id][$q_id]) || !is_array($_POST['answer'][$lang_id][$q_id]))
744
					{
745
						if (isset($context['question_answers'][$q_id]))
746
							$changes['delete'][] = $q_id;
747
						continue;
748
					}
749
					// Now get them and check that they might be viable.
750
					$answers = array();
751
					foreach ($_POST['answer'][$lang_id][$q_id] as $answer)
752
						if (!empty($answer) && trim($answer) !== '')
753
							$answers[] = $smcFunc['htmlspecialchars'](trim($answer));
754
					if (empty($answers))
755
					{
756
						if (isset($context['question_answers'][$q_id]))
757
							$changes['delete'][] = $q_id;
758
						continue;
759
					}
760
					$answers = $smcFunc['json_encode']($answers);
761
762
					// At this point we know we have a question and some answers. What are we doing with it?
763
					if (!isset($context['question_answers'][$q_id]))
764
					{
765
						// New question. Now, we don't want to randomly consume ids, so we'll set those, rather than trusting the browser's supplied ids.
766
						$changes['insert'][] = array($lang_id, $question, $answers);
767
					}
768
					else
769
					{
770
						// It's an existing question. Let's see what's changed, if anything.
771
						if ($lang_id != $context['question_answers'][$q_id]['lngfile'] || $question != $context['question_answers'][$q_id]['question'] || $answers != $context['question_answers'][$q_id]['answers'])
772
							$changes['replace'][$q_id] = array('lngfile' => $lang_id, 'question' => $question, 'answers' => $answers);
773
					}
774
775
					if (!isset($qs_per_lang[$lang_id]))
776
						$qs_per_lang[$lang_id] = 0;
777
					$qs_per_lang[$lang_id]++;
778
				}
779
			}
780
		}
781
782
		// OK, so changes?
783
		if (!empty($changes['delete']))
784
		{
785
			$smcFunc['db_query']('', '
786
				DELETE FROM {db_prefix}qanda
787
				WHERE id_question IN ({array_int:questions})',
788
				array(
789
					'questions' => $changes['delete'],
790
				)
791
			);
792
		}
793
794
		if (!empty($changes['replace']))
795
		{
796
			foreach ($changes['replace'] as $q_id => $question)
797
			{
798
				$smcFunc['db_query']('', '
799
					UPDATE {db_prefix}qanda
800
					SET lngfile = {string:lngfile},
801
						question = {string:question},
802
						answers = {string:answers}
803
					WHERE id_question = {int:id_question}',
804
					array(
805
						'id_question' => $q_id,
806
						'lngfile' => $question['lngfile'],
807
						'question' => $question['question'],
808
						'answers' => $question['answers'],
809
					)
810
				);
811
			}
812
		}
813
814
		if (!empty($changes['insert']))
815
		{
816
			$smcFunc['db_insert']('insert',
817
				'{db_prefix}qanda',
818
				array('lngfile' => 'string-50', 'question' => 'string-255', 'answers' => 'string-65534'),
819
				$changes['insert'],
820
				array('id_question')
821
			);
822
		}
823
824
		// Lastly, the count of messages needs to be no more than the lowest number of questions for any one language.
825
		$count_questions = empty($qs_per_lang) ? 0 : min($qs_per_lang);
826
		if (empty($count_questions) || $_POST['qa_verification_number'] > $count_questions)
827
			$_POST['qa_verification_number'] = $count_questions;
828
829
		call_integration_hook('integrate_save_spam_settings', array(&$save_vars));
830
831
		// Now save.
832
		saveDBSettings($save_vars);
833
		$_SESSION['adm-save'] = true;
834
835
		cache_put_data('verificationQuestions', null, 300);
836
837
		redirectexit('action=admin;area=antispam');
838
	}
839
840
	$character_range = array_merge(range('A', 'H'), array('K', 'M', 'N', 'P', 'R'), range('T', 'Y'));
841
	$_SESSION['visual_verification_code'] = '';
842
	for ($i = 0; $i < 6; $i++)
843
		$_SESSION['visual_verification_code'] .= $character_range[array_rand($character_range)];
844
845
	// Some javascript for CAPTCHA.
846
	$context['settings_post_javascript'] = '';
847
	if ($context['use_graphic_library'])
848
		$context['settings_post_javascript'] .= '
849
		function refreshImages()
850
		{
851
			var imageType = document.getElementById(\'visual_verification_type\').value;
852
			document.getElementById(\'verification_image\').src = \'' . $context['verification_image_href'] . ';type=\' + imageType;
853
		}';
854
855
	// Show the image itself, or text saying we can't.
856
	if ($context['use_graphic_library'])
857
		$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>';
858
	else
859
		$config_vars['vv']['postinput'] = '<br><span class="smalltext">' . $txt['setting_image_verification_nogd'] . '</span>';
860
861
	// Hack for PM spam settings.
862
	list ($modSettings['max_pm_recipients'], $modSettings['pm_posts_verification'], $modSettings['pm_posts_per_hour']) = explode(',', $modSettings['pm_spam_settings']);
863
864
	// Hack for guests requiring verification.
865
	$modSettings['guests_require_captcha'] = !empty($modSettings['posts_require_captcha']);
866
	$modSettings['posts_require_captcha'] = !isset($modSettings['posts_require_captcha']) || $modSettings['posts_require_captcha'] == -1 ? 0 : $modSettings['posts_require_captcha'];
867
868
	// Some minor javascript for the guest post setting.
869
	if ($modSettings['posts_require_captcha'])
870
		$context['settings_post_javascript'] .= '
871
		document.getElementById(\'guests_require_captcha\').disabled = true;';
872
873
	// And everything else.
874
	$context['post_url'] = $scripturl . '?action=admin;area=antispam;save';
875
	$context['settings_title'] = $txt['antispam_Settings'];
876
	$context['page_title'] = $txt['antispam_title'];
877
	$context['sub_template'] = 'show_settings';
878
879
	$context[$context['admin_menu_name']]['tab_data'] = array(
880
		'title' => $txt['antispam_title'],
881
		'description' => $txt['antispam_Settings_desc'],
882
	);
883
884
	prepareDBSettingContext($config_vars);
885
}
886
887
/**
888
 * You'll never guess what this function does...
889
 *
890
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
891
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
892
 */
893
function ModifySignatureSettings($return_config = false)
894
{
895
	global $context, $txt, $modSettings, $sig_start, $smcFunc, $scripturl;
896
897
	$config_vars = array(
898
			// Are signatures even enabled?
899
			array('check', 'signature_enable'),
900
		'',
901
			// Tweaking settings!
902
			array('int', 'signature_max_length', 'subtext' => $txt['zero_for_no_limit']),
903
			array('int', 'signature_max_lines', 'subtext' => $txt['zero_for_no_limit']),
904
			array('int', 'signature_max_font_size', 'subtext' => $txt['zero_for_no_limit']),
905
			array('check', 'signature_allow_smileys', 'onclick' => 'document.getElementById(\'signature_max_smileys\').disabled = !this.checked;'),
906
			array('int', 'signature_max_smileys', 'subtext' => $txt['zero_for_no_limit']),
907
		'',
908
			// Image settings.
909
			array('int', 'signature_max_images', 'subtext' => $txt['signature_max_images_note']),
910
			array('int', 'signature_max_image_width', 'subtext' => $txt['zero_for_no_limit']),
911
			array('int', 'signature_max_image_height', 'subtext' => $txt['zero_for_no_limit']),
912
		'',
913
			array('bbc', 'signature_bbc'),
914
	);
915
916
	call_integration_hook('integrate_signature_settings', array(&$config_vars));
917
918
	if ($return_config)
919
		return $config_vars;
920
921
	// Setup the template.
922
	$context['page_title'] = $txt['signature_settings'];
923
	$context['sub_template'] = 'show_settings';
924
925
	// Disable the max smileys option if we don't allow smileys at all!
926
	$context['settings_post_javascript'] = 'document.getElementById(\'signature_max_smileys\').disabled = !document.getElementById(\'signature_allow_smileys\').checked;';
927
928
	// Load all the signature settings.
929
	list ($sig_limits, $sig_bbc) = explode(':', $modSettings['signature_settings']);
930
	$sig_limits = explode(',', $sig_limits);
931
	$disabledTags = !empty($sig_bbc) ? explode(',', $sig_bbc) : array();
932
933
	// Applying to ALL signatures?!!
934
	if (isset($_GET['apply']))
935
	{
936
		// Security!
937
		checkSession('get');
938
939
		$sig_start = time();
940
		// This is horrid - but I suppose some people will want the option to do it.
941
		$_GET['step'] = isset($_GET['step']) ? (int) $_GET['step'] : 0;
942
		$done = false;
943
944
		$request = $smcFunc['db_query']('', '
945
			SELECT MAX(id_member)
946
			FROM {db_prefix}members',
947
			array(
948
			)
949
		);
950
		list ($context['max_member']) = $smcFunc['db_fetch_row']($request);
951
		$smcFunc['db_free_result']($request);
952
953
		while (!$done)
954
		{
955
			$changes = array();
956
957
			$request = $smcFunc['db_query']('', '
958
				SELECT id_member, signature
959
				FROM {db_prefix}members
960
				WHERE id_member BETWEEN {int:step} AND {int:step} + 49
961
					AND id_group != {int:admin_group}
962
					AND FIND_IN_SET({int:admin_group}, additional_groups) = 0',
963
				array(
964
					'admin_group' => 1,
965
					'step' => $_GET['step'],
966
				)
967
			);
968
			while ($row = $smcFunc['db_fetch_assoc']($request))
969
			{
970
				// Apply all the rules we can realistically do.
971
				$sig = strtr($row['signature'], array('<br>' => "\n"));
972
973
				// Max characters...
974
				if (!empty($sig_limits[1]))
975
					$sig = $smcFunc['substr']($sig, 0, $sig_limits[1]);
976
				// Max lines...
977
				if (!empty($sig_limits[2]))
978
				{
979
					$count = 0;
980
					for ($i = 0; $i < strlen($sig); $i++)
981
					{
982
						if ($sig[$i] == "\n")
983
						{
984
							$count++;
985
							if ($count >= $sig_limits[2])
986
								$sig = substr($sig, 0, $i) . strtr(substr($sig, $i), array("\n" => ' '));
987
						}
988
					}
989
				}
990
991
				if (!empty($sig_limits[7]) && preg_match_all('~\[size=([\d\.]+)?(px|pt|em|x-large|larger)~i', $sig, $matches) !== false && isset($matches[2]))
992
				{
993
					foreach ($matches[1] as $ind => $size)
994
					{
995
						$limit_broke = 0;
996
						// Attempt to allow all sizes of abuse, so to speak.
997
						if ($matches[2][$ind] == 'px' && $size > $sig_limits[7])
998
							$limit_broke = $sig_limits[7] . 'px';
999
						elseif ($matches[2][$ind] == 'pt' && $size > ($sig_limits[7] * 0.75))
1000
							$limit_broke = ((int) $sig_limits[7] * 0.75) . 'pt';
1001
						elseif ($matches[2][$ind] == 'em' && $size > ((float) $sig_limits[7] / 16))
1002
							$limit_broke = ((float) $sig_limits[7] / 16) . 'em';
1003
						elseif ($matches[2][$ind] != 'px' && $matches[2][$ind] != 'pt' && $matches[2][$ind] != 'em' && $sig_limits[7] < 18)
1004
							$limit_broke = 'large';
1005
1006
						if ($limit_broke)
1007
							$sig = str_replace($matches[0][$ind], '[size=' . $sig_limits[7] . 'px', $sig);
1008
					}
1009
				}
1010
1011
				// Stupid images - this is stupidly, stupidly challenging.
1012
				if ((!empty($sig_limits[3]) || !empty($sig_limits[5]) || !empty($sig_limits[6])))
1013
				{
1014
					$replaces = array();
1015
					$img_count = 0;
1016
					// Get all BBC tags...
1017
					preg_match_all('~\[img(\s+width=([\d]+))?(\s+height=([\d]+))?(\s+width=([\d]+))?\s*\](?:<br>)*([^<">]+?)(?:<br>)*\[/img\]~i', $sig, $matches);
1018
					// ... and all HTML ones.
1019
					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);
1020
					// And stick the HTML in the BBC.
1021
					if (!empty($matches2))
1022
					{
1023
						foreach ($matches2[0] as $ind => $dummy)
1024
						{
1025
							$matches[0][] = $matches2[0][$ind];
1026
							$matches[1][] = '';
1027
							$matches[2][] = '';
1028
							$matches[3][] = '';
1029
							$matches[4][] = '';
1030
							$matches[5][] = '';
1031
							$matches[6][] = '';
1032
							$matches[7][] = $matches2[1][$ind];
1033
						}
1034
					}
1035
					// Try to find all the images!
1036
					if (!empty($matches))
1037
					{
1038
						$image_count_holder = array();
1039
						foreach ($matches[0] as $key => $image)
1040
						{
1041
							$width = -1; $height = -1;
1042
							$img_count++;
1043
							// Too many images?
1044
							if (!empty($sig_limits[3]) && $img_count > $sig_limits[3])
1045
							{
1046
								// If we've already had this before we only want to remove the excess.
1047
								if (isset($image_count_holder[$image]))
1048
								{
1049
									$img_offset = -1;
1050
									$rep_img_count = 0;
1051
									while ($img_offset !== false)
1052
									{
1053
										$img_offset = strpos($sig, $image, $img_offset + 1);
1054
										$rep_img_count++;
1055
										if ($rep_img_count > $image_count_holder[$image])
1056
										{
1057
											// Only replace the excess.
1058
											$sig = substr($sig, 0, $img_offset) . str_replace($image, '', substr($sig, $img_offset));
1059
											// Stop looping.
1060
											$img_offset = false;
1061
										}
1062
									}
1063
								}
1064
								else
1065
									$replaces[$image] = '';
1066
1067
								continue;
1068
							}
1069
1070
							// Does it have predefined restraints? Width first.
1071
							if ($matches[6][$key])
1072
								$matches[2][$key] = $matches[6][$key];
1073
							if ($matches[2][$key] && $sig_limits[5] && $matches[2][$key] > $sig_limits[5])
1074
							{
1075
								$width = $sig_limits[5];
1076
								$matches[4][$key] = $matches[4][$key] * ($width / $matches[2][$key]);
1077
							}
1078
							elseif ($matches[2][$key])
1079
								$width = $matches[2][$key];
1080
							// ... and height.
1081
							if ($matches[4][$key] && $sig_limits[6] && $matches[4][$key] > $sig_limits[6])
1082
							{
1083
								$height = $sig_limits[6];
1084
								if ($width != -1)
1085
									$width = $width * ($height / $matches[4][$key]);
1086
							}
1087
							elseif ($matches[4][$key])
1088
								$height = $matches[4][$key];
1089
1090
							// If the dimensions are still not fixed - we need to check the actual image.
1091
							if (($width == -1 && $sig_limits[5]) || ($height == -1 && $sig_limits[6]))
1092
							{
1093
								$sizes = url_image_size($matches[7][$key]);
1094
								if (is_array($sizes))
1095
								{
1096
									// Too wide?
1097
									if ($sizes[0] > $sig_limits[5] && $sig_limits[5])
1098
									{
1099
										$width = $sig_limits[5];
1100
										$sizes[1] = $sizes[1] * ($width / $sizes[0]);
1101
									}
1102
									// Too high?
1103
									if ($sizes[1] > $sig_limits[6] && $sig_limits[6])
1104
									{
1105
										$height = $sig_limits[6];
1106
										if ($width == -1)
1107
											$width = $sizes[0];
1108
										$width = $width * ($height / $sizes[1]);
1109
									}
1110
									elseif ($width != -1)
1111
										$height = $sizes[1];
1112
								}
1113
							}
1114
1115
							// Did we come up with some changes? If so remake the string.
1116
							if ($width != -1 || $height != -1)
1117
							{
1118
								$replaces[$image] = '[img' . ($width != -1 ? ' width=' . round($width) : '') . ($height != -1 ? ' height=' . round($height) : '') . ']' . $matches[7][$key] . '[/img]';
1119
							}
1120
1121
							// Record that we got one.
1122
							$image_count_holder[$image] = isset($image_count_holder[$image]) ? $image_count_holder[$image] + 1 : 1;
1123
						}
1124
						if (!empty($replaces))
1125
							$sig = str_replace(array_keys($replaces), array_values($replaces), $sig);
1126
					}
1127
				}
1128
				// Try to fix disabled tags.
1129
				if (!empty($disabledTags))
1130
				{
1131
					$sig = preg_replace('~\[(?:' . implode('|', $disabledTags) . ').+?\]~i', '', $sig);
1132
					$sig = preg_replace('~\[/(?:' . implode('|', $disabledTags) . ')\]~i', '', $sig);
1133
				}
1134
1135
				$sig = strtr($sig, array("\n" => '<br>'));
1136
				call_integration_hook('integrate_apply_signature_settings', array(&$sig, $sig_limits, $disabledTags));
1137
				if ($sig != $row['signature'])
1138
					$changes[$row['id_member']] = $sig;
1139
			}
1140
			if ($smcFunc['db_num_rows']($request) == 0)
1141
				$done = true;
1142
			$smcFunc['db_free_result']($request);
1143
1144
			// Do we need to delete what we have?
1145
			if (!empty($changes))
1146
			{
1147
				foreach ($changes as $id => $sig)
1148
					$smcFunc['db_query']('', '
1149
						UPDATE {db_prefix}members
1150
						SET signature = {string:signature}
1151
						WHERE id_member = {int:id_member}',
1152
						array(
1153
							'id_member' => $id,
1154
							'signature' => $sig,
1155
						)
1156
					);
1157
			}
1158
1159
			$_GET['step'] += 50;
1160
			if (!$done)
1161
				pauseSignatureApplySettings();
1162
		}
1163
		$settings_applied = true;
1164
	}
1165
1166
	$context['signature_settings'] = array(
1167
		'enable' => isset($sig_limits[0]) ? $sig_limits[0] : 0,
1168
		'max_length' => isset($sig_limits[1]) ? $sig_limits[1] : 0,
1169
		'max_lines' => isset($sig_limits[2]) ? $sig_limits[2] : 0,
1170
		'max_images' => isset($sig_limits[3]) ? $sig_limits[3] : 0,
1171
		'allow_smileys' => isset($sig_limits[4]) && $sig_limits[4] == -1 ? 0 : 1,
1172
		'max_smileys' => isset($sig_limits[4]) && $sig_limits[4] != -1 ? $sig_limits[4] : 0,
1173
		'max_image_width' => isset($sig_limits[5]) ? $sig_limits[5] : 0,
1174
		'max_image_height' => isset($sig_limits[6]) ? $sig_limits[6] : 0,
1175
		'max_font_size' => isset($sig_limits[7]) ? $sig_limits[7] : 0,
1176
	);
1177
1178
	// Temporarily make each setting a modSetting!
1179
	foreach ($context['signature_settings'] as $key => $value)
1180
		$modSettings['signature_' . $key] = $value;
1181
1182
	// Make sure we check the right tags!
1183
	$modSettings['bbc_disabled_signature_bbc'] = $disabledTags;
1184
1185
	// Saving?
1186
	if (isset($_GET['save']))
1187
	{
1188
		checkSession();
1189
1190
		// Clean up the tag stuff!
1191
		$bbcTags = array();
1192
		foreach (parse_bbc(false) as $tag)
1193
			$bbcTags[] = $tag['tag'];
1194
1195
		if (!isset($_POST['signature_bbc_enabledTags']))
1196
			$_POST['signature_bbc_enabledTags'] = array();
1197
		elseif (!is_array($_POST['signature_bbc_enabledTags']))
1198
			$_POST['signature_bbc_enabledTags'] = array($_POST['signature_bbc_enabledTags']);
1199
1200
		$sig_limits = array();
1201
		foreach ($context['signature_settings'] as $key => $value)
1202
		{
1203
			if ($key == 'allow_smileys')
1204
				continue;
1205
			elseif ($key == 'max_smileys' && empty($_POST['signature_allow_smileys']))
1206
				$sig_limits[] = -1;
1207
			else
1208
				$sig_limits[] = !empty($_POST['signature_' . $key]) ? max(1, (int) $_POST['signature_' . $key]) : 0;
1209
		}
1210
1211
		call_integration_hook('integrate_save_signature_settings', array(&$sig_limits, &$bbcTags));
1212
1213
		$_POST['signature_settings'] = implode(',', $sig_limits) . ':' . implode(',', array_diff($bbcTags, $_POST['signature_bbc_enabledTags']));
1214
1215
		// Even though we have practically no settings let's keep the convention going!
1216
		$save_vars = array();
1217
		$save_vars[] = array('text', 'signature_settings');
1218
1219
		saveDBSettings($save_vars);
1220
		$_SESSION['adm-save'] = true;
1221
		redirectexit('action=admin;area=featuresettings;sa=sig');
1222
	}
1223
1224
	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=sig';
1225
	$context['settings_title'] = $txt['signature_settings'];
1226
1227
	$context['settings_message'] = !empty($settings_applied) ? '<div class="infobox">' . $txt['signature_settings_applied'] . '</div>' : '<p class="centertext">' . sprintf($txt['signature_settings_warning'], $context['session_id'], $context['session_var']) . '</p>';
1228
1229
	prepareDBSettingContext($config_vars);
1230
}
1231
1232
/**
1233
 * Just pause the signature applying thing.
1234
 */
1235
function pauseSignatureApplySettings()
1236
{
1237
	global $context, $txt, $sig_start;
1238
1239
	// Try get more time...
1240
	@set_time_limit(600);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for set_time_limit(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

1240
	/** @scrutinizer ignore-unhandled */ @set_time_limit(600);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1241
	if (function_exists('apache_reset_timeout'))
1242
		@apache_reset_timeout();
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for apache_reset_timeout(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

1242
		/** @scrutinizer ignore-unhandled */ @apache_reset_timeout();

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1243
1244
	// Have we exhausted all the time we allowed?
1245
	if (time() - array_sum(explode(' ', $sig_start)) < 3)
1246
		return;
1247
1248
	$context['continue_get_data'] = '?action=admin;area=featuresettings;sa=sig;apply;step=' . $_GET['step'] . ';' . $context['session_var'] . '=' . $context['session_id'];
1249
	$context['page_title'] = $txt['not_done_title'];
1250
	$context['continue_post_data'] = '';
1251
	$context['continue_countdown'] = '2';
1252
	$context['sub_template'] = 'not_done';
1253
1254
	// Specific stuff to not break this template!
1255
	$context[$context['admin_menu_name']]['current_subsection'] = 'sig';
1256
1257
	// Get the right percent.
1258
	$context['continue_percent'] = round(($_GET['step'] / $context['max_member']) * 100);
1259
1260
	// Never more than 100%!
1261
	$context['continue_percent'] = min($context['continue_percent'], 100);
1262
1263
	obExit();
1264
}
1265
1266
/**
1267
 * Show all the custom profile fields available to the user.
1268
 */
1269
function ShowCustomProfiles()
1270
{
1271
	global $txt, $scripturl, $context;
1272
	global $sourcedir;
1273
1274
	$context['page_title'] = $txt['custom_profile_title'];
1275
	$context['sub_template'] = 'show_custom_profile';
1276
1277
	// What about standard fields they can tweak?
1278
	$standard_fields = array('website', 'personal_text', 'timezone', 'posts', 'warning_status');
1279
	// What fields can't you put on the registration page?
1280
	$context['fields_no_registration'] = array('posts', 'warning_status');
1281
1282
	// Are we saving any standard field changes?
1283
	if (isset($_POST['save']))
1284
	{
1285
		checkSession();
1286
		validateToken('admin-scp');
1287
1288
		// Do the active ones first.
1289
		$disable_fields = array_flip($standard_fields);
1290
		if (!empty($_POST['active']))
1291
		{
1292
			foreach ($_POST['active'] as $value)
1293
				if (isset($disable_fields[$value]))
1294
					unset($disable_fields[$value]);
1295
		}
1296
		// What we have left!
1297
		$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...
1298
1299
		// Things we want to show on registration?
1300
		$reg_fields = array();
1301
		if (!empty($_POST['reg']))
1302
		{
1303
			foreach ($_POST['reg'] as $value)
1304
				if (in_array($value, $standard_fields) && !isset($disable_fields[$value]))
1305
					$reg_fields[] = $value;
1306
		}
1307
		// What we have left!
1308
		$changes['registration_fields'] = empty($reg_fields) ? '' : implode(',', $reg_fields);
1309
1310
		$_SESSION['adm-save'] = true;
1311
		if (!empty($changes))
1312
			updateSettings($changes);
1313
	}
1314
1315
	createToken('admin-scp');
1316
1317
	// Need to know the max order for custom fields
1318
	$context['custFieldsMaxOrder'] = custFieldsMaxOrder();
1319
1320
	require_once($sourcedir . '/Subs-List.php');
1321
1322
	$listOptions = array(
1323
		'id' => 'standard_profile_fields',
1324
		'title' => $txt['standard_profile_title'],
1325
		'base_href' => $scripturl . '?action=admin;area=featuresettings;sa=profile',
1326
		'get_items' => array(
1327
			'function' => 'list_getProfileFields',
1328
			'params' => array(
1329
				true,
1330
			),
1331
		),
1332
		'columns' => array(
1333
			'field' => array(
1334
				'header' => array(
1335
					'value' => $txt['standard_profile_field'],
1336
				),
1337
				'data' => array(
1338
					'db' => 'label',
1339
					'style' => 'width: 60%;',
1340
				),
1341
			),
1342
			'active' => array(
1343
				'header' => array(
1344
					'value' => $txt['custom_edit_active'],
1345
					'class' => 'centercol',
1346
				),
1347
				'data' => array(
1348
					'function' => function ($rowData)
1349
					{
1350
						$isChecked = $rowData['disabled'] ? '' : ' checked';
1351
						$onClickHandler = $rowData['can_show_register'] ? sprintf(' onclick="document.getElementById(\'reg_%1$s\').disabled = !this.checked;"', $rowData['id']) : '';
1352
						return sprintf('<input type="checkbox" name="active[]" id="active_%1$s" value="%1$s" %2$s%3$s>', $rowData['id'], $isChecked, $onClickHandler);
1353
					},
1354
					'style' => 'width: 20%;',
1355
					'class' => 'centercol',
1356
				),
1357
			),
1358
			'show_on_registration' => array(
1359
				'header' => array(
1360
					'value' => $txt['custom_edit_registration'],
1361
					'class' => 'centercol',
1362
				),
1363
				'data' => array(
1364
					'function' => function ($rowData)
1365
					{
1366
						$isChecked = $rowData['on_register'] && !$rowData['disabled'] ? ' checked' : '';
1367
						$isDisabled = $rowData['can_show_register'] ? '' : ' disabled';
1368
						return sprintf('<input type="checkbox" name="reg[]" id="reg_%1$s" value="%1$s" %2$s%3$s>', $rowData['id'], $isChecked, $isDisabled);
1369
					},
1370
					'style' => 'width: 20%;',
1371
					'class' => 'centercol',
1372
				),
1373
			),
1374
		),
1375
		'form' => array(
1376
			'href' => $scripturl . '?action=admin;area=featuresettings;sa=profile',
1377
			'name' => 'standardProfileFields',
1378
			'token' => 'admin-scp',
1379
		),
1380
		'additional_rows' => array(
1381
			array(
1382
				'position' => 'below_table_data',
1383
				'value' => '<input type="submit" name="save" value="' . $txt['save'] . '" class="button">',
1384
			),
1385
		),
1386
	);
1387
	createList($listOptions);
1388
1389
	$listOptions = array(
1390
		'id' => 'custom_profile_fields',
1391
		'title' => $txt['custom_profile_title'],
1392
		'base_href' => $scripturl . '?action=admin;area=featuresettings;sa=profile',
1393
		'default_sort_col' => 'field_order',
1394
		'no_items_label' => $txt['custom_profile_none'],
1395
		'items_per_page' => 25,
1396
		'get_items' => array(
1397
			'function' => 'list_getProfileFields',
1398
			'params' => array(
1399
				false,
1400
			),
1401
		),
1402
		'get_count' => array(
1403
			'function' => 'list_getProfileFieldSize',
1404
		),
1405
		'columns' => array(
1406
			'field_order' => array(
1407
				'header' => array(
1408
					'value' => $txt['custom_profile_fieldorder'],
1409
				),
1410
				'data' => array(
1411
					'function' => function ($rowData) use ($context, $txt, $scripturl)
1412
					{
1413
						$return = '<p class="centertext bold_text">'. $rowData['field_order'] .'<br>';
1414
1415
						if ($rowData['field_order'] > 1)
1416
							$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>';
1417
1418
						if ($rowData['field_order'] < $context['custFieldsMaxOrder'])
1419
							$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>';
1420
1421
						$return .= '</p>';
1422
1423
						return $return;
1424
					},
1425
					'style' => 'width: 12%;',
1426
				),
1427
				'sort' => array(
1428
					'default' => 'field_order',
1429
					'reverse' => 'field_order DESC',
1430
				),
1431
			),
1432
			'field_name' => array(
1433
				'header' => array(
1434
					'value' => $txt['custom_profile_fieldname'],
1435
				),
1436
				'data' => array(
1437
					'function' => function ($rowData) use ($scripturl)
1438
					{
1439
						return sprintf('<a href="%1$s?action=admin;area=featuresettings;sa=profileedit;fid=%2$d">%3$s</a><div class="smalltext">%4$s</div>', $scripturl, $rowData['id_field'], $rowData['field_name'], $rowData['field_desc']);
1440
					},
1441
					'style' => 'width: 62%;',
1442
				),
1443
				'sort' => array(
1444
					'default' => 'field_name',
1445
					'reverse' => 'field_name DESC',
1446
				),
1447
			),
1448
			'field_type' => array(
1449
				'header' => array(
1450
					'value' => $txt['custom_profile_fieldtype'],
1451
				),
1452
				'data' => array(
1453
					'function' => function ($rowData) use ($txt)
1454
					{
1455
						$textKey = sprintf('custom_profile_type_%1$s', $rowData['field_type']);
1456
						return isset($txt[$textKey]) ? $txt[$textKey] : $textKey;
1457
					},
1458
					'style' => 'width: 15%;',
1459
				),
1460
				'sort' => array(
1461
					'default' => 'field_type',
1462
					'reverse' => 'field_type DESC',
1463
				),
1464
			),
1465
			'active' => array(
1466
				'header' => array(
1467
					'value' => $txt['custom_profile_active'],
1468
				),
1469
				'data' => array(
1470
					'function' => function ($rowData) use ($txt)
1471
					{
1472
						return $rowData['active'] ? $txt['yes'] : $txt['no'];
1473
					},
1474
					'style' => 'width: 8%;',
1475
				),
1476
				'sort' => array(
1477
					'default' => 'active DESC',
1478
					'reverse' => 'active',
1479
				),
1480
			),
1481
			'placement' => array(
1482
				'header' => array(
1483
					'value' => $txt['custom_profile_placement'],
1484
				),
1485
				'data' => array(
1486
					'function' => function ($rowData)
1487
					{
1488
						global $txt, $context;
1489
1490
						return $txt['custom_profile_placement_' . (empty($rowData['placement']) ? 'standard' : $context['cust_profile_fields_placement'][$rowData['placement']])];
1491
					},
1492
					'style' => 'width: 8%;',
1493
				),
1494
				'sort' => array(
1495
					'default' => 'placement DESC',
1496
					'reverse' => 'placement',
1497
				),
1498
			),
1499
			'show_on_registration' => array(
1500
				'data' => array(
1501
					'sprintf' => array(
1502
						'format' => '<a href="' . $scripturl . '?action=admin;area=featuresettings;sa=profileedit;fid=%1$s">' . $txt['modify'] . '</a>',
1503
						'params' => array(
1504
							'id_field' => false,
1505
						),
1506
					),
1507
					'style' => 'width: 15%;',
1508
				),
1509
			),
1510
		),
1511
		'form' => array(
1512
			'href' => $scripturl . '?action=admin;area=featuresettings;sa=profileedit',
1513
			'name' => 'customProfileFields',
1514
		),
1515
		'additional_rows' => array(
1516
			array(
1517
				'position' => 'below_table_data',
1518
				'value' => '<input type="submit" name="new" value="' . $txt['custom_profile_make_new'] . '" class="button">',
1519
			),
1520
		),
1521
	);
1522
	createList($listOptions);
1523
1524
	// There are two different ways we could get to this point. To keep it simple, they both do
1525
	// the same basic thing.
1526
	if (isset($_SESSION['adm-save']))
1527
	{
1528
		$context['saved_successful'] = true;
1529
		unset ($_SESSION['adm-save']);
1530
	}
1531
}
1532
1533
/**
1534
 * Callback for createList().
1535
 * @param int $start The item to start with (used for pagination purposes)
1536
 * @param int $items_per_page The number of items to display per page
1537
 * @param string $sort A string indicating how to sort the results
1538
 * @param bool $standardFields Whether or not to include standard fields as well
1539
 * @return array An array of info about the various profile fields
1540
 */
1541
function list_getProfileFields($start, $items_per_page, $sort, $standardFields)
1542
{
1543
	global $txt, $modSettings, $smcFunc;
1544
1545
	$list = array();
1546
1547
	if ($standardFields)
1548
	{
1549
		$standard_fields = array('website', 'personal_text', 'timezone', 'posts', 'warning_status');
1550
		$fields_no_registration = array('posts', 'warning_status');
1551
		$disabled_fields = isset($modSettings['disabled_profile_fields']) ? explode(',', $modSettings['disabled_profile_fields']) : array();
1552
		$registration_fields = isset($modSettings['registration_fields']) ? explode(',', $modSettings['registration_fields']) : array();
1553
1554
		foreach ($standard_fields as $field)
1555
			$list[] = array(
1556
				'id' => $field,
1557
				'label' => isset($txt['standard_profile_field_' . $field]) ? $txt['standard_profile_field_' . $field] : (isset($txt[$field]) ? $txt[$field] : $field),
1558
				'disabled' => in_array($field, $disabled_fields),
1559
				'on_register' => in_array($field, $registration_fields) && !in_array($field, $fields_no_registration),
1560
				'can_show_register' => !in_array($field, $fields_no_registration),
1561
			);
1562
	}
1563
	else
1564
	{
1565
		// Load all the fields.
1566
		$request = $smcFunc['db_query']('', '
1567
			SELECT id_field, col_name, field_name, field_desc, field_type, field_order, active, placement
1568
			FROM {db_prefix}custom_fields
1569
			ORDER BY {raw:sort}
1570
			LIMIT {int:start}, {int:items_per_page}',
1571
			array(
1572
				'sort' => $sort,
1573
				'start' => $start,
1574
				'items_per_page' => $items_per_page,
1575
			)
1576
		);
1577
		while ($row = $smcFunc['db_fetch_assoc']($request))
1578
			$list[] = $row;
1579
		$smcFunc['db_free_result']($request);
1580
	}
1581
1582
	return $list;
1583
}
1584
1585
/**
1586
 * Callback for createList().
1587
 * @return int The total number of custom profile fields
1588
 */
1589
function list_getProfileFieldSize()
1590
{
1591
	global $smcFunc;
1592
1593
	$request = $smcFunc['db_query']('', '
1594
		SELECT COUNT(*)
1595
		FROM {db_prefix}custom_fields',
1596
		array(
1597
		)
1598
	);
1599
1600
	list ($numProfileFields) = $smcFunc['db_fetch_row']($request);
1601
	$smcFunc['db_free_result']($request);
1602
1603
	return $numProfileFields;
1604
}
1605
1606
/**
1607
 * Edit some profile fields?
1608
 */
1609
function EditCustomProfiles()
1610
{
1611
	global $txt, $scripturl, $context, $smcFunc;
1612
1613
	// Sort out the context!
1614
	$context['fid'] = isset($_GET['fid']) ? (int) $_GET['fid'] : 0;
1615
	$context[$context['admin_menu_name']]['current_subsection'] = 'profile';
1616
	$context['page_title'] = $context['fid'] ? $txt['custom_edit_title'] : $txt['custom_add_title'];
1617
	$context['sub_template'] = 'edit_profile_field';
1618
1619
	// Load the profile language for section names.
1620
	loadLanguage('Profile');
1621
1622
	// There's really only a few places we can go...
1623
	$move_to = array('up', 'down');
1624
1625
	// We need this for both moving and saving so put it right here.
1626
	$order_count = custFieldsMaxOrder();
1627
1628
	if ($context['fid'])
1629
	{
1630
		$request = $smcFunc['db_query']('', '
1631
			SELECT
1632
				id_field, col_name, field_name, field_desc, field_type, field_order, field_length, field_options,
1633
				show_reg, show_display, show_mlist, show_profile, private, active, default_value, can_search,
1634
				bbc, mask, enclose, placement
1635
			FROM {db_prefix}custom_fields
1636
			WHERE id_field = {int:current_field}',
1637
			array(
1638
				'current_field' => $context['fid'],
1639
			)
1640
		);
1641
		$context['field'] = array();
1642
		while ($row = $smcFunc['db_fetch_assoc']($request))
1643
		{
1644
			if ($row['field_type'] == 'textarea')
1645
				@list ($rows, $cols) = @explode(',', $row['default_value']);
1646
			else
1647
			{
1648
				$rows = 3;
1649
				$cols = 30;
1650
			}
1651
1652
			$context['field'] = array(
1653
				'name' => $row['field_name'],
1654
				'desc' => $row['field_desc'],
1655
				'col_name' => $row['col_name'],
1656
				'profile_area' => $row['show_profile'],
1657
				'reg' => $row['show_reg'],
1658
				'display' => $row['show_display'],
1659
				'mlist' => $row['show_mlist'],
1660
				'type' => $row['field_type'],
1661
				'order' => $row['field_order'],
1662
				'max_length' => $row['field_length'],
1663
				'rows' => $rows,
1664
				'cols' => $cols,
1665
				'bbc' => $row['bbc'] ? true : false,
1666
				'default_check' => $row['field_type'] == 'check' && $row['default_value'] ? true : false,
1667
				'default_select' => $row['field_type'] == 'select' || $row['field_type'] == 'radio' ? $row['default_value'] : '',
1668
				'options' => strlen($row['field_options']) > 1 ? explode(',', $row['field_options']) : array('', '', ''),
1669
				'active' => $row['active'],
1670
				'private' => $row['private'],
1671
				'can_search' => $row['can_search'],
1672
				'mask' => $row['mask'],
1673
				'regex' => substr($row['mask'], 0, 5) == 'regex' ? substr($row['mask'], 5) : '',
1674
				'enclose' => $row['enclose'],
1675
				'placement' => $row['placement'],
1676
			);
1677
		}
1678
		$smcFunc['db_free_result']($request);
1679
	}
1680
1681
	// Setup the default values as needed.
1682
	if (empty($context['field']))
1683
		$context['field'] = array(
1684
			'name' => '',
1685
			'col_name' => '???',
1686
			'desc' => '',
1687
			'profile_area' => 'forumprofile',
1688
			'reg' => false,
1689
			'display' => false,
1690
			'mlist' => false,
1691
			'type' => 'text',
1692
			'order' => 0,
1693
			'max_length' => 255,
1694
			'rows' => 4,
1695
			'cols' => 30,
1696
			'bbc' => false,
1697
			'default_check' => false,
1698
			'default_select' => '',
1699
			'options' => array('', '', ''),
1700
			'active' => true,
1701
			'private' => false,
1702
			'can_search' => false,
1703
			'mask' => 'nohtml',
1704
			'regex' => '',
1705
			'enclose' => '',
1706
			'placement' => 0,
1707
		);
1708
1709
	// Are we moving it?
1710
	if (isset($_GET['move']) && in_array($smcFunc['htmlspecialchars']($_GET['move']), $move_to))
1711
	{
1712
		// Down is the new up.
1713
		$new_order = ($_GET['move'] == 'up' ? ($context['field']['order'] - 1) : ($context['field']['order'] + 1));
1714
1715
		// Is this a valid position?
1716
		if ($new_order <= 0 || $new_order > $order_count)
1717
			redirectexit('action=admin;area=featuresettings;sa=profile'); // @todo implement an error handler
1718
1719
		// All good, proceed.
1720
		$smcFunc['db_query']('','
1721
			UPDATE {db_prefix}custom_fields
1722
			SET field_order = {int:old_order}
1723
			WHERE field_order = {int:new_order}',
1724
			array(
1725
				'new_order' => $new_order,
1726
				'old_order' => $context['field']['order'],
1727
			)
1728
		);
1729
		$smcFunc['db_query']('','
1730
			UPDATE {db_prefix}custom_fields
1731
			SET field_order = {int:new_order}
1732
			WHERE id_field = {int:id_field}',
1733
			array(
1734
				'new_order' => $new_order,
1735
				'id_field' => $context['fid'],
1736
			)
1737
		);
1738
		redirectexit('action=admin;area=featuresettings;sa=profile'); // @todo perhaps a nice confirmation message, dunno.
1739
	}
1740
1741
	// Are we saving?
1742
	if (isset($_POST['save']))
1743
	{
1744
		checkSession();
1745
		validateToken('admin-ecp');
1746
1747
		// Everyone needs a name - even the (bracket) unknown...
1748
		if (trim($_POST['field_name']) == '')
1749
			redirectexit($scripturl . '?action=admin;area=featuresettings;sa=profileedit;fid=' . $_GET['fid'] . ';msg=need_name');
1750
1751
		// Regex you say?  Do a very basic test to see if the pattern is valid
1752
		if (!empty($_POST['regex']) && @preg_match($_POST['regex'], 'dummy') === false)
1753
			redirectexit($scripturl . '?action=admin;area=featuresettings;sa=profileedit;fid=' . $_GET['fid'] . ';msg=regex_error');
1754
1755
		$_POST['field_name'] = $smcFunc['htmlspecialchars']($_POST['field_name']);
1756
		$_POST['field_desc'] = $smcFunc['htmlspecialchars']($_POST['field_desc']);
1757
1758
		// Checkboxes...
1759
		$show_reg = isset($_POST['reg']) ? (int) $_POST['reg'] : 0;
1760
		$show_display = isset($_POST['display']) ? 1 : 0;
1761
		$show_mlist = isset($_POST['mlist']) ? 1 : 0;
1762
		$bbc = isset($_POST['bbc']) ? 1 : 0;
1763
		$show_profile = $_POST['profile_area'];
1764
		$active = isset($_POST['active']) ? 1 : 0;
1765
		$private = isset($_POST['private']) ? (int) $_POST['private'] : 0;
1766
		$can_search = isset($_POST['can_search']) ? 1 : 0;
1767
1768
		// Some masking stuff...
1769
		$mask = isset($_POST['mask']) ? $_POST['mask'] : '';
1770
		if ($mask == 'regex' && isset($_POST['regex']))
1771
			$mask .= $_POST['regex'];
1772
1773
		$field_length = isset($_POST['max_length']) ? (int) $_POST['max_length'] : 255;
1774
		$enclose = isset($_POST['enclose']) ? $_POST['enclose'] : '';
1775
		$placement = isset($_POST['placement']) ? (int) $_POST['placement'] : 0;
1776
1777
		// Select options?
1778
		$field_options = '';
1779
		$newOptions = array();
1780
		$default = isset($_POST['default_check']) && $_POST['field_type'] == 'check' ? 1 : '';
1781
		if (!empty($_POST['select_option']) && ($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio'))
1782
		{
1783
			foreach ($_POST['select_option'] as $k => $v)
1784
			{
1785
				// Clean, clean, clean...
1786
				$v = $smcFunc['htmlspecialchars']($v);
1787
				$v = strtr($v, array(',' => ''));
1788
1789
				// Nada, zip, etc...
1790
				if (trim($v) == '')
1791
					continue;
1792
1793
				// Otherwise, save it boy.
1794
				$field_options .= $v . ',';
1795
				// This is just for working out what happened with old options...
1796
				$newOptions[$k] = $v;
1797
1798
				// Is it default?
1799
				if (isset($_POST['default_select']) && $_POST['default_select'] == $k)
1800
					$default = $v;
1801
			}
1802
			$field_options = substr($field_options, 0, -1);
1803
		}
1804
1805
		// Text area has default has dimensions
1806
		if ($_POST['field_type'] == 'textarea')
1807
			$default = (int) $_POST['rows'] . ',' . (int) $_POST['cols'];
1808
1809
		// Come up with the unique name?
1810
		if (empty($context['fid']))
1811
		{
1812
			$col_name = $smcFunc['substr'](strtr($_POST['field_name'], array(' ' => '')), 0, 6);
1813
			preg_match('~([\w\d_-]+)~', $col_name, $matches);
1814
1815
			// If there is nothing to the name, then let's start out own - for foreign languages etc.
1816
			if (isset($matches[1]))
1817
				$col_name = $initial_col_name = 'cust_' . strtolower($matches[1]);
1818
			else
1819
				$col_name = $initial_col_name = 'cust_' . mt_rand(1, 9999);
1820
1821
			// Make sure this is unique.
1822
			$current_fields = array();
1823
			$request = $smcFunc['db_query']('', '
1824
				SELECT id_field, col_name
1825
				FROM {db_prefix}custom_fields');
1826
			while ($row = $smcFunc['db_fetch_assoc']($request))
1827
				$current_fields[$row['id_field']] = $row['col_name'];
1828
			$smcFunc['db_free_result']($request);
1829
1830
			$unique = false;
1831
			for ($i = 0; !$unique && $i < 9; $i ++)
1832
			{
1833
				if (!in_array($col_name, $current_fields))
1834
					$unique = true;
1835
				else
1836
					$col_name = $initial_col_name . $i;
1837
			}
1838
1839
			// Still not a unique column name? Leave it up to the user, then.
1840
			if (!$unique)
1841
				fatal_lang_error('custom_option_not_unique');
1842
		}
1843
		// Work out what to do with the user data otherwise...
1844
		else
1845
		{
1846
			// Anything going to check or select is pointless keeping - as is anything coming from check!
1847
			if (($_POST['field_type'] == 'check' && $context['field']['type'] != 'check')
1848
				|| (($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio') && $context['field']['type'] != 'select' && $context['field']['type'] != 'radio')
1849
				|| ($context['field']['type'] == 'check' && $_POST['field_type'] != 'check'))
1850
			{
1851
				$smcFunc['db_query']('', '
1852
					DELETE FROM {db_prefix}themes
1853
					WHERE variable = {string:current_column}
1854
						AND id_member > {int:no_member}',
1855
					array(
1856
						'no_member' => 0,
1857
						'current_column' => $context['field']['col_name'],
1858
					)
1859
				);
1860
			}
1861
			// Otherwise - if the select is edited may need to adjust!
1862
			elseif ($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio')
1863
			{
1864
				$optionChanges = array();
1865
				$takenKeys = array();
1866
				// Work out what's changed!
1867
				foreach ($context['field']['options'] as $k => $option)
1868
				{
1869
					if (trim($option) == '')
1870
						continue;
1871
1872
					// Still exists?
1873
					if (in_array($option, $newOptions))
1874
					{
1875
						$takenKeys[] = $k;
1876
						continue;
1877
					}
1878
				}
1879
1880
				// Finally - have we renamed it - or is it really gone?
1881
				foreach ($optionChanges as $k => $option)
1882
				{
1883
					// Just been renamed?
1884
					if (!in_array($k, $takenKeys) && !empty($newOptions[$k]))
1885
						$smcFunc['db_query']('', '
1886
							UPDATE {db_prefix}themes
1887
							SET value = {string:new_value}
1888
							WHERE variable = {string:current_column}
1889
								AND value = {string:old_value}
1890
								AND id_member > {int:no_member}',
1891
							array(
1892
								'no_member' => 0,
1893
								'new_value' => $newOptions[$k],
1894
								'current_column' => $context['field']['col_name'],
1895
								'old_value' => $option,
1896
							)
1897
						);
1898
				}
1899
			}
1900
			// @todo Maybe we should adjust based on new text length limits?
1901
		}
1902
1903
		// Do the insertion/updates.
1904
		if ($context['fid'])
1905
		{
1906
			$smcFunc['db_query']('', '
1907
				UPDATE {db_prefix}custom_fields
1908
				SET
1909
					field_name = {string:field_name}, field_desc = {string:field_desc},
1910
					field_type = {string:field_type}, field_length = {int:field_length},
1911
					field_options = {string:field_options}, show_reg = {int:show_reg},
1912
					show_display = {int:show_display}, show_mlist = {int:show_mlist}, show_profile = {string:show_profile},
1913
					private = {int:private}, active = {int:active}, default_value = {string:default_value},
1914
					can_search = {int:can_search}, bbc = {int:bbc}, mask = {string:mask},
1915
					enclose = {string:enclose}, placement = {int:placement}
1916
				WHERE id_field = {int:current_field}',
1917
				array(
1918
					'field_length' => $field_length,
1919
					'show_reg' => $show_reg,
1920
					'show_display' => $show_display,
1921
					'show_mlist' => $show_mlist,
1922
					'private' => $private,
1923
					'active' => $active,
1924
					'can_search' => $can_search,
1925
					'bbc' => $bbc,
1926
					'current_field' => $context['fid'],
1927
					'field_name' => $_POST['field_name'],
1928
					'field_desc' => $_POST['field_desc'],
1929
					'field_type' => $_POST['field_type'],
1930
					'field_options' => $field_options,
1931
					'show_profile' => $show_profile,
1932
					'default_value' => $default,
1933
					'mask' => $mask,
1934
					'enclose' => $enclose,
1935
					'placement' => $placement,
1936
				)
1937
			);
1938
1939
			// Just clean up any old selects - these are a pain!
1940
			if (($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio') && !empty($newOptions))
1941
				$smcFunc['db_query']('', '
1942
					DELETE FROM {db_prefix}themes
1943
					WHERE variable = {string:current_column}
1944
						AND value NOT IN ({array_string:new_option_values})
1945
						AND id_member > {int:no_member}',
1946
					array(
1947
						'no_member' => 0,
1948
						'new_option_values' => $newOptions,
1949
						'current_column' => $context['field']['col_name'],
1950
					)
1951
				);
1952
		}
1953
		else
1954
		{
1955
			// Gotta figure it out the order.
1956
			$new_order = $order_count > 1 ? ($order_count + 1) : 1;
1957
1958
			$smcFunc['db_insert']('',
1959
				'{db_prefix}custom_fields',
1960
				array(
1961
					'col_name' => 'string', 'field_name' => 'string', 'field_desc' => 'string',
1962
					'field_type' => 'string', 'field_length' => 'string', 'field_options' => 'string', 'field_order' => 'int',
1963
					'show_reg' => 'int', 'show_display' => 'int', 'show_mlist' => 'int', 'show_profile' => 'string',
1964
					'private' => 'int', 'active' => 'int', 'default_value' => 'string', 'can_search' => 'int',
1965
					'bbc' => 'int', 'mask' => 'string', 'enclose' => 'string', 'placement' => 'int',
1966
				),
1967
				array(
1968
					$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...
1969
					$_POST['field_type'], $field_length, $field_options, $new_order,
1970
					$show_reg, $show_display, $show_mlist, $show_profile,
1971
					$private, $active, $default, $can_search,
1972
					$bbc, $mask, $enclose, $placement,
1973
				),
1974
				array('id_field')
1975
			);
1976
		}
1977
	}
1978
	// Deleting?
1979
	elseif (isset($_POST['delete']) && $context['field']['col_name'])
1980
	{
1981
		checkSession();
1982
		validateToken('admin-ecp');
1983
1984
		// Delete the user data first.
1985
		$smcFunc['db_query']('', '
1986
			DELETE FROM {db_prefix}themes
1987
			WHERE variable = {string:current_column}
1988
				AND id_member > {int:no_member}',
1989
			array(
1990
				'no_member' => 0,
1991
				'current_column' => $context['field']['col_name'],
1992
			)
1993
		);
1994
		// Finally - the field itself is gone!
1995
		$smcFunc['db_query']('', '
1996
			DELETE FROM {db_prefix}custom_fields
1997
			WHERE id_field = {int:current_field}',
1998
			array(
1999
				'current_field' => $context['fid'],
2000
			)
2001
		);
2002
2003
		// Re-arrange the order.
2004
		$smcFunc['db_query']('','
2005
			UPDATE {db_prefix}custom_fields
2006
			SET field_order = field_order - 1
2007
			WHERE field_order > {int:current_order}',
2008
			array(
2009
				'current_order' => $context['field']['order'],
2010
			)
2011
		);
2012
	}
2013
2014
	// Rebuild display cache etc.
2015
	if (isset($_POST['delete']) || isset($_POST['save']))
2016
	{
2017
		checkSession();
2018
2019
		$request = $smcFunc['db_query']('', '
2020
			SELECT col_name, field_name, field_type, field_order, bbc, enclose, placement, show_mlist, field_options
2021
			FROM {db_prefix}custom_fields
2022
			WHERE show_display = {int:is_displayed}
2023
				AND active = {int:active}
2024
				AND private != {int:not_owner_only}
2025
				AND private != {int:not_admin_only}
2026
			ORDER BY field_order',
2027
			array(
2028
				'is_displayed' => 1,
2029
				'active' => 1,
2030
				'not_owner_only' => 2,
2031
				'not_admin_only' => 3,
2032
			)
2033
		);
2034
2035
		$fields = array();
2036
		while ($row = $smcFunc['db_fetch_assoc']($request))
2037
		{
2038
			$fields[] = array(
2039
				'col_name' => strtr($row['col_name'], array('|' => '', ';' => '')),
2040
				'title' => strtr($row['field_name'], array('|' => '', ';' => '')),
2041
				'type' => $row['field_type'],
2042
				'order' => $row['field_order'],
2043
				'bbc' => $row['bbc'] ? '1' : '0',
2044
				'placement' => !empty($row['placement']) ? $row['placement'] : '0',
2045
				'enclose' => !empty($row['enclose']) ? $row['enclose'] : '',
2046
				'mlist' => $row['show_mlist'],
2047
				'options' => (!empty($row['field_options']) ? explode(',', $row['field_options']) : array()),
2048
			);
2049
		}
2050
		$smcFunc['db_free_result']($request);
2051
2052
		updateSettings(array('displayFields' => $smcFunc['json_encode']($fields)));
2053
		$_SESSION['adm-save'] = true;
2054
		redirectexit('action=admin;area=featuresettings;sa=profile');
2055
	}
2056
2057
	createToken('admin-ecp');
2058
}
2059
2060
/**
2061
 * Returns the maximum field_order value for the custom fields
2062
 * @return int The maximum value of field_order from the custom_fields table
2063
 */
2064
function custFieldsMaxOrder()
2065
{
2066
	global $smcFunc;
2067
2068
	// Gotta know the order limit
2069
	$result = $smcFunc['db_query']('', '
2070
			SELECT MAX(field_order)
2071
			FROM {db_prefix}custom_fields',
2072
			array()
2073
		);
2074
2075
	list ($order_count) = $smcFunc['db_fetch_row']($result);
2076
	$smcFunc['db_free_result']($result);
2077
2078
	return (int) $order_count;
2079
}
2080
2081
/**
2082
 * Allow to edit the settings on the pruning screen.
2083
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
2084
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
2085
 */
2086
function ModifyLogSettings($return_config = false)
2087
{
2088
	global $txt, $scripturl, $sourcedir, $context, $modSettings;
2089
2090
	// Make sure we understand what's going on.
2091
	loadLanguage('ManageSettings');
2092
2093
	$context['page_title'] = $txt['log_settings'];
2094
2095
	$config_vars = array(
2096
			array('check', 'modlog_enabled', 'help' => 'modlog'),
2097
			array('check', 'adminlog_enabled', 'help' => 'adminlog'),
2098
			array('check', 'userlog_enabled', 'help' => 'userlog'),
2099
			// The error log is a wonderful thing.
2100
			array('title', 'errlog'),
2101
			array('desc', 'error_log_desc'),
2102
			array('check', 'enableErrorLogging'),
2103
			array('check', 'enableErrorQueryLogging'),
2104
			array('check', 'log_ban_hits'),
2105
			// Even do the pruning?
2106
			array('title', 'pruning_title'),
2107
			array('desc', 'pruning_desc'),
2108
			// The array indexes are there so we can remove/change them before saving.
2109
			'pruningOptions' => array('check', 'pruningOptions'),
2110
		'',
2111
			// Various logs that could be pruned.
2112
			array('int', 'pruneErrorLog', 'postinput' => $txt['days_word'], 'subtext' => $txt['zero_to_disable']), // Error log.
2113
			array('int', 'pruneModLog', 'postinput' => $txt['days_word'], 'subtext' => $txt['zero_to_disable']), // Moderation log.
2114
			array('int', 'pruneBanLog', 'postinput' => $txt['days_word'], 'subtext' => $txt['zero_to_disable']), // Ban hit log.
2115
			array('int', 'pruneReportLog', 'postinput' => $txt['days_word'], 'subtext' => $txt['zero_to_disable']), // Report to moderator log.
2116
			array('int', 'pruneScheduledTaskLog', 'postinput' => $txt['days_word'], 'subtext' => $txt['zero_to_disable']), // Log of the scheduled tasks and how long they ran.
2117
			array('int', 'pruneSpiderHitLog', 'postinput' => $txt['days_word'], 'subtext' => $txt['zero_to_disable']), // Log of the scheduled tasks and how long they ran.
2118
			// 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.
2119
			// Mod Developers: Do NOT use the pruningOptions master variable for this as SMF Core may overwrite your setting in the future!
2120
	);
2121
2122
	// 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.
2123
	$prune_toggle = array('pruneErrorLog', 'pruneModLog', 'pruneBanLog', 'pruneReportLog', 'pruneScheduledTaskLog', 'pruneSpiderHitLog');
2124
2125
	call_integration_hook('integrate_prune_settings', array(&$config_vars, &$prune_toggle, false));
2126
2127
	$prune_toggle_dt = array();
2128
	foreach ($prune_toggle as $item)
2129
		$prune_toggle_dt[] = 'setting_' . $item;
2130
2131
	if ($return_config)
2132
		return $config_vars;
2133
2134
	addInlineJavaScript('
2135
	function togglePruned()
2136
	{
2137
		var newval = $("#pruningOptions").prop("checked");
2138
		$("#' . implode(', #', $prune_toggle) . '").closest("dd").toggle(newval);
2139
		$("#' . implode(', #', $prune_toggle_dt) . '").closest("dt").toggle(newval);
2140
	};
2141
	togglePruned();
2142
	$("#pruningOptions").click(function() { togglePruned(); });', true);
2143
2144
	// We'll need this in a bit.
2145
	require_once($sourcedir . '/ManageServer.php');
2146
2147
	// Saving?
2148
	if (isset($_GET['save']))
2149
	{
2150
		checkSession();
2151
2152
		// Because of the excitement attached to combining pruning log items, we need to duplicate everything here.
2153
		$savevar = array(
2154
			array('check', 'modlog_enabled'),
2155
			array('check', 'adminlog_enabled'),
2156
			array('check', 'userlog_enabled'),
2157
			array('check', 'enableErrorLogging'),
2158
			array('check', 'enableErrorQueryLogging'),
2159
			array('check', 'log_ban_hits'),
2160
			array('text', 'pruningOptions')
2161
		);
2162
2163
		call_integration_hook('integrate_prune_settings', array(&$savevar, &$prune_toggle, true));
2164
2165
		if (!empty($_POST['pruningOptions']))
2166
		{
2167
			$vals = array();
2168
			foreach ($config_vars as $index => $dummy)
2169
			{
2170
				if (!is_array($dummy) || $index == 'pruningOptions' || !in_array($dummy[1], $prune_toggle))
2171
					continue;
2172
2173
				$vals[] = empty($_POST[$dummy[1]]) || $_POST[$dummy[1]] < 0 ? 0 : (int) $_POST[$dummy[1]];
2174
			}
2175
			$_POST['pruningOptions'] = implode(',', $vals);
2176
		}
2177
		else
2178
			$_POST['pruningOptions'] = '';
2179
2180
		saveDBSettings($savevar);
2181
		$_SESSION['adm-save'] = true;
2182
		redirectexit('action=admin;area=logs;sa=settings');
2183
	}
2184
2185
	$context['post_url'] = $scripturl . '?action=admin;area=logs;save;sa=settings';
2186
	$context['settings_title'] = $txt['log_settings'];
2187
	$context['sub_template'] = 'show_settings';
2188
2189
	// Get the actual values
2190
	if (!empty($modSettings['pruningOptions']))
2191
		@list ($modSettings['pruneErrorLog'], $modSettings['pruneModLog'], $modSettings['pruneBanLog'], $modSettings['pruneReportLog'], $modSettings['pruneScheduledTaskLog'], $modSettings['pruneSpiderHitLog']) = explode(',', $modSettings['pruningOptions']);
2192
	else
2193
		$modSettings['pruneErrorLog'] = $modSettings['pruneModLog'] = $modSettings['pruneBanLog'] = $modSettings['pruneReportLog'] = $modSettings['pruneScheduledTaskLog'] = $modSettings['pruneSpiderHitLog'] = 0;
2194
2195
	prepareDBSettingContext($config_vars);
2196
}
2197
2198
/**
2199
 * If you have a general mod setting to add stick it here.
2200
 *
2201
 * @param bool $return_config Whether or not to return the config_vars array (used for admin search)
2202
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
2203
 */
2204
function ModifyGeneralModSettings($return_config = false)
2205
{
2206
	global $txt, $scripturl, $context;
2207
2208
	$config_vars = array(
2209
		// Mod authors, add any settings UNDER this line. Include a comma at the end of the line and don't remove this statement!!
2210
	);
2211
2212
	// Make it even easier to add new settings.
2213
	call_integration_hook('integrate_general_mod_settings', array(&$config_vars));
2214
2215
	if ($return_config)
2216
		return $config_vars;
2217
2218
	$context['post_url'] = $scripturl . '?action=admin;area=modsettings;save;sa=general';
2219
	$context['settings_title'] = $txt['mods_cat_modifications_misc'];
2220
2221
	// No removing this line you, dirty unwashed mod authors. :p
2222
	if (empty($config_vars))
2223
	{
2224
		$context['settings_save_dont_show'] = true;
2225
		$context['settings_message'] = '<div class="centertext">' . $txt['modification_no_misc_settings'] . '</div>';
2226
2227
		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...
2228
	}
2229
2230
	// Saving?
2231
	if (isset($_GET['save']))
2232
	{
2233
		checkSession();
2234
2235
		$save_vars = $config_vars;
2236
2237
		call_integration_hook('integrate_save_general_mod_settings', array(&$save_vars));
2238
2239
		// This line is to help mod authors do a search/add after if you want to add something here. Keyword: FOOT TAPPING SUCKS!
2240
		saveDBSettings($save_vars);
2241
2242
		// This line is to remind mod authors that it's nice to let the users know when something has been saved.
2243
		$_SESSION['adm-save'] = true;
2244
2245
		// This line is to help mod authors do a search/add after if you want to add something here. Keyword: I LOVE TEA!
2246
		redirectexit('action=admin;area=modsettings;sa=general');
2247
	}
2248
2249
	// 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!
2250
	prepareDBSettingContext($config_vars);
2251
}
2252
2253
/**
2254
 * Handles modifying the alerts settings
2255
 */
2256
function ModifyAlertsSettings()
2257
{
2258
	global $context, $modSettings, $sourcedir, $txt;
2259
2260
	// Dummy settings for the template...
2261
	$modSettings['allow_disableAnnounce'] = false;
2262
	$context['user']['is_owner'] = false;
2263
	$context['member'] = array();
2264
	$context['id_member'] = 0;
2265
	$context['menu_item_selected'] = 'alerts';
2266
	$context['token_check'] = 'noti-admin';
2267
2268
	// Specify our action since we'll want to post back here instead of the profile
2269
	$context['action'] = 'action=admin;area=featuresettings;sa=alerts;'. $context['session_var'] .'='. $context['session_id'];
2270
2271
	loadTemplate('Profile');
2272
	loadLanguage('Profile');
2273
2274
	include_once($sourcedir . '/Profile-Modify.php');
2275
	alert_configuration(0);
2276
2277
	$context['page_title'] = $txt['notify_settings'];
2278
2279
	// Override the description
2280
	$context['description'] = $txt['notifications_desc'];
2281
	$context['sub_template'] = 'alert_configuration';
2282
}
2283
2284
/**
2285
 * Config array for changing privacy settings
2286
 * Accessed  from ?action=admin;area=featuresettings;sa=privacy;
2287
 *
2288
 * @param bool $return_config Whether or not to return the config_vars array
2289
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
2290
 */
2291
function ModifyPrivacySettings($return_config = false)
2292
{
2293
	global $txt, $scripturl, $context;
2294
2295
	$config_vars = array(
2296
		array('check', 'enable_privacy_userexport'),
2297
		array('permissions', 'privacy_userexport_own'),
2298
		array('permissions', 'privacy_userexport_any'),
2299
	);
2300
2301
	call_integration_hook('integrate_privacy_settings', array(&$config_vars));
2302
2303
	if ($return_config)
2304
		return $config_vars;
2305
2306
	// Saving?
2307
	if (isset($_GET['save']))
2308
	{
2309
		checkSession();
2310
2311
		call_integration_hook('integrate_save_privacy_settings');
2312
2313
		saveDBSettings($config_vars);
2314
		$_SESSION['adm-save'] = true;
2315
		redirectexit('action=admin;area=featuresettings;sa=privacy');
2316
	}
2317
2318
	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=privacy';
2319
	$context['settings_title'] = $txt['privacy'];
2320
2321
	prepareDBSettingContext($config_vars);
2322
}
2323
2324
/**
2325
 * Config array for changing policy settings
2326
 * Accessed  from ?action=admin;area=featuresettings;sa=policy;
2327
 *
2328
 * @param bool $return_config Whether or not to return the config_vars array
2329
 * @return void|array Returns nothing or returns the $config_vars array if $return_config is true
2330
 */
2331
function ModifyPolicySettings($return_config = false)
2332
{
2333
	global $txt, $scripturl, $context, $sourcedir, $modSettings, $smcFunc;
2334
	
2335
	// Needed for the WYSIWYG editor.
2336
	require_once($sourcedir . '/Subs-Editor.php');
2337
	$context['sub_template'] = 'edit_policy';
2338
	$context['page_title'] = $txt['policy_management'];
2339
2340
	$config_vars = array(
2341
		array('check', 'enable_policy_function'),
2342
		array('text', 'policy_text'),
2343
	);
2344
	
2345
	$currentVersion = !empty($modSettings['policy_version']) ? substr($modSettings['policy_version'], 11) : 0;
2346
2347
	// Now create the editor.
2348
	$editorOptions = array(
2349
		'id' => 'policy_text',
2350
		'value' => !empty($modSettings['policy_text' . $currentVersion]) ? $modSettings['policy_text' . $currentVersion] : '',
2351
		'height' => '250px',
2352
		'width' => '100%',
2353
		'labels' => array(
2354
			'post_button' => $txt['policy_save'],
2355
		),
2356
		'preview_type' => 2,
2357
		'required' => true,
2358
	);
2359
	create_control_richedit($editorOptions);
2360
	// Store the ID for old compatibility.
2361
	$context['post_box_name'] = $editorOptions['id'];
2362
	
2363
	call_integration_hook('integrate_policy_settings', array(&$config_vars));
2364
	
2365
	$request = $smcFunc['db_query']('', '
2366
		SELECT count( case when th.value is null then 1 end) novalid,
2367
			count( case when th.value is not null and th.value != {string:policy_version} then 1 end) outdated,
2368
			count( case when th.value = {string:policy_version} then 1 end) fresh
2369
		FROM {db_prefix}members mem
2370
		LEFT JOIN {db_prefix}themes th ON (mem.id_member = th.id_member AND th.id_theme = 1 AND th.variable = {string:policy_approved})',
2371
		array(
2372
			'policy_version' => 'policy_text' . $currentVersion,
2373
			'policy_approved' => 'policy_approved',
2374
		)
2375
	);
2376
	
2377
	list ($context['policy']['invalid'], $context['policy']['outdated'], $context['policy']['fresh']) = $smcFunc['db_fetch_row']($request);
2378
	$smcFunc['db_free_result']($request);
2379
	
2380
	$request = $smcFunc['db_query']('', '
2381
		SELECT a.variable, count(b.value) amount
2382
		FROM {db_prefix}settings a
2383
		LEFT JOIN {db_prefix}themes b ON (a.variable = b.value and b.variable = {string:policy_approved})
2384
		WHERE a.variable like {string:avar}
2385
		GROUP BY a.variable
2386
		ORDER BY a.variable desc',
2387
		array(
2388
			'policy_approved' => 'policy_approved',
2389
			'avar' => 'policy_text%',
2390
		)
2391
	);
2392
	
2393
	$context['poc']['policy_management'] = array();
2394
	while ($row = $smcFunc['db_fetch_assoc']($request))
2395
	{
2396
		$context['poc']['policy_management'][] = array(
2397
			'name' => $row['variable'],
2398
			'amount' => $row['amount'],
2399
			'new' => ($row['variable'] == 'policy_text' . $currentVersion ? true : false),
2400
		);
2401
	}
2402
	$smcFunc['db_free_result']($request);
2403
	if ($return_config)
2404
		return $config_vars;
2405
2406
	// Saving?
2407
	if (isset($_GET['save']))
2408
	{
2409
		checkSession();
2410
2411
		call_integration_hook('integrate_save_policy_settings');
2412
2413
		if (!empty($_REQUEST['enforce_new']))
2414
		{
2415
		$select = '
2416
			UPDATE {db_prefix}themes
2417
			SET value = {string:value}
2418
			WHERE EXISTS (
2419
				SELECT a.id_member
2420
				FROM {db_prefix}themes a
2421
				LEFT JOIN {db_prefix}themes b ON (a.id_member = b.id_member and b.variable = {string:bvar})
2422
				WHERE a.variable = {string:avar} and a.value = {string:aval} 
2423
					AND ( b.value != {string:bval}  or b.value is null)
2424
					AND a.id_member = {db_prefix}themes.id_member
2425
			)
2426
			AND variable = {string:avar}';
2427
			
2428
			$smcFunc['db_query']('managePrivacyNew',
2429
				$select,
2430
				array(
2431
					'value' => '0',
2432
					'bvar' => 'policy_approved',
2433
					'avar' => 'policy_isvalid',
2434
					'aval' => '1',
2435
					'bval' => 'policy_text' . $currentVersion,
2436
				)
2437
			);
2438
		}
2439
		elseif (!empty($_REQUEST['save_setting']))
2440
		{
2441
			unset($config_vars[1]);
2442
			saveDBSettings($config_vars);
2443
		}
2444
		elseif (!empty($_REQUEST['save_new_policy']) || !empty($_REQUEST['update_policy']))
2445
		{
2446
			if (!empty($_REQUEST['save_new_policy']))
2447
				$currentVersion++;
2448
			
2449
			$config_vars[] = array('text', 'policy_text'.$currentVersion);
2450
			$_POST['policy_text'.$currentVersion] = $_REQUEST['policy_text'];
2451
			$config_vars[] = array('text', 'policy_version');
2452
			$_POST['policy_version'] = 'policy_text'.$currentVersion;
2453
			unset($config_vars[1]);
2454
			saveDBSettings($config_vars);
2455
		}
2456
2457
		$_SESSION['adm-save'] = true;
2458
		redirectexit('action=admin;area=featuresettings;sa=policy');
2459
	}
2460
	elseif (isset($_GET['manage']))
2461
	{
2462
		checkSession();
2463
		
2464
		call_integration_hook('integrate_manage_policy_settings');
2465
		
2466
		// set user with the policy invalid
2467
		$select = '
2468
			UPDATE {db_prefix}themes
2469
			SET value = {string:value}
2470
			WHERE EXISTS (
2471
				SELECT a.id_member
2472
				FROM {db_prefix}themes a
2473
				LEFT JOIN {db_prefix}themes b ON (a.id_member = b.id_member and b.variable = {string:bvar})
2474
				WHERE a.variable = {string:avar} and a.value = {string:aval} 
2475
					AND b.value = {string:bval}
2476
					AND a.id_member = {db_prefix}themes.id_member
2477
			)
2478
			AND variable = {string:avar}';
2479
2480
		$smcFunc['db_query']('managePrivacyInvalid',
2481
				$select,
2482
			array(
2483
				'value' => '0',
2484
				'bvar' => 'policy_approved',
2485
				'avar' => 'policy_isvalid',
2486
				'aval' => '1',
2487
				'bval' => $_REQUEST['delete_policy'],
2488
			)
2489
		);
2490
		
2491
		// empty users
2492
		$select = '
2493
			UPDATE {db_prefix}themes
2494
			SET value = {string:value}
2495
			WHERE EXISTS (
2496
				SELECT a.id_member
2497
				FROM {db_prefix}themes a
2498
				LEFT JOIN {db_prefix}themes b ON (a.id_member = b.id_member and b.variable = {string:bvar})
2499
				WHERE a.variable = {string:avar} and a.value = {string:aval} 
2500
					AND b.value = {string:bval}
2501
					AND a.id_member = {db_prefix}themes.id_member
2502
			)
2503
			and variable = {string:bvar}';
2504
		$smcFunc['db_query']('managePrivacyEmptyusers',
2505
			$select,
2506
			array(
2507
				'value' => '',
2508
				'bvar' => 'policy_approved',
2509
				'avar' => 'policy_isvalid',
2510
				'aval' => '0',
2511
				'bval' => $_REQUEST['delete_policy'],
2512
			)
2513
		);
2514
		
2515
		$smcFunc['db_query']('','
2516
			DELETE FROM {db_prefix}settings
2517
			WHERE variable = {string:policy_text}',
2518
			array(
2519
				'policy_text' => $_REQUEST['delete_policy'],
2520
			)
2521
		);
2522
		
2523
		
2524
		$_SESSION['adm-save'] = true;
2525
		redirectexit('action=admin;area=featuresettings;sa=policy');
2526
	}
2527
2528
	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=policy';
2529
	$context['settings_title'] = $txt['privacy'];
2530
2531
	prepareDBSettingContext($config_vars);
2532
}
2533
2534
?>