loadThemeOptions()   C
last analyzed

Complexity

Conditions 12
Paths 45

Size

Total Lines 46
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 25
nop 1
dl 0
loc 46
rs 6.9666
c 0
b 0
f 0
nc 45

How to fix   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 has the primary job of showing and editing people's profiles.
5
 * 	It also allows the user to change some of their or another's preferences,
6
 * 	and such things
7
 *
8
 * Simple Machines Forum (SMF)
9
 *
10
 * @package SMF
11
 * @author Simple Machines http://www.simplemachines.org
12
 * @copyright 2019 Simple Machines and individual contributors
13
 * @license http://www.simplemachines.org/about/smf/license.php BSD
14
 *
15
 * @version 2.1 RC2
16
 */
17
18
if (!defined('SMF'))
19
	die('No direct access...');
20
21
/**
22
 * This defines every profile field known to man.
23
 *
24
 * @param bool $force_reload Whether to reload the data
25
 */
26
function loadProfileFields($force_reload = false)
27
{
28
	global $context, $profile_fields, $txt, $scripturl, $modSettings, $user_info, $smcFunc, $cur_profile, $language;
29
	global $sourcedir, $profile_vars, $settings;
30
31
	// Don't load this twice!
32
	if (!empty($profile_fields) && !$force_reload)
33
		return;
34
35
	/* This horrific array defines all the profile fields in the whole world!
36
		In general each "field" has one array - the key of which is the database column name associated with said field. Each item
37
		can have the following attributes:
38
39
				string $type:			The type of field this is - valid types are:
40
					- callback:		This is a field which has its own callback mechanism for templating.
41
					- check:		A simple checkbox.
42
					- hidden:		This doesn't have any visual aspects but may have some validity.
43
					- password:		A password box.
44
					- select:		A select box.
45
					- text:			A string of some description.
46
47
				string $label:			The label for this item - default will be $txt[$key] if this isn't set.
48
				string $subtext:		The subtext (Small label) for this item.
49
				int $size:			Optional size for a text area.
50
				array $input_attr:		An array of text strings to be added to the input box for this item.
51
				string $value:			The value of the item. If not set $cur_profile[$key] is assumed.
52
				string $permission:		Permission required for this item (Excluded _any/_own subfix which is applied automatically).
53
				function $input_validate:	A runtime function which validates the element before going to the database. It is passed
54
								the relevant $_POST element if it exists and should be treated like a reference.
55
56
								Return types:
57
					- true:			Element can be stored.
58
					- false:		Skip this element.
59
					- a text string:	An error occured - this is the error message.
60
61
				function $preload:		A function that is used to load data required for this element to be displayed. Must return
62
								true to be displayed at all.
63
64
				string $cast_type:		If set casts the element to a certain type. Valid types (bool, int, float).
65
				string $save_key:		If the index of this element isn't the database column name it can be overriden
66
								with this string.
67
				bool $is_dummy:			If set then nothing is acted upon for this element.
68
				bool $enabled:			A test to determine whether this is even available - if not is unset.
69
				string $link_with:		Key which links this field to an overall set.
70
71
		Note that all elements that have a custom input_validate must ensure they set the value of $cur_profile correct to enable
72
		the changes to be displayed correctly on submit of the form.
73
74
	*/
75
76
	$profile_fields = array(
77
		'avatar_choice' => array(
78
			'type' => 'callback',
79
			'callback_func' => 'avatar_select',
80
			// This handles the permissions too.
81
			'preload' => 'profileLoadAvatarData',
82
			'input_validate' => 'profileSaveAvatarData',
83
			'save_key' => 'avatar',
84
		),
85
		'bday1' => array(
86
			'type' => 'callback',
87
			'callback_func' => 'birthdate',
88
			'permission' => 'profile_extra',
89
			'preload' => function() use ($cur_profile, &$context)
90
			{
91
				// Split up the birthdate....
92
				list ($uyear, $umonth, $uday) = explode('-', empty($cur_profile['birthdate']) || $cur_profile['birthdate'] === '1004-01-01' ? '--' : $cur_profile['birthdate']);
93
				$context['member']['birth_date'] = array(
94
					'year' => $uyear,
95
					'month' => $umonth,
96
					'day' => $uday,
97
				);
98
99
				return true;
100
			},
101
			'input_validate' => function(&$value) use (&$cur_profile, &$profile_vars)
102
			{
103
				if (isset($_POST['bday2'], $_POST['bday3']) && $value > 0 && $_POST['bday2'] > 0)
104
				{
105
					// Set to blank?
106
					if ((int) $_POST['bday3'] == 1 && (int) $_POST['bday2'] == 1 && (int) $value == 1)
107
						$value = '1004-01-01';
108
					else
109
						$value = checkdate($value, $_POST['bday2'], $_POST['bday3'] < 1004 ? 1004 : $_POST['bday3']) ? sprintf('%04d-%02d-%02d', $_POST['bday3'] < 1004 ? 1004 : $_POST['bday3'], $_POST['bday1'], $_POST['bday2']) : '1004-01-01';
110
				}
111
				else
112
					$value = '1004-01-01';
113
114
				$profile_vars['birthdate'] = $value;
115
				$cur_profile['birthdate'] = $value;
116
				return false;
117
			},
118
		),
119
		// Setting the birthdate the old style way?
120
		'birthdate' => array(
121
			'type' => 'hidden',
122
			'permission' => 'profile_extra',
123
			'input_validate' => function(&$value) use ($cur_profile)
124
			{
125
				// @todo Should we check for this year and tell them they made a mistake :P? (based on coppa at least?)
126
				if (preg_match('/(\d{4})[\-\., ](\d{2})[\-\., ](\d{2})/', $value, $dates) === 1)
127
				{
128
					$value = checkdate($dates[2], $dates[3], $dates[1] < 4 ? 4 : $dates[1]) ? sprintf('%04d-%02d-%02d', $dates[1] < 4 ? 4 : $dates[1], $dates[2], $dates[3]) : '1004-01-01';
129
					return true;
130
				}
131
				else
132
				{
133
					$value = empty($cur_profile['birthdate']) ? '1004-01-01' : $cur_profile['birthdate'];
134
					return false;
135
				}
136
			},
137
		),
138
		'date_registered' => array(
139
			'type' => 'date',
140
			'value' => empty($cur_profile['date_registered']) ? $txt['not_applicable'] : strftime('%Y-%m-%d', $cur_profile['date_registered'] + ($user_info['time_offset'] + $modSettings['time_offset']) * 3600),
141
			'label' => $txt['date_registered'],
142
			'log_change' => true,
143
			'permission' => 'moderate_forum',
144
			'input_validate' => function(&$value) use ($txt, $user_info, $modSettings, $cur_profile, $context)
0 ignored issues
show
Unused Code introduced by
The import $context is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
145
			{
146
				// Bad date!  Go try again - please?
147
				if (($value = strtotime($value)) === false)
148
				{
149
					$value = $cur_profile['date_registered'];
150
					return $txt['invalid_registration'] . ' ' . strftime('%d %b %Y ' . (strpos($user_info['time_format'], '%H') !== false ? '%I:%M:%S %p' : '%H:%M:%S'), forum_time(false));
151
				}
152
153
				// As long as it doesn't equal "N/A"...
154
				elseif ($value != $txt['not_applicable'] && $value != strtotime(strftime('%Y-%m-%d', $cur_profile['date_registered'] + ($user_info['time_offset'] + $modSettings['time_offset']) * 3600)))
155
					$value = $value - ($user_info['time_offset'] + $modSettings['time_offset']) * 3600;
156
157
				else
158
					$value = $cur_profile['date_registered'];
159
160
				return true;
161
			},
162
		),
163
		'email_address' => array(
164
			'type' => 'email',
165
			'label' => $txt['user_email_address'],
166
			'subtext' => $txt['valid_email'],
167
			'log_change' => true,
168
			'permission' => 'profile_password',
169
			'js_submit' => !empty($modSettings['send_validation_onChange']) ? '
170
	form_handle.addEventListener(\'submit\', function(event)
171
	{
172
		if (this.email_address.value != "' . (!empty($cur_profile['email_address']) ? $cur_profile['email_address'] : '') . '")
173
		{
174
			alert(' . JavaScriptEscape($txt['email_change_logout']) . ');
175
			return true;
176
		}
177
	}, false);' : '',
178
			'input_validate' => function(&$value)
179
			{
180
				global $context, $old_profile, $profile_vars, $sourcedir, $modSettings;
181
182
				if (strtolower($value) == strtolower($old_profile['email_address']))
183
					return false;
184
185
				$isValid = profileValidateEmail($value, $context['id_member']);
186
187
				// Do they need to revalidate? If so schedule the function!
188
				if ($isValid === true && !empty($modSettings['send_validation_onChange']) && !allowedTo('moderate_forum'))
189
				{
190
					require_once($sourcedir . '/Subs-Members.php');
191
					$profile_vars['validation_code'] = generateValidationCode();
192
					$profile_vars['is_activated'] = 2;
193
					$context['profile_execute_on_save'][] = 'profileSendActivation';
194
					unset($context['profile_execute_on_save']['reload_user']);
195
				}
196
197
				return $isValid;
198
			},
199
		),
200
		// Selecting group membership is a complicated one so we treat it separate!
201
		'id_group' => array(
202
			'type' => 'callback',
203
			'callback_func' => 'group_manage',
204
			'permission' => 'manage_membergroups',
205
			'preload' => 'profileLoadGroups',
206
			'log_change' => true,
207
			'input_validate' => 'profileSaveGroups',
208
		),
209
		'id_theme' => array(
210
			'type' => 'callback',
211
			'callback_func' => 'theme_pick',
212
			'permission' => 'profile_extra',
213
			'enabled' => $modSettings['theme_allow'] || allowedTo('admin_forum'),
214
			'preload' => function() use ($smcFunc, &$context, $cur_profile, $txt)
215
			{
216
				$request = $smcFunc['db_query']('', '
217
					SELECT value
218
					FROM {db_prefix}themes
219
					WHERE id_theme = {int:id_theme}
220
						AND variable = {string:variable}
221
					LIMIT 1', array(
222
						'id_theme' => $cur_profile['id_theme'],
223
						'variable' => 'name',
224
					)
225
				);
226
				list ($name) = $smcFunc['db_fetch_row']($request);
227
				$smcFunc['db_free_result']($request);
228
229
				$context['member']['theme'] = array(
230
					'id' => $cur_profile['id_theme'],
231
					'name' => empty($cur_profile['id_theme']) ? $txt['theme_forum_default'] : $name
232
				);
233
				return true;
234
			},
235
			'input_validate' => function(&$value)
236
			{
237
				$value = (int) $value;
238
				return true;
239
			},
240
		),
241
		'lngfile' => array(
242
			'type' => 'select',
243
			'options' => function() use (&$context)
244
			{
245
				return $context['profile_languages'];
246
			},
247
			'label' => $txt['preferred_language'],
248
			'permission' => 'profile_identity',
249
			'preload' => 'profileLoadLanguages',
250
			'enabled' => !empty($modSettings['userLanguage']),
251
			'value' => empty($cur_profile['lngfile']) ? $language : $cur_profile['lngfile'],
252
			'input_validate' => function(&$value) use (&$context, $cur_profile)
253
			{
254
				// Load the languages.
255
				profileLoadLanguages();
256
257
				if (isset($context['profile_languages'][$value]))
258
				{
259
					if ($context['user']['is_owner'] && empty($context['password_auth_failed']))
260
						$_SESSION['language'] = $value;
261
					return true;
262
				}
263
				else
264
				{
265
					$value = $cur_profile['lngfile'];
266
					return false;
267
				}
268
			},
269
		),
270
		// The username is not always editable - so adjust it as such.
271
		'member_name' => array(
272
			'type' => allowedTo('admin_forum') && isset($_GET['changeusername']) ? 'text' : 'label',
273
			'label' => $txt['username'],
274
			'subtext' => allowedTo('admin_forum') && !isset($_GET['changeusername']) ? '[<a href="' . $scripturl . '?action=profile;u=' . $context['id_member'] . ';area=account;changeusername" style="font-style: italic;">' . $txt['username_change'] . '</a>]' : '',
275
			'log_change' => true,
276
			'permission' => 'profile_identity',
277
			'prehtml' => allowedTo('admin_forum') && isset($_GET['changeusername']) ? '<div class="alert">' . $txt['username_warning'] . '</div>' : '',
278
			'input_validate' => function(&$value) use ($sourcedir, $context, $user_info, $cur_profile)
279
			{
280
				if (allowedTo('admin_forum'))
281
				{
282
					// We'll need this...
283
					require_once($sourcedir . '/Subs-Auth.php');
284
285
					// Maybe they are trying to change their password as well?
286
					$resetPassword = true;
287
					if (isset($_POST['passwrd1']) && $_POST['passwrd1'] != '' && isset($_POST['passwrd2']) && $_POST['passwrd1'] == $_POST['passwrd2'] && validatePassword($_POST['passwrd1'], $value, array($cur_profile['real_name'], $user_info['username'], $user_info['name'], $user_info['email'])) == null)
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing validatePassword($_POST[..., $user_info['email'])) of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
288
						$resetPassword = false;
289
290
					// Do the reset... this will send them an email too.
291
					if ($resetPassword)
292
						resetPassword($context['id_member'], $value);
293
					elseif ($value !== null)
294
					{
295
						validateUsername($context['id_member'], trim(preg_replace('~[\t\n\r \x0B\0' . ($context['utf8'] ? '\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}' : '\x00-\x08\x0B\x0C\x0E-\x19\xA0') . ']+~' . ($context['utf8'] ? 'u' : ''), ' ', $value)));
296
						updateMemberData($context['id_member'], array('member_name' => $value));
297
298
						// Call this here so any integrated systems will know about the name change (resetPassword() takes care of this if we're letting SMF generate the password)
299
						call_integration_hook('integrate_reset_pass', array($cur_profile['member_name'], $value, $_POST['passwrd1']));
300
					}
301
				}
302
				return false;
303
			},
304
		),
305
		'passwrd1' => array(
306
			'type' => 'password',
307
			'label' => ucwords($txt['choose_pass']),
308
			'subtext' => $txt['password_strength'],
309
			'size' => 20,
310
			'value' => '',
311
			'permission' => 'profile_password',
312
			'save_key' => 'passwd',
313
			// Note this will only work if passwrd2 also exists!
314
			'input_validate' => function(&$value) use ($sourcedir, $user_info, $smcFunc, $cur_profile)
0 ignored issues
show
Unused Code introduced by
The import $smcFunc is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
315
			{
316
				// If we didn't try it then ignore it!
317
				if ($value == '')
318
					return false;
319
320
				// Do the two entries for the password even match?
321
				if (!isset($_POST['passwrd2']) || $value != $_POST['passwrd2'])
322
					return 'bad_new_password';
323
324
				// Let's get the validation function into play...
325
				require_once($sourcedir . '/Subs-Auth.php');
326
				$passwordErrors = validatePassword($value, $cur_profile['member_name'], array($cur_profile['real_name'], $user_info['username'], $user_info['name'], $user_info['email']));
327
328
				// Were there errors?
329
				if ($passwordErrors != null)
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $passwordErrors of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
330
					return 'password_' . $passwordErrors;
331
332
				// Set up the new password variable... ready for storage.
333
				$value = hash_password($cur_profile['member_name'], un_htmlspecialchars($value));
334
335
				return true;
336
			},
337
		),
338
		'passwrd2' => array(
339
			'type' => 'password',
340
			'label' => ucwords($txt['verify_pass']),
341
			'size' => 20,
342
			'value' => '',
343
			'permission' => 'profile_password',
344
			'is_dummy' => true,
345
		),
346
		'personal_text' => array(
347
			'type' => 'text',
348
			'label' => $txt['personal_text'],
349
			'log_change' => true,
350
			'input_attr' => array('maxlength="50"'),
351
			'size' => 50,
352
			'permission' => 'profile_blurb',
353
			'input_validate' => function(&$value) use ($smcFunc)
354
			{
355
				if ($smcFunc['strlen']($value) > 50)
356
					return 'personal_text_too_long';
357
358
				return true;
359
			},
360
		),
361
		// This does ALL the pm settings
362
		'pm_prefs' => array(
363
			'type' => 'callback',
364
			'callback_func' => 'pm_settings',
365
			'permission' => 'pm_read',
366
			'preload' => function() use (&$context, $cur_profile)
367
			{
368
				$context['display_mode'] = $cur_profile['pm_prefs'] & 3;
369
				$context['receive_from'] = !empty($cur_profile['pm_receive_from']) ? $cur_profile['pm_receive_from'] : 0;
370
371
				return true;
372
			},
373
			'input_validate' => function(&$value) use (&$cur_profile, &$profile_vars)
374
			{
375
				// Simple validate and apply the two "sub settings"
376
				$value = max(min($value, 2), 0);
377
378
				$cur_profile['pm_receive_from'] = $profile_vars['pm_receive_from'] = max(min((int) $_POST['pm_receive_from'], 4), 0);
379
380
				return true;
381
			},
382
		),
383
		'posts' => array(
384
			'type' => 'int',
385
			'label' => $txt['profile_posts'],
386
			'log_change' => true,
387
			'size' => 7,
388
			'permission' => 'moderate_forum',
389
			'input_validate' => function(&$value)
390
			{
391
				if (!is_numeric($value))
392
					return 'digits_only';
393
				else
394
					$value = $value != '' ? strtr($value, array(',' => '', '.' => '', ' ' => '')) : 0;
395
				return true;
396
			},
397
		),
398
		'real_name' => array(
399
			'type' => allowedTo('profile_displayed_name_own') || allowedTo('profile_displayed_name_any') || allowedTo('moderate_forum') ? 'text' : 'label',
400
			'label' => $txt['name'],
401
			'subtext' => $txt['display_name_desc'],
402
			'log_change' => true,
403
			'input_attr' => array('maxlength="60"'),
404
			'permission' => 'profile_displayed_name',
405
			'enabled' => allowedTo('profile_displayed_name_own') || allowedTo('profile_displayed_name_any') || allowedTo('moderate_forum'),
406
			'input_validate' => function(&$value) use ($context, $smcFunc, $sourcedir, $cur_profile)
407
			{
408
				$value = trim(preg_replace('~[\t\n\r \x0B\0' . ($context['utf8'] ? '\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}' : '\x00-\x08\x0B\x0C\x0E-\x19\xA0') . ']+~' . ($context['utf8'] ? 'u' : ''), ' ', $value));
409
410
				if (trim($value) == '')
411
					return 'no_name';
412
				elseif ($smcFunc['strlen']($value) > 60)
413
					return 'name_too_long';
414
				elseif ($cur_profile['real_name'] != $value)
415
				{
416
					require_once($sourcedir . '/Subs-Members.php');
417
					if (isReservedName($value, $context['id_member']))
418
						return 'name_taken';
419
				}
420
				return true;
421
			},
422
		),
423
		'secret_question' => array(
424
			'type' => 'text',
425
			'label' => $txt['secret_question'],
426
			'subtext' => $txt['secret_desc'],
427
			'size' => 50,
428
			'permission' => 'profile_password',
429
		),
430
		'secret_answer' => array(
431
			'type' => 'text',
432
			'label' => $txt['secret_answer'],
433
			'subtext' => $txt['secret_desc2'],
434
			'size' => 20,
435
			'postinput' => '<span class="smalltext"><a href="' . $scripturl . '?action=helpadmin;help=secret_why_blank" onclick="return reqOverlayDiv(this.href);"><span class="main_icons help"></span> ' . $txt['secret_why_blank'] . '</a></span>',
436
			'value' => '',
437
			'permission' => 'profile_password',
438
			'input_validate' => function(&$value) use ($cur_profile)
439
			{
440
				$value = $value != '' ? hash_password($cur_profile['member_name'], $value) : '';
441
				return true;
442
			},
443
		),
444
		'signature' => array(
445
			'type' => 'callback',
446
			'callback_func' => 'signature_modify',
447
			'permission' => 'profile_signature',
448
			'enabled' => substr($modSettings['signature_settings'], 0, 1) == 1,
449
			'preload' => 'profileLoadSignatureData',
450
			'input_validate' => 'profileValidateSignature',
451
		),
452
		'show_online' => array(
453
			'type' => 'check',
454
			'label' => $txt['show_online'],
455
			'permission' => 'profile_identity',
456
			'enabled' => !empty($modSettings['allow_hideOnline']) || allowedTo('moderate_forum'),
457
		),
458
		'smiley_set' => array(
459
			'type' => 'callback',
460
			'callback_func' => 'smiley_pick',
461
			'enabled' => !empty($modSettings['smiley_sets_enable']),
462
			'permission' => 'profile_extra',
463
			'preload' => function() use ($modSettings, &$context, &$txt, $cur_profile, $smcFunc, $settings, $language)
464
			{
465
				$context['member']['smiley_set']['id'] = empty($cur_profile['smiley_set']) ? '' : $cur_profile['smiley_set'];
466
				$context['smiley_sets'] = explode(',', 'none,,' . $modSettings['smiley_sets_known']);
467
				$set_names = explode("\n", $txt['smileys_none'] . "\n" . $txt['smileys_forum_board_default'] . "\n" . $modSettings['smiley_sets_names']);
468
469
				$filenames = array();
470
				$result = $smcFunc['db_query']('', '
471
					SELECT f.filename, f.smiley_set
472
					FROM {db_prefix}smiley_files AS f
473
						JOIN {db_prefix}smileys AS s ON (s.id_smiley = f.id_smiley)
474
					WHERE s.code = {string:smiley}',
475
					array(
476
						'smiley' => ':)',
477
					)
478
				);
479
				while ($row = $smcFunc['db_fetch_assoc']($result))
480
					$filenames[$row['smiley_set']] = $row['filename'];
481
				$smcFunc['db_free_result']($result);
482
483
				// In case any sets don't contain a ':)' smiley
484
				$no_smiley_sets = array_diff(explode(',', $modSettings['smiley_sets_known']), array_keys($filenames));
485
				foreach ($no_smiley_sets as $set)
486
				{
487
					$allowedTypes = array('gif', 'png', 'jpg', 'jpeg', 'tiff', 'svg');
488
					$images = glob(implode('/', array($modSettings['smileys_dir'], $set, '*.{' . (implode(',', $allowedTypes) . '}'))), GLOB_BRACE);
489
490
					// Just use some image or other
491
					if (!empty($images))
492
					{
493
						$image = array_pop($images);
494
						$filenames[$set] = pathinfo($image, PATHINFO_BASENAME);
495
					}
496
					// No images at all? That's no good. Let the admin know, and quietly skip for this user.
497
					else
498
					{
499
						loadLanguage('Errors', $language);
500
						log_error(sprintf($txt['smiley_set_dir_not_found'], $set_names[array_search($set, $context['smiley_sets'])]));
501
502
						$context['smiley_sets'] = array_filter($context['smiley_sets'], function($v) use ($set)
503
							{
504
								return $v != $set;
505
							});
506
					}
507
				}
508
509
				foreach ($context['smiley_sets'] as $i => $set)
510
				{
511
					$context['smiley_sets'][$i] = array(
512
						'id' => $smcFunc['htmlspecialchars']($set),
513
						'name' => $smcFunc['htmlspecialchars']($set_names[$i]),
514
						'selected' => $set == $context['member']['smiley_set']['id']
515
					);
516
517
					if ($set === 'none')
518
						$context['smiley_sets'][$i]['preview'] = $settings['images_url'] . '/blank.png';
519
					elseif ($set === '')
520
					{
521
						$default_set = !empty($settings['smiley_sets_default']) ? $settings['smiley_sets_default'] : $modSettings['smiley_sets_default'];
522
						$context['smiley_sets'][$i]['preview'] = implode('/', array($modSettings['smileys_url'], $default_set, $filenames[$default_set]));
523
					}
524
					else
525
						$context['smiley_sets'][$i]['preview'] = implode('/', array($modSettings['smileys_url'], $set, $filenames[$set]));
526
527
					if ($context['smiley_sets'][$i]['selected'])
528
					{
529
						$context['member']['smiley_set']['name'] = $set_names[$i];
530
						$context['member']['smiley_set']['preview'] = $context['smiley_sets'][$i]['preview'];
531
					}
532
533
					$context['smiley_sets'][$i]['preview'] = $smcFunc['htmlspecialchars']($context['smiley_sets'][$i]['preview']);
534
				}
535
536
				return true;
537
			},
538
			'input_validate' => function(&$value)
539
			{
540
				global $modSettings;
541
542
				$smiley_sets = explode(',', $modSettings['smiley_sets_known']);
543
				if (!in_array($value, $smiley_sets) && $value != 'none')
544
					$value = '';
545
				return true;
546
			},
547
		),
548
		// Pretty much a dummy entry - it populates all the theme settings.
549
		'theme_settings' => array(
550
			'type' => 'callback',
551
			'callback_func' => 'theme_settings',
552
			'permission' => 'profile_extra',
553
			'is_dummy' => true,
554
			'preload' => function() use (&$context, $user_info, $modSettings)
555
			{
556
				loadLanguage('Settings');
557
558
				$context['allow_no_censored'] = false;
559
				if ($user_info['is_admin'] || $context['user']['is_owner'])
560
					$context['allow_no_censored'] = !empty($modSettings['allow_no_censored']);
561
562
				return true;
563
			},
564
		),
565
		'tfa' => array(
566
			'type' => 'callback',
567
			'callback_func' => 'tfa',
568
			'permission' => 'profile_password',
569
			'enabled' => !empty($modSettings['tfa_mode']),
570
			'preload' => function() use (&$context, $cur_profile)
571
			{
572
				$context['tfa_enabled'] = !empty($cur_profile['tfa_secret']);
573
574
				return true;
575
			},
576
		),
577
		'time_format' => array(
578
			'type' => 'callback',
579
			'callback_func' => 'timeformat_modify',
580
			'permission' => 'profile_extra',
581
			'preload' => function() use (&$context, $user_info, $txt, $cur_profile, $modSettings)
582
			{
583
				$context['easy_timeformats'] = array(
584
					array('format' => '', 'title' => $txt['timeformat_default']),
585
					array('format' => '%B %d, %Y, %I:%M:%S %p', 'title' => $txt['timeformat_easy1']),
586
					array('format' => '%B %d, %Y, %H:%M:%S', 'title' => $txt['timeformat_easy2']),
587
					array('format' => '%Y-%m-%d, %H:%M:%S', 'title' => $txt['timeformat_easy3']),
588
					array('format' => '%d %B %Y, %H:%M:%S', 'title' => $txt['timeformat_easy4']),
589
					array('format' => '%d-%m-%Y, %H:%M:%S', 'title' => $txt['timeformat_easy5'])
590
				);
591
592
				$context['member']['time_format'] = $cur_profile['time_format'];
593
				$context['current_forum_time'] = timeformat(time() - $user_info['time_offset'] * 3600, false);
594
				$context['current_forum_time_js'] = strftime('%Y,' . ((int) strftime('%m', time() + $modSettings['time_offset'] * 3600) - 1) . ',%d,%H,%M,%S', time() + $modSettings['time_offset'] * 3600);
595
				$context['current_forum_time_hour'] = (int) strftime('%H', forum_time(false));
596
				return true;
597
			},
598
		),
599
		'timezone' => array(
600
			'type' => 'select',
601
			'options' => smf_list_timezones(),
602
			'disabled_options' => array_filter(array_keys(smf_list_timezones()), 'is_int'),
603
			'permission' => 'profile_extra',
604
			'label' => $txt['timezone'],
605
			'input_validate' => function($value)
606
			{
607
				$tz = smf_list_timezones();
608
				if (!isset($tz[$value]))
609
					return 'bad_timezone';
610
611
				return true;
612
			},
613
		),
614
		'usertitle' => array(
615
			'type' => 'text',
616
			'label' => $txt['custom_title'],
617
			'log_change' => true,
618
			'input_attr' => array('maxlength="50"'),
619
			'size' => 50,
620
			'permission' => 'profile_title',
621
			'enabled' => !empty($modSettings['titlesEnable']),
622
			'input_validate' => function(&$value) use ($smcFunc)
623
			{
624
				if ($smcFunc['strlen']($value) > 50)
625
					return 'user_title_too_long';
626
627
				return true;
628
			},
629
		),
630
		'website_title' => array(
631
			'type' => 'text',
632
			'label' => $txt['website_title'],
633
			'subtext' => $txt['include_website_url'],
634
			'size' => 50,
635
			'permission' => 'profile_website',
636
			'link_with' => 'website',
637
		),
638
		'website_url' => array(
639
			'type' => 'url',
640
			'label' => $txt['website_url'],
641
			'subtext' => $txt['complete_url'],
642
			'size' => 50,
643
			'permission' => 'profile_website',
644
			// Fix the URL...
645
			'input_validate' => function(&$value)
646
			{
647
				if (strlen(trim($value)) > 0 && strpos($value, '://') === false)
648
					$value = 'http://' . $value;
649
				if (strlen($value) < 8 || (substr($value, 0, 7) !== 'http://' && substr($value, 0, 8) !== 'https://'))
650
					$value = '';
651
				$value = (string) validate_iri(sanitize_iri($value));
652
				return true;
653
			},
654
			'link_with' => 'website',
655
		),
656
	);
657
658
	call_integration_hook('integrate_load_profile_fields', array(&$profile_fields));
659
660
	$disabled_fields = !empty($modSettings['disabled_profile_fields']) ? explode(',', $modSettings['disabled_profile_fields']) : array();
661
	// For each of the above let's take out the bits which don't apply - to save memory and security!
662
	foreach ($profile_fields as $key => $field)
663
	{
664
		// Do we have permission to do this?
665
		if (isset($field['permission']) && !allowedTo(($context['user']['is_owner'] ? array($field['permission'] . '_own', $field['permission'] . '_any') : $field['permission'] . '_any')) && !allowedTo($field['permission']))
666
			unset($profile_fields[$key]);
667
668
		// Is it enabled?
669
		if (isset($field['enabled']) && !$field['enabled'])
670
			unset($profile_fields[$key]);
671
672
		// Is it specifically disabled?
673
		if (in_array($key, $disabled_fields) || (isset($field['link_with']) && in_array($field['link_with'], $disabled_fields)))
674
			unset($profile_fields[$key]);
675
	}
676
}
677
678
/**
679
 * Setup the context for a page load!
680
 *
681
 * @param array $fields The profile fields to display. Each item should correspond to an item in the $profile_fields array generated by loadProfileFields
682
 */
683
function setupProfileContext($fields)
684
{
685
	global $profile_fields, $context, $cur_profile, $txt;
686
687
	// Some default bits.
688
	$context['profile_prehtml'] = '';
689
	$context['profile_posthtml'] = '';
690
	$context['profile_javascript'] = '';
691
	$context['profile_onsubmit_javascript'] = '';
692
693
	call_integration_hook('integrate_setup_profile_context', array(&$fields));
694
695
	// Make sure we have this!
696
	loadProfileFields(true);
697
698
	// First check for any linked sets.
699
	foreach ($profile_fields as $key => $field)
700
		if (isset($field['link_with']) && in_array($field['link_with'], $fields))
701
			$fields[] = $key;
702
703
	$i = 0;
704
	$last_type = '';
705
	foreach ($fields as $key => $field)
706
	{
707
		if (isset($profile_fields[$field]))
708
		{
709
			// Shortcut.
710
			$cur_field = &$profile_fields[$field];
711
712
			// Does it have a preload and does that preload succeed?
713
			if (isset($cur_field['preload']) && !$cur_field['preload']())
714
				continue;
715
716
			// If this is anything but complex we need to do more cleaning!
717
			if ($cur_field['type'] != 'callback' && $cur_field['type'] != 'hidden')
718
			{
719
				if (!isset($cur_field['label']))
720
					$cur_field['label'] = isset($txt[$field]) ? $txt[$field] : $field;
721
722
				// Everything has a value!
723
				if (!isset($cur_field['value']))
724
					$cur_field['value'] = isset($cur_profile[$field]) ? $cur_profile[$field] : '';
725
726
				// Any input attributes?
727
				$cur_field['input_attr'] = !empty($cur_field['input_attr']) ? implode(',', $cur_field['input_attr']) : '';
728
			}
729
730
			// Was there an error with this field on posting?
731
			if (isset($context['profile_errors'][$field]))
732
				$cur_field['is_error'] = true;
733
734
			// Any javascript stuff?
735
			if (!empty($cur_field['js_submit']))
736
				$context['profile_onsubmit_javascript'] .= $cur_field['js_submit'];
737
			if (!empty($cur_field['js']))
738
				$context['profile_javascript'] .= $cur_field['js'];
739
740
			// Any template stuff?
741
			if (!empty($cur_field['prehtml']))
742
				$context['profile_prehtml'] .= $cur_field['prehtml'];
743
			if (!empty($cur_field['posthtml']))
744
				$context['profile_posthtml'] .= $cur_field['posthtml'];
745
746
			// Finally put it into context?
747
			if ($cur_field['type'] != 'hidden')
748
			{
749
				$last_type = $cur_field['type'];
750
				$context['profile_fields'][$field] = &$profile_fields[$field];
751
			}
752
		}
753
		// Bodge in a line break - without doing two in a row ;)
754
		elseif ($field == 'hr' && $last_type != 'hr' && $last_type != '')
755
		{
756
			$last_type = 'hr';
757
			$context['profile_fields'][$i++]['type'] = 'hr';
758
		}
759
	}
760
761
	// Some spicy JS.
762
	addInlineJavaScript('
763
	var form_handle = document.forms.creator;
764
	createEventListener(form_handle);
765
	' . (!empty($context['require_password']) ? '
766
	form_handle.addEventListener(\'submit\', function(event)
767
	{
768
		if (this.oldpasswrd.value == "")
769
		{
770
			event.preventDefault();
771
			alert(' . (JavaScriptEscape($txt['required_security_reasons'])) . ');
772
			return false;
773
		}
774
	}, false);' : ''), true);
775
776
	// Any onsubmit javascript?
777
	if (!empty($context['profile_onsubmit_javascript']))
778
		addInlineJavaScript($context['profile_onsubmit_javascript'], true);
779
780
	// Any totally custom stuff?
781
	if (!empty($context['profile_javascript']))
782
		addInlineJavaScript($context['profile_javascript'], true);
783
784
	// Free up some memory.
785
	unset($profile_fields);
786
}
787
788
/**
789
 * Save the profile changes.
790
 */
791
function saveProfileFields()
792
{
793
	global $profile_fields, $profile_vars, $context, $old_profile, $post_errors, $cur_profile;
794
795
	// Load them up.
796
	loadProfileFields();
797
798
	// This makes things easier...
799
	$old_profile = $cur_profile;
800
801
	// This allows variables to call activities when they save - by default just to reload their settings
802
	$context['profile_execute_on_save'] = array();
803
	if ($context['user']['is_owner'])
804
		$context['profile_execute_on_save']['reload_user'] = 'profileReloadUser';
805
806
	// Assume we log nothing.
807
	$context['log_changes'] = array();
808
809
	// Cycle through the profile fields working out what to do!
810
	foreach ($profile_fields as $key => $field)
811
	{
812
		if (!isset($_POST[$key]) || !empty($field['is_dummy']) || (isset($_POST['preview_signature']) && $key == 'signature'))
813
			continue;
814
815
		// What gets updated?
816
		$db_key = isset($field['save_key']) ? $field['save_key'] : $key;
817
818
		// Right - we have something that is enabled, we can act upon and has a value posted to it. Does it have a validation function?
819
		if (isset($field['input_validate']))
820
		{
821
			$is_valid = $field['input_validate']($_POST[$key]);
822
			// An error occurred - set it as such!
823
			if ($is_valid !== true)
824
			{
825
				// Is this an actual error?
826
				if ($is_valid !== false)
827
				{
828
					$post_errors[$key] = $is_valid;
829
					$profile_fields[$key]['is_error'] = $is_valid;
830
				}
831
				// Retain the old value.
832
				$cur_profile[$key] = $_POST[$key];
833
				continue;
834
			}
835
		}
836
837
		// Are we doing a cast?
838
		$field['cast_type'] = empty($field['cast_type']) ? $field['type'] : $field['cast_type'];
839
840
		// Finally, clean up certain types.
841
		if ($field['cast_type'] == 'int')
842
			$_POST[$key] = (int) $_POST[$key];
843
		elseif ($field['cast_type'] == 'float')
844
			$_POST[$key] = (float) $_POST[$key];
845
		elseif ($field['cast_type'] == 'check')
846
			$_POST[$key] = !empty($_POST[$key]) ? 1 : 0;
847
848
		// If we got here we're doing OK.
849
		if ($field['type'] != 'hidden' && (!isset($old_profile[$key]) || $_POST[$key] != $old_profile[$key]))
850
		{
851
			// Set the save variable.
852
			$profile_vars[$db_key] = $_POST[$key];
853
			// And update the user profile.
854
			$cur_profile[$key] = $_POST[$key];
855
856
			// Are we logging it?
857
			if (!empty($field['log_change']) && isset($old_profile[$key]))
858
				$context['log_changes'][$key] = array(
859
					'previous' => $old_profile[$key],
860
					'new' => $_POST[$key],
861
				);
862
		}
863
864
		// Logging group changes are a bit different...
865
		if ($key == 'id_group' && $field['log_change'])
866
		{
867
			profileLoadGroups();
868
869
			// Any changes to primary group?
870
			if ($_POST['id_group'] != $old_profile['id_group'])
871
			{
872
				$context['log_changes']['id_group'] = array(
873
					'previous' => !empty($old_profile[$key]) && isset($context['member_groups'][$old_profile[$key]]) ? $context['member_groups'][$old_profile[$key]]['name'] : '',
874
					'new' => !empty($_POST[$key]) && isset($context['member_groups'][$_POST[$key]]) ? $context['member_groups'][$_POST[$key]]['name'] : '',
875
				);
876
			}
877
878
			// Prepare additional groups for comparison.
879
			$additional_groups = array(
880
				'previous' => !empty($old_profile['additional_groups']) ? explode(',', $old_profile['additional_groups']) : array(),
881
				'new' => !empty($_POST['additional_groups']) ? array_diff($_POST['additional_groups'], array(0)) : array(),
882
			);
883
884
			sort($additional_groups['previous']);
885
			sort($additional_groups['new']);
886
887
			// What about additional groups?
888
			if ($additional_groups['previous'] != $additional_groups['new'])
889
			{
890
				foreach ($additional_groups as $type => $groups)
891
				{
892
					foreach ($groups as $id => $group)
893
					{
894
						if (isset($context['member_groups'][$group]))
895
							$additional_groups[$type][$id] = $context['member_groups'][$group]['name'];
896
						else
897
							unset($additional_groups[$type][$id]);
898
					}
899
					$additional_groups[$type] = implode(', ', $additional_groups[$type]);
900
				}
901
902
				$context['log_changes']['additional_groups'] = $additional_groups;
903
			}
904
		}
905
	}
906
907
	// @todo Temporary
908
	if ($context['user']['is_owner'])
909
		$changeOther = allowedTo(array('profile_extra_any', 'profile_extra_own'));
910
	else
911
		$changeOther = allowedTo('profile_extra_any');
912
	if ($changeOther && empty($post_errors))
913
	{
914
		makeThemeChanges($context['id_member'], isset($_POST['id_theme']) ? (int) $_POST['id_theme'] : $old_profile['id_theme']);
915
		if (!empty($_REQUEST['sa']))
916
		{
917
			$custom_fields_errors = makeCustomFieldChanges($context['id_member'], $_REQUEST['sa'], false, true);
918
919
			if (!empty($custom_fields_errors))
920
				$post_errors = array_merge($post_errors, $custom_fields_errors);
921
		}
922
	}
923
924
	// Free memory!
925
	unset($profile_fields);
926
}
927
928
/**
929
 * Save the profile changes
930
 *
931
 * @param array &$profile_vars The items to save
932
 * @param array &$post_errors An array of information about any errors that occurred
933
 * @param int $memID The ID of the member whose profile we're saving
934
 */
935
function saveProfileChanges(&$profile_vars, &$post_errors, $memID)
936
{
937
	global $user_profile, $context;
938
939
	// These make life easier....
940
	$old_profile = &$user_profile[$memID];
941
942
	// Permissions...
943
	if ($context['user']['is_owner'])
944
	{
945
		$changeOther = allowedTo(array('profile_extra_any', 'profile_extra_own', 'profile_website_any', 'profile_website_own', 'profile_signature_any', 'profile_signature_own'));
946
	}
947
	else
948
		$changeOther = allowedTo(array('profile_extra_any', 'profile_website_any', 'profile_signature_any'));
949
950
	// Arrays of all the changes - makes things easier.
951
	$profile_bools = array();
952
	$profile_ints = array();
953
	$profile_floats = array();
954
	$profile_strings = array(
955
		'buddy_list',
956
		'ignore_boards',
957
	);
958
959
	if (isset($_POST['sa']) && $_POST['sa'] == 'ignoreboards' && empty($_POST['ignore_brd']))
960
		$_POST['ignore_brd'] = array();
961
962
	unset($_POST['ignore_boards']); // Whatever it is set to is a dirty filthy thing.  Kinda like our minds.
963
	if (isset($_POST['ignore_brd']))
964
	{
965
		if (!is_array($_POST['ignore_brd']))
966
			$_POST['ignore_brd'] = array($_POST['ignore_brd']);
967
968
		foreach ($_POST['ignore_brd'] as $k => $d)
969
		{
970
			$d = (int) $d;
971
			if ($d != 0)
972
				$_POST['ignore_brd'][$k] = $d;
973
			else
974
				unset($_POST['ignore_brd'][$k]);
975
		}
976
		$_POST['ignore_boards'] = implode(',', $_POST['ignore_brd']);
977
		unset($_POST['ignore_brd']);
978
	}
979
980
	// Here's where we sort out all the 'other' values...
981
	if ($changeOther)
982
	{
983
		makeThemeChanges($memID, isset($_POST['id_theme']) ? (int) $_POST['id_theme'] : $old_profile['id_theme']);
984
		//makeAvatarChanges($memID, $post_errors);
985
986
		if (!empty($_REQUEST['sa']))
987
			makeCustomFieldChanges($memID, $_REQUEST['sa'], false);
988
989
		foreach ($profile_bools as $var)
990
			if (isset($_POST[$var]))
991
				$profile_vars[$var] = empty($_POST[$var]) ? '0' : '1';
992
		foreach ($profile_ints as $var)
993
			if (isset($_POST[$var]))
994
				$profile_vars[$var] = $_POST[$var] != '' ? (int) $_POST[$var] : '';
995
		foreach ($profile_floats as $var)
996
			if (isset($_POST[$var]))
997
				$profile_vars[$var] = (float) $_POST[$var];
998
		foreach ($profile_strings as $var)
999
			if (isset($_POST[$var]))
1000
				$profile_vars[$var] = $_POST[$var];
1001
	}
1002
}
1003
1004
/**
1005
 * Make any theme changes that are sent with the profile.
1006
 *
1007
 * @param int $memID The ID of the user
1008
 * @param int $id_theme The ID of the theme
1009
 */
1010
function makeThemeChanges($memID, $id_theme)
1011
{
1012
	global $modSettings, $smcFunc, $context, $user_info;
1013
1014
	$reservedVars = array(
1015
		'actual_theme_url',
1016
		'actual_images_url',
1017
		'base_theme_dir',
1018
		'base_theme_url',
1019
		'default_images_url',
1020
		'default_theme_dir',
1021
		'default_theme_url',
1022
		'default_template',
1023
		'images_url',
1024
		'number_recent_posts',
1025
		'smiley_sets_default',
1026
		'theme_dir',
1027
		'theme_id',
1028
		'theme_layers',
1029
		'theme_templates',
1030
		'theme_url',
1031
	);
1032
1033
	// Can't change reserved vars.
1034
	if ((isset($_POST['options']) && count(array_intersect(array_keys($_POST['options']), $reservedVars)) != 0) || (isset($_POST['default_options']) && count(array_intersect(array_keys($_POST['default_options']), $reservedVars)) != 0))
1035
		fatal_lang_error('no_access', false);
1036
1037
	// Don't allow any overriding of custom fields with default or non-default options.
1038
	$request = $smcFunc['db_query']('', '
1039
		SELECT col_name
1040
		FROM {db_prefix}custom_fields
1041
		WHERE active = {int:is_active}',
1042
		array(
1043
			'is_active' => 1,
1044
		)
1045
	);
1046
	$custom_fields = array();
1047
	while ($row = $smcFunc['db_fetch_assoc']($request))
1048
		$custom_fields[] = $row['col_name'];
1049
	$smcFunc['db_free_result']($request);
1050
1051
	// These are the theme changes...
1052
	$themeSetArray = array();
1053
	if (isset($_POST['options']) && is_array($_POST['options']))
1054
	{
1055
		foreach ($_POST['options'] as $opt => $val)
1056
		{
1057
			if (in_array($opt, $custom_fields))
1058
				continue;
1059
1060
			// These need to be controlled.
1061
			if ($opt == 'topics_per_page' || $opt == 'messages_per_page')
1062
				$val = max(0, min($val, 50));
1063
			// We don't set this per theme anymore.
1064
			elseif ($opt == 'allow_no_censored')
1065
				continue;
1066
1067
			$themeSetArray[] = array($memID, $id_theme, $opt, is_array($val) ? implode(',', $val) : $val);
1068
		}
1069
	}
1070
1071
	$erase_options = array();
1072
	if (isset($_POST['default_options']) && is_array($_POST['default_options']))
1073
		foreach ($_POST['default_options'] as $opt => $val)
1074
		{
1075
			if (in_array($opt, $custom_fields))
1076
				continue;
1077
1078
			// These need to be controlled.
1079
			if ($opt == 'topics_per_page' || $opt == 'messages_per_page')
1080
				$val = max(0, min($val, 50));
1081
			// Only let admins and owners change the censor.
1082
			elseif ($opt == 'allow_no_censored' && !$user_info['is_admin'] && !$context['user']['is_owner'])
1083
				continue;
1084
1085
			$themeSetArray[] = array($memID, 1, $opt, is_array($val) ? implode(',', $val) : $val);
1086
			$erase_options[] = $opt;
1087
		}
1088
1089
	// If themeSetArray isn't still empty, send it to the database.
1090
	if (empty($context['password_auth_failed']))
1091
	{
1092
		if (!empty($themeSetArray))
1093
		{
1094
			$smcFunc['db_insert']('replace',
1095
				'{db_prefix}themes',
1096
				array('id_member' => 'int', 'id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
1097
				$themeSetArray,
1098
				array('id_member', 'id_theme', 'variable')
1099
			);
1100
		}
1101
1102
		if (!empty($erase_options))
1103
		{
1104
			$smcFunc['db_query']('', '
1105
				DELETE FROM {db_prefix}themes
1106
				WHERE id_theme != {int:id_theme}
1107
					AND variable IN ({array_string:erase_variables})
1108
					AND id_member = {int:id_member}',
1109
				array(
1110
					'id_theme' => 1,
1111
					'id_member' => $memID,
1112
					'erase_variables' => $erase_options
1113
				)
1114
			);
1115
		}
1116
1117
		// Admins can choose any theme, even if it's not enabled...
1118
		$themes = allowedTo('admin_forum') ? explode(',', $modSettings['knownThemes']) : explode(',', $modSettings['enableThemes']);
1119
		foreach ($themes as $t)
1120
			cache_put_data('theme_settings-' . $t . ':' . $memID, null, 60);
1121
	}
1122
}
1123
1124
/**
1125
 * Make any notification changes that need to be made.
1126
 *
1127
 * @param int $memID The ID of the member
1128
 */
1129
function makeNotificationChanges($memID)
1130
{
1131
	global $smcFunc, $sourcedir;
1132
1133
	require_once($sourcedir . '/Subs-Notify.php');
1134
1135
	// Update the boards they are being notified on.
1136
	if (isset($_POST['edit_notify_boards']) && !empty($_POST['notify_boards']))
1137
	{
1138
		// Make sure only integers are deleted.
1139
		foreach ($_POST['notify_boards'] as $index => $id)
1140
			$_POST['notify_boards'][$index] = (int) $id;
1141
1142
		// id_board = 0 is reserved for topic notifications.
1143
		$_POST['notify_boards'] = array_diff($_POST['notify_boards'], array(0));
1144
1145
		$smcFunc['db_query']('', '
1146
			DELETE FROM {db_prefix}log_notify
1147
			WHERE id_board IN ({array_int:board_list})
1148
				AND id_member = {int:selected_member}',
1149
			array(
1150
				'board_list' => $_POST['notify_boards'],
1151
				'selected_member' => $memID,
1152
			)
1153
		);
1154
	}
1155
1156
	// We are editing topic notifications......
1157
	elseif (isset($_POST['edit_notify_topics']) && !empty($_POST['notify_topics']))
1158
	{
1159
		foreach ($_POST['notify_topics'] as $index => $id)
1160
			$_POST['notify_topics'][$index] = (int) $id;
1161
1162
		// Make sure there are no zeros left.
1163
		$_POST['notify_topics'] = array_diff($_POST['notify_topics'], array(0));
1164
1165
		$smcFunc['db_query']('', '
1166
			DELETE FROM {db_prefix}log_notify
1167
			WHERE id_topic IN ({array_int:topic_list})
1168
				AND id_member = {int:selected_member}',
1169
			array(
1170
				'topic_list' => $_POST['notify_topics'],
1171
				'selected_member' => $memID,
1172
			)
1173
		);
1174
		foreach ($_POST['notify_topics'] as $topic)
1175
			setNotifyPrefs($memID, array('topic_notify_' . $topic => 0));
1176
	}
1177
1178
	// We are removing topic preferences
1179
	elseif (isset($_POST['remove_notify_topics']) && !empty($_POST['notify_topics']))
1180
	{
1181
		$prefs = array();
1182
		foreach ($_POST['notify_topics'] as $topic)
1183
			$prefs[] = 'topic_notify_' . $topic;
1184
		deleteNotifyPrefs($memID, $prefs);
1185
	}
1186
1187
	// We are removing board preferences
1188
	elseif (isset($_POST['remove_notify_board']) && !empty($_POST['notify_boards']))
1189
	{
1190
		$prefs = array();
1191
		foreach ($_POST['notify_boards'] as $board)
1192
			$prefs[] = 'board_notify_' . $board;
1193
		deleteNotifyPrefs($memID, $prefs);
1194
	}
1195
}
1196
1197
/**
1198
 * Save any changes to the custom profile fields
1199
 *
1200
 * @param int $memID The ID of the member
1201
 * @param string $area The area of the profile these fields are in
1202
 * @param bool $sanitize = true Whether or not to sanitize the data
1203
 * @param bool $returnErrors Whether or not to return any error information
1204
 * @return void|array Returns nothing or returns an array of error info if $returnErrors is true
1205
 */
1206
function makeCustomFieldChanges($memID, $area, $sanitize = true, $returnErrors = false)
1207
{
1208
	global $context, $smcFunc, $user_profile, $user_info, $modSettings;
1209
	global $sourcedir;
1210
1211
	$errors = array();
1212
1213
	if ($sanitize && isset($_POST['customfield']))
1214
		$_POST['customfield'] = htmlspecialchars__recursive($_POST['customfield']);
1215
1216
	$where = $area == 'register' ? 'show_reg != 0' : 'show_profile = {string:area}';
1217
1218
	// Load the fields we are saving too - make sure we save valid data (etc).
1219
	$request = $smcFunc['db_query']('', '
1220
		SELECT col_name, field_name, field_desc, field_type, field_length, field_options, default_value, show_reg, mask, private
1221
		FROM {db_prefix}custom_fields
1222
		WHERE ' . $where . '
1223
			AND active = {int:is_active}',
1224
		array(
1225
			'is_active' => 1,
1226
			'area' => $area,
1227
		)
1228
	);
1229
	$changes = array();
1230
	$deletes = array();
1231
	$log_changes = array();
1232
	while ($row = $smcFunc['db_fetch_assoc']($request))
1233
	{
1234
		/* This means don't save if:
1235
			- The user is NOT an admin.
1236
			- The data is not freely viewable and editable by users.
1237
			- The data is not invisible to users but editable by the owner (or if it is the user is not the owner)
1238
			- The area isn't registration, and if it is that the field is not supposed to be shown there.
1239
		*/
1240
		if ($row['private'] != 0 && !allowedTo('admin_forum') && ($memID != $user_info['id'] || $row['private'] != 2) && ($area != 'register' || $row['show_reg'] == 0))
1241
			continue;
1242
1243
		// Validate the user data.
1244
		if ($row['field_type'] == 'check')
1245
			$value = isset($_POST['customfield'][$row['col_name']]) ? 1 : 0;
1246
		elseif ($row['field_type'] == 'select' || $row['field_type'] == 'radio')
1247
		{
1248
			$value = $row['default_value'];
1249
			foreach (explode(',', $row['field_options']) as $k => $v)
1250
				if (isset($_POST['customfield'][$row['col_name']]) && $_POST['customfield'][$row['col_name']] == $k)
1251
					$value = $v;
1252
		}
1253
		// Otherwise some form of text!
1254
		else
1255
		{
1256
			$value = isset($_POST['customfield'][$row['col_name']]) ? $_POST['customfield'][$row['col_name']] : '';
1257
1258
			if ($row['field_length'])
1259
				$value = $smcFunc['substr']($value, 0, $row['field_length']);
1260
1261
			// Any masks?
1262
			if ($row['field_type'] == 'text' && !empty($row['mask']) && $row['mask'] != 'none')
1263
			{
1264
				$value = $smcFunc['htmltrim']($value);
1265
				$valueReference = un_htmlspecialchars($value);
1266
1267
				// Try and avoid some checks. '0' could be a valid non-empty value.
1268
				if (empty($value) && !is_numeric($value))
1269
					$value = '';
1270
1271
				if ($row['mask'] == 'nohtml' && ($valueReference != strip_tags($valueReference) || $value != filter_var($value, FILTER_SANITIZE_STRING) || preg_match('/<(.+?)[\s]*\/?[\s]*>/si', $valueReference)))
1272
				{
1273
					if ($returnErrors)
1274
						$errors[] = 'custom_field_nohtml_fail';
1275
1276
					else
1277
						$value = '';
1278
				}
1279
				elseif ($row['mask'] == 'email' && !empty($value) && (!filter_var($value, FILTER_VALIDATE_EMAIL) || strlen($value) > 255))
1280
				{
1281
					if ($returnErrors)
1282
						$errors[] = 'custom_field_mail_fail';
1283
1284
					else
1285
						$value = '';
1286
				}
1287
				elseif ($row['mask'] == 'number')
1288
				{
1289
					$value = (int) $value;
1290
				}
1291
				elseif (substr($row['mask'], 0, 5) == 'regex' && trim($value) != '' && preg_match(substr($row['mask'], 5), $value) === 0)
1292
				{
1293
					if ($returnErrors)
1294
						$errors[] = 'custom_field_regex_fail';
1295
1296
					else
1297
						$value = '';
1298
				}
1299
1300
				unset($valueReference);
1301
			}
1302
		}
1303
1304
		if (!isset($user_profile[$memID]['options'][$row['col_name']]))
1305
			$user_profile[$memID]['options'][$row['col_name']] = '';
1306
1307
		// Did it change?
1308
		if ($user_profile[$memID]['options'][$row['col_name']] != $value)
1309
		{
1310
			$log_changes[] = array(
1311
				'action' => 'customfield_' . $row['col_name'],
1312
				'log_type' => 'user',
1313
				'extra' => array(
1314
					'previous' => !empty($user_profile[$memID]['options'][$row['col_name']]) ? $user_profile[$memID]['options'][$row['col_name']] : '',
1315
					'new' => $value,
1316
					'applicator' => $user_info['id'],
1317
					'member_affected' => $memID,
1318
				),
1319
			);
1320
			if (empty($value))
1321
			{
1322
				$deletes[] = array('id_theme' => 1, 'variable' => $row['col_name'], 'id_member' => $memID);
1323
				unset($user_profile[$memID]['options'][$row['col_name']]);
1324
			}
1325
			else
1326
			{
1327
				$changes[] = array(1, $row['col_name'], $value, $memID);
1328
				$user_profile[$memID]['options'][$row['col_name']] = $value;
1329
			}
1330
		}
1331
	}
1332
	$smcFunc['db_free_result']($request);
1333
1334
	$hook_errors = call_integration_hook('integrate_save_custom_profile_fields', array(&$changes, &$log_changes, &$errors, $returnErrors, $memID, $area, $sanitize, &$deletes));
1335
1336
	if (!empty($hook_errors) && is_array($hook_errors))
1337
		$errors = array_merge($errors, $hook_errors);
1338
1339
	// Make those changes!
1340
	if ((!empty($changes) || !empty($deletes)) && empty($context['password_auth_failed']) && empty($errors))
1341
	{
1342
		if (!empty($changes))
1343
			$smcFunc['db_insert']('replace',
1344
				'{db_prefix}themes',
1345
				array('id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534', 'id_member' => 'int'),
1346
				$changes,
1347
				array('id_theme', 'variable', 'id_member')
1348
			);
1349
		if (!empty($deletes))
1350
			foreach ($deletes as $delete)
1351
				$smcFunc['db_query']('', '
1352
					DELETE FROM {db_prefix}themes
1353
					WHERE id_theme = {int:id_theme}
1354
						AND variable = {string:variable}
1355
						AND id_member = {int:id_member}',
1356
					$delete
1357
				);
1358
		if (!empty($log_changes) && !empty($modSettings['modlog_enabled']))
1359
		{
1360
			require_once($sourcedir . '/Logging.php');
1361
			logActions($log_changes);
1362
		}
1363
	}
1364
1365
	if ($returnErrors)
1366
		return $errors;
1367
}
1368
1369
/**
1370
 * Show all the users buddies, as well as a add/delete interface.
1371
 *
1372
 * @param int $memID The ID of the member
1373
 */
1374
function editBuddyIgnoreLists($memID)
1375
{
1376
	global $context, $txt, $modSettings;
1377
1378
	// Do a quick check to ensure people aren't getting here illegally!
1379
	if (!$context['user']['is_owner'] || empty($modSettings['enable_buddylist']))
1380
		fatal_lang_error('no_access', false);
1381
1382
	// Can we email the user direct?
1383
	$context['can_moderate_forum'] = allowedTo('moderate_forum');
1384
	$context['can_send_email'] = allowedTo('moderate_forum');
1385
1386
	$subActions = array(
1387
		'buddies' => array('editBuddies', $txt['editBuddies']),
1388
		'ignore' => array('editIgnoreList', $txt['editIgnoreList']),
1389
	);
1390
1391
	$context['list_area'] = isset($_GET['sa']) && isset($subActions[$_GET['sa']]) ? $_GET['sa'] : 'buddies';
1392
1393
	// Create the tabs for the template.
1394
	$context[$context['profile_menu_name']]['tab_data'] = array(
1395
		'title' => $txt['editBuddyIgnoreLists'],
1396
		'description' => $txt['buddy_ignore_desc'],
1397
		'icon' => 'profile_hd.png',
1398
		'tabs' => array(
1399
			'buddies' => array(),
1400
			'ignore' => array(),
1401
		),
1402
	);
1403
1404
	loadJavaScriptFile('suggest.js', array('defer' => false, 'minimize' => true), 'smf_suggest');
1405
1406
	// Pass on to the actual function.
1407
	$context['sub_template'] = $subActions[$context['list_area']][0];
1408
	$call = call_helper($subActions[$context['list_area']][0], true);
1409
1410
	if (!empty($call))
1411
		call_user_func($call, $memID);
0 ignored issues
show
Bug introduced by
It seems like $call can also be of type boolean; however, parameter $function of call_user_func() does only seem to accept callable, maybe add an additional type check? ( Ignorable by Annotation )

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

1411
		call_user_func(/** @scrutinizer ignore-type */ $call, $memID);
Loading history...
1412
}
1413
1414
/**
1415
 * Show all the users buddies, as well as a add/delete interface.
1416
 *
1417
 * @param int $memID The ID of the member
1418
 */
1419
function editBuddies($memID)
1420
{
1421
	global $txt, $scripturl, $settings, $modSettings;
1422
	global $context, $user_profile, $memberContext, $smcFunc;
1423
1424
	// For making changes!
1425
	$buddiesArray = explode(',', $user_profile[$memID]['buddy_list']);
1426
	foreach ($buddiesArray as $k => $dummy)
1427
		if ($dummy == '')
1428
			unset($buddiesArray[$k]);
1429
1430
	// Removing a buddy?
1431
	if (isset($_GET['remove']))
1432
	{
1433
		checkSession('get');
1434
1435
		call_integration_hook('integrate_remove_buddy', array($memID));
1436
1437
		$_SESSION['prf-save'] = $txt['could_not_remove_person'];
1438
1439
		// Heh, I'm lazy, do it the easy way...
1440
		foreach ($buddiesArray as $key => $buddy)
1441
			if ($buddy == (int) $_GET['remove'])
1442
			{
1443
				unset($buddiesArray[$key]);
1444
				$_SESSION['prf-save'] = true;
1445
			}
1446
1447
		// Make the changes.
1448
		$user_profile[$memID]['buddy_list'] = implode(',', $buddiesArray);
1449
		updateMemberData($memID, array('buddy_list' => $user_profile[$memID]['buddy_list']));
1450
1451
		// Redirect off the page because we don't like all this ugly query stuff to stick in the history.
1452
		redirectexit('action=profile;area=lists;sa=buddies;u=' . $memID);
1453
	}
1454
	elseif (isset($_POST['new_buddy']))
1455
	{
1456
		checkSession();
1457
1458
		// Prepare the string for extraction...
1459
		$_POST['new_buddy'] = strtr($smcFunc['htmlspecialchars']($_POST['new_buddy'], ENT_QUOTES), array('&quot;' => '"'));
1460
		preg_match_all('~"([^"]+)"~', $_POST['new_buddy'], $matches);
1461
		$new_buddies = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $_POST['new_buddy']))));
1462
1463
		foreach ($new_buddies as $k => $dummy)
1464
		{
1465
			$new_buddies[$k] = strtr(trim($new_buddies[$k]), array('\'' => '&#039;'));
1466
1467
			if (strlen($new_buddies[$k]) == 0 || in_array($new_buddies[$k], array($user_profile[$memID]['member_name'], $user_profile[$memID]['real_name'])))
1468
				unset($new_buddies[$k]);
1469
		}
1470
1471
		call_integration_hook('integrate_add_buddies', array($memID, &$new_buddies));
1472
1473
		$_SESSION['prf-save'] = $txt['could_not_add_person'];
1474
		if (!empty($new_buddies))
1475
		{
1476
			// Now find out the id_member of the buddy.
1477
			$request = $smcFunc['db_query']('', '
1478
				SELECT id_member
1479
				FROM {db_prefix}members
1480
				WHERE member_name IN ({array_string:new_buddies}) OR real_name IN ({array_string:new_buddies})
1481
				LIMIT {int:count_new_buddies}',
1482
				array(
1483
					'new_buddies' => $new_buddies,
1484
					'count_new_buddies' => count($new_buddies),
1485
				)
1486
			);
1487
1488
			if ($smcFunc['db_num_rows']($request) != 0)
1489
				$_SESSION['prf-save'] = true;
1490
1491
			// Add the new member to the buddies array.
1492
			while ($row = $smcFunc['db_fetch_assoc']($request))
1493
			{
1494
				if (in_array($row['id_member'], $buddiesArray))
1495
					continue;
1496
				else
1497
					$buddiesArray[] = (int) $row['id_member'];
1498
			}
1499
			$smcFunc['db_free_result']($request);
1500
1501
			// Now update the current users buddy list.
1502
			$user_profile[$memID]['buddy_list'] = implode(',', $buddiesArray);
1503
			updateMemberData($memID, array('buddy_list' => $user_profile[$memID]['buddy_list']));
1504
		}
1505
1506
		// Back to the buddy list!
1507
		redirectexit('action=profile;area=lists;sa=buddies;u=' . $memID);
1508
	}
1509
1510
	// Get all the users "buddies"...
1511
	$buddies = array();
1512
1513
	// Gotta load the custom profile fields names.
1514
	$request = $smcFunc['db_query']('', '
1515
		SELECT col_name, field_name, field_desc, field_type, bbc, enclose
1516
		FROM {db_prefix}custom_fields
1517
		WHERE active = {int:active}
1518
			AND private < {int:private_level}',
1519
		array(
1520
			'active' => 1,
1521
			'private_level' => 2,
1522
		)
1523
	);
1524
1525
	$context['custom_pf'] = array();
1526
	$disabled_fields = isset($modSettings['disabled_profile_fields']) ? array_flip(explode(',', $modSettings['disabled_profile_fields'])) : array();
1527
	while ($row = $smcFunc['db_fetch_assoc']($request))
1528
		if (!isset($disabled_fields[$row['col_name']]))
1529
			$context['custom_pf'][$row['col_name']] = array(
1530
				'label' => $row['field_name'],
1531
				'type' => $row['field_type'],
1532
				'bbc' => !empty($row['bbc']),
1533
				'enclose' => $row['enclose'],
1534
			);
1535
1536
	// Gotta disable the gender option.
1537
	if (isset($context['custom_pf']['cust_gender']) && $context['custom_pf']['cust_gender'] == 'None')
1538
		unset($context['custom_pf']['cust_gender']);
1539
1540
	$smcFunc['db_free_result']($request);
1541
1542
	if (!empty($buddiesArray))
1543
	{
1544
		$result = $smcFunc['db_query']('', '
1545
			SELECT id_member
1546
			FROM {db_prefix}members
1547
			WHERE id_member IN ({array_int:buddy_list})
1548
			ORDER BY real_name
1549
			LIMIT {int:buddy_list_count}',
1550
			array(
1551
				'buddy_list' => $buddiesArray,
1552
				'buddy_list_count' => substr_count($user_profile[$memID]['buddy_list'], ',') + 1,
1553
			)
1554
		);
1555
		while ($row = $smcFunc['db_fetch_assoc']($result))
1556
			$buddies[] = $row['id_member'];
1557
		$smcFunc['db_free_result']($result);
1558
	}
1559
1560
	$context['buddy_count'] = count($buddies);
1561
1562
	// Load all the members up.
1563
	loadMemberData($buddies, false, 'profile');
1564
1565
	// Setup the context for each buddy.
1566
	$context['buddies'] = array();
1567
	foreach ($buddies as $buddy)
1568
	{
1569
		loadMemberContext($buddy);
1570
		$context['buddies'][$buddy] = $memberContext[$buddy];
1571
1572
		// Make sure to load the appropriate fields for each user
1573
		if (!empty($context['custom_pf']))
1574
		{
1575
			foreach ($context['custom_pf'] as $key => $column)
1576
			{
1577
				// Don't show anything if there isn't anything to show.
1578
				if (!isset($context['buddies'][$buddy]['options'][$key]))
1579
				{
1580
					$context['buddies'][$buddy]['options'][$key] = '';
1581
					continue;
1582
				}
1583
1584
				if ($column['bbc'] && !empty($context['buddies'][$buddy]['options'][$key]))
1585
					$context['buddies'][$buddy]['options'][$key] = strip_tags(parse_bbc($context['buddies'][$buddy]['options'][$key]));
1586
1587
				elseif ($column['type'] == 'check')
1588
					$context['buddies'][$buddy]['options'][$key] = $context['buddies'][$buddy]['options'][$key] == 0 ? $txt['no'] : $txt['yes'];
1589
1590
				// Enclosing the user input within some other text?
1591
				if (!empty($column['enclose']) && !empty($context['buddies'][$buddy]['options'][$key]))
1592
					$context['buddies'][$buddy]['options'][$key] = strtr($column['enclose'], array(
1593
						'{SCRIPTURL}' => $scripturl,
1594
						'{IMAGES_URL}' => $settings['images_url'],
1595
						'{DEFAULT_IMAGES_URL}' => $settings['default_images_url'],
1596
						'{INPUT}' => $context['buddies'][$buddy]['options'][$key],
1597
					));
1598
			}
1599
		}
1600
	}
1601
1602
	if (isset($_SESSION['prf-save']))
1603
	{
1604
		if ($_SESSION['prf-save'] === true)
1605
			$context['saved_successful'] = true;
1606
		else
1607
			$context['saved_failed'] = $_SESSION['prf-save'];
1608
1609
		unset($_SESSION['prf-save']);
1610
	}
1611
1612
	call_integration_hook('integrate_view_buddies', array($memID));
1613
}
1614
1615
/**
1616
 * Allows the user to view their ignore list, as well as the option to manage members on it.
1617
 *
1618
 * @param int $memID The ID of the member
1619
 */
1620
function editIgnoreList($memID)
1621
{
1622
	global $txt;
1623
	global $context, $user_profile, $memberContext, $smcFunc;
1624
1625
	// For making changes!
1626
	$ignoreArray = explode(',', $user_profile[$memID]['pm_ignore_list']);
1627
	foreach ($ignoreArray as $k => $dummy)
1628
		if ($dummy == '')
1629
			unset($ignoreArray[$k]);
1630
1631
	// Removing a member from the ignore list?
1632
	if (isset($_GET['remove']))
1633
	{
1634
		checkSession('get');
1635
1636
		$_SESSION['prf-save'] = $txt['could_not_remove_person'];
1637
1638
		// Heh, I'm lazy, do it the easy way...
1639
		foreach ($ignoreArray as $key => $id_remove)
1640
			if ($id_remove == (int) $_GET['remove'])
1641
			{
1642
				unset($ignoreArray[$key]);
1643
				$_SESSION['prf-save'] = true;
1644
			}
1645
1646
		// Make the changes.
1647
		$user_profile[$memID]['pm_ignore_list'] = implode(',', $ignoreArray);
1648
		updateMemberData($memID, array('pm_ignore_list' => $user_profile[$memID]['pm_ignore_list']));
1649
1650
		// Redirect off the page because we don't like all this ugly query stuff to stick in the history.
1651
		redirectexit('action=profile;area=lists;sa=ignore;u=' . $memID);
1652
	}
1653
	elseif (isset($_POST['new_ignore']))
1654
	{
1655
		checkSession();
1656
		// Prepare the string for extraction...
1657
		$_POST['new_ignore'] = strtr($smcFunc['htmlspecialchars']($_POST['new_ignore'], ENT_QUOTES), array('&quot;' => '"'));
1658
		preg_match_all('~"([^"]+)"~', $_POST['new_ignore'], $matches);
1659
		$new_entries = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $_POST['new_ignore']))));
1660
1661
		foreach ($new_entries as $k => $dummy)
1662
		{
1663
			$new_entries[$k] = strtr(trim($new_entries[$k]), array('\'' => '&#039;'));
1664
1665
			if (strlen($new_entries[$k]) == 0 || in_array($new_entries[$k], array($user_profile[$memID]['member_name'], $user_profile[$memID]['real_name'])))
1666
				unset($new_entries[$k]);
1667
		}
1668
1669
		$_SESSION['prf-save'] = $txt['could_not_add_person'];
1670
		if (!empty($new_entries))
1671
		{
1672
			// Now find out the id_member for the members in question.
1673
			$request = $smcFunc['db_query']('', '
1674
				SELECT id_member
1675
				FROM {db_prefix}members
1676
				WHERE member_name IN ({array_string:new_entries}) OR real_name IN ({array_string:new_entries})
1677
				LIMIT {int:count_new_entries}',
1678
				array(
1679
					'new_entries' => $new_entries,
1680
					'count_new_entries' => count($new_entries),
1681
				)
1682
			);
1683
1684
			if ($smcFunc['db_num_rows']($request) != 0)
1685
				$_SESSION['prf-save'] = true;
1686
1687
			// Add the new member to the buddies array.
1688
			while ($row = $smcFunc['db_fetch_assoc']($request))
1689
			{
1690
				if (in_array($row['id_member'], $ignoreArray))
1691
					continue;
1692
				else
1693
					$ignoreArray[] = (int) $row['id_member'];
1694
			}
1695
			$smcFunc['db_free_result']($request);
1696
1697
			// Now update the current users buddy list.
1698
			$user_profile[$memID]['pm_ignore_list'] = implode(',', $ignoreArray);
1699
			updateMemberData($memID, array('pm_ignore_list' => $user_profile[$memID]['pm_ignore_list']));
1700
		}
1701
1702
		// Back to the list of pityful people!
1703
		redirectexit('action=profile;area=lists;sa=ignore;u=' . $memID);
1704
	}
1705
1706
	// Initialise the list of members we're ignoring.
1707
	$ignored = array();
1708
1709
	if (!empty($ignoreArray))
1710
	{
1711
		$result = $smcFunc['db_query']('', '
1712
			SELECT id_member
1713
			FROM {db_prefix}members
1714
			WHERE id_member IN ({array_int:ignore_list})
1715
			ORDER BY real_name
1716
			LIMIT {int:ignore_list_count}',
1717
			array(
1718
				'ignore_list' => $ignoreArray,
1719
				'ignore_list_count' => substr_count($user_profile[$memID]['pm_ignore_list'], ',') + 1,
1720
			)
1721
		);
1722
		while ($row = $smcFunc['db_fetch_assoc']($result))
1723
			$ignored[] = $row['id_member'];
1724
		$smcFunc['db_free_result']($result);
1725
	}
1726
1727
	$context['ignore_count'] = count($ignored);
1728
1729
	// Load all the members up.
1730
	loadMemberData($ignored, false, 'profile');
1731
1732
	// Setup the context for each buddy.
1733
	$context['ignore_list'] = array();
1734
	foreach ($ignored as $ignore_member)
1735
	{
1736
		loadMemberContext($ignore_member);
1737
		$context['ignore_list'][$ignore_member] = $memberContext[$ignore_member];
1738
	}
1739
1740
	if (isset($_SESSION['prf-save']))
1741
	{
1742
		if ($_SESSION['prf-save'] === true)
1743
			$context['saved_successful'] = true;
1744
		else
1745
			$context['saved_failed'] = $_SESSION['prf-save'];
1746
1747
		unset($_SESSION['prf-save']);
1748
	}
1749
}
1750
1751
/**
1752
 * Handles the account section of the profile
1753
 *
1754
 * @param int $memID The ID of the member
1755
 */
1756
function account($memID)
1757
{
1758
	global $context, $txt;
1759
1760
	loadThemeOptions($memID);
1761
	if (allowedTo(array('profile_identity_own', 'profile_identity_any', 'profile_password_own', 'profile_password_any')))
1762
		loadCustomFields($memID, 'account');
1763
1764
	$context['sub_template'] = 'edit_options';
1765
	$context['page_desc'] = $txt['account_info'];
1766
1767
	setupProfileContext(
1768
		array(
1769
			'member_name', 'real_name', 'date_registered', 'posts', 'lngfile', 'hr',
1770
			'id_group', 'hr',
1771
			'email_address', 'show_online', 'hr',
1772
			'tfa', 'hr',
1773
			'passwrd1', 'passwrd2', 'hr',
1774
			'secret_question', 'secret_answer',
1775
		)
1776
	);
1777
}
1778
1779
/**
1780
 * Handles the main "Forum Profile" section of the profile
1781
 *
1782
 * @param int $memID The ID of the member
1783
 */
1784
function forumProfile($memID)
1785
{
1786
	global $context, $txt;
1787
1788
	loadThemeOptions($memID);
1789
	if (allowedTo(array('profile_forum_own', 'profile_forum_any')))
1790
		loadCustomFields($memID, 'forumprofile');
1791
1792
	$context['sub_template'] = 'edit_options';
1793
	$context['page_desc'] = $txt['forumProfile_info'];
1794
	$context['show_preview_button'] = true;
1795
1796
	setupProfileContext(
1797
		array(
1798
			'avatar_choice', 'hr', 'personal_text', 'hr',
1799
			'bday1', 'usertitle', 'signature', 'hr',
1800
			'website_title', 'website_url',
1801
		)
1802
	);
1803
}
1804
1805
/**
1806
 * Recursive function to retrieve server-stored avatar files
1807
 *
1808
 * @param string $directory The directory to look for files in
1809
 * @param int $level How many levels we should go in the directory
1810
 * @return array An array of information about the files and directories found
1811
 */
1812
function getAvatars($directory, $level)
1813
{
1814
	global $context, $txt, $modSettings, $smcFunc;
1815
1816
	$result = array();
1817
1818
	// Open the directory..
1819
	$dir = dir($modSettings['avatar_directory'] . (!empty($directory) ? '/' : '') . $directory);
1820
	$dirs = array();
1821
	$files = array();
1822
1823
	if (!$dir)
1824
		return array();
1825
1826
	while ($line = $dir->read())
1827
	{
1828
		if (in_array($line, array('.', '..', 'blank.png', 'index.php')))
1829
			continue;
1830
1831
		if (is_dir($modSettings['avatar_directory'] . '/' . $directory . (!empty($directory) ? '/' : '') . $line))
1832
			$dirs[] = $line;
1833
		else
1834
			$files[] = $line;
1835
	}
1836
	$dir->close();
1837
1838
	// Sort the results...
1839
	natcasesort($dirs);
1840
	natcasesort($files);
1841
1842
	if ($level == 0)
1843
	{
1844
		$result[] = array(
1845
			'filename' => 'blank.png',
1846
			'checked' => in_array($context['member']['avatar']['server_pic'], array('', 'blank.png')),
1847
			'name' => $txt['no_pic'],
1848
			'is_dir' => false
1849
		);
1850
	}
1851
1852
	foreach ($dirs as $line)
1853
	{
1854
		$tmp = getAvatars($directory . (!empty($directory) ? '/' : '') . $line, $level + 1);
1855
		if (!empty($tmp))
1856
			$result[] = array(
1857
				'filename' => $smcFunc['htmlspecialchars']($line),
1858
				'checked' => strpos($context['member']['avatar']['server_pic'], $line . '/') !== false,
1859
				'name' => '[' . $smcFunc['htmlspecialchars'](str_replace('_', ' ', $line)) . ']',
1860
				'is_dir' => true,
1861
				'files' => $tmp
1862
			);
1863
		unset($tmp);
1864
	}
1865
1866
	foreach ($files as $line)
1867
	{
1868
		$filename = substr($line, 0, (strlen($line) - strlen(strrchr($line, '.'))));
1869
		$extension = substr(strrchr($line, '.'), 1);
1870
1871
		// Make sure it is an image.
1872
		if (strcasecmp($extension, 'gif') != 0 && strcasecmp($extension, 'jpg') != 0 && strcasecmp($extension, 'jpeg') != 0 && strcasecmp($extension, 'png') != 0 && strcasecmp($extension, 'bmp') != 0)
1873
			continue;
1874
1875
		$result[] = array(
1876
			'filename' => $smcFunc['htmlspecialchars']($line),
1877
			'checked' => $line == $context['member']['avatar']['server_pic'],
1878
			'name' => $smcFunc['htmlspecialchars'](str_replace('_', ' ', $filename)),
1879
			'is_dir' => false
1880
		);
1881
		if ($level == 1)
1882
			$context['avatar_list'][] = $directory . '/' . $line;
1883
	}
1884
1885
	return $result;
1886
}
1887
1888
/**
1889
 * Handles the "Look and Layout" section of the profile
1890
 *
1891
 * @param int $memID The ID of the member
1892
 */
1893
function theme($memID)
1894
{
1895
	global $txt, $context;
1896
1897
	loadTemplate('Settings');
1898
	loadSubTemplate('options');
1899
1900
	// Let mods hook into the theme options.
1901
	call_integration_hook('integrate_theme_options');
1902
1903
	loadThemeOptions($memID);
1904
	if (allowedTo(array('profile_extra_own', 'profile_extra_any')))
1905
		loadCustomFields($memID, 'theme');
1906
1907
	$context['sub_template'] = 'edit_options';
1908
	$context['page_desc'] = $txt['theme_info'];
1909
1910
	setupProfileContext(
1911
		array(
1912
			'id_theme', 'smiley_set', 'hr',
1913
			'time_format', 'timezone', 'hr',
1914
			'theme_settings',
1915
		)
1916
	);
1917
}
1918
1919
/**
1920
 * Display the notifications and settings for changes.
1921
 *
1922
 * @param int $memID The ID of the member
1923
 */
1924
function notification($memID)
1925
{
1926
	global $txt, $context;
1927
1928
	// Going to want this for consistency.
1929
	loadCSSFile('admin.css', array(), 'smf_admin');
1930
1931
	// This is just a bootstrap for everything else.
1932
	$sa = array(
1933
		'alerts' => 'alert_configuration',
1934
		'markread' => 'alert_markread',
1935
		'topics' => 'alert_notifications_topics',
1936
		'boards' => 'alert_notifications_boards',
1937
	);
1938
1939
	$subAction = !empty($_GET['sa']) && isset($sa[$_GET['sa']]) ? $_GET['sa'] : 'alerts';
1940
1941
	$context['sub_template'] = $sa[$subAction];
1942
	$context[$context['profile_menu_name']]['tab_data'] = array(
1943
		'title' => $txt['notification'],
1944
		'help' => '',
1945
		'description' => $txt['notification_info'],
1946
	);
1947
	$sa[$subAction]($memID);
1948
}
1949
1950
/**
1951
 * Handles configuration of alert preferences
1952
 *
1953
 * @param int $memID The ID of the member
1954
 */
1955
function alert_configuration($memID)
1956
{
1957
	global $txt, $context, $modSettings, $smcFunc, $sourcedir;
1958
1959
	if (!isset($context['token_check']))
1960
		$context['token_check'] = 'profile-nt' . $memID;
1961
1962
	is_not_guest();
1963
	if (!$context['user']['is_owner'])
1964
		isAllowedTo('profile_extra_any');
1965
1966
	// Set the post action if we're coming from the profile...
1967
	if (!isset($context['action']))
1968
		$context['action'] = 'action=profile;area=notification;sa=alerts;u=' . $memID;
1969
1970
	// What options are set
1971
	loadThemeOptions($memID);
1972
	loadJavaScriptFile('alertSettings.js', array('minimize' => true), 'smf_alertSettings');
1973
1974
	// Now load all the values for this user.
1975
	require_once($sourcedir . '/Subs-Notify.php');
1976
	$prefs = getNotifyPrefs($memID, '', $memID != 0);
1977
1978
	$context['alert_prefs'] = !empty($prefs[$memID]) ? $prefs[$memID] : array();
1979
1980
	$context['member'] += array(
1981
		'alert_timeout' => isset($context['alert_prefs']['alert_timeout']) ? $context['alert_prefs']['alert_timeout'] : 10,
1982
		'notify_announcements' => isset($context['alert_prefs']['announcements']) ? $context['alert_prefs']['announcements'] : 0,
1983
	);
1984
	$context['can_disable_announce'] = $memID == 0 || !empty($modSettings['allow_disableAnnounce']);
1985
1986
	// Now for the exciting stuff.
1987
	// We have groups of items, each item has both an alert and an email key as well as an optional help string.
1988
	// Valid values for these keys are 'always', 'yes', 'never'; if using always or never you should add a help string.
1989
	$alert_types = array(
1990
		'board' => array(
1991
			'topic_notify' => array('alert' => 'yes', 'email' => 'yes'),
1992
			'board_notify' => array('alert' => 'yes', 'email' => 'yes'),
1993
		),
1994
		'msg' => array(
1995
			'msg_mention' => array('alert' => 'yes', 'email' => 'yes'),
1996
			'msg_quote' => array('alert' => 'yes', 'email' => 'yes'),
1997
			'msg_like' => array('alert' => 'yes', 'email' => 'never'),
1998
			'unapproved_reply' => array('alert' => 'yes', 'email' => 'yes'),
1999
		),
2000
		'pm' => array(
2001
			'pm_new' => array('alert' => 'never', 'email' => 'yes', 'help' => 'alert_pm_new', 'permission' => array('name' => 'pm_read', 'is_board' => false)),
2002
			'pm_reply' => array('alert' => 'never', 'email' => 'yes', 'help' => 'alert_pm_new', 'permission' => array('name' => 'pm_send', 'is_board' => false)),
2003
		),
2004
		'groupr' => array(
2005
			'groupr_approved' => array('alert' => 'yes', 'email' => 'yes'),
2006
			'groupr_rejected' => array('alert' => 'yes', 'email' => 'yes'),
2007
		),
2008
		'moderation' => array(
2009
			'unapproved_attachment' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'approve_posts', 'is_board' => true)),
2010
			'unapproved_post' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'approve_posts', 'is_board' => true)),
2011
			'msg_report' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_board', 'is_board' => true)),
2012
			'msg_report_reply' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_board', 'is_board' => true)),
2013
			'member_report' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_forum', 'is_board' => false)),
2014
			'member_report_reply' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_forum', 'is_board' => false)),
2015
		),
2016
		'members' => array(
2017
			'member_register' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_forum', 'is_board' => false)),
2018
			'request_group' => array('alert' => 'yes', 'email' => 'yes'),
2019
			'warn_any' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'issue_warning', 'is_board' => false)),
2020
			'buddy_request' => array('alert' => 'yes', 'email' => 'never'),
2021
			'birthday' => array('alert' => 'yes', 'email' => 'yes'),
2022
		),
2023
		'calendar' => array(
2024
			'event_new' => array('alert' => 'yes', 'email' => 'yes', 'help' => 'alert_event_new'),
2025
		),
2026
		'paidsubs' => array(
2027
			'paidsubs_expiring' => array('alert' => 'yes', 'email' => 'yes'),
2028
		),
2029
	);
2030
	$group_options = array(
2031
		'board' => array(
2032
			array('check', 'msg_auto_notify', 'label' => 'after'),
2033
			array('check', 'msg_receive_body', 'label' => 'after'),
2034
			array('select', 'msg_notify_pref', 'label' => 'before', 'opts' => array(
2035
				0 => $txt['alert_opt_msg_notify_pref_nothing'],
2036
				1 => $txt['alert_opt_msg_notify_pref_instant'],
2037
				2 => $txt['alert_opt_msg_notify_pref_first'],
2038
				3 => $txt['alert_opt_msg_notify_pref_daily'],
2039
				4 => $txt['alert_opt_msg_notify_pref_weekly'],
2040
			)),
2041
			array('select', 'msg_notify_type', 'label' => 'before', 'opts' => array(
2042
				1 => $txt['notify_send_type_everything'],
2043
				2 => $txt['notify_send_type_everything_own'],
2044
				3 => $txt['notify_send_type_only_replies'],
2045
				4 => $txt['notify_send_type_nothing'],
2046
			)),
2047
		),
2048
		'pm' => array(
2049
			array('select', 'pm_notify', 'label' => 'before', 'opts' => array(
2050
				1 => $txt['email_notify_all'],
2051
				2 => $txt['email_notify_buddies'],
2052
			)),
2053
		),
2054
	);
2055
2056
	// There are certain things that are disabled at the group level.
2057
	if (empty($modSettings['cal_enabled']))
2058
		unset($alert_types['calendar']);
2059
2060
	// Disable paid subscriptions at group level if they're disabled
2061
	if (empty($modSettings['paid_enabled']))
2062
		unset($alert_types['paidsubs']);
2063
2064
	// Disable membergroup requests at group level if they're disabled
2065
	if (empty($modSettings['show_group_membership']))
2066
		unset($alert_types['groupr'], $alert_types['members']['request_group']);
2067
2068
	// Disable mentions if they're disabled
2069
	if (empty($modSettings['enable_mentions']))
2070
		unset($alert_types['msg']['msg_mention']);
2071
2072
	// Disable likes if they're disabled
2073
	if (empty($modSettings['enable_likes']))
2074
		unset($alert_types['msg']['msg_like']);
2075
2076
	// Disable buddy requests if they're disabled
2077
	if (empty($modSettings['enable_buddylist']))
2078
		unset($alert_types['members']['buddy_request']);
2079
2080
	// Now, now, we could pass this through global but we should really get into the habit of
2081
	// passing content to hooks, not expecting hooks to splatter everything everywhere.
2082
	call_integration_hook('integrate_alert_types', array(&$alert_types, &$group_options));
2083
2084
	// Now we have to do some permissions testing - but only if we're not loading this from the admin center
2085
	if (!empty($memID))
2086
	{
2087
		require_once($sourcedir . '/Subs-Members.php');
2088
		$perms_cache = array();
2089
		$request = $smcFunc['db_query']('', '
2090
			SELECT COUNT(*)
2091
			FROM {db_prefix}group_moderators
2092
			WHERE id_member = {int:memID}',
2093
			array(
2094
				'memID' => $memID,
2095
			)
2096
		);
2097
2098
		list ($can_mod) = $smcFunc['db_fetch_row']($request);
2099
2100
		if (!isset($perms_cache['manage_membergroups']))
2101
		{
2102
			$members = membersAllowedTo('manage_membergroups');
2103
			$perms_cache['manage_membergroups'] = in_array($memID, $members);
2104
		}
2105
2106
		if (!($perms_cache['manage_membergroups'] || $can_mod != 0))
2107
			unset($alert_types['members']['request_group']);
2108
2109
		foreach ($alert_types as $group => $items)
2110
		{
2111
			foreach ($items as $alert_key => $alert_value)
2112
			{
2113
				if (!isset($alert_value['permission']))
2114
					continue;
2115
				if (!isset($perms_cache[$alert_value['permission']['name']]))
2116
				{
2117
					$in_board = !empty($alert_value['permission']['is_board']) ? 0 : null;
2118
					$members = membersAllowedTo($alert_value['permission']['name'], $in_board);
2119
					$perms_cache[$alert_value['permission']['name']] = in_array($memID, $members);
2120
				}
2121
2122
				if (!$perms_cache[$alert_value['permission']['name']])
2123
					unset ($alert_types[$group][$alert_key]);
2124
			}
2125
2126
			if (empty($alert_types[$group]))
2127
				unset ($alert_types[$group]);
2128
		}
2129
	}
2130
2131
	// And finally, exporting it to be useful later.
2132
	$context['alert_types'] = $alert_types;
2133
	$context['alert_group_options'] = $group_options;
2134
2135
	$context['alert_bits'] = array(
2136
		'alert' => 0x01,
2137
		'email' => 0x02,
2138
	);
2139
2140
	if (isset($_POST['notify_submit']))
2141
	{
2142
		checkSession();
2143
		validateToken($context['token_check'], 'post');
2144
2145
		// We need to step through the list of valid settings and figure out what the user has set.
2146
		$update_prefs = array();
2147
2148
		// Now the group level options
2149
		foreach ($context['alert_group_options'] as $opt_group => $group)
2150
		{
2151
			foreach ($group as $this_option)
2152
			{
2153
				switch ($this_option[0])
2154
				{
2155
					case 'check':
2156
						$update_prefs[$this_option[1]] = !empty($_POST['opt_' . $this_option[1]]) ? 1 : 0;
2157
						break;
2158
					case 'select':
2159
						if (isset($_POST['opt_' . $this_option[1]], $this_option['opts'][$_POST['opt_' . $this_option[1]]]))
2160
							$update_prefs[$this_option[1]] = $_POST['opt_' . $this_option[1]];
2161
						else
2162
						{
2163
							// We didn't have a sane value. Let's grab the first item from the possibles.
2164
							$keys = array_keys($this_option['opts']);
2165
							$first = array_shift($keys);
2166
							$update_prefs[$this_option[1]] = $first;
2167
						}
2168
						break;
2169
				}
2170
			}
2171
		}
2172
2173
		// Now the individual options
2174
		foreach ($context['alert_types'] as $alert_group => $items)
2175
		{
2176
			foreach ($items as $item_key => $this_options)
2177
			{
2178
				$this_value = 0;
2179
				foreach ($context['alert_bits'] as $type => $bitvalue)
2180
				{
2181
					if ($this_options[$type] == 'yes' && !empty($_POST[$type . '_' . $item_key]) || $this_options[$type] == 'always')
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($this_options[$type] ==...ions[$type] == 'always', Probably Intended Meaning: $this_options[$type] == ...ons[$type] == 'always')
Loading history...
2182
						$this_value |= $bitvalue;
2183
				}
2184
				if (!isset($context['alert_prefs'][$item_key]) || $context['alert_prefs'][$item_key] != $this_value)
2185
					$update_prefs[$item_key] = $this_value;
2186
			}
2187
		}
2188
2189
		if (!empty($_POST['opt_alert_timeout']))
2190
			$update_prefs['alert_timeout'] = $context['member']['alert_timeout'] = (int) $_POST['opt_alert_timeout'];
2191
2192
		if (!empty($_POST['notify_announcements']))
2193
			$update_prefs['announcements'] = $context['member']['notify_announcements'] = (int) $_POST['notify_announcements'];
2194
2195
		setNotifyPrefs((int) $memID, $update_prefs);
2196
		foreach ($update_prefs as $pref => $value)
2197
			$context['alert_prefs'][$pref] = $value;
2198
2199
		makeNotificationChanges($memID);
2200
2201
		$context['profile_updated'] = $txt['profile_updated_own'];
2202
	}
2203
2204
	createToken($context['token_check'], 'post');
2205
}
2206
2207
/**
2208
 * Marks all alerts as read for the specified user
2209
 *
2210
 * @param int $memID The ID of the member
2211
 */
2212
function alert_markread($memID)
2213
{
2214
	global $context, $db_show_debug, $smcFunc;
2215
2216
	// We do not want to output debug information here.
2217
	$db_show_debug = false;
2218
2219
	// We only want to output our little layer here.
2220
	$context['template_layers'] = array();
2221
	$context['sub_template'] = 'alerts_all_read';
2222
2223
	loadLanguage('Alerts');
2224
2225
	// Now we're all set up.
2226
	is_not_guest();
2227
	if (!$context['user']['is_owner'])
2228
		fatal_error('no_access');
2229
2230
	checkSession('get');
2231
2232
	// Assuming we're here, mark everything as read and head back.
2233
	// We only spit back the little layer because this should be called AJAXively.
2234
	$smcFunc['db_query']('', '
2235
		UPDATE {db_prefix}user_alerts
2236
		SET is_read = {int:now}
2237
		WHERE id_member = {int:current_member}
2238
			AND is_read = 0',
2239
		array(
2240
			'now' => time(),
2241
			'current_member' => $memID,
2242
		)
2243
	);
2244
2245
	updateMemberData($memID, array('alerts' => 0));
2246
}
2247
2248
/**
2249
 * Marks a group of alerts as un/read
2250
 *
2251
 * @param int $memID The user ID.
2252
 * @param array|integer $toMark The ID of a single alert or an array of IDs. The function will convert single integers to arrays for better handling.
2253
 * @param integer $read To mark as read or unread, 1 for read, 0 or any other value different than 1 for unread.
2254
 * @return integer How many alerts remain unread
2255
 */
2256
function alert_mark($memID, $toMark, $read = 0)
2257
{
2258
	global $smcFunc;
2259
2260
	if (empty($toMark) || empty($memID))
2261
		return false;
2262
2263
	$toMark = (array) $toMark;
2264
2265
	$smcFunc['db_query']('', '
2266
		UPDATE {db_prefix}user_alerts
2267
		SET is_read = {int:read}
2268
		WHERE id_alert IN({array_int:toMark})',
2269
		array(
2270
			'read' => $read == 1 ? time() : 0,
2271
			'toMark' => $toMark,
2272
		)
2273
	);
2274
2275
	// Gotta know how many unread alerts are left.
2276
	$count = alert_count($memID, true);
2277
2278
	updateMemberData($memID, array('alerts' => $count));
2279
2280
	// Might want to know this.
2281
	return $count;
2282
}
2283
2284
/**
2285
 * Deletes a single or a group of alerts by ID
2286
 *
2287
 * @param int|array The ID of a single alert to delete or an array containing the IDs of multiple alerts. The function will convert integers into an array for better handling.
0 ignored issues
show
Bug introduced by
The type The was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
2288
 * @param bool|int $memID The user ID. Used to update the user unread alerts count.
2289
 * @return void|int If the $memID param is set, returns the new amount of unread alerts.
2290
 */
2291
function alert_delete($toDelete, $memID = false)
2292
{
2293
	global $smcFunc;
2294
2295
	if (empty($toDelete))
2296
		return false;
2297
2298
	$toDelete = (array) $toDelete;
2299
2300
	$smcFunc['db_query']('', '
2301
		DELETE FROM {db_prefix}user_alerts
2302
		WHERE id_alert IN({array_int:toDelete})',
2303
		array(
2304
			'toDelete' => $toDelete,
2305
		)
2306
	);
2307
2308
	// Gotta know how many unread alerts are left.
2309
	if ($memID)
2310
	{
2311
		$count = alert_count($memID, true);
0 ignored issues
show
Bug introduced by
It seems like $memID can also be of type true; however, parameter $memID of alert_count() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

2311
		$count = alert_count(/** @scrutinizer ignore-type */ $memID, true);
Loading history...
2312
2313
		updateMemberData($memID, array('alerts' => $count));
2314
2315
		// Might want to know this.
2316
		return $count;
2317
	}
2318
}
2319
2320
/**
2321
 * Counts how many alerts a user has - either unread or all depending on $unread
2322
 * We can't use db_num_rows here, as we have to determine what boards the user can see
2323
 * Possibly in future versions as database support for json is mainstream, we can simplify this.
2324
 *
2325
 * @param int $memID The user ID.
2326
 * @param bool $unread Whether to only count unread alerts.
2327
 * @return int The number of requested alerts
2328
 */
2329
function alert_count($memID, $unread = false)
2330
{
2331
	global $smcFunc, $user_info;
2332
2333
	if (empty($memID))
2334
		return false;
2335
2336
	$alerts = array();
2337
	$possible_topics = array();
2338
	$possible_msgs = array();
2339
	$possible_attachments = array();
0 ignored issues
show
Unused Code introduced by
The assignment to $possible_attachments is dead and can be removed.
Loading history...
2340
2341
	// We have to do this the slow way as to iterate over all possible boards the user can see.
2342
	$request = $smcFunc['db_query']('', '
2343
		SELECT id_alert, content_id, content_type, content_action
2344
		FROM {db_prefix}user_alerts
2345
		WHERE id_member = {int:id_member}
2346
			' . ($unread ? '
2347
			AND is_read = 0' : ''),
2348
		array(
2349
			'id_member' => $memID,
2350
		)
2351
	);
2352
	// First we dump alerts and possible boards information out.
2353
	while ($row = $smcFunc['db_fetch_assoc']($request))
2354
	{
2355
		$alerts[$row['id_alert']] = $row;
2356
2357
		// For these types, we need to check whether they can actually see the content.
2358
		if ($row['content_type'] == 'msg')
2359
		{
2360
			$alerts[$row['id_alert']]['visible'] = false;
2361
			$possible_msgs[$row['id_alert']] = $row['content_id'];
2362
		}
2363
		elseif (in_array($row['content_type'], array('topic', 'board')))
2364
		{
2365
			$alerts[$row['id_alert']]['visible'] = false;
2366
			$possible_topics[$row['id_alert']] = $row['content_id'];
2367
		}
2368
		// For the rest, they can always see it.
2369
		else
2370
			$alerts[$row['id_alert']]['visible'] = true;
2371
	}
2372
	$smcFunc['db_free_result']($request);
2373
2374
	// If we need to check board access, use the correct board access filter for the member in question.
2375
	if ((!isset($user_info['query_see_board']) || $user_info['id'] != $memID) && (!empty($possible_msgs) || !empty($possible_topics)))
2376
		$qb = build_query_board($memID);
2377
	else
2378
	{
2379
		$qb['query_see_topic_board'] = '{query_see_topic_board}';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$qb was never initialized. Although not strictly required by PHP, it is generally a good practice to add $qb = array(); before regardless.
Loading history...
2380
		$qb['query_see_message_board'] = '{query_see_message_board}';
2381
	}
2382
2383
	// We want only the stuff they can see.
2384
	if (!empty($possible_msgs))
2385
	{
2386
		$flipped_msgs = array();
2387
		foreach ($possible_msgs as $id_alert => $id_msg)
2388
		{
2389
			if (!isset($flipped_msgs[$id_msg]))
2390
				$flipped_msgs[$id_msg] = array();
2391
2392
			$flipped_msgs[$id_msg][] = $id_alert;
2393
		}
2394
2395
		$request = $smcFunc['db_query']('', '
2396
			SELECT m.id_msg
2397
			FROM {db_prefix}messages AS m
2398
			WHERE ' . $qb['query_see_message_board'] . '
2399
				AND m.id_msg IN ({array_int:msgs})',
2400
			array(
2401
				'msgs' => $possible_msgs,
2402
			)
2403
		);
2404
		while ($row = $smcFunc['db_fetch_assoc']($request))
2405
		{
2406
			foreach ($flipped_msgs[$row['id_msg']] as $id_alert)
2407
				$alerts[$id_alert]['visible'] = true;
2408
		}
2409
		$smcFunc['db_free_result']($request);
2410
	}
2411
	if (!empty($possible_topics))
2412
	{
2413
		$flipped_topics = array();
2414
		foreach ($possible_topics as $id_alert => $id_topic)
2415
		{
2416
			if (!isset($flipped_topics[$id_topic]))
2417
				$flipped_topics[$id_topic] = array();
2418
2419
			$flipped_topics[$id_topic][] = $id_alert;
2420
		}
2421
2422
		$request = $smcFunc['db_query']('', '
2423
			SELECT t.id_topic
2424
			FROM {db_prefix}topics AS t
2425
			WHERE ' . $qb['query_see_topic_board'] . '
2426
				AND t.id_topic IN ({array_int:topics})',
2427
			array(
2428
				'topics' => $possible_topics,
2429
			)
2430
		);
2431
		while ($row = $smcFunc['db_fetch_assoc']($request))
2432
		{
2433
			foreach ($flipped_topics[$row['id_topic']] as $id_alert)
2434
				$alerts[$id_alert]['visible'] = true;
2435
		}
2436
		$smcFunc['db_free_result']($request);
2437
	}
2438
2439
	// Now check alerts again and remove any they can't see.
2440
	foreach ($alerts as $id_alert => $alert)
2441
	{
2442
		if (!$alert['visible'])
2443
			unset($alerts[$id_alert]);
2444
	}
2445
2446
	return count($alerts);
2447
}
2448
2449
/**
2450
 * Handles alerts related to topics and posts
2451
 *
2452
 * @param int $memID The ID of the member
2453
 */
2454
function alert_notifications_topics($memID)
2455
{
2456
	global $txt, $scripturl, $context, $modSettings, $sourcedir;
2457
2458
	// Because of the way this stuff works, we want to do this ourselves.
2459
	if (isset($_POST['edit_notify_topics']) || isset($_POST['remove_notify_topics']))
2460
	{
2461
		checkSession();
2462
		validateToken(str_replace('%u', $memID, 'profile-nt%u'), 'post');
2463
2464
		makeNotificationChanges($memID);
2465
		$context['profile_updated'] = $txt['profile_updated_own'];
2466
	}
2467
2468
	// Now set up for the token check.
2469
	$context['token_check'] = str_replace('%u', $memID, 'profile-nt%u');
2470
	createToken($context['token_check'], 'post');
2471
2472
	// Gonna want this for the list.
2473
	require_once($sourcedir . '/Subs-List.php');
2474
2475
	// Do the topic notifications.
2476
	$listOptions = array(
2477
		'id' => 'topic_notification_list',
2478
		'width' => '100%',
2479
		'items_per_page' => $modSettings['defaultMaxListItems'],
2480
		'no_items_label' => $txt['notifications_topics_none'] . '<br><br>' . $txt['notifications_topics_howto'],
2481
		'no_items_align' => 'left',
2482
		'base_href' => $scripturl . '?action=profile;u=' . $memID . ';area=notification;sa=topics',
2483
		'default_sort_col' => 'last_post',
2484
		'get_items' => array(
2485
			'function' => 'list_getTopicNotifications',
2486
			'params' => array(
2487
				$memID,
2488
			),
2489
		),
2490
		'get_count' => array(
2491
			'function' => 'list_getTopicNotificationCount',
2492
			'params' => array(
2493
				$memID,
2494
			),
2495
		),
2496
		'columns' => array(
2497
			'subject' => array(
2498
				'header' => array(
2499
					'value' => $txt['notifications_topics'],
2500
					'class' => 'lefttext',
2501
				),
2502
				'data' => array(
2503
					'function' => function($topic) use ($txt)
2504
					{
2505
						$link = $topic['link'];
2506
2507
						if ($topic['new'])
2508
							$link .= ' <a href="' . $topic['new_href'] . '" class="new_posts">' . $txt['new'] . '</a>';
2509
2510
						$link .= '<br><span class="smalltext"><em>' . $txt['in'] . ' ' . $topic['board_link'] . '</em></span>';
2511
2512
						return $link;
2513
					},
2514
				),
2515
				'sort' => array(
2516
					'default' => 'ms.subject',
2517
					'reverse' => 'ms.subject DESC',
2518
				),
2519
			),
2520
			'started_by' => array(
2521
				'header' => array(
2522
					'value' => $txt['started_by'],
2523
					'class' => 'lefttext',
2524
				),
2525
				'data' => array(
2526
					'db' => 'poster_link',
2527
				),
2528
				'sort' => array(
2529
					'default' => 'real_name_col',
2530
					'reverse' => 'real_name_col DESC',
2531
				),
2532
			),
2533
			'last_post' => array(
2534
				'header' => array(
2535
					'value' => $txt['last_post'],
2536
					'class' => 'lefttext',
2537
				),
2538
				'data' => array(
2539
					'sprintf' => array(
2540
						'format' => '<span class="smalltext">%1$s<br>' . $txt['by'] . ' %2$s</span>',
2541
						'params' => array(
2542
							'updated' => false,
2543
							'poster_updated_link' => false,
2544
						),
2545
					),
2546
				),
2547
				'sort' => array(
2548
					'default' => 'ml.id_msg DESC',
2549
					'reverse' => 'ml.id_msg',
2550
				),
2551
			),
2552
			'alert' => array(
2553
				'header' => array(
2554
					'value' => $txt['notify_what_how'],
2555
					'class' => 'lefttext',
2556
				),
2557
				'data' => array(
2558
					'function' => function($topic) use ($txt)
2559
					{
2560
						$pref = $topic['notify_pref'];
2561
						$mode = !empty($topic['unwatched']) ? 0 : ($pref & 0x02 ? 3 : ($pref & 0x01 ? 2 : 1));
2562
						return $txt['notify_topic_' . $mode];
2563
					},
2564
				),
2565
			),
2566
			'delete' => array(
2567
				'header' => array(
2568
					'value' => '<input type="checkbox" onclick="invertAll(this, this.form);">',
2569
					'style' => 'width: 4%;',
2570
					'class' => 'centercol',
2571
				),
2572
				'data' => array(
2573
					'sprintf' => array(
2574
						'format' => '<input type="checkbox" name="notify_topics[]" value="%1$d">',
2575
						'params' => array(
2576
							'id' => false,
2577
						),
2578
					),
2579
					'class' => 'centercol',
2580
				),
2581
			),
2582
		),
2583
		'form' => array(
2584
			'href' => $scripturl . '?action=profile;area=notification;sa=topics',
2585
			'include_sort' => true,
2586
			'include_start' => true,
2587
			'hidden_fields' => array(
2588
				'u' => $memID,
2589
				'sa' => $context['menu_item_selected'],
2590
				$context['session_var'] => $context['session_id'],
2591
			),
2592
			'token' => $context['token_check'],
2593
		),
2594
		'additional_rows' => array(
2595
			array(
2596
				'position' => 'bottom_of_list',
2597
				'value' => '<input type="submit" name="edit_notify_topics" value="' . $txt['notifications_update'] . '" class="button" />
2598
							<input type="submit" name="remove_notify_topics" value="' . $txt['notification_remove_pref'] . '" class="button" />',
2599
				'class' => 'floatright',
2600
			),
2601
		),
2602
	);
2603
2604
	// Create the notification list.
2605
	createList($listOptions);
2606
}
2607
2608
/**
2609
 * Handles preferences related to board-level notifications
2610
 *
2611
 * @param int $memID The ID of the member
2612
 */
2613
function alert_notifications_boards($memID)
2614
{
2615
	global $txt, $scripturl, $context, $sourcedir;
2616
2617
	// Because of the way this stuff works, we want to do this ourselves.
2618
	if (isset($_POST['edit_notify_boards']) || isset($_POSt['remove_notify_boards']))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $_POSt seems to never exist and therefore isset should always be false.
Loading history...
2619
	{
2620
		checkSession();
2621
		validateToken(str_replace('%u', $memID, 'profile-nt%u'), 'post');
2622
2623
		makeNotificationChanges($memID);
2624
		$context['profile_updated'] = $txt['profile_updated_own'];
2625
	}
2626
2627
	// Now set up for the token check.
2628
	$context['token_check'] = str_replace('%u', $memID, 'profile-nt%u');
2629
	createToken($context['token_check'], 'post');
2630
2631
	// Gonna want this for the list.
2632
	require_once($sourcedir . '/Subs-List.php');
2633
2634
	// Fine, start with the board list.
2635
	$listOptions = array(
2636
		'id' => 'board_notification_list',
2637
		'width' => '100%',
2638
		'no_items_label' => $txt['notifications_boards_none'] . '<br><br>' . $txt['notifications_boards_howto'],
2639
		'no_items_align' => 'left',
2640
		'base_href' => $scripturl . '?action=profile;u=' . $memID . ';area=notification;sa=boards',
2641
		'default_sort_col' => 'board_name',
2642
		'get_items' => array(
2643
			'function' => 'list_getBoardNotifications',
2644
			'params' => array(
2645
				$memID,
2646
			),
2647
		),
2648
		'columns' => array(
2649
			'board_name' => array(
2650
				'header' => array(
2651
					'value' => $txt['notifications_boards'],
2652
					'class' => 'lefttext',
2653
				),
2654
				'data' => array(
2655
					'function' => function($board) use ($txt)
2656
					{
2657
						$link = $board['link'];
2658
2659
						if ($board['new'])
2660
							$link .= ' <a href="' . $board['href'] . '" class="new_posts">' . $txt['new'] . '</a>';
2661
2662
						return $link;
2663
					},
2664
				),
2665
				'sort' => array(
2666
					'default' => 'name',
2667
					'reverse' => 'name DESC',
2668
				),
2669
			),
2670
			'alert' => array(
2671
				'header' => array(
2672
					'value' => $txt['notify_what_how'],
2673
					'class' => 'lefttext',
2674
				),
2675
				'data' => array(
2676
					'function' => function($board) use ($txt)
2677
					{
2678
						$pref = $board['notify_pref'];
2679
						$mode = $pref & 0x02 ? 3 : ($pref & 0x01 ? 2 : 1);
2680
						return $txt['notify_board_' . $mode];
2681
					},
2682
				),
2683
			),
2684
			'delete' => array(
2685
				'header' => array(
2686
					'value' => '<input type="checkbox" onclick="invertAll(this, this.form);">',
2687
					'style' => 'width: 4%;',
2688
					'class' => 'centercol',
2689
				),
2690
				'data' => array(
2691
					'sprintf' => array(
2692
						'format' => '<input type="checkbox" name="notify_boards[]" value="%1$d">',
2693
						'params' => array(
2694
							'id' => false,
2695
						),
2696
					),
2697
					'class' => 'centercol',
2698
				),
2699
			),
2700
		),
2701
		'form' => array(
2702
			'href' => $scripturl . '?action=profile;area=notification;sa=boards',
2703
			'include_sort' => true,
2704
			'include_start' => true,
2705
			'hidden_fields' => array(
2706
				'u' => $memID,
2707
				'sa' => $context['menu_item_selected'],
2708
				$context['session_var'] => $context['session_id'],
2709
			),
2710
			'token' => $context['token_check'],
2711
		),
2712
		'additional_rows' => array(
2713
			array(
2714
				'position' => 'bottom_of_list',
2715
				'value' => '<input type="submit" name="edit_notify_boards" value="' . $txt['notifications_update'] . '" class="button">
2716
							<input type="submit" name="remove_notify_boards" value="' . $txt['notification_remove_pref'] . '" class="button" />',
2717
				'class' => 'floatright',
2718
			),
2719
		),
2720
	);
2721
2722
	// Create the board notification list.
2723
	createList($listOptions);
2724
}
2725
2726
/**
2727
 * Determins how many topics a user has requested notifications for
2728
 *
2729
 * @param int $memID The ID of the member
2730
 * @return int The number of topic notifications for this user
2731
 */
2732
function list_getTopicNotificationCount($memID)
2733
{
2734
	global $smcFunc, $user_info, $modSettings;
2735
2736
	$request = $smcFunc['db_query']('', '
2737
		SELECT COUNT(*)
2738
		FROM {db_prefix}log_notify AS ln' . (!$modSettings['postmod_active'] && $user_info['query_see_board'] === '1=1' ? '' : '
2739
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ln.id_topic)') . '
2740
		WHERE ln.id_member = {int:selected_member}' . ($user_info['query_see_topic_board'] === '1=1' ? '' : '
2741
			AND {query_see_topic_board}') . ($modSettings['postmod_active'] ? '
2742
			AND t.approved = {int:is_approved}' : ''),
2743
		array(
2744
			'selected_member' => $memID,
2745
			'is_approved' => 1,
2746
		)
2747
	);
2748
	list ($totalNotifications) = $smcFunc['db_fetch_row']($request);
2749
	$smcFunc['db_free_result']($request);
2750
2751
	return (int) $totalNotifications;
2752
}
2753
2754
/**
2755
 * Gets information about all the topics a user has requested notifications for. Callback for the list in alert_notifications_topics
2756
 *
2757
 * @param int $start Which item to start with (for pagination purposes)
2758
 * @param int $items_per_page How many items to display on each page
2759
 * @param string $sort A string indicating how to sort the results
2760
 * @param int $memID The ID of the member
2761
 * @return array An array of information about the topics a user has subscribed to
2762
 */
2763
function list_getTopicNotifications($start, $items_per_page, $sort, $memID)
2764
{
2765
	global $smcFunc, $scripturl, $user_info, $modSettings, $sourcedir;
2766
2767
	require_once($sourcedir . '/Subs-Notify.php');
2768
	$prefs = getNotifyPrefs($memID);
2769
	$prefs = isset($prefs[$memID]) ? $prefs[$memID] : array();
2770
2771
	// All the topics with notification on...
2772
	$request = $smcFunc['db_query']('', '
2773
		SELECT
2774
			COALESCE(lt.id_msg, lmr.id_msg, -1) + 1 AS new_from, b.id_board, b.name,
2775
			t.id_topic, ms.subject, ms.id_member, COALESCE(mem.real_name, ms.poster_name) AS real_name_col,
2776
			ml.id_msg_modified, ml.poster_time, ml.id_member AS id_member_updated,
2777
			COALESCE(mem2.real_name, ml.poster_name) AS last_real_name,
2778
			lt.unwatched
2779
		FROM {db_prefix}log_notify AS ln
2780
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ln.id_topic' . ($modSettings['postmod_active'] ? ' AND t.approved = {int:is_approved}' : '') . ')
2781
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board AND {query_see_board})
2782
			INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
2783
			INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
2784
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ms.id_member)
2785
			LEFT JOIN {db_prefix}members AS mem2 ON (mem2.id_member = ml.id_member)
2786
			LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
2787
			LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = b.id_board AND lmr.id_member = {int:current_member})
2788
		WHERE ln.id_member = {int:selected_member}
2789
		ORDER BY {raw:sort}
2790
		LIMIT {int:offset}, {int:items_per_page}',
2791
		array(
2792
			'current_member' => $user_info['id'],
2793
			'is_approved' => 1,
2794
			'selected_member' => $memID,
2795
			'sort' => $sort,
2796
			'offset' => $start,
2797
			'items_per_page' => $items_per_page,
2798
		)
2799
	);
2800
	$notification_topics = array();
2801
	while ($row = $smcFunc['db_fetch_assoc']($request))
2802
	{
2803
		censorText($row['subject']);
2804
2805
		$notification_topics[] = array(
2806
			'id' => $row['id_topic'],
2807
			'poster_link' => empty($row['id_member']) ? $row['real_name_col'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name_col'] . '</a>',
2808
			'poster_updated_link' => empty($row['id_member_updated']) ? $row['last_real_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_updated'] . '">' . $row['last_real_name'] . '</a>',
2809
			'subject' => $row['subject'],
2810
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
2811
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['subject'] . '</a>',
2812
			'new' => $row['new_from'] <= $row['id_msg_modified'],
2813
			'new_from' => $row['new_from'],
2814
			'updated' => timeformat($row['poster_time']),
2815
			'new_href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['new_from'] . '#new',
2816
			'new_link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['new_from'] . '#new">' . $row['subject'] . '</a>',
2817
			'board_link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['name'] . '</a>',
2818
			'notify_pref' => isset($prefs['topic_notify_' . $row['id_topic']]) ? $prefs['topic_notify_' . $row['id_topic']] : (!empty($prefs['topic_notify']) ? $prefs['topic_notify'] : 0),
2819
			'unwatched' => $row['unwatched'],
2820
		);
2821
	}
2822
	$smcFunc['db_free_result']($request);
2823
2824
	return $notification_topics;
2825
}
2826
2827
/**
2828
 * Gets information about all the boards a user has requested notifications for. Callback for the list in alert_notifications_boards
2829
 *
2830
 * @param int $start Which item to start with (not used here)
2831
 * @param int $items_per_page How many items to show on each page (not used here)
2832
 * @param string $sort A string indicating how to sort the results
2833
 * @param int $memID The ID of the member
2834
 * @return array An array of information about all the boards a user is subscribed to
2835
 */
2836
function list_getBoardNotifications($start, $items_per_page, $sort, $memID)
2837
{
2838
	global $smcFunc, $scripturl, $user_info, $sourcedir;
2839
2840
	require_once($sourcedir . '/Subs-Notify.php');
2841
	$prefs = getNotifyPrefs($memID);
2842
	$prefs = isset($prefs[$memID]) ? $prefs[$memID] : array();
2843
2844
	$request = $smcFunc['db_query']('', '
2845
		SELECT b.id_board, b.name, COALESCE(lb.id_msg, 0) AS board_read, b.id_msg_updated
2846
		FROM {db_prefix}log_notify AS ln
2847
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = ln.id_board)
2848
			LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = b.id_board AND lb.id_member = {int:current_member})
2849
		WHERE ln.id_member = {int:selected_member}
2850
			AND {query_see_board}
2851
		ORDER BY {raw:sort}',
2852
		array(
2853
			'current_member' => $user_info['id'],
2854
			'selected_member' => $memID,
2855
			'sort' => $sort,
2856
		)
2857
	);
2858
	$notification_boards = array();
2859
	while ($row = $smcFunc['db_fetch_assoc']($request))
2860
		$notification_boards[] = array(
2861
			'id' => $row['id_board'],
2862
			'name' => $row['name'],
2863
			'href' => $scripturl . '?board=' . $row['id_board'] . '.0',
2864
			'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['name'] . '</a>',
2865
			'new' => $row['board_read'] < $row['id_msg_updated'],
2866
			'notify_pref' => isset($prefs['board_notify_' . $row['id_board']]) ? $prefs['board_notify_' . $row['id_board']] : (!empty($prefs['board_notify']) ? $prefs['board_notify'] : 0),
2867
		);
2868
	$smcFunc['db_free_result']($request);
2869
2870
	return $notification_boards;
2871
}
2872
2873
/**
2874
 * Loads the theme options for a user
2875
 *
2876
 * @param int $memID The ID of the member
2877
 */
2878
function loadThemeOptions($memID)
2879
{
2880
	global $context, $options, $cur_profile, $smcFunc;
2881
2882
	if (isset($_POST['default_options']))
2883
		$_POST['options'] = isset($_POST['options']) ? $_POST['options'] + $_POST['default_options'] : $_POST['default_options'];
2884
2885
	if ($context['user']['is_owner'])
2886
	{
2887
		$context['member']['options'] = $options;
2888
		if (isset($_POST['options']) && is_array($_POST['options']))
2889
			foreach ($_POST['options'] as $k => $v)
2890
				$context['member']['options'][$k] = $v;
2891
	}
2892
	else
2893
	{
2894
		$request = $smcFunc['db_query']('', '
2895
			SELECT id_member, variable, value
2896
			FROM {db_prefix}themes
2897
			WHERE id_theme IN (1, {int:member_theme})
2898
				AND id_member IN (-1, {int:selected_member})',
2899
			array(
2900
				'member_theme' => (int) $cur_profile['id_theme'],
2901
				'selected_member' => $memID,
2902
			)
2903
		);
2904
		$temp = array();
2905
		while ($row = $smcFunc['db_fetch_assoc']($request))
2906
		{
2907
			if ($row['id_member'] == -1)
2908
			{
2909
				$temp[$row['variable']] = $row['value'];
2910
				continue;
2911
			}
2912
2913
			if (isset($_POST['options'][$row['variable']]))
2914
				$row['value'] = $_POST['options'][$row['variable']];
2915
			$context['member']['options'][$row['variable']] = $row['value'];
2916
		}
2917
		$smcFunc['db_free_result']($request);
2918
2919
		// Load up the default theme options for any missing.
2920
		foreach ($temp as $k => $v)
2921
		{
2922
			if (!isset($context['member']['options'][$k]))
2923
				$context['member']['options'][$k] = $v;
2924
		}
2925
	}
2926
}
2927
2928
/**
2929
 * Handles the "ignored boards" section of the profile (if enabled)
2930
 *
2931
 * @param int $memID The ID of the member
2932
 */
2933
function ignoreboards($memID)
2934
{
2935
	global $context, $modSettings, $smcFunc, $cur_profile, $sourcedir;
2936
2937
	// Have the admins enabled this option?
2938
	if (empty($modSettings['allow_ignore_boards']))
2939
		fatal_lang_error('ignoreboards_disallowed', 'user');
2940
2941
	// Find all the boards this user is allowed to see.
2942
	$request = $smcFunc['db_query']('order_by_board_order', '
2943
		SELECT b.id_cat, c.name AS cat_name, b.id_board, b.name, b.child_level,
2944
			' . (!empty($cur_profile['ignore_boards']) ? 'b.id_board IN ({array_int:ignore_boards})' : '0') . ' AS is_ignored
2945
		FROM {db_prefix}boards AS b
2946
			LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
2947
		WHERE {query_see_board}
2948
			AND redirect = {string:empty_string}',
2949
		array(
2950
			'ignore_boards' => !empty($cur_profile['ignore_boards']) ? explode(',', $cur_profile['ignore_boards']) : array(),
2951
			'empty_string' => '',
2952
		)
2953
	);
2954
	$context['num_boards'] = $smcFunc['db_num_rows']($request);
2955
	$context['categories'] = array();
2956
	while ($row = $smcFunc['db_fetch_assoc']($request))
2957
	{
2958
		// This category hasn't been set up yet..
2959
		if (!isset($context['categories'][$row['id_cat']]))
2960
			$context['categories'][$row['id_cat']] = array(
2961
				'id' => $row['id_cat'],
2962
				'name' => $row['cat_name'],
2963
				'boards' => array()
2964
			);
2965
2966
		// Set this board up, and let the template know when it's a child.  (indent them..)
2967
		$context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array(
2968
			'id' => $row['id_board'],
2969
			'name' => $row['name'],
2970
			'child_level' => $row['child_level'],
2971
			'selected' => $row['is_ignored'],
2972
		);
2973
	}
2974
	$smcFunc['db_free_result']($request);
2975
2976
	require_once($sourcedir . '/Subs-Boards.php');
2977
	sortCategories($context['categories']);
2978
2979
	// Now, let's sort the list of categories into the boards for templates that like that.
2980
	$temp_boards = array();
2981
	foreach ($context['categories'] as $category)
2982
	{
2983
		// Include a list of boards per category for easy toggling.
2984
		$context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']);
2985
2986
		$temp_boards[] = array(
2987
			'name' => $category['name'],
2988
			'child_ids' => array_keys($category['boards'])
2989
		);
2990
		$temp_boards = array_merge($temp_boards, array_values($category['boards']));
2991
	}
2992
2993
	$max_boards = ceil(count($temp_boards) / 2);
2994
	if ($max_boards == 1)
2995
		$max_boards = 2;
2996
2997
	// Now, alternate them so they can be shown left and right ;).
2998
	$context['board_columns'] = array();
2999
	for ($i = 0; $i < $max_boards; $i++)
3000
	{
3001
		$context['board_columns'][] = $temp_boards[$i];
3002
		if (isset($temp_boards[$i + $max_boards]))
3003
			$context['board_columns'][] = $temp_boards[$i + $max_boards];
3004
		else
3005
			$context['board_columns'][] = array();
3006
	}
3007
3008
	loadThemeOptions($memID);
3009
}
3010
3011
/**
3012
 * Load all the languages for the profile
3013
 * .
3014
 * @return bool Whether or not the forum has multiple languages installed
3015
 */
3016
function profileLoadLanguages()
3017
{
3018
	global $context;
3019
3020
	$context['profile_languages'] = array();
3021
3022
	// Get our languages!
3023
	getLanguages();
3024
3025
	// Setup our languages.
3026
	foreach ($context['languages'] as $lang)
3027
	{
3028
		$context['profile_languages'][$lang['filename']] = strtr($lang['name'], array('-utf8' => ''));
3029
	}
3030
	ksort($context['profile_languages']);
3031
3032
	// Return whether we should proceed with this.
3033
	return count($context['profile_languages']) > 1 ? true : false;
3034
}
3035
3036
/**
3037
 * Handles the "manage groups" section of the profile
3038
 *
3039
 * @return true Always returns true
3040
 */
3041
function profileLoadGroups()
3042
{
3043
	global $cur_profile, $txt, $context, $smcFunc, $user_settings;
3044
3045
	$context['member_groups'] = array(
3046
		0 => array(
3047
			'id' => 0,
3048
			'name' => $txt['no_primary_membergroup'],
3049
			'is_primary' => $cur_profile['id_group'] == 0,
3050
			'can_be_additional' => false,
3051
			'can_be_primary' => true,
3052
		)
3053
	);
3054
	$curGroups = explode(',', $cur_profile['additional_groups']);
3055
3056
	// Load membergroups, but only those groups the user can assign.
3057
	$request = $smcFunc['db_query']('', '
3058
		SELECT group_name, id_group, hidden
3059
		FROM {db_prefix}membergroups
3060
		WHERE id_group != {int:moderator_group}
3061
			AND min_posts = {int:min_posts}' . (allowedTo('admin_forum') ? '' : '
3062
			AND group_type != {int:is_protected}') . '
3063
		ORDER BY min_posts, CASE WHEN id_group < {int:newbie_group} THEN id_group ELSE 4 END, group_name',
3064
		array(
3065
			'moderator_group' => 3,
3066
			'min_posts' => -1,
3067
			'is_protected' => 1,
3068
			'newbie_group' => 4,
3069
		)
3070
	);
3071
	while ($row = $smcFunc['db_fetch_assoc']($request))
3072
	{
3073
		// We should skip the administrator group if they don't have the admin_forum permission!
3074
		if ($row['id_group'] == 1 && !allowedTo('admin_forum'))
3075
			continue;
3076
3077
		$context['member_groups'][$row['id_group']] = array(
3078
			'id' => $row['id_group'],
3079
			'name' => $row['group_name'],
3080
			'is_primary' => $cur_profile['id_group'] == $row['id_group'],
3081
			'is_additional' => in_array($row['id_group'], $curGroups),
3082
			'can_be_additional' => true,
3083
			'can_be_primary' => $row['hidden'] != 2,
3084
		);
3085
	}
3086
	$smcFunc['db_free_result']($request);
3087
3088
	$context['member']['group_id'] = $user_settings['id_group'];
3089
3090
	return true;
3091
}
3092
3093
/**
3094
 * Load key signature context data.
3095
 *
3096
 * @return true Always returns true
3097
 */
3098
function profileLoadSignatureData()
3099
{
3100
	global $modSettings, $context, $txt, $cur_profile, $memberContext;
3101
3102
	// Signature limits.
3103
	list ($sig_limits, $sig_bbc) = explode(':', $modSettings['signature_settings']);
3104
	$sig_limits = explode(',', $sig_limits);
3105
3106
	$context['signature_enabled'] = isset($sig_limits[0]) ? $sig_limits[0] : 0;
3107
	$context['signature_limits'] = array(
3108
		'max_length' => isset($sig_limits[1]) ? $sig_limits[1] : 0,
3109
		'max_lines' => isset($sig_limits[2]) ? $sig_limits[2] : 0,
3110
		'max_images' => isset($sig_limits[3]) ? $sig_limits[3] : 0,
3111
		'max_smileys' => isset($sig_limits[4]) ? $sig_limits[4] : 0,
3112
		'max_image_width' => isset($sig_limits[5]) ? $sig_limits[5] : 0,
3113
		'max_image_height' => isset($sig_limits[6]) ? $sig_limits[6] : 0,
3114
		'max_font_size' => isset($sig_limits[7]) ? $sig_limits[7] : 0,
3115
		'bbc' => !empty($sig_bbc) ? explode(',', $sig_bbc) : array(),
3116
	);
3117
	// Kept this line in for backwards compatibility!
3118
	$context['max_signature_length'] = $context['signature_limits']['max_length'];
3119
	// Warning message for signature image limits?
3120
	$context['signature_warning'] = '';
3121
	if ($context['signature_limits']['max_image_width'] && $context['signature_limits']['max_image_height'])
3122
		$context['signature_warning'] = sprintf($txt['profile_error_signature_max_image_size'], $context['signature_limits']['max_image_width'], $context['signature_limits']['max_image_height']);
3123
	elseif ($context['signature_limits']['max_image_width'] || $context['signature_limits']['max_image_height'])
3124
		$context['signature_warning'] = sprintf($txt['profile_error_signature_max_image_' . ($context['signature_limits']['max_image_width'] ? 'width' : 'height')], $context['signature_limits'][$context['signature_limits']['max_image_width'] ? 'max_image_width' : 'max_image_height']);
3125
3126
	$context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && (function_exists('pspell_new') || (function_exists('enchant_broker_init') && ($txt['lang_character_set'] == 'UTF-8' || function_exists('iconv'))));
3127
3128
	if (empty($context['do_preview']))
3129
		$context['member']['signature'] = empty($cur_profile['signature']) ? '' : str_replace(array('<br>', '<', '>', '"', '\''), array("\n", '&lt;', '&gt;', '&quot;', '&#039;'), $cur_profile['signature']);
3130
	else
3131
	{
3132
		$signature = !empty($_POST['signature']) ? $_POST['signature'] : '';
3133
		$validation = profileValidateSignature($signature);
3134
		if (empty($context['post_errors']))
3135
		{
3136
			loadLanguage('Errors');
3137
			$context['post_errors'] = array();
3138
		}
3139
		$context['post_errors'][] = 'signature_not_yet_saved';
3140
		if ($validation !== true && $validation !== false)
3141
			$context['post_errors'][] = $validation;
3142
3143
		censorText($context['member']['signature']);
3144
		$context['member']['current_signature'] = $context['member']['signature'];
3145
		censorText($signature);
3146
		$context['member']['signature_preview'] = parse_bbc($signature, true, 'sig' . $memberContext[$context['id_member']]);
3147
		$context['member']['signature'] = $_POST['signature'];
3148
	}
3149
3150
	// Load the spell checker?
3151
	if ($context['show_spellchecking'])
3152
		loadJavaScriptFile('spellcheck.js', array('defer' => false, 'minimize' => true), 'smf_spellcheck');
3153
3154
	return true;
3155
}
3156
3157
/**
3158
 * Load avatar context data.
3159
 *
3160
 * @return true Always returns true
3161
 */
3162
function profileLoadAvatarData()
3163
{
3164
	global $context, $cur_profile, $modSettings, $scripturl;
3165
3166
	$context['avatar_url'] = $modSettings['avatar_url'];
3167
3168
	// Default context.
3169
	$context['member']['avatar'] += array(
3170
		'custom' => stristr($cur_profile['avatar'], 'http://') || stristr($cur_profile['avatar'], 'https://') ? $cur_profile['avatar'] : 'http://',
3171
		'selection' => $cur_profile['avatar'] == '' || (stristr($cur_profile['avatar'], 'http://') || stristr($cur_profile['avatar'], 'https://')) ? '' : $cur_profile['avatar'],
3172
		'allow_server_stored' => (empty($modSettings['gravatarEnabled']) || empty($modSettings['gravatarOverride'])) && (allowedTo('profile_server_avatar') || (!$context['user']['is_owner'] && allowedTo('profile_extra_any'))),
3173
		'allow_upload' => (empty($modSettings['gravatarEnabled']) || empty($modSettings['gravatarOverride'])) && (allowedTo('profile_upload_avatar') || (!$context['user']['is_owner'] && allowedTo('profile_extra_any'))),
3174
		'allow_external' => (empty($modSettings['gravatarEnabled']) || empty($modSettings['gravatarOverride'])) && (allowedTo('profile_remote_avatar') || (!$context['user']['is_owner'] && allowedTo('profile_extra_any'))),
3175
		'allow_gravatar' => !empty($modSettings['gravatarEnabled']) || !empty($modSettings['gravatarOverride']),
3176
	);
3177
3178
	if ($context['member']['avatar']['allow_gravatar'] && (stristr($cur_profile['avatar'], 'gravatar://') || !empty($modSettings['gravatarOverride'])))
3179
	{
3180
		$context['member']['avatar'] += array(
3181
			'choice' => 'gravatar',
3182
			'server_pic' => 'blank.png',
3183
			'external' => $cur_profile['avatar'] == 'gravatar://' || empty($modSettings['gravatarAllowExtraEmail']) || !empty($modSettings['gravatarOverride']) ? $cur_profile['email_address'] : substr($cur_profile['avatar'], 11)
3184
		);
3185
		$context['member']['avatar']['href'] = get_gravatar_url($context['member']['avatar']['external']);
3186
	}
3187
	elseif ($cur_profile['avatar'] == '' && $cur_profile['id_attach'] > 0 && $context['member']['avatar']['allow_upload'])
3188
	{
3189
		$context['member']['avatar'] += array(
3190
			'choice' => 'upload',
3191
			'server_pic' => 'blank.png',
3192
			'external' => 'http://'
3193
		);
3194
		$context['member']['avatar']['href'] = empty($cur_profile['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $cur_profile['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $cur_profile['filename'];
3195
	}
3196
	// Use "avatar_original" here so we show what the user entered even if the image proxy is enabled
3197
	elseif ((stristr($cur_profile['avatar'], 'http://') || stristr($cur_profile['avatar'], 'https://')) && $context['member']['avatar']['allow_external'])
3198
		$context['member']['avatar'] += array(
3199
			'choice' => 'external',
3200
			'server_pic' => 'blank.png',
3201
			'external' => $cur_profile['avatar_original']
3202
		);
3203
	elseif ($cur_profile['avatar'] != '' && file_exists($modSettings['avatar_directory'] . '/' . $cur_profile['avatar']) && $context['member']['avatar']['allow_server_stored'])
3204
		$context['member']['avatar'] += array(
3205
			'choice' => 'server_stored',
3206
			'server_pic' => $cur_profile['avatar'] == '' ? 'blank.png' : $cur_profile['avatar'],
3207
			'external' => 'http://'
3208
		);
3209
	else
3210
		$context['member']['avatar'] += array(
3211
			'choice' => 'none',
3212
			'server_pic' => 'blank.png',
3213
			'external' => 'http://'
3214
		);
3215
3216
	// Get a list of all the avatars.
3217
	if ($context['member']['avatar']['allow_server_stored'])
3218
	{
3219
		$context['avatar_list'] = array();
3220
		$context['avatars'] = is_dir($modSettings['avatar_directory']) ? getAvatars('', 0) : array();
3221
	}
3222
	else
3223
		$context['avatars'] = array();
3224
3225
	// Second level selected avatar...
3226
	$context['avatar_selected'] = substr(strrchr($context['member']['avatar']['server_pic'], '/'), 1);
3227
	return !empty($context['member']['avatar']['allow_server_stored']) || !empty($context['member']['avatar']['allow_external']) || !empty($context['member']['avatar']['allow_upload']) || !empty($context['member']['avatar']['allow_gravatar']);
3228
}
3229
3230
/**
3231
 * Save a members group.
3232
 *
3233
 * @param int &$value The ID of the (new) primary group
3234
 * @return true Always returns true
3235
 */
3236
function profileSaveGroups(&$value)
3237
{
3238
	global $profile_vars, $old_profile, $context, $smcFunc, $cur_profile;
3239
3240
	// Do we need to protect some groups?
3241
	if (!allowedTo('admin_forum'))
3242
	{
3243
		$request = $smcFunc['db_query']('', '
3244
			SELECT id_group
3245
			FROM {db_prefix}membergroups
3246
			WHERE group_type = {int:is_protected}',
3247
			array(
3248
				'is_protected' => 1,
3249
			)
3250
		);
3251
		$protected_groups = array(1);
3252
		while ($row = $smcFunc['db_fetch_assoc']($request))
3253
			$protected_groups[] = $row['id_group'];
3254
		$smcFunc['db_free_result']($request);
3255
3256
		$protected_groups = array_unique($protected_groups);
3257
	}
3258
3259
	// The account page allows the change of your id_group - but not to a protected group!
3260
	if (empty($protected_groups) || count(array_intersect(array((int) $value, $old_profile['id_group']), $protected_groups)) == 0)
3261
		$value = (int) $value;
3262
	// ... otherwise it's the old group sir.
3263
	else
3264
		$value = $old_profile['id_group'];
3265
3266
	// Find the additional membergroups (if any)
3267
	if (isset($_POST['additional_groups']) && is_array($_POST['additional_groups']))
3268
	{
3269
		$additional_groups = array();
3270
		foreach ($_POST['additional_groups'] as $group_id)
3271
		{
3272
			$group_id = (int) $group_id;
3273
			if (!empty($group_id) && (empty($protected_groups) || !in_array($group_id, $protected_groups)))
3274
				$additional_groups[] = $group_id;
3275
		}
3276
3277
		// Put the protected groups back in there if you don't have permission to take them away.
3278
		$old_additional_groups = explode(',', $old_profile['additional_groups']);
3279
		foreach ($old_additional_groups as $group_id)
3280
		{
3281
			if (!empty($protected_groups) && in_array($group_id, $protected_groups))
3282
				$additional_groups[] = $group_id;
3283
		}
3284
3285
		if (implode(',', $additional_groups) !== $old_profile['additional_groups'])
3286
		{
3287
			$profile_vars['additional_groups'] = implode(',', $additional_groups);
3288
			$cur_profile['additional_groups'] = implode(',', $additional_groups);
3289
		}
3290
	}
3291
3292
	// Too often, people remove delete their own account, or something.
3293
	if (in_array(1, explode(',', $old_profile['additional_groups'])) || $old_profile['id_group'] == 1)
3294
	{
3295
		$stillAdmin = $value == 1 || (isset($additional_groups) && in_array(1, $additional_groups));
3296
3297
		// If they would no longer be an admin, look for any other...
3298
		if (!$stillAdmin)
3299
		{
3300
			$request = $smcFunc['db_query']('', '
3301
				SELECT id_member
3302
				FROM {db_prefix}members
3303
				WHERE (id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0)
3304
					AND id_member != {int:selected_member}
3305
				LIMIT 1',
3306
				array(
3307
					'admin_group' => 1,
3308
					'selected_member' => $context['id_member'],
3309
				)
3310
			);
3311
			list ($another) = $smcFunc['db_fetch_row']($request);
3312
			$smcFunc['db_free_result']($request);
3313
3314
			if (empty($another))
3315
				fatal_lang_error('at_least_one_admin', 'critical');
3316
		}
3317
	}
3318
3319
	// If we are changing group status, update permission cache as necessary.
3320
	if ($value != $old_profile['id_group'] || isset($profile_vars['additional_groups']))
3321
	{
3322
		if ($context['user']['is_owner'])
3323
			$_SESSION['mc']['time'] = 0;
3324
		else
3325
			updateSettings(array('settings_updated' => time()));
3326
	}
3327
3328
	// Announce to any hooks that we have changed groups, but don't allow them to change it.
3329
	call_integration_hook('integrate_profile_profileSaveGroups', array($value, $additional_groups));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $additional_groups does not seem to be defined for all execution paths leading up to this point.
Loading history...
3330
3331
	return true;
3332
}
3333
3334
/**
3335
 * The avatar is incredibly complicated, what with the options... and what not.
3336
 *
3337
 * @todo argh, the avatar here. Take this out of here!
3338
 *
3339
 * @param string &$value What kind of avatar we're expecting. Can be 'none', 'server_stored', 'gravatar', 'external' or 'upload'
3340
 * @return bool|string False if success (or if memID is empty and password authentication failed), otherwise a string indicating what error occurred
3341
 */
3342
function profileSaveAvatarData(&$value)
3343
{
3344
	global $modSettings, $sourcedir, $smcFunc, $profile_vars, $cur_profile, $context;
3345
3346
	$memID = $context['id_member'];
3347
	if (empty($memID) && !empty($context['password_auth_failed']))
3348
		return false;
3349
3350
	require_once($sourcedir . '/ManageAttachments.php');
3351
3352
	// We're going to put this on a nice custom dir.
3353
	$uploadDir = $modSettings['custom_avatar_dir'];
3354
	$id_folder = 1;
3355
3356
	$downloadedExternalAvatar = false;
3357
	if ($value == 'external' && allowedTo('profile_remote_avatar') && (stripos($_POST['userpicpersonal'], 'http://') === 0 || stripos($_POST['userpicpersonal'], 'https://') === 0) && strlen($_POST['userpicpersonal']) > 7 && !empty($modSettings['avatar_download_external']))
3358
	{
3359
		if (!is_writable($uploadDir))
3360
			fatal_lang_error('attachments_no_write', 'critical');
3361
3362
		$url = parse_url($_POST['userpicpersonal']);
3363
		$contents = fetch_web_data($url['scheme'] . '://' . $url['host'] . (empty($url['port']) ? '' : ':' . $url['port']) . str_replace(' ', '%20', trim($url['path'])));
3364
3365
		$new_filename = $uploadDir . '/' . getAttachmentFilename('avatar_tmp_' . $memID, false, null, true);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type integer expected by parameter $attachment_id of getAttachmentFilename(). ( Ignorable by Annotation )

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

3365
		$new_filename = $uploadDir . '/' . getAttachmentFilename('avatar_tmp_' . $memID, /** @scrutinizer ignore-type */ false, null, true);
Loading history...
3366
		if ($contents != false && $tmpAvatar = fopen($new_filename, 'wb'))
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $contents of type false|string against false; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
3367
		{
3368
			fwrite($tmpAvatar, $contents);
3369
			fclose($tmpAvatar);
3370
3371
			$downloadedExternalAvatar = true;
3372
			$_FILES['attachment']['tmp_name'] = $new_filename;
3373
		}
3374
	}
3375
3376
	// Removes whatever attachment there was before updating
3377
	if ($value == 'none')
3378
	{
3379
		$profile_vars['avatar'] = '';
3380
3381
		// Reset the attach ID.
3382
		$cur_profile['id_attach'] = 0;
3383
		$cur_profile['attachment_type'] = 0;
3384
		$cur_profile['filename'] = '';
3385
3386
		removeAttachments(array('id_member' => $memID));
3387
	}
3388
3389
	// An avatar from the server-stored galleries.
3390
	elseif ($value == 'server_stored' && allowedTo('profile_server_avatar'))
3391
	{
3392
		$profile_vars['avatar'] = strtr(empty($_POST['file']) ? (empty($_POST['cat']) ? '' : $_POST['cat']) : $_POST['file'], array('&amp;' => '&'));
3393
		$profile_vars['avatar'] = preg_match('~^([\w _!@%*=\-#()\[\]&.,]+/)?[\w _!@%*=\-#()\[\]&.,]+$~', $profile_vars['avatar']) != 0 && preg_match('/\.\./', $profile_vars['avatar']) == 0 && file_exists($modSettings['avatar_directory'] . '/' . $profile_vars['avatar']) ? ($profile_vars['avatar'] == 'blank.png' ? '' : $profile_vars['avatar']) : '';
3394
3395
		// Clear current profile...
3396
		$cur_profile['id_attach'] = 0;
3397
		$cur_profile['attachment_type'] = 0;
3398
		$cur_profile['filename'] = '';
3399
3400
		// Get rid of their old avatar. (if uploaded.)
3401
		removeAttachments(array('id_member' => $memID));
3402
	}
3403
	elseif ($value == 'gravatar' && !empty($modSettings['gravatarEnabled']))
3404
	{
3405
		// One wasn't specified, or it's not allowed to use extra email addresses, or it's not a valid one, reset to default Gravatar.
3406
		if (empty($_POST['gravatarEmail']) || empty($modSettings['gravatarAllowExtraEmail']) || !filter_var($_POST['gravatarEmail'], FILTER_VALIDATE_EMAIL))
3407
			$profile_vars['avatar'] = 'gravatar://';
3408
		else
3409
			$profile_vars['avatar'] = 'gravatar://' . ($_POST['gravatarEmail'] != $cur_profile['email_address'] ? $_POST['gravatarEmail'] : '');
3410
3411
		// Get rid of their old avatar. (if uploaded.)
3412
		removeAttachments(array('id_member' => $memID));
3413
	}
3414
	elseif ($value == 'external' && allowedTo('profile_remote_avatar') && (stripos($_POST['userpicpersonal'], 'http://') === 0 || stripos($_POST['userpicpersonal'], 'https://') === 0) && empty($modSettings['avatar_download_external']))
3415
	{
3416
		// We need these clean...
3417
		$cur_profile['id_attach'] = 0;
3418
		$cur_profile['attachment_type'] = 0;
3419
		$cur_profile['filename'] = '';
3420
3421
		// Remove any attached avatar...
3422
		removeAttachments(array('id_member' => $memID));
3423
3424
		$profile_vars['avatar'] = str_replace(' ', '%20', preg_replace('~action(?:=|%3d)(?!dlattach)~i', 'action-', $_POST['userpicpersonal']));
3425
3426
		if ($profile_vars['avatar'] == 'http://' || $profile_vars['avatar'] == 'http:///')
3427
			$profile_vars['avatar'] = '';
3428
		// Trying to make us do something we'll regret?
3429
		elseif (substr($profile_vars['avatar'], 0, 7) != 'http://' && substr($profile_vars['avatar'], 0, 8) != 'https://')
3430
			return 'bad_avatar_invalid_url';
3431
		// Should we check dimensions?
3432
		elseif (!empty($modSettings['avatar_max_height_external']) || !empty($modSettings['avatar_max_width_external']))
3433
		{
3434
			// Now let's validate the avatar.
3435
			$sizes = url_image_size($profile_vars['avatar']);
3436
3437
			if (is_array($sizes) && (($sizes[0] > $modSettings['avatar_max_width_external'] && !empty($modSettings['avatar_max_width_external'])) || ($sizes[1] > $modSettings['avatar_max_height_external'] && !empty($modSettings['avatar_max_height_external']))))
0 ignored issues
show
introduced by
The condition is_array($sizes) is always false.
Loading history...
3438
			{
3439
				// Houston, we have a problem. The avatar is too large!!
3440
				if ($modSettings['avatar_action_too_large'] == 'option_refuse')
3441
					return 'bad_avatar_too_large';
3442
				elseif ($modSettings['avatar_action_too_large'] == 'option_download_and_resize')
3443
				{
3444
					// @todo remove this if appropriate
3445
					require_once($sourcedir . '/Subs-Graphics.php');
3446
					if (downloadAvatar($profile_vars['avatar'], $memID, $modSettings['avatar_max_width_external'], $modSettings['avatar_max_height_external']))
3447
					{
3448
						$profile_vars['avatar'] = '';
3449
						$cur_profile['id_attach'] = $modSettings['new_avatar_data']['id'];
3450
						$cur_profile['filename'] = $modSettings['new_avatar_data']['filename'];
3451
						$cur_profile['attachment_type'] = $modSettings['new_avatar_data']['type'];
3452
					}
3453
					else
3454
						return 'bad_avatar';
3455
				}
3456
			}
3457
		}
3458
	}
3459
	elseif (($value == 'upload' && allowedTo('profile_upload_avatar')) || $downloadedExternalAvatar)
3460
	{
3461
		if ((isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') || $downloadedExternalAvatar)
3462
		{
3463
			// Get the dimensions of the image.
3464
			if (!$downloadedExternalAvatar)
3465
			{
3466
				if (!is_writable($uploadDir))
3467
					fatal_lang_error('attachments_no_write', 'critical');
3468
3469
				$new_filename = $uploadDir . '/' . getAttachmentFilename('avatar_tmp_' . $memID, false, null, true);
3470
				if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $new_filename))
3471
					fatal_lang_error('attach_timeout', 'critical');
3472
3473
				$_FILES['attachment']['tmp_name'] = $new_filename;
3474
			}
3475
3476
			$sizes = @getimagesize($_FILES['attachment']['tmp_name']);
3477
3478
			// No size, then it's probably not a valid pic.
3479
			if ($sizes === false)
3480
			{
3481
				@unlink($_FILES['attachment']['tmp_name']);
3482
				return 'bad_avatar';
3483
			}
3484
			// Check whether the image is too large.
3485
			elseif ((!empty($modSettings['avatar_max_width_upload']) && $sizes[0] > $modSettings['avatar_max_width_upload']) || (!empty($modSettings['avatar_max_height_upload']) && $sizes[1] > $modSettings['avatar_max_height_upload']))
3486
			{
3487
				if (!empty($modSettings['avatar_resize_upload']))
3488
				{
3489
					// Attempt to chmod it.
3490
					smf_chmod($_FILES['attachment']['tmp_name'], 0644);
3491
3492
					// @todo remove this require when appropriate
3493
					require_once($sourcedir . '/Subs-Graphics.php');
3494
					if (!downloadAvatar($_FILES['attachment']['tmp_name'], $memID, $modSettings['avatar_max_width_upload'], $modSettings['avatar_max_height_upload']))
3495
					{
3496
						@unlink($_FILES['attachment']['tmp_name']);
3497
						return 'bad_avatar';
3498
					}
3499
3500
					// Reset attachment avatar data.
3501
					$cur_profile['id_attach'] = $modSettings['new_avatar_data']['id'];
3502
					$cur_profile['filename'] = $modSettings['new_avatar_data']['filename'];
3503
					$cur_profile['attachment_type'] = $modSettings['new_avatar_data']['type'];
3504
				}
3505
3506
				// Admin doesn't want to resize large avatars, can't do much about it but to tell you to use a different one :(
3507
				else
3508
				{
3509
					@unlink($_FILES['attachment']['tmp_name']);
3510
					return 'bad_avatar_too_large';
3511
				}
3512
			}
3513
3514
			// So far, so good, checks lies ahead!
3515
			elseif (is_array($sizes))
0 ignored issues
show
introduced by
The condition is_array($sizes) is always true.
Loading history...
3516
			{
3517
				// Now try to find an infection.
3518
				require_once($sourcedir . '/Subs-Graphics.php');
3519
				if (!checkImageContents($_FILES['attachment']['tmp_name'], !empty($modSettings['avatar_paranoid'])))
3520
				{
3521
					// It's bad. Try to re-encode the contents?
3522
					if (empty($modSettings['avatar_reencode']) || (!reencodeImage($_FILES['attachment']['tmp_name'], $sizes[2])))
3523
					{
3524
						@unlink($_FILES['attachment']['tmp_name']);
3525
						return 'bad_avatar_fail_reencode';
3526
					}
3527
					// We were successful. However, at what price?
3528
					$sizes = @getimagesize($_FILES['attachment']['tmp_name']);
3529
					// Hard to believe this would happen, but can you bet?
3530
					if ($sizes === false)
3531
					{
3532
						@unlink($_FILES['attachment']['tmp_name']);
3533
						return 'bad_avatar';
3534
					}
3535
				}
3536
3537
				$extensions = array(
3538
					'1' => 'gif',
3539
					'2' => 'jpg',
3540
					'3' => 'png',
3541
					'6' => 'bmp'
3542
				);
3543
3544
				$extension = isset($extensions[$sizes[2]]) ? $extensions[$sizes[2]] : 'bmp';
3545
				$mime_type = 'image/' . ($extension === 'jpg' ? 'jpeg' : ($extension === 'bmp' ? 'x-ms-bmp' : $extension));
3546
				$destName = 'avatar_' . $memID . '_' . time() . '.' . $extension;
3547
				list ($width, $height) = getimagesize($_FILES['attachment']['tmp_name']);
3548
				$file_hash = '';
3549
3550
				// Remove previous attachments this member might have had.
3551
				removeAttachments(array('id_member' => $memID));
3552
3553
				$cur_profile['id_attach'] = $smcFunc['db_insert']('',
3554
					'{db_prefix}attachments',
3555
					array(
3556
						'id_member' => 'int', 'attachment_type' => 'int', 'filename' => 'string', 'file_hash' => 'string', 'fileext' => 'string', 'size' => 'int',
3557
						'width' => 'int', 'height' => 'int', 'mime_type' => 'string', 'id_folder' => 'int',
3558
					),
3559
					array(
3560
						$memID, 1, $destName, $file_hash, $extension, filesize($_FILES['attachment']['tmp_name']),
3561
						(int) $width, (int) $height, $mime_type, $id_folder,
3562
					),
3563
					array('id_attach'),
3564
					1
3565
				);
3566
3567
				$cur_profile['filename'] = $destName;
3568
				$cur_profile['attachment_type'] = 1;
3569
3570
				$destinationPath = $uploadDir . '/' . (empty($file_hash) ? $destName : $cur_profile['id_attach'] . '_' . $file_hash . '.dat');
0 ignored issues
show
introduced by
The condition empty($file_hash) is always true.
Loading history...
3571
				if (!rename($_FILES['attachment']['tmp_name'], $destinationPath))
3572
				{
3573
					// I guess a man can try.
3574
					removeAttachments(array('id_member' => $memID));
3575
					fatal_lang_error('attach_timeout', 'critical');
3576
				}
3577
3578
				// Attempt to chmod it.
3579
				smf_chmod($uploadDir . '/' . $destinationPath, 0644);
3580
			}
3581
			$profile_vars['avatar'] = '';
3582
3583
			// Delete any temporary file.
3584
			if (file_exists($_FILES['attachment']['tmp_name']))
3585
				@unlink($_FILES['attachment']['tmp_name']);
3586
		}
3587
		// Selected the upload avatar option and had one already uploaded before or didn't upload one.
3588
		else
3589
			$profile_vars['avatar'] = '';
3590
	}
3591
	elseif ($value == 'gravatar' && allowedTo('profile_gravatar_avatar'))
3592
		$profile_vars['avatar'] = 'gravatar://www.gravatar.com/avatar/' . md5(strtolower(trim($cur_profile['email_address'])));
3593
	else
3594
		$profile_vars['avatar'] = '';
3595
3596
	// Setup the profile variables so it shows things right on display!
3597
	$cur_profile['avatar'] = $profile_vars['avatar'];
3598
3599
	return false;
3600
}
3601
3602
/**
3603
 * Validate the signature
3604
 *
3605
 * @param string &$value The new signature
3606
 * @return bool|string True if the signature passes the checks, otherwise a string indicating what the problem is
3607
 */
3608
function profileValidateSignature(&$value)
3609
{
3610
	global $sourcedir, $modSettings, $smcFunc, $txt;
3611
3612
	require_once($sourcedir . '/Subs-Post.php');
3613
3614
	// Admins can do whatever they hell they want!
3615
	if (!allowedTo('admin_forum'))
3616
	{
3617
		// Load all the signature limits.
3618
		list ($sig_limits, $sig_bbc) = explode(':', $modSettings['signature_settings']);
3619
		$sig_limits = explode(',', $sig_limits);
3620
		$disabledTags = !empty($sig_bbc) ? explode(',', $sig_bbc) : array();
3621
3622
		$unparsed_signature = strtr(un_htmlspecialchars($value), array("\r" => '', '&#039' => '\''));
3623
3624
		// Too many lines?
3625
		if (!empty($sig_limits[2]) && substr_count($unparsed_signature, "\n") >= $sig_limits[2])
3626
		{
3627
			$txt['profile_error_signature_max_lines'] = sprintf($txt['profile_error_signature_max_lines'], $sig_limits[2]);
3628
			return 'signature_max_lines';
3629
		}
3630
3631
		// Too many images?!
3632
		if (!empty($sig_limits[3]) && (substr_count(strtolower($unparsed_signature), '[img') + substr_count(strtolower($unparsed_signature), '<img')) > $sig_limits[3])
3633
		{
3634
			$txt['profile_error_signature_max_image_count'] = sprintf($txt['profile_error_signature_max_image_count'], $sig_limits[3]);
3635
			return 'signature_max_image_count';
3636
		}
3637
3638
		// What about too many smileys!
3639
		$smiley_parsed = $unparsed_signature;
3640
		parsesmileys($smiley_parsed);
3641
		$smiley_count = substr_count(strtolower($smiley_parsed), '<img') - substr_count(strtolower($unparsed_signature), '<img');
3642
		if (!empty($sig_limits[4]) && $sig_limits[4] == -1 && $smiley_count > 0)
3643
			return 'signature_allow_smileys';
3644
		elseif (!empty($sig_limits[4]) && $sig_limits[4] > 0 && $smiley_count > $sig_limits[4])
3645
		{
3646
			$txt['profile_error_signature_max_smileys'] = sprintf($txt['profile_error_signature_max_smileys'], $sig_limits[4]);
3647
			return 'signature_max_smileys';
3648
		}
3649
3650
		// Maybe we are abusing font sizes?
3651
		if (!empty($sig_limits[7]) && preg_match_all('~\[size=([\d\.]+)?(px|pt|em|x-large|larger)~i', $unparsed_signature, $matches) !== false && isset($matches[2]))
3652
		{
3653
			foreach ($matches[1] as $ind => $size)
3654
			{
3655
				$limit_broke = 0;
3656
				// Attempt to allow all sizes of abuse, so to speak.
3657
				if ($matches[2][$ind] == 'px' && $size > $sig_limits[7])
3658
					$limit_broke = $sig_limits[7] . 'px';
3659
				elseif ($matches[2][$ind] == 'pt' && $size > ($sig_limits[7] * 0.75))
3660
					$limit_broke = ((int) $sig_limits[7] * 0.75) . 'pt';
3661
				elseif ($matches[2][$ind] == 'em' && $size > ((float) $sig_limits[7] / 16))
3662
					$limit_broke = ((float) $sig_limits[7] / 16) . 'em';
3663
				elseif ($matches[2][$ind] != 'px' && $matches[2][$ind] != 'pt' && $matches[2][$ind] != 'em' && $sig_limits[7] < 18)
3664
					$limit_broke = 'large';
3665
3666
				if ($limit_broke)
3667
				{
3668
					$txt['profile_error_signature_max_font_size'] = sprintf($txt['profile_error_signature_max_font_size'], $limit_broke);
3669
					return 'signature_max_font_size';
3670
				}
3671
			}
3672
		}
3673
3674
		// The difficult one - image sizes! Don't error on this - just fix it.
3675
		if ((!empty($sig_limits[5]) || !empty($sig_limits[6])))
3676
		{
3677
			// Get all BBC tags...
3678
			preg_match_all('~\[img(\s+width=([\d]+))?(\s+height=([\d]+))?(\s+width=([\d]+))?\s*\](?:<br>)*([^<">]+?)(?:<br>)*\[/img\]~i', $unparsed_signature, $matches);
3679
			// ... and all HTML ones.
3680
			preg_match_all('~<img\s+src=(?:")?((?:http://|ftp://|https://|ftps://).+?)(?:")?(?:\s+alt=(?:")?(.*?)(?:")?)?(?:\s?/)?' . '>~i', $unparsed_signature, $matches2, PREG_PATTERN_ORDER);
3681
			// And stick the HTML in the BBC.
3682
			if (!empty($matches2))
3683
			{
3684
				foreach ($matches2[0] as $ind => $dummy)
3685
				{
3686
					$matches[0][] = $matches2[0][$ind];
3687
					$matches[1][] = '';
3688
					$matches[2][] = '';
3689
					$matches[3][] = '';
3690
					$matches[4][] = '';
3691
					$matches[5][] = '';
3692
					$matches[6][] = '';
3693
					$matches[7][] = $matches2[1][$ind];
3694
				}
3695
			}
3696
3697
			$replaces = array();
3698
			// Try to find all the images!
3699
			if (!empty($matches))
3700
			{
3701
				foreach ($matches[0] as $key => $image)
3702
				{
3703
					$width = -1;
3704
					$height = -1;
3705
3706
					// Does it have predefined restraints? Width first.
3707
					if ($matches[6][$key])
3708
						$matches[2][$key] = $matches[6][$key];
3709
					if ($matches[2][$key] && $sig_limits[5] && $matches[2][$key] > $sig_limits[5])
3710
					{
3711
						$width = $sig_limits[5];
3712
						$matches[4][$key] = $matches[4][$key] * ($width / $matches[2][$key]);
3713
					}
3714
					elseif ($matches[2][$key])
3715
						$width = $matches[2][$key];
3716
					// ... and height.
3717
					if ($matches[4][$key] && $sig_limits[6] && $matches[4][$key] > $sig_limits[6])
3718
					{
3719
						$height = $sig_limits[6];
3720
						if ($width != -1)
3721
							$width = $width * ($height / $matches[4][$key]);
3722
					}
3723
					elseif ($matches[4][$key])
3724
						$height = $matches[4][$key];
3725
3726
					// If the dimensions are still not fixed - we need to check the actual image.
3727
					if (($width == -1 && $sig_limits[5]) || ($height == -1 && $sig_limits[6]))
3728
					{
3729
						$sizes = url_image_size($matches[7][$key]);
3730
						if (is_array($sizes))
3731
						{
3732
							// Too wide?
3733
							if ($sizes[0] > $sig_limits[5] && $sig_limits[5])
3734
							{
3735
								$width = $sig_limits[5];
3736
								$sizes[1] = $sizes[1] * ($width / $sizes[0]);
3737
							}
3738
							// Too high?
3739
							if ($sizes[1] > $sig_limits[6] && $sig_limits[6])
3740
							{
3741
								$height = $sig_limits[6];
3742
								if ($width == -1)
3743
									$width = $sizes[0];
3744
								$width = $width * ($height / $sizes[1]);
3745
							}
3746
							elseif ($width != -1)
3747
								$height = $sizes[1];
3748
						}
3749
					}
3750
3751
					// Did we come up with some changes? If so remake the string.
3752
					if ($width != -1 || $height != -1)
3753
						$replaces[$image] = '[img' . ($width != -1 ? ' width=' . round($width) : '') . ($height != -1 ? ' height=' . round($height) : '') . ']' . $matches[7][$key] . '[/img]';
3754
				}
3755
				if (!empty($replaces))
3756
					$value = str_replace(array_keys($replaces), array_values($replaces), $value);
3757
			}
3758
		}
3759
3760
		// Any disabled BBC?
3761
		$disabledSigBBC = implode('|', $disabledTags);
3762
		if (!empty($disabledSigBBC))
3763
		{
3764
			if (preg_match('~\[(' . $disabledSigBBC . '[ =\]/])~i', $unparsed_signature, $matches) !== false && isset($matches[1]))
3765
			{
3766
				$disabledTags = array_unique($disabledTags);
3767
				$txt['profile_error_signature_disabled_bbc'] = sprintf($txt['profile_error_signature_disabled_bbc'], implode(', ', $disabledTags));
3768
				return 'signature_disabled_bbc';
3769
			}
3770
		}
3771
	}
3772
3773
	preparsecode($value);
3774
3775
	// Too long?
3776
	if (!allowedTo('admin_forum') && !empty($sig_limits[1]) && $smcFunc['strlen'](str_replace('<br>', "\n", $value)) > $sig_limits[1])
3777
	{
3778
		$_POST['signature'] = trim($smcFunc['htmlspecialchars'](str_replace('<br>', "\n", $value), ENT_QUOTES));
3779
		$txt['profile_error_signature_max_length'] = sprintf($txt['profile_error_signature_max_length'], $sig_limits[1]);
3780
		return 'signature_max_length';
3781
	}
3782
3783
	return true;
3784
}
3785
3786
/**
3787
 * Validate an email address.
3788
 *
3789
 * @param string $email The email address to validate
3790
 * @param int $memID The ID of the member (used to prevent false positives from the current user)
3791
 * @return bool|string True if the email is valid, otherwise a string indicating what the problem is
3792
 */
3793
function profileValidateEmail($email, $memID = 0)
3794
{
3795
	global $smcFunc;
3796
3797
	$email = strtr($email, array('&#039;' => '\''));
3798
3799
	// Check the name and email for validity.
3800
	if (trim($email) == '')
3801
		return 'no_email';
3802
	if (!filter_var($email, FILTER_VALIDATE_EMAIL))
3803
		return 'bad_email';
3804
3805
	// Email addresses should be and stay unique.
3806
	$request = $smcFunc['db_query']('', '
3807
		SELECT id_member
3808
		FROM {db_prefix}members
3809
		WHERE ' . ($memID != 0 ? 'id_member != {int:selected_member} AND ' : '') . '
3810
			email_address = {string:email_address}
3811
		LIMIT 1',
3812
		array(
3813
			'selected_member' => $memID,
3814
			'email_address' => $email,
3815
		)
3816
	);
3817
3818
	if ($smcFunc['db_num_rows']($request) > 0)
3819
		return 'email_taken';
3820
	$smcFunc['db_free_result']($request);
3821
3822
	return true;
3823
}
3824
3825
/**
3826
 * Reload a user's settings.
3827
 */
3828
function profileReloadUser()
3829
{
3830
	global $modSettings, $context, $cur_profile;
3831
3832
	if (isset($_POST['passwrd2']) && $_POST['passwrd2'] != '')
3833
		setLoginCookie(60 * $modSettings['cookieTime'], $context['id_member'], hash_salt($_POST['passwrd1'], $cur_profile['password_salt']));
3834
3835
	loadUserSettings();
3836
	writeLog();
3837
}
3838
3839
/**
3840
 * Send the user a new activation email if they need to reactivate!
3841
 */
3842
function profileSendActivation()
3843
{
3844
	global $sourcedir, $profile_vars, $context, $scripturl, $smcFunc, $cookiename, $cur_profile, $language, $modSettings;
3845
3846
	require_once($sourcedir . '/Subs-Post.php');
3847
3848
	// Shouldn't happen but just in case.
3849
	if (empty($profile_vars['email_address']))
3850
		return;
3851
3852
	$replacements = array(
3853
		'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $context['id_member'] . ';code=' . $profile_vars['validation_code'],
3854
		'ACTIVATIONCODE' => $profile_vars['validation_code'],
3855
		'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $context['id_member'],
3856
	);
3857
3858
	// Send off the email.
3859
	$emaildata = loadEmailTemplate('activate_reactivate', $replacements, empty($cur_profile['lngfile']) || empty($modSettings['userLanguage']) ? $language : $cur_profile['lngfile']);
3860
	sendmail($profile_vars['email_address'], $emaildata['subject'], $emaildata['body'], null, 'reactivate', $emaildata['is_html'], 0);
3861
3862
	// Log the user out.
3863
	$smcFunc['db_query']('', '
3864
		DELETE FROM {db_prefix}log_online
3865
		WHERE id_member = {int:selected_member}',
3866
		array(
3867
			'selected_member' => $context['id_member'],
3868
		)
3869
	);
3870
	$_SESSION['log_time'] = 0;
3871
	$_SESSION['login_' . $cookiename] = $smcFunc['json_encode'](array(0, '', 0));
3872
3873
	if (isset($_COOKIE[$cookiename]))
3874
		$_COOKIE[$cookiename] = '';
3875
3876
	loadUserSettings();
3877
3878
	$context['user']['is_logged'] = false;
3879
	$context['user']['is_guest'] = true;
3880
3881
	redirectexit('action=sendactivation');
3882
}
3883
3884
/**
3885
 * Function to allow the user to choose group membership etc...
3886
 *
3887
 * @param int $memID The ID of the member
3888
 */
3889
function groupMembership($memID)
3890
{
3891
	global $txt, $user_profile, $context, $smcFunc;
3892
3893
	$curMember = $user_profile[$memID];
3894
	$context['primary_group'] = $curMember['id_group'];
3895
3896
	// Can they manage groups?
3897
	$context['can_manage_membergroups'] = allowedTo('manage_membergroups');
3898
	$context['can_manage_protected'] = allowedTo('admin_forum');
3899
	$context['can_edit_primary'] = $context['can_manage_protected'];
3900
	$context['update_message'] = isset($_GET['msg']) && isset($txt['group_membership_msg_' . $_GET['msg']]) ? $txt['group_membership_msg_' . $_GET['msg']] : '';
3901
3902
	// Get all the groups this user is a member of.
3903
	$groups = explode(',', $curMember['additional_groups']);
3904
	$groups[] = $curMember['id_group'];
3905
3906
	// Ensure the query doesn't croak!
3907
	if (empty($groups))
3908
		$groups = array(0);
3909
	// Just to be sure...
3910
	foreach ($groups as $k => $v)
3911
		$groups[$k] = (int) $v;
3912
3913
	// Get all the membergroups they can join.
3914
	$request = $smcFunc['db_query']('', '
3915
		SELECT mg.id_group, mg.group_name, mg.description, mg.group_type, mg.online_color, mg.hidden,
3916
			COALESCE(lgr.id_member, 0) AS pending
3917
		FROM {db_prefix}membergroups AS mg
3918
			LEFT JOIN {db_prefix}log_group_requests AS lgr ON (lgr.id_member = {int:selected_member} AND lgr.id_group = mg.id_group AND lgr.status = {int:status_open})
3919
		WHERE (mg.id_group IN ({array_int:group_list})
3920
			OR mg.group_type > {int:nonjoin_group_id})
3921
			AND mg.min_posts = {int:min_posts}
3922
			AND mg.id_group != {int:moderator_group}
3923
		ORDER BY group_name',
3924
		array(
3925
			'group_list' => $groups,
3926
			'selected_member' => $memID,
3927
			'status_open' => 0,
3928
			'nonjoin_group_id' => 1,
3929
			'min_posts' => -1,
3930
			'moderator_group' => 3,
3931
		)
3932
	);
3933
	// This beast will be our group holder.
3934
	$context['groups'] = array(
3935
		'member' => array(),
3936
		'available' => array()
3937
	);
3938
	while ($row = $smcFunc['db_fetch_assoc']($request))
3939
	{
3940
		// Can they edit their primary group?
3941
		if (($row['id_group'] == $context['primary_group'] && $row['group_type'] > 1) || ($row['hidden'] != 2 && $context['primary_group'] == 0 && in_array($row['id_group'], $groups)))
3942
			$context['can_edit_primary'] = true;
3943
3944
		// If they can't manage (protected) groups, and it's not publically joinable or already assigned, they can't see it.
3945
		if (((!$context['can_manage_protected'] && $row['group_type'] == 1) || (!$context['can_manage_membergroups'] && $row['group_type'] == 0)) && $row['id_group'] != $context['primary_group'])
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! $context['can_manage_...ontext['primary_group'], Probably Intended Meaning: ! $context['can_manage_p...ntext['primary_group'])
Loading history...
3946
			continue;
3947
3948
		$context['groups'][in_array($row['id_group'], $groups) ? 'member' : 'available'][$row['id_group']] = array(
3949
			'id' => $row['id_group'],
3950
			'name' => $row['group_name'],
3951
			'desc' => $row['description'],
3952
			'color' => $row['online_color'],
3953
			'type' => $row['group_type'],
3954
			'pending' => $row['pending'],
3955
			'is_primary' => $row['id_group'] == $context['primary_group'],
3956
			'can_be_primary' => $row['hidden'] != 2,
3957
			// Anything more than this needs to be done through account settings for security.
3958
			'can_leave' => $row['id_group'] != 1 && $row['group_type'] > 1 ? true : false,
3959
		);
3960
	}
3961
	$smcFunc['db_free_result']($request);
3962
3963
	// Add registered members on the end.
3964
	$context['groups']['member'][0] = array(
3965
		'id' => 0,
3966
		'name' => $txt['regular_members'],
3967
		'desc' => $txt['regular_members_desc'],
3968
		'type' => 0,
3969
		'is_primary' => $context['primary_group'] == 0 ? true : false,
3970
		'can_be_primary' => true,
3971
		'can_leave' => 0,
3972
	);
3973
3974
	// No changing primary one unless you have enough groups!
3975
	if (count($context['groups']['member']) < 2)
3976
		$context['can_edit_primary'] = false;
3977
3978
	// In the special case that someone is requesting membership of a group, setup some special context vars.
3979
	if (isset($_REQUEST['request']) && isset($context['groups']['available'][(int) $_REQUEST['request']]) && $context['groups']['available'][(int) $_REQUEST['request']]['type'] == 2)
3980
		$context['group_request'] = $context['groups']['available'][(int) $_REQUEST['request']];
3981
}
3982
3983
/**
3984
 * This function actually makes all the group changes
3985
 *
3986
 * @param array $profile_vars The profile variables
3987
 * @param array $post_errors Any errors that have occurred
3988
 * @param int $memID The ID of the member
3989
 * @return string What type of change this is - 'primary' if changing the primary group, 'request' if requesting to join a group or 'free' if it's an open group
3990
 */
3991
function groupMembership2($profile_vars, $post_errors, $memID)
3992
{
3993
	global $user_info, $context, $user_profile, $modSettings, $smcFunc;
3994
3995
	// Let's be extra cautious...
3996
	if (!$context['user']['is_owner'] || empty($modSettings['show_group_membership']))
3997
		isAllowedTo('manage_membergroups');
3998
	if (!isset($_REQUEST['gid']) && !isset($_POST['primary']))
3999
		fatal_lang_error('no_access', false);
4000
4001
	checkSession(isset($_GET['gid']) ? 'get' : 'post');
4002
4003
	$old_profile = &$user_profile[$memID];
4004
	$context['can_manage_membergroups'] = allowedTo('manage_membergroups');
4005
	$context['can_manage_protected'] = allowedTo('admin_forum');
4006
4007
	// By default the new primary is the old one.
4008
	$newPrimary = $old_profile['id_group'];
4009
	$addGroups = array_flip(explode(',', $old_profile['additional_groups']));
4010
	$canChangePrimary = $old_profile['id_group'] == 0 ? 1 : 0;
4011
	$changeType = isset($_POST['primary']) ? 'primary' : (isset($_POST['req']) ? 'request' : 'free');
4012
4013
	// One way or another, we have a target group in mind...
4014
	$group_id = isset($_REQUEST['gid']) ? (int) $_REQUEST['gid'] : (int) $_POST['primary'];
4015
	$foundTarget = $changeType == 'primary' && $group_id == 0 ? true : false;
4016
4017
	// Sanity check!!
4018
	if ($group_id == 1)
4019
		isAllowedTo('admin_forum');
4020
	// Protected groups too!
4021
	else
4022
	{
4023
		$request = $smcFunc['db_query']('', '
4024
			SELECT group_type
4025
			FROM {db_prefix}membergroups
4026
			WHERE id_group = {int:current_group}
4027
			LIMIT {int:limit}',
4028
			array(
4029
				'current_group' => $group_id,
4030
				'limit' => 1,
4031
			)
4032
		);
4033
		list ($is_protected) = $smcFunc['db_fetch_row']($request);
4034
		$smcFunc['db_free_result']($request);
4035
4036
		if ($is_protected == 1)
4037
			isAllowedTo('admin_forum');
4038
	}
4039
4040
	// What ever we are doing, we need to determine if changing primary is possible!
4041
	$request = $smcFunc['db_query']('', '
4042
		SELECT id_group, group_type, hidden, group_name
4043
		FROM {db_prefix}membergroups
4044
		WHERE id_group IN ({int:group_list}, {int:current_group})',
4045
		array(
4046
			'group_list' => $group_id,
4047
			'current_group' => $old_profile['id_group'],
4048
		)
4049
	);
4050
	while ($row = $smcFunc['db_fetch_assoc']($request))
4051
	{
4052
		// Is this the new group?
4053
		if ($row['id_group'] == $group_id)
4054
		{
4055
			$foundTarget = true;
4056
			$group_name = $row['group_name'];
4057
4058
			// Does the group type match what we're doing - are we trying to request a non-requestable group?
4059
			if ($changeType == 'request' && $row['group_type'] != 2)
4060
				fatal_lang_error('no_access', false);
4061
			// What about leaving a requestable group we are not a member of?
4062
			elseif ($changeType == 'free' && $row['group_type'] == 2 && $old_profile['id_group'] != $row['id_group'] && !isset($addGroups[$row['id_group']]))
4063
				fatal_lang_error('no_access', false);
4064
			elseif ($changeType == 'free' && $row['group_type'] != 3 && $row['group_type'] != 2)
4065
				fatal_lang_error('no_access', false);
4066
4067
			// We can't change the primary group if this is hidden!
4068
			if ($row['hidden'] == 2)
4069
				$canChangePrimary = false;
4070
		}
4071
4072
		// If this is their old primary, can we change it?
4073
		if ($row['id_group'] == $old_profile['id_group'] && ($row['group_type'] > 1 || $context['can_manage_membergroups']) && $canChangePrimary !== false)
4074
			$canChangePrimary = 1;
4075
4076
		// If we are not doing a force primary move, don't do it automatically if current primary is not 0.
4077
		if ($changeType != 'primary' && $old_profile['id_group'] != 0)
4078
			$canChangePrimary = false;
4079
4080
		// If this is the one we are acting on, can we even act?
4081
		if ((!$context['can_manage_protected'] && $row['group_type'] == 1) || (!$context['can_manage_membergroups'] && $row['group_type'] == 0))
4082
			$canChangePrimary = false;
4083
	}
4084
	$smcFunc['db_free_result']($request);
4085
4086
	// Didn't find the target?
4087
	if (!$foundTarget)
4088
		fatal_lang_error('no_access', false);
4089
4090
	// Final security check, don't allow users to promote themselves to admin.
4091
	if ($context['can_manage_membergroups'] && !allowedTo('admin_forum'))
4092
	{
4093
		$request = $smcFunc['db_query']('', '
4094
			SELECT COUNT(permission)
4095
			FROM {db_prefix}permissions
4096
			WHERE id_group = {int:selected_group}
4097
				AND permission = {string:admin_forum}
4098
				AND add_deny = {int:not_denied}',
4099
			array(
4100
				'selected_group' => $group_id,
4101
				'not_denied' => 1,
4102
				'admin_forum' => 'admin_forum',
4103
			)
4104
		);
4105
		list ($disallow) = $smcFunc['db_fetch_row']($request);
4106
		$smcFunc['db_free_result']($request);
4107
4108
		if ($disallow)
4109
			isAllowedTo('admin_forum');
4110
	}
4111
4112
	// If we're requesting, add the note then return.
4113
	if ($changeType == 'request')
4114
	{
4115
		$request = $smcFunc['db_query']('', '
4116
			SELECT id_member
4117
			FROM {db_prefix}log_group_requests
4118
			WHERE id_member = {int:selected_member}
4119
				AND id_group = {int:selected_group}
4120
				AND status = {int:status_open}',
4121
			array(
4122
				'selected_member' => $memID,
4123
				'selected_group' => $group_id,
4124
				'status_open' => 0,
4125
			)
4126
		);
4127
		if ($smcFunc['db_num_rows']($request) != 0)
4128
			fatal_lang_error('profile_error_already_requested_group');
4129
		$smcFunc['db_free_result']($request);
4130
4131
		// Log the request.
4132
		$smcFunc['db_insert']('',
4133
			'{db_prefix}log_group_requests',
4134
			array(
4135
				'id_member' => 'int', 'id_group' => 'int', 'time_applied' => 'int', 'reason' => 'string-65534',
4136
				'status' => 'int', 'id_member_acted' => 'int', 'member_name_acted' => 'string', 'time_acted' => 'int', 'act_reason' => 'string',
4137
			),
4138
			array(
4139
				$memID, $group_id, time(), $_POST['reason'],
4140
				0, 0, '', 0, '',
4141
			),
4142
			array('id_request')
4143
		);
4144
4145
		// Set up some data for our background task...
4146
		$data = $smcFunc['json_encode'](array('id_member' => $memID, 'member_name' => $user_info['name'], 'id_group' => $group_id, 'group_name' => $group_name, 'reason' => $_POST['reason'], 'time' => time()));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $group_name does not seem to be defined for all execution paths leading up to this point.
Loading history...
4147
4148
		// Add a background task to handle notifying people of this request
4149
		$smcFunc['db_insert']('insert', '{db_prefix}background_tasks',
4150
			array('task_file' => 'string-255', 'task_class' => 'string-255', 'task_data' => 'string', 'claimed_time' => 'int'),
4151
			array('$sourcedir/tasks/GroupReq-Notify.php', 'GroupReq_Notify_Background', $data, 0), array()
4152
		);
4153
4154
		return $changeType;
4155
	}
4156
	// Otherwise we are leaving/joining a group.
4157
	elseif ($changeType == 'free')
4158
	{
4159
		// Are we leaving?
4160
		if ($old_profile['id_group'] == $group_id || isset($addGroups[$group_id]))
4161
		{
4162
			if ($old_profile['id_group'] == $group_id)
4163
				$newPrimary = 0;
4164
			else
4165
				unset($addGroups[$group_id]);
4166
		}
4167
		// ... if not, must be joining.
4168
		else
4169
		{
4170
			// Can we change the primary, and do we want to?
4171
			if ($canChangePrimary)
4172
			{
4173
				if ($old_profile['id_group'] != 0)
4174
					$addGroups[$old_profile['id_group']] = -1;
4175
				$newPrimary = $group_id;
4176
			}
4177
			// Otherwise it's an additional group...
4178
			else
4179
				$addGroups[$group_id] = -1;
4180
		}
4181
	}
4182
	// Finally, we must be setting the primary.
4183
	elseif ($canChangePrimary)
4184
	{
4185
		if ($old_profile['id_group'] != 0)
4186
			$addGroups[$old_profile['id_group']] = -1;
4187
		if (isset($addGroups[$group_id]))
4188
			unset($addGroups[$group_id]);
4189
		$newPrimary = $group_id;
4190
	}
4191
4192
	// Finally, we can make the changes!
4193
	foreach ($addGroups as $id => $dummy)
4194
		if (empty($id))
4195
			unset($addGroups[$id]);
4196
	$addGroups = implode(',', array_flip($addGroups));
4197
4198
	// Ensure that we don't cache permissions if the group is changing.
4199
	if ($context['user']['is_owner'])
4200
		$_SESSION['mc']['time'] = 0;
4201
	else
4202
		updateSettings(array('settings_updated' => time()));
4203
4204
	updateMemberData($memID, array('id_group' => $newPrimary, 'additional_groups' => $addGroups));
4205
4206
	return $changeType;
4207
}
4208
4209
/**
4210
 * Provides interface to setup Two Factor Auth in SMF
4211
 *
4212
 * @param int $memID The ID of the member
4213
 */
4214
function tfasetup($memID)
4215
{
4216
	global $user_info, $context, $user_settings, $sourcedir, $modSettings, $smcFunc;
4217
4218
	require_once($sourcedir . '/Class-TOTP.php');
4219
	require_once($sourcedir . '/Subs-Auth.php');
4220
4221
	// load JS lib for QR
4222
	loadJavaScriptFile('qrcode.js', array('force_current' => false, 'validate' => true));
4223
4224
	// If TFA has not been setup, allow them to set it up
4225
	if (empty($user_settings['tfa_secret']) && $context['user']['is_owner'])
4226
	{
4227
		// Check to ensure we're forcing SSL for authentication
4228
		if (!empty($modSettings['force_ssl']) && empty($maintenance) && !httpsOn())
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $maintenance seems to never exist and therefore empty should always be true.
Loading history...
4229
			fatal_lang_error('login_ssl_required', false);
4230
4231
		// In some cases (forced 2FA or backup code) they would be forced to be redirected here,
4232
		// we do not want too much AJAX to confuse them.
4233
		if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && !isset($_REQUEST['backup']) && !isset($_REQUEST['forced']))
4234
		{
4235
			$context['from_ajax'] = true;
4236
			$context['template_layers'] = array();
4237
		}
4238
4239
		// When the code is being sent, verify to make sure the user got it right
4240
		if (!empty($_REQUEST['save']) && !empty($_SESSION['tfa_secret']))
4241
		{
4242
			$code = $_POST['tfa_code'];
4243
			$totp = new \TOTP\Auth($_SESSION['tfa_secret']);
4244
			$totp->setRange(1);
4245
			$valid_code = strlen($code) == $totp->getCodeLength() && $totp->validateCode($code);
4246
4247
			if (empty($context['password_auth_failed']) && $valid_code)
4248
			{
4249
				$backup = substr(sha1($smcFunc['random_int']()), 0, 16);
4250
				$backup_encrypted = hash_password($user_settings['member_name'], $backup);
4251
4252
				updateMemberData($memID, array(
4253
					'tfa_secret' => $_SESSION['tfa_secret'],
4254
					'tfa_backup' => $backup_encrypted,
4255
				));
4256
4257
				setTFACookie(3153600, $memID, hash_salt($backup_encrypted, $user_settings['password_salt']));
4258
4259
				unset($_SESSION['tfa_secret']);
4260
4261
				$context['tfa_backup'] = $backup;
4262
				$context['sub_template'] = 'tfasetup_backup';
4263
4264
				return;
4265
			}
4266
			else
4267
			{
4268
				$context['tfa_secret'] = $_SESSION['tfa_secret'];
4269
				$context['tfa_error'] = !$valid_code;
4270
				$context['tfa_pass_value'] = $_POST['oldpasswrd'];
4271
				$context['tfa_value'] = $_POST['tfa_code'];
4272
			}
4273
		}
4274
		else
4275
		{
4276
			$totp = new \TOTP\Auth();
4277
			$secret = $totp->generateCode();
4278
			$_SESSION['tfa_secret'] = $secret;
4279
			$context['tfa_secret'] = $secret;
4280
			$context['tfa_backup'] = isset($_REQUEST['backup']);
4281
		}
4282
4283
		$context['tfa_qr_url'] = $totp->getQrCodeUrl($context['forum_name'] . ':' . $user_info['name'], $context['tfa_secret']);
4284
	}
4285
	else
4286
		redirectexit('action=profile;area=account;u=' . $memID);
4287
}
4288
4289
/**
4290
 * Provides interface to disable two-factor authentication in SMF
4291
 *
4292
 * @param int $memID The ID of the member
4293
 */
4294
function tfadisable($memID)
4295
{
4296
	global $context, $modSettings, $smcFunc, $user_settings;
4297
4298
	if (!empty($user_settings['tfa_secret']))
4299
	{
4300
		// Bail if we're forcing SSL for authentication and the network connection isn't secure.
4301
		if (!empty($modSettings['force_ssl']) && !httpsOn())
4302
			fatal_lang_error('login_ssl_required', false);
4303
4304
		// The admin giveth...
4305
		elseif ($modSettings['tfa_mode'] == 3 && $context['user']['is_owner'])
4306
			fatal_lang_error('cannot_disable_tfa', false);
4307
		elseif ($modSettings['tfa_mode'] == 2 && $context['user']['is_owner'])
4308
		{
4309
			$groups = array($user_settings['id_group']);
4310
			if (!empty($user_settings['additional_groups']))
4311
				$groups = array_unique(array_merge($groups, explode(',', $user_settings['additional_groups'])));
4312
4313
			$request = $smcFunc['db_query']('', '
4314
				SELECT id_group
4315
				FROM {db_prefix}membergroups
4316
				WHERE tfa_required = {int:tfa_required}
4317
					AND id_group IN ({array_int:groups})',
4318
				array(
4319
					'tfa_required' => 1,
4320
					'groups' => $groups,
4321
				)
4322
			);
4323
			$tfa_required_groups = $smcFunc['db_num_rows']($request);
4324
			$smcFunc['db_free_result']($request);
4325
4326
			// They belong to a membergroup that requires tfa.
4327
			if (!empty($tfa_required_groups))
4328
				fatal_lang_error('cannot_disable_tfa2', false);
4329
		}
4330
	}
4331
	else
4332
		redirectexit('action=profile;area=account;u=' . $memID);
4333
}
4334
4335
?>