Completed
Pull Request — release-2.1 (#5647)
by Mathias
12:18 queued 01:11
created

alert_unsubscribe()   C

Complexity

Conditions 8
Paths 5

Size

Total Lines 166
Code Lines 105

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 105
c 0
b 0
f 0
nc 5
nop 1
dl 0
loc 166
rs 6.7555

How to fix   Long Method   

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

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

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

3546
		$new_filename = $uploadDir . '/' . getAttachmentFilename('avatar_tmp_' . $memID, /** @scrutinizer ignore-type */ false, null, true);
Loading history...
3547
		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...
3548
		{
3549
			fwrite($tmpAvatar, $contents);
3550
			fclose($tmpAvatar);
3551
3552
			$downloadedExternalAvatar = true;
3553
			$_FILES['attachment']['tmp_name'] = $new_filename;
3554
		}
3555
	}
3556
3557
	// Removes whatever attachment there was before updating
3558
	if ($value == 'none')
3559
	{
3560
		$profile_vars['avatar'] = '';
3561
3562
		// Reset the attach ID.
3563
		$cur_profile['id_attach'] = 0;
3564
		$cur_profile['attachment_type'] = 0;
3565
		$cur_profile['filename'] = '';
3566
3567
		removeAttachments(array('id_member' => $memID));
3568
	}
3569
3570
	// An avatar from the server-stored galleries.
3571
	elseif ($value == 'server_stored' && allowedTo('profile_server_avatar'))
3572
	{
3573
		$profile_vars['avatar'] = strtr(empty($_POST['file']) ? (empty($_POST['cat']) ? '' : $_POST['cat']) : $_POST['file'], array('&amp;' => '&'));
3574
		$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']) : '';
3575
3576
		// Clear current profile...
3577
		$cur_profile['id_attach'] = 0;
3578
		$cur_profile['attachment_type'] = 0;
3579
		$cur_profile['filename'] = '';
3580
3581
		// Get rid of their old avatar. (if uploaded.)
3582
		removeAttachments(array('id_member' => $memID));
3583
	}
3584
	elseif ($value == 'gravatar' && !empty($modSettings['gravatarEnabled']))
3585
	{
3586
		// 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.
3587
		if (empty($_POST['gravatarEmail']) || empty($modSettings['gravatarAllowExtraEmail']) || !filter_var($_POST['gravatarEmail'], FILTER_VALIDATE_EMAIL))
3588
			$profile_vars['avatar'] = 'gravatar://';
3589
		else
3590
			$profile_vars['avatar'] = 'gravatar://' . ($_POST['gravatarEmail'] != $cur_profile['email_address'] ? $_POST['gravatarEmail'] : '');
3591
3592
		// Get rid of their old avatar. (if uploaded.)
3593
		removeAttachments(array('id_member' => $memID));
3594
	}
3595
	elseif ($value == 'external' && allowedTo('profile_remote_avatar') && (stripos($_POST['userpicpersonal'], 'http://') === 0 || stripos($_POST['userpicpersonal'], 'https://') === 0) && empty($modSettings['avatar_download_external']))
3596
	{
3597
		// We need these clean...
3598
		$cur_profile['id_attach'] = 0;
3599
		$cur_profile['attachment_type'] = 0;
3600
		$cur_profile['filename'] = '';
3601
3602
		// Remove any attached avatar...
3603
		removeAttachments(array('id_member' => $memID));
3604
3605
		$profile_vars['avatar'] = str_replace(' ', '%20', preg_replace('~action(?:=|%3d)(?!dlattach)~i', 'action-', $_POST['userpicpersonal']));
3606
3607
		if ($profile_vars['avatar'] == 'http://' || $profile_vars['avatar'] == 'http:///')
3608
			$profile_vars['avatar'] = '';
3609
		// Trying to make us do something we'll regret?
3610
		elseif (substr($profile_vars['avatar'], 0, 7) != 'http://' && substr($profile_vars['avatar'], 0, 8) != 'https://')
3611
			return 'bad_avatar_invalid_url';
3612
		// Should we check dimensions?
3613
		elseif (!empty($modSettings['avatar_max_height_external']) || !empty($modSettings['avatar_max_width_external']))
3614
		{
3615
			// Now let's validate the avatar.
3616
			$sizes = url_image_size($profile_vars['avatar']);
3617
3618
			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...
3619
			{
3620
				// Houston, we have a problem. The avatar is too large!!
3621
				if ($modSettings['avatar_action_too_large'] == 'option_refuse')
3622
					return 'bad_avatar_too_large';
3623
				elseif ($modSettings['avatar_action_too_large'] == 'option_download_and_resize')
3624
				{
3625
					// @todo remove this if appropriate
3626
					require_once($sourcedir . '/Subs-Graphics.php');
3627
					if (downloadAvatar($profile_vars['avatar'], $memID, $modSettings['avatar_max_width_external'], $modSettings['avatar_max_height_external']))
3628
					{
3629
						$profile_vars['avatar'] = '';
3630
						$cur_profile['id_attach'] = $modSettings['new_avatar_data']['id'];
3631
						$cur_profile['filename'] = $modSettings['new_avatar_data']['filename'];
3632
						$cur_profile['attachment_type'] = $modSettings['new_avatar_data']['type'];
3633
					}
3634
					else
3635
						return 'bad_avatar';
3636
				}
3637
			}
3638
		}
3639
	}
3640
	elseif (($value == 'upload' && allowedTo('profile_upload_avatar')) || $downloadedExternalAvatar)
3641
	{
3642
		if ((isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') || $downloadedExternalAvatar)
3643
		{
3644
			// Get the dimensions of the image.
3645
			if (!$downloadedExternalAvatar)
3646
			{
3647
				if (!is_writable($uploadDir))
3648
					fatal_lang_error('attachments_no_write', 'critical');
3649
3650
				$new_filename = $uploadDir . '/' . getAttachmentFilename('avatar_tmp_' . $memID, false, null, true);
3651
				if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $new_filename))
3652
					fatal_lang_error('attach_timeout', 'critical');
3653
3654
				$_FILES['attachment']['tmp_name'] = $new_filename;
3655
			}
3656
3657
			$sizes = @getimagesize($_FILES['attachment']['tmp_name']);
3658
3659
			// No size, then it's probably not a valid pic.
3660
			if ($sizes === false)
3661
			{
3662
				@unlink($_FILES['attachment']['tmp_name']);
3663
				return 'bad_avatar';
3664
			}
3665
			// Check whether the image is too large.
3666
			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']))
3667
			{
3668
				if (!empty($modSettings['avatar_resize_upload']))
3669
				{
3670
					// Attempt to chmod it.
3671
					smf_chmod($_FILES['attachment']['tmp_name'], 0644);
3672
3673
					// @todo remove this require when appropriate
3674
					require_once($sourcedir . '/Subs-Graphics.php');
3675
					if (!downloadAvatar($_FILES['attachment']['tmp_name'], $memID, $modSettings['avatar_max_width_upload'], $modSettings['avatar_max_height_upload']))
3676
					{
3677
						@unlink($_FILES['attachment']['tmp_name']);
3678
						return 'bad_avatar';
3679
					}
3680
3681
					// Reset attachment avatar data.
3682
					$cur_profile['id_attach'] = $modSettings['new_avatar_data']['id'];
3683
					$cur_profile['filename'] = $modSettings['new_avatar_data']['filename'];
3684
					$cur_profile['attachment_type'] = $modSettings['new_avatar_data']['type'];
3685
				}
3686
3687
				// Admin doesn't want to resize large avatars, can't do much about it but to tell you to use a different one :(
3688
				else
3689
				{
3690
					@unlink($_FILES['attachment']['tmp_name']);
3691
					return 'bad_avatar_too_large';
3692
				}
3693
			}
3694
3695
			// So far, so good, checks lies ahead!
3696
			elseif (is_array($sizes))
0 ignored issues
show
introduced by
The condition is_array($sizes) is always true.
Loading history...
3697
			{
3698
				// Now try to find an infection.
3699
				require_once($sourcedir . '/Subs-Graphics.php');
3700
				if (!checkImageContents($_FILES['attachment']['tmp_name'], !empty($modSettings['avatar_paranoid'])))
3701
				{
3702
					// It's bad. Try to re-encode the contents?
3703
					if (empty($modSettings['avatar_reencode']) || (!reencodeImage($_FILES['attachment']['tmp_name'], $sizes[2])))
3704
					{
3705
						@unlink($_FILES['attachment']['tmp_name']);
3706
						return 'bad_avatar_fail_reencode';
3707
					}
3708
					// We were successful. However, at what price?
3709
					$sizes = @getimagesize($_FILES['attachment']['tmp_name']);
3710
					// Hard to believe this would happen, but can you bet?
3711
					if ($sizes === false)
3712
					{
3713
						@unlink($_FILES['attachment']['tmp_name']);
3714
						return 'bad_avatar';
3715
					}
3716
				}
3717
3718
				$extensions = array(
3719
					'1' => 'gif',
3720
					'2' => 'jpg',
3721
					'3' => 'png',
3722
					'6' => 'bmp'
3723
				);
3724
3725
				$extension = isset($extensions[$sizes[2]]) ? $extensions[$sizes[2]] : 'bmp';
3726
				$mime_type = 'image/' . ($extension === 'jpg' ? 'jpeg' : ($extension === 'bmp' ? 'x-ms-bmp' : $extension));
3727
				$destName = 'avatar_' . $memID . '_' . time() . '.' . $extension;
3728
				list ($width, $height) = getimagesize($_FILES['attachment']['tmp_name']);
3729
				$file_hash = '';
3730
3731
				// Remove previous attachments this member might have had.
3732
				removeAttachments(array('id_member' => $memID));
3733
3734
				$cur_profile['id_attach'] = $smcFunc['db_insert']('',
3735
					'{db_prefix}attachments',
3736
					array(
3737
						'id_member' => 'int', 'attachment_type' => 'int', 'filename' => 'string', 'file_hash' => 'string', 'fileext' => 'string', 'size' => 'int',
3738
						'width' => 'int', 'height' => 'int', 'mime_type' => 'string', 'id_folder' => 'int',
3739
					),
3740
					array(
3741
						$memID, 1, $destName, $file_hash, $extension, filesize($_FILES['attachment']['tmp_name']),
3742
						(int) $width, (int) $height, $mime_type, $id_folder,
3743
					),
3744
					array('id_attach'),
3745
					1
3746
				);
3747
3748
				$cur_profile['filename'] = $destName;
3749
				$cur_profile['attachment_type'] = 1;
3750
3751
				$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...
3752
				if (!rename($_FILES['attachment']['tmp_name'], $destinationPath))
3753
				{
3754
					// I guess a man can try.
3755
					removeAttachments(array('id_member' => $memID));
3756
					fatal_lang_error('attach_timeout', 'critical');
3757
				}
3758
3759
				// Attempt to chmod it.
3760
				smf_chmod($uploadDir . '/' . $destinationPath, 0644);
3761
			}
3762
			$profile_vars['avatar'] = '';
3763
3764
			// Delete any temporary file.
3765
			if (file_exists($_FILES['attachment']['tmp_name']))
3766
				@unlink($_FILES['attachment']['tmp_name']);
3767
		}
3768
		// Selected the upload avatar option and had one already uploaded before or didn't upload one.
3769
		else
3770
			$profile_vars['avatar'] = '';
3771
	}
3772
	elseif ($value == 'gravatar' && allowedTo('profile_gravatar_avatar'))
3773
		$profile_vars['avatar'] = 'gravatar://www.gravatar.com/avatar/' . md5(strtolower(trim($cur_profile['email_address'])));
3774
	else
3775
		$profile_vars['avatar'] = '';
3776
3777
	// Setup the profile variables so it shows things right on display!
3778
	$cur_profile['avatar'] = $profile_vars['avatar'];
3779
3780
	return false;
3781
}
3782
3783
/**
3784
 * Validate the signature
3785
 *
3786
 * @param string &$value The new signature
3787
 * @return bool|string True if the signature passes the checks, otherwise a string indicating what the problem is
3788
 */
3789
function profileValidateSignature(&$value)
3790
{
3791
	global $sourcedir, $modSettings, $smcFunc, $txt;
3792
3793
	require_once($sourcedir . '/Subs-Post.php');
3794
3795
	// Admins can do whatever they hell they want!
3796
	if (!allowedTo('admin_forum'))
3797
	{
3798
		// Load all the signature limits.
3799
		list ($sig_limits, $sig_bbc) = explode(':', $modSettings['signature_settings']);
3800
		$sig_limits = explode(',', $sig_limits);
3801
		$disabledTags = !empty($sig_bbc) ? explode(',', $sig_bbc) : array();
3802
3803
		$unparsed_signature = strtr(un_htmlspecialchars($value), array("\r" => '', '&#039' => '\''));
3804
3805
		// Too many lines?
3806
		if (!empty($sig_limits[2]) && substr_count($unparsed_signature, "\n") >= $sig_limits[2])
3807
		{
3808
			$txt['profile_error_signature_max_lines'] = sprintf($txt['profile_error_signature_max_lines'], $sig_limits[2]);
3809
			return 'signature_max_lines';
3810
		}
3811
3812
		// Too many images?!
3813
		if (!empty($sig_limits[3]) && (substr_count(strtolower($unparsed_signature), '[img') + substr_count(strtolower($unparsed_signature), '<img')) > $sig_limits[3])
3814
		{
3815
			$txt['profile_error_signature_max_image_count'] = sprintf($txt['profile_error_signature_max_image_count'], $sig_limits[3]);
3816
			return 'signature_max_image_count';
3817
		}
3818
3819
		// What about too many smileys!
3820
		$smiley_parsed = $unparsed_signature;
3821
		parsesmileys($smiley_parsed);
3822
		$smiley_count = substr_count(strtolower($smiley_parsed), '<img') - substr_count(strtolower($unparsed_signature), '<img');
3823
		if (!empty($sig_limits[4]) && $sig_limits[4] == -1 && $smiley_count > 0)
3824
			return 'signature_allow_smileys';
3825
		elseif (!empty($sig_limits[4]) && $sig_limits[4] > 0 && $smiley_count > $sig_limits[4])
3826
		{
3827
			$txt['profile_error_signature_max_smileys'] = sprintf($txt['profile_error_signature_max_smileys'], $sig_limits[4]);
3828
			return 'signature_max_smileys';
3829
		}
3830
3831
		// Maybe we are abusing font sizes?
3832
		if (!empty($sig_limits[7]) && preg_match_all('~\[size=([\d\.]+)?(px|pt|em|x-large|larger)~i', $unparsed_signature, $matches) !== false && isset($matches[2]))
3833
		{
3834
			foreach ($matches[1] as $ind => $size)
3835
			{
3836
				$limit_broke = 0;
3837
				// Attempt to allow all sizes of abuse, so to speak.
3838
				if ($matches[2][$ind] == 'px' && $size > $sig_limits[7])
3839
					$limit_broke = $sig_limits[7] . 'px';
3840
				elseif ($matches[2][$ind] == 'pt' && $size > ($sig_limits[7] * 0.75))
3841
					$limit_broke = ((int) $sig_limits[7] * 0.75) . 'pt';
3842
				elseif ($matches[2][$ind] == 'em' && $size > ((float) $sig_limits[7] / 16))
3843
					$limit_broke = ((float) $sig_limits[7] / 16) . 'em';
3844
				elseif ($matches[2][$ind] != 'px' && $matches[2][$ind] != 'pt' && $matches[2][$ind] != 'em' && $sig_limits[7] < 18)
3845
					$limit_broke = 'large';
3846
3847
				if ($limit_broke)
3848
				{
3849
					$txt['profile_error_signature_max_font_size'] = sprintf($txt['profile_error_signature_max_font_size'], $limit_broke);
3850
					return 'signature_max_font_size';
3851
				}
3852
			}
3853
		}
3854
3855
		// The difficult one - image sizes! Don't error on this - just fix it.
3856
		if ((!empty($sig_limits[5]) || !empty($sig_limits[6])))
3857
		{
3858
			// Get all BBC tags...
3859
			preg_match_all('~\[img(\s+width=([\d]+))?(\s+height=([\d]+))?(\s+width=([\d]+))?\s*\](?:<br>)*([^<">]+?)(?:<br>)*\[/img\]~i', $unparsed_signature, $matches);
3860
			// ... and all HTML ones.
3861
			preg_match_all('~<img\s+src=(?:")?((?:http://|ftp://|https://|ftps://).+?)(?:")?(?:\s+alt=(?:")?(.*?)(?:")?)?(?:\s?/)?' . '>~i', $unparsed_signature, $matches2, PREG_PATTERN_ORDER);
3862
			// And stick the HTML in the BBC.
3863
			if (!empty($matches2))
3864
			{
3865
				foreach ($matches2[0] as $ind => $dummy)
3866
				{
3867
					$matches[0][] = $matches2[0][$ind];
3868
					$matches[1][] = '';
3869
					$matches[2][] = '';
3870
					$matches[3][] = '';
3871
					$matches[4][] = '';
3872
					$matches[5][] = '';
3873
					$matches[6][] = '';
3874
					$matches[7][] = $matches2[1][$ind];
3875
				}
3876
			}
3877
3878
			$replaces = array();
3879
			// Try to find all the images!
3880
			if (!empty($matches))
3881
			{
3882
				foreach ($matches[0] as $key => $image)
3883
				{
3884
					$width = -1;
3885
					$height = -1;
3886
3887
					// Does it have predefined restraints? Width first.
3888
					if ($matches[6][$key])
3889
						$matches[2][$key] = $matches[6][$key];
3890
					if ($matches[2][$key] && $sig_limits[5] && $matches[2][$key] > $sig_limits[5])
3891
					{
3892
						$width = $sig_limits[5];
3893
						$matches[4][$key] = $matches[4][$key] * ($width / $matches[2][$key]);
3894
					}
3895
					elseif ($matches[2][$key])
3896
						$width = $matches[2][$key];
3897
					// ... and height.
3898
					if ($matches[4][$key] && $sig_limits[6] && $matches[4][$key] > $sig_limits[6])
3899
					{
3900
						$height = $sig_limits[6];
3901
						if ($width != -1)
3902
							$width = $width * ($height / $matches[4][$key]);
3903
					}
3904
					elseif ($matches[4][$key])
3905
						$height = $matches[4][$key];
3906
3907
					// If the dimensions are still not fixed - we need to check the actual image.
3908
					if (($width == -1 && $sig_limits[5]) || ($height == -1 && $sig_limits[6]))
3909
					{
3910
						$sizes = url_image_size($matches[7][$key]);
3911
						if (is_array($sizes))
3912
						{
3913
							// Too wide?
3914
							if ($sizes[0] > $sig_limits[5] && $sig_limits[5])
3915
							{
3916
								$width = $sig_limits[5];
3917
								$sizes[1] = $sizes[1] * ($width / $sizes[0]);
3918
							}
3919
							// Too high?
3920
							if ($sizes[1] > $sig_limits[6] && $sig_limits[6])
3921
							{
3922
								$height = $sig_limits[6];
3923
								if ($width == -1)
3924
									$width = $sizes[0];
3925
								$width = $width * ($height / $sizes[1]);
3926
							}
3927
							elseif ($width != -1)
3928
								$height = $sizes[1];
3929
						}
3930
					}
3931
3932
					// Did we come up with some changes? If so remake the string.
3933
					if ($width != -1 || $height != -1)
3934
						$replaces[$image] = '[img' . ($width != -1 ? ' width=' . round($width) : '') . ($height != -1 ? ' height=' . round($height) : '') . ']' . $matches[7][$key] . '[/img]';
3935
				}
3936
				if (!empty($replaces))
3937
					$value = str_replace(array_keys($replaces), array_values($replaces), $value);
3938
			}
3939
		}
3940
3941
		// Any disabled BBC?
3942
		$disabledSigBBC = implode('|', $disabledTags);
3943
		if (!empty($disabledSigBBC))
3944
		{
3945
			if (preg_match('~\[(' . $disabledSigBBC . '[ =\]/])~i', $unparsed_signature, $matches) !== false && isset($matches[1]))
3946
			{
3947
				$disabledTags = array_unique($disabledTags);
3948
				$txt['profile_error_signature_disabled_bbc'] = sprintf($txt['profile_error_signature_disabled_bbc'], implode(', ', $disabledTags));
3949
				return 'signature_disabled_bbc';
3950
			}
3951
		}
3952
	}
3953
3954
	preparsecode($value);
3955
3956
	// Too long?
3957
	if (!allowedTo('admin_forum') && !empty($sig_limits[1]) && $smcFunc['strlen'](str_replace('<br>', "\n", $value)) > $sig_limits[1])
3958
	{
3959
		$_POST['signature'] = trim($smcFunc['htmlspecialchars'](str_replace('<br>', "\n", $value), ENT_QUOTES));
3960
		$txt['profile_error_signature_max_length'] = sprintf($txt['profile_error_signature_max_length'], $sig_limits[1]);
3961
		return 'signature_max_length';
3962
	}
3963
3964
	return true;
3965
}
3966
3967
/**
3968
 * Validate an email address.
3969
 *
3970
 * @param string $email The email address to validate
3971
 * @param int $memID The ID of the member (used to prevent false positives from the current user)
3972
 * @return bool|string True if the email is valid, otherwise a string indicating what the problem is
3973
 */
3974
function profileValidateEmail($email, $memID = 0)
3975
{
3976
	global $smcFunc;
3977
3978
	$email = strtr($email, array('&#039;' => '\''));
3979
3980
	// Check the name and email for validity.
3981
	if (trim($email) == '')
3982
		return 'no_email';
3983
	if (!filter_var($email, FILTER_VALIDATE_EMAIL))
3984
		return 'bad_email';
3985
3986
	// Email addresses should be and stay unique.
3987
	$request = $smcFunc['db_query']('', '
3988
		SELECT id_member
3989
		FROM {db_prefix}members
3990
		WHERE ' . ($memID != 0 ? 'id_member != {int:selected_member} AND ' : '') . '
3991
			email_address = {string:email_address}
3992
		LIMIT 1',
3993
		array(
3994
			'selected_member' => $memID,
3995
			'email_address' => $email,
3996
		)
3997
	);
3998
3999
	if ($smcFunc['db_num_rows']($request) > 0)
4000
		return 'email_taken';
4001
	$smcFunc['db_free_result']($request);
4002
4003
	return true;
4004
}
4005
4006
/**
4007
 * Reload a user's settings.
4008
 */
4009
function profileReloadUser()
4010
{
4011
	global $modSettings, $context, $cur_profile;
4012
4013
	if (isset($_POST['passwrd2']) && $_POST['passwrd2'] != '')
4014
		setLoginCookie(60 * $modSettings['cookieTime'], $context['id_member'], hash_salt($_POST['passwrd1'], $cur_profile['password_salt']));
4015
4016
	loadUserSettings();
4017
	writeLog();
4018
}
4019
4020
/**
4021
 * Send the user a new activation email if they need to reactivate!
4022
 */
4023
function profileSendActivation()
4024
{
4025
	global $sourcedir, $profile_vars, $context, $scripturl, $smcFunc, $cookiename, $cur_profile, $language, $modSettings;
4026
4027
	require_once($sourcedir . '/Subs-Post.php');
4028
4029
	// Shouldn't happen but just in case.
4030
	if (empty($profile_vars['email_address']))
4031
		return;
4032
4033
	$replacements = array(
4034
		'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $context['id_member'] . ';code=' . $profile_vars['validation_code'],
4035
		'ACTIVATIONCODE' => $profile_vars['validation_code'],
4036
		'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $context['id_member'],
4037
	);
4038
4039
	// Send off the email.
4040
	$emaildata = loadEmailTemplate('activate_reactivate', $replacements, empty($cur_profile['lngfile']) || empty($modSettings['userLanguage']) ? $language : $cur_profile['lngfile']);
4041
	sendmail($profile_vars['email_address'], $emaildata['subject'], $emaildata['body'], null, 'reactivate', $emaildata['is_html'], 0);
4042
4043
	// Log the user out.
4044
	$smcFunc['db_query']('', '
4045
		DELETE FROM {db_prefix}log_online
4046
		WHERE id_member = {int:selected_member}',
4047
		array(
4048
			'selected_member' => $context['id_member'],
4049
		)
4050
	);
4051
	$_SESSION['log_time'] = 0;
4052
	$_SESSION['login_' . $cookiename] = $smcFunc['json_encode'](array(0, '', 0));
4053
4054
	if (isset($_COOKIE[$cookiename]))
4055
		$_COOKIE[$cookiename] = '';
4056
4057
	loadUserSettings();
4058
4059
	$context['user']['is_logged'] = false;
4060
	$context['user']['is_guest'] = true;
4061
4062
	redirectexit('action=sendactivation');
4063
}
4064
4065
/**
4066
 * Function to allow the user to choose group membership etc...
4067
 *
4068
 * @param int $memID The ID of the member
4069
 */
4070
function groupMembership($memID)
4071
{
4072
	global $txt, $user_profile, $context, $smcFunc;
4073
4074
	$curMember = $user_profile[$memID];
4075
	$context['primary_group'] = $curMember['id_group'];
4076
4077
	// Can they manage groups?
4078
	$context['can_manage_membergroups'] = allowedTo('manage_membergroups');
4079
	$context['can_manage_protected'] = allowedTo('admin_forum');
4080
	$context['can_edit_primary'] = $context['can_manage_protected'];
4081
	$context['update_message'] = isset($_GET['msg']) && isset($txt['group_membership_msg_' . $_GET['msg']]) ? $txt['group_membership_msg_' . $_GET['msg']] : '';
4082
4083
	// Get all the groups this user is a member of.
4084
	$groups = explode(',', $curMember['additional_groups']);
4085
	$groups[] = $curMember['id_group'];
4086
4087
	// Ensure the query doesn't croak!
4088
	if (empty($groups))
4089
		$groups = array(0);
4090
	// Just to be sure...
4091
	foreach ($groups as $k => $v)
4092
		$groups[$k] = (int) $v;
4093
4094
	// Get all the membergroups they can join.
4095
	$request = $smcFunc['db_query']('', '
4096
		SELECT mg.id_group, mg.group_name, mg.description, mg.group_type, mg.online_color, mg.hidden,
4097
			COALESCE(lgr.id_member, 0) AS pending
4098
		FROM {db_prefix}membergroups AS mg
4099
			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})
4100
		WHERE (mg.id_group IN ({array_int:group_list})
4101
			OR mg.group_type > {int:nonjoin_group_id})
4102
			AND mg.min_posts = {int:min_posts}
4103
			AND mg.id_group != {int:moderator_group}
4104
		ORDER BY group_name',
4105
		array(
4106
			'group_list' => $groups,
4107
			'selected_member' => $memID,
4108
			'status_open' => 0,
4109
			'nonjoin_group_id' => 1,
4110
			'min_posts' => -1,
4111
			'moderator_group' => 3,
4112
		)
4113
	);
4114
	// This beast will be our group holder.
4115
	$context['groups'] = array(
4116
		'member' => array(),
4117
		'available' => array()
4118
	);
4119
	while ($row = $smcFunc['db_fetch_assoc']($request))
4120
	{
4121
		// Can they edit their primary group?
4122
		if (($row['id_group'] == $context['primary_group'] && $row['group_type'] > 1) || ($row['hidden'] != 2 && $context['primary_group'] == 0 && in_array($row['id_group'], $groups)))
4123
			$context['can_edit_primary'] = true;
4124
4125
		// If they can't manage (protected) groups, and it's not publically joinable or already assigned, they can't see it.
4126
		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...
4127
			continue;
4128
4129
		$context['groups'][in_array($row['id_group'], $groups) ? 'member' : 'available'][$row['id_group']] = array(
4130
			'id' => $row['id_group'],
4131
			'name' => $row['group_name'],
4132
			'desc' => $row['description'],
4133
			'color' => $row['online_color'],
4134
			'type' => $row['group_type'],
4135
			'pending' => $row['pending'],
4136
			'is_primary' => $row['id_group'] == $context['primary_group'],
4137
			'can_be_primary' => $row['hidden'] != 2,
4138
			// Anything more than this needs to be done through account settings for security.
4139
			'can_leave' => $row['id_group'] != 1 && $row['group_type'] > 1 ? true : false,
4140
		);
4141
	}
4142
	$smcFunc['db_free_result']($request);
4143
4144
	// Add registered members on the end.
4145
	$context['groups']['member'][0] = array(
4146
		'id' => 0,
4147
		'name' => $txt['regular_members'],
4148
		'desc' => $txt['regular_members_desc'],
4149
		'type' => 0,
4150
		'is_primary' => $context['primary_group'] == 0 ? true : false,
4151
		'can_be_primary' => true,
4152
		'can_leave' => 0,
4153
	);
4154
4155
	// No changing primary one unless you have enough groups!
4156
	if (count($context['groups']['member']) < 2)
4157
		$context['can_edit_primary'] = false;
4158
4159
	// In the special case that someone is requesting membership of a group, setup some special context vars.
4160
	if (isset($_REQUEST['request']) && isset($context['groups']['available'][(int) $_REQUEST['request']]) && $context['groups']['available'][(int) $_REQUEST['request']]['type'] == 2)
4161
		$context['group_request'] = $context['groups']['available'][(int) $_REQUEST['request']];
4162
}
4163
4164
/**
4165
 * This function actually makes all the group changes
4166
 *
4167
 * @param array $profile_vars The profile variables
4168
 * @param array $post_errors Any errors that have occurred
4169
 * @param int $memID The ID of the member
4170
 * @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
4171
 */
4172
function groupMembership2($profile_vars, $post_errors, $memID)
4173
{
4174
	global $user_info, $context, $user_profile, $modSettings, $smcFunc;
4175
4176
	// Let's be extra cautious...
4177
	if (!$context['user']['is_owner'] || empty($modSettings['show_group_membership']))
4178
		isAllowedTo('manage_membergroups');
4179
	if (!isset($_REQUEST['gid']) && !isset($_POST['primary']))
4180
		fatal_lang_error('no_access', false);
4181
4182
	checkSession(isset($_GET['gid']) ? 'get' : 'post');
4183
4184
	$old_profile = &$user_profile[$memID];
4185
	$context['can_manage_membergroups'] = allowedTo('manage_membergroups');
4186
	$context['can_manage_protected'] = allowedTo('admin_forum');
4187
4188
	// By default the new primary is the old one.
4189
	$newPrimary = $old_profile['id_group'];
4190
	$addGroups = array_flip(explode(',', $old_profile['additional_groups']));
4191
	$canChangePrimary = $old_profile['id_group'] == 0 ? 1 : 0;
4192
	$changeType = isset($_POST['primary']) ? 'primary' : (isset($_POST['req']) ? 'request' : 'free');
4193
4194
	// One way or another, we have a target group in mind...
4195
	$group_id = isset($_REQUEST['gid']) ? (int) $_REQUEST['gid'] : (int) $_POST['primary'];
4196
	$foundTarget = $changeType == 'primary' && $group_id == 0 ? true : false;
4197
4198
	// Sanity check!!
4199
	if ($group_id == 1)
4200
		isAllowedTo('admin_forum');
4201
	// Protected groups too!
4202
	else
4203
	{
4204
		$request = $smcFunc['db_query']('', '
4205
			SELECT group_type
4206
			FROM {db_prefix}membergroups
4207
			WHERE id_group = {int:current_group}
4208
			LIMIT {int:limit}',
4209
			array(
4210
				'current_group' => $group_id,
4211
				'limit' => 1,
4212
			)
4213
		);
4214
		list ($is_protected) = $smcFunc['db_fetch_row']($request);
4215
		$smcFunc['db_free_result']($request);
4216
4217
		if ($is_protected == 1)
4218
			isAllowedTo('admin_forum');
4219
	}
4220
4221
	// What ever we are doing, we need to determine if changing primary is possible!
4222
	$request = $smcFunc['db_query']('', '
4223
		SELECT id_group, group_type, hidden, group_name
4224
		FROM {db_prefix}membergroups
4225
		WHERE id_group IN ({int:group_list}, {int:current_group})',
4226
		array(
4227
			'group_list' => $group_id,
4228
			'current_group' => $old_profile['id_group'],
4229
		)
4230
	);
4231
	while ($row = $smcFunc['db_fetch_assoc']($request))
4232
	{
4233
		// Is this the new group?
4234
		if ($row['id_group'] == $group_id)
4235
		{
4236
			$foundTarget = true;
4237
			$group_name = $row['group_name'];
4238
4239
			// Does the group type match what we're doing - are we trying to request a non-requestable group?
4240
			if ($changeType == 'request' && $row['group_type'] != 2)
4241
				fatal_lang_error('no_access', false);
4242
			// What about leaving a requestable group we are not a member of?
4243
			elseif ($changeType == 'free' && $row['group_type'] == 2 && $old_profile['id_group'] != $row['id_group'] && !isset($addGroups[$row['id_group']]))
4244
				fatal_lang_error('no_access', false);
4245
			elseif ($changeType == 'free' && $row['group_type'] != 3 && $row['group_type'] != 2)
4246
				fatal_lang_error('no_access', false);
4247
4248
			// We can't change the primary group if this is hidden!
4249
			if ($row['hidden'] == 2)
4250
				$canChangePrimary = false;
4251
		}
4252
4253
		// If this is their old primary, can we change it?
4254
		if ($row['id_group'] == $old_profile['id_group'] && ($row['group_type'] > 1 || $context['can_manage_membergroups']) && $canChangePrimary !== false)
4255
			$canChangePrimary = 1;
4256
4257
		// If we are not doing a force primary move, don't do it automatically if current primary is not 0.
4258
		if ($changeType != 'primary' && $old_profile['id_group'] != 0)
4259
			$canChangePrimary = false;
4260
4261
		// If this is the one we are acting on, can we even act?
4262
		if ((!$context['can_manage_protected'] && $row['group_type'] == 1) || (!$context['can_manage_membergroups'] && $row['group_type'] == 0))
4263
			$canChangePrimary = false;
4264
	}
4265
	$smcFunc['db_free_result']($request);
4266
4267
	// Didn't find the target?
4268
	if (!$foundTarget)
4269
		fatal_lang_error('no_access', false);
4270
4271
	// Final security check, don't allow users to promote themselves to admin.
4272
	if ($context['can_manage_membergroups'] && !allowedTo('admin_forum'))
4273
	{
4274
		$request = $smcFunc['db_query']('', '
4275
			SELECT COUNT(permission)
4276
			FROM {db_prefix}permissions
4277
			WHERE id_group = {int:selected_group}
4278
				AND permission = {string:admin_forum}
4279
				AND add_deny = {int:not_denied}',
4280
			array(
4281
				'selected_group' => $group_id,
4282
				'not_denied' => 1,
4283
				'admin_forum' => 'admin_forum',
4284
			)
4285
		);
4286
		list ($disallow) = $smcFunc['db_fetch_row']($request);
4287
		$smcFunc['db_free_result']($request);
4288
4289
		if ($disallow)
4290
			isAllowedTo('admin_forum');
4291
	}
4292
4293
	// If we're requesting, add the note then return.
4294
	if ($changeType == 'request')
4295
	{
4296
		$request = $smcFunc['db_query']('', '
4297
			SELECT id_member
4298
			FROM {db_prefix}log_group_requests
4299
			WHERE id_member = {int:selected_member}
4300
				AND id_group = {int:selected_group}
4301
				AND status = {int:status_open}',
4302
			array(
4303
				'selected_member' => $memID,
4304
				'selected_group' => $group_id,
4305
				'status_open' => 0,
4306
			)
4307
		);
4308
		if ($smcFunc['db_num_rows']($request) != 0)
4309
			fatal_lang_error('profile_error_already_requested_group');
4310
		$smcFunc['db_free_result']($request);
4311
4312
		// Log the request.
4313
		$smcFunc['db_insert']('',
4314
			'{db_prefix}log_group_requests',
4315
			array(
4316
				'id_member' => 'int', 'id_group' => 'int', 'time_applied' => 'int', 'reason' => 'string-65534',
4317
				'status' => 'int', 'id_member_acted' => 'int', 'member_name_acted' => 'string', 'time_acted' => 'int', 'act_reason' => 'string',
4318
			),
4319
			array(
4320
				$memID, $group_id, time(), $_POST['reason'],
4321
				0, 0, '', 0, '',
4322
			),
4323
			array('id_request')
4324
		);
4325
4326
		// Set up some data for our background task...
4327
		$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...
4328
4329
		// Add a background task to handle notifying people of this request
4330
		$smcFunc['db_insert']('insert', '{db_prefix}background_tasks',
4331
			array('task_file' => 'string-255', 'task_class' => 'string-255', 'task_data' => 'string', 'claimed_time' => 'int'),
4332
			array('$sourcedir/tasks/GroupReq-Notify.php', 'GroupReq_Notify_Background', $data, 0), array()
4333
		);
4334
4335
		return $changeType;
4336
	}
4337
	// Otherwise we are leaving/joining a group.
4338
	elseif ($changeType == 'free')
4339
	{
4340
		// Are we leaving?
4341
		if ($old_profile['id_group'] == $group_id || isset($addGroups[$group_id]))
4342
		{
4343
			if ($old_profile['id_group'] == $group_id)
4344
				$newPrimary = 0;
4345
			else
4346
				unset($addGroups[$group_id]);
4347
		}
4348
		// ... if not, must be joining.
4349
		else
4350
		{
4351
			// Can we change the primary, and do we want to?
4352
			if ($canChangePrimary)
4353
			{
4354
				if ($old_profile['id_group'] != 0)
4355
					$addGroups[$old_profile['id_group']] = -1;
4356
				$newPrimary = $group_id;
4357
			}
4358
			// Otherwise it's an additional group...
4359
			else
4360
				$addGroups[$group_id] = -1;
4361
		}
4362
	}
4363
	// Finally, we must be setting the primary.
4364
	elseif ($canChangePrimary)
4365
	{
4366
		if ($old_profile['id_group'] != 0)
4367
			$addGroups[$old_profile['id_group']] = -1;
4368
		if (isset($addGroups[$group_id]))
4369
			unset($addGroups[$group_id]);
4370
		$newPrimary = $group_id;
4371
	}
4372
4373
	// Finally, we can make the changes!
4374
	foreach ($addGroups as $id => $dummy)
4375
		if (empty($id))
4376
			unset($addGroups[$id]);
4377
	$addGroups = implode(',', array_flip($addGroups));
4378
4379
	// Ensure that we don't cache permissions if the group is changing.
4380
	if ($context['user']['is_owner'])
4381
		$_SESSION['mc']['time'] = 0;
4382
	else
4383
		updateSettings(array('settings_updated' => time()));
4384
4385
	updateMemberData($memID, array('id_group' => $newPrimary, 'additional_groups' => $addGroups));
4386
4387
	return $changeType;
4388
}
4389
4390
/**
4391
 * Provides interface to setup Two Factor Auth in SMF
4392
 *
4393
 * @param int $memID The ID of the member
4394
 */
4395
function tfasetup($memID)
4396
{
4397
	global $user_info, $context, $user_settings, $sourcedir, $modSettings, $smcFunc;
4398
4399
	require_once($sourcedir . '/Class-TOTP.php');
4400
	require_once($sourcedir . '/Subs-Auth.php');
4401
4402
	// load JS lib for QR
4403
	loadJavaScriptFile('qrcode.js', array('force_current' => false, 'validate' => true));
4404
4405
	// If TFA has not been setup, allow them to set it up
4406
	if (empty($user_settings['tfa_secret']) && $context['user']['is_owner'])
4407
	{
4408
		// Check to ensure we're forcing SSL for authentication
4409
		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...
4410
			fatal_lang_error('login_ssl_required', false);
4411
4412
		// In some cases (forced 2FA or backup code) they would be forced to be redirected here,
4413
		// we do not want too much AJAX to confuse them.
4414
		if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && !isset($_REQUEST['backup']) && !isset($_REQUEST['forced']))
4415
		{
4416
			$context['from_ajax'] = true;
4417
			$context['template_layers'] = array();
4418
		}
4419
4420
		// When the code is being sent, verify to make sure the user got it right
4421
		if (!empty($_REQUEST['save']) && !empty($_SESSION['tfa_secret']))
4422
		{
4423
			$code = $_POST['tfa_code'];
4424
			$totp = new \TOTP\Auth($_SESSION['tfa_secret']);
4425
			$totp->setRange(1);
4426
			$valid_code = strlen($code) == $totp->getCodeLength() && $totp->validateCode($code);
4427
4428
			if (empty($context['password_auth_failed']) && $valid_code)
4429
			{
4430
				$backup = substr(sha1($smcFunc['random_int']()), 0, 16);
4431
				$backup_encrypted = hash_password($user_settings['member_name'], $backup);
4432
4433
				updateMemberData($memID, array(
4434
					'tfa_secret' => $_SESSION['tfa_secret'],
4435
					'tfa_backup' => $backup_encrypted,
4436
				));
4437
4438
				setTFACookie(3153600, $memID, hash_salt($backup_encrypted, $user_settings['password_salt']));
4439
4440
				unset($_SESSION['tfa_secret']);
4441
4442
				$context['tfa_backup'] = $backup;
4443
				$context['sub_template'] = 'tfasetup_backup';
4444
4445
				return;
4446
			}
4447
			else
4448
			{
4449
				$context['tfa_secret'] = $_SESSION['tfa_secret'];
4450
				$context['tfa_error'] = !$valid_code;
4451
				$context['tfa_pass_value'] = $_POST['passwd'];
4452
				$context['tfa_value'] = $_POST['tfa_code'];
4453
			}
4454
		}
4455
		else
4456
		{
4457
			$totp = new \TOTP\Auth();
4458
			$secret = $totp->generateCode();
4459
			$_SESSION['tfa_secret'] = $secret;
4460
			$context['tfa_secret'] = $secret;
4461
			$context['tfa_backup'] = isset($_REQUEST['backup']);
4462
		}
4463
4464
		$context['tfa_qr_url'] = $totp->getQrCodeUrl($context['forum_name'] . ':' . $user_info['name'], $context['tfa_secret']);
4465
	}
4466
	else
4467
		redirectexit('action=profile;area=account;u=' . $memID);
4468
}
4469
4470
/**
4471
 * Provides interface to disable two-factor authentication in SMF
4472
 *
4473
 * @param int $memID The ID of the member
4474
 */
4475
function tfadisable($memID)
4476
{
4477
	global $context, $modSettings, $smcFunc, $user_settings;
4478
4479
	if (!empty($user_settings['tfa_secret']))
4480
	{
4481
		// Bail if we're forcing SSL for authentication and the network connection isn't secure.
4482
		if (!empty($modSettings['force_ssl']) && !httpsOn())
4483
			fatal_lang_error('login_ssl_required', false);
4484
4485
		// The admin giveth...
4486
		elseif ($modSettings['tfa_mode'] == 3 && $context['user']['is_owner'])
4487
			fatal_lang_error('cannot_disable_tfa', false);
4488
		elseif ($modSettings['tfa_mode'] == 2 && $context['user']['is_owner'])
4489
		{
4490
			$groups = array($user_settings['id_group']);
4491
			if (!empty($user_settings['additional_groups']))
4492
				$groups = array_unique(array_merge($groups, explode(',', $user_settings['additional_groups'])));
4493
4494
			$request = $smcFunc['db_query']('', '
4495
				SELECT id_group
4496
				FROM {db_prefix}membergroups
4497
				WHERE tfa_required = {int:tfa_required}
4498
					AND id_group IN ({array_int:groups})',
4499
				array(
4500
					'tfa_required' => 1,
4501
					'groups' => $groups,
4502
				)
4503
			);
4504
			$tfa_required_groups = $smcFunc['db_num_rows']($request);
4505
			$smcFunc['db_free_result']($request);
4506
4507
			// They belong to a membergroup that requires tfa.
4508
			if (!empty($tfa_required_groups))
4509
				fatal_lang_error('cannot_disable_tfa2', false);
4510
		}
4511
	}
4512
	else
4513
		redirectexit('action=profile;area=account;u=' . $memID);
4514
}
4515
4516
?>