Passed
Push — release-2.1 ( f78a97...d22fc2 )
by Mathias
32s queued 10s
created

alert_count()   D

Complexity

Conditions 22
Paths 97

Size

Total Lines 118
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 22
eloc 60
nc 97
nop 2
dl 0
loc 118
rs 4.1666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This file 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
	);
1936
1937
	$subAction = !empty($_GET['sa']) && isset($sa[$_GET['sa']]) ? $_GET['sa'] : 'alerts';
1938
1939
	$context['sub_template'] = $sa[$subAction];
1940
	$context[$context['profile_menu_name']]['tab_data'] = array(
1941
		'title' => $txt['notification'],
1942
		'help' => '',
1943
		'description' => $txt['notification_info'],
1944
	);
1945
	$sa[$subAction]($memID);
1946
}
1947
1948
/**
1949
 * Handles configuration of alert preferences
1950
 *
1951
 * @param int $memID The ID of the member
1952
 */
1953
function alert_configuration($memID)
1954
{
1955
	global $txt, $context, $modSettings, $smcFunc, $sourcedir;
1956
1957
	if (!isset($context['token_check']))
1958
		$context['token_check'] = 'profile-nt' . $memID;
1959
1960
	is_not_guest();
1961
	if (!$context['user']['is_owner'])
1962
		isAllowedTo('profile_extra_any');
1963
1964
	// Set the post action if we're coming from the profile...
1965
	if (!isset($context['action']))
1966
		$context['action'] = 'action=profile;area=notification;sa=alerts;u=' . $memID;
1967
1968
	// What options are set
1969
	loadThemeOptions($memID);
1970
	loadJavaScriptFile('alertSettings.js', array('minimize' => true), 'smf_alertSettings');
1971
1972
	// Now load all the values for this user.
1973
	require_once($sourcedir . '/Subs-Notify.php');
1974
	$prefs = getNotifyPrefs($memID, '', $memID != 0);
1975
1976
	$context['alert_prefs'] = !empty($prefs[$memID]) ? $prefs[$memID] : array();
1977
1978
	$context['member'] += array(
1979
		'alert_timeout' => isset($context['alert_prefs']['alert_timeout']) ? $context['alert_prefs']['alert_timeout'] : 10,
1980
		'notify_announcements' => isset($context['alert_prefs']['announcements']) ? $context['alert_prefs']['announcements'] : 0,
1981
	);
1982
	$context['can_disable_announce'] = $memID == 0 || !empty($modSettings['allow_disableAnnounce']);
1983
1984
	// Now for the exciting stuff.
1985
	// We have groups of items, each item has both an alert and an email key as well as an optional help string.
1986
	// Valid values for these keys are 'always', 'yes', 'never'; if using always or never you should add a help string.
1987
	$alert_types = array(
1988
		'board' => array(
1989
			'topic_notify' => array('alert' => 'yes', 'email' => 'yes'),
1990
			'board_notify' => array('alert' => 'yes', 'email' => 'yes'),
1991
		),
1992
		'msg' => array(
1993
			'msg_mention' => array('alert' => 'yes', 'email' => 'yes'),
1994
			'msg_quote' => array('alert' => 'yes', 'email' => 'yes'),
1995
			'msg_like' => array('alert' => 'yes', 'email' => 'never'),
1996
			'unapproved_reply' => array('alert' => 'yes', 'email' => 'yes'),
1997
		),
1998
		'pm' => array(
1999
			'pm_new' => array('alert' => 'never', 'email' => 'yes', 'help' => 'alert_pm_new', 'permission' => array('name' => 'pm_read', 'is_board' => false)),
2000
			'pm_reply' => array('alert' => 'never', 'email' => 'yes', 'help' => 'alert_pm_new', 'permission' => array('name' => 'pm_send', 'is_board' => false)),
2001
		),
2002
		'groupr' => array(
2003
			'groupr_approved' => array('alert' => 'always', 'email' => 'yes'),
2004
			'groupr_rejected' => array('alert' => 'always', 'email' => 'yes'),
2005
		),
2006
		'moderation' => array(
2007
			'unapproved_attachment' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'approve_posts', 'is_board' => true)),
2008
			'unapproved_post' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'approve_posts', 'is_board' => true)),
2009
			'msg_report' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_board', 'is_board' => true)),
2010
			'msg_report_reply' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_board', 'is_board' => true)),
2011
			'member_report' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_forum', 'is_board' => false)),
2012
			'member_report_reply' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_forum', 'is_board' => false)),
2013
		),
2014
		'members' => array(
2015
			'member_register' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_forum', 'is_board' => false)),
2016
			'request_group' => array('alert' => 'yes', 'email' => 'yes'),
2017
			'warn_any' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'issue_warning', 'is_board' => false)),
2018
			'buddy_request' => array('alert' => 'yes', 'email' => 'never'),
2019
			'birthday' => array('alert' => 'yes', 'email' => 'yes'),
2020
		),
2021
		'calendar' => array(
2022
			'event_new' => array('alert' => 'yes', 'email' => 'yes', 'help' => 'alert_event_new'),
2023
		),
2024
		'paidsubs' => array(
2025
			'paidsubs_expiring' => array('alert' => 'yes', 'email' => 'yes'),
2026
		),
2027
	);
2028
	$group_options = array(
2029
		'board' => array(
2030
			array('check', 'msg_auto_notify', 'label' => 'after'),
2031
			array('check', 'msg_receive_body', 'label' => 'after'),
2032
			array('select', 'msg_notify_pref', 'label' => 'before', 'opts' => array(
2033
				0 => $txt['alert_opt_msg_notify_pref_nothing'],
2034
				1 => $txt['alert_opt_msg_notify_pref_instant'],
2035
				2 => $txt['alert_opt_msg_notify_pref_first'],
2036
				3 => $txt['alert_opt_msg_notify_pref_daily'],
2037
				4 => $txt['alert_opt_msg_notify_pref_weekly'],
2038
			)),
2039
			array('select', 'msg_notify_type', 'label' => 'before', 'opts' => array(
2040
				1 => $txt['notify_send_type_everything'],
2041
				2 => $txt['notify_send_type_everything_own'],
2042
				3 => $txt['notify_send_type_only_replies'],
2043
				4 => $txt['notify_send_type_nothing'],
2044
			)),
2045
		),
2046
		'pm' => array(
2047
			array('select', 'pm_notify', 'label' => 'before', 'opts' => array(
2048
				1 => $txt['email_notify_all'],
2049
				2 => $txt['email_notify_buddies'],
2050
			)),
2051
		),
2052
	);
2053
2054
	// There are certain things that are disabled at the group level.
2055
	if (empty($modSettings['cal_enabled']))
2056
		unset($alert_types['calendar']);
2057
2058
	// Disable paid subscriptions at group level if they're disabled
2059
	if (empty($modSettings['paid_enabled']))
2060
		unset($alert_types['paidsubs']);
2061
2062
	// Disable membergroup requests at group level if they're disabled
2063
	if (empty($modSettings['show_group_membership']))
2064
		unset($alert_types['groupr'], $alert_types['members']['request_group']);
2065
2066
	// Disable mentions if they're disabled
2067
	if (empty($modSettings['enable_mentions']))
2068
		unset($alert_types['msg']['msg_mention']);
2069
2070
	// Disable likes if they're disabled
2071
	if (empty($modSettings['enable_likes']))
2072
		unset($alert_types['msg']['msg_like']);
2073
2074
	// Disable buddy requests if they're disabled
2075
	if (empty($modSettings['enable_buddylist']))
2076
		unset($alert_types['members']['buddy_request']);
2077
2078
	// Now, now, we could pass this through global but we should really get into the habit of
2079
	// passing content to hooks, not expecting hooks to splatter everything everywhere.
2080
	call_integration_hook('integrate_alert_types', array(&$alert_types, &$group_options));
2081
2082
	// Now we have to do some permissions testing - but only if we're not loading this from the admin center
2083
	if (!empty($memID))
2084
	{
2085
		require_once($sourcedir . '/Subs-Members.php');
2086
		$perms_cache = array();
2087
		$request = $smcFunc['db_query']('', '
2088
			SELECT COUNT(*)
2089
			FROM {db_prefix}group_moderators
2090
			WHERE id_member = {int:memID}',
2091
			array(
2092
				'memID' => $memID,
2093
			)
2094
		);
2095
2096
		list ($can_mod) = $smcFunc['db_fetch_row']($request);
2097
2098
		if (!isset($perms_cache['manage_membergroups']))
2099
		{
2100
			$members = membersAllowedTo('manage_membergroups');
2101
			$perms_cache['manage_membergroups'] = in_array($memID, $members);
2102
		}
2103
2104
		if (!($perms_cache['manage_membergroups'] || $can_mod != 0))
2105
			unset($alert_types['members']['request_group']);
2106
2107
		foreach ($alert_types as $group => $items)
2108
		{
2109
			foreach ($items as $alert_key => $alert_value)
2110
			{
2111
				if (!isset($alert_value['permission']))
2112
					continue;
2113
				if (!isset($perms_cache[$alert_value['permission']['name']]))
2114
				{
2115
					$in_board = !empty($alert_value['permission']['is_board']) ? 0 : null;
2116
					$members = membersAllowedTo($alert_value['permission']['name'], $in_board);
2117
					$perms_cache[$alert_value['permission']['name']] = in_array($memID, $members);
2118
				}
2119
2120
				if (!$perms_cache[$alert_value['permission']['name']])
2121
					unset ($alert_types[$group][$alert_key]);
2122
			}
2123
2124
			if (empty($alert_types[$group]))
2125
				unset ($alert_types[$group]);
2126
		}
2127
	}
2128
2129
	// And finally, exporting it to be useful later.
2130
	$context['alert_types'] = $alert_types;
2131
	$context['alert_group_options'] = $group_options;
2132
2133
	$context['alert_bits'] = array(
2134
		'alert' => 0x01,
2135
		'email' => 0x02,
2136
	);
2137
2138
	if (isset($_POST['notify_submit']))
2139
	{
2140
		checkSession();
2141
		validateToken($context['token_check'], 'post');
2142
2143
		// We need to step through the list of valid settings and figure out what the user has set.
2144
		$update_prefs = array();
2145
2146
		// Now the group level options
2147
		foreach ($context['alert_group_options'] as $opt_group => $group)
2148
		{
2149
			foreach ($group as $this_option)
2150
			{
2151
				switch ($this_option[0])
2152
				{
2153
					case 'check':
2154
						$update_prefs[$this_option[1]] = !empty($_POST['opt_' . $this_option[1]]) ? 1 : 0;
2155
						break;
2156
					case 'select':
2157
						if (isset($_POST['opt_' . $this_option[1]], $this_option['opts'][$_POST['opt_' . $this_option[1]]]))
2158
							$update_prefs[$this_option[1]] = $_POST['opt_' . $this_option[1]];
2159
						else
2160
						{
2161
							// We didn't have a sane value. Let's grab the first item from the possibles.
2162
							$keys = array_keys($this_option['opts']);
2163
							$first = array_shift($keys);
2164
							$update_prefs[$this_option[1]] = $first;
2165
						}
2166
						break;
2167
				}
2168
			}
2169
		}
2170
2171
		// Now the individual options
2172
		foreach ($context['alert_types'] as $alert_group => $items)
2173
		{
2174
			foreach ($items as $item_key => $this_options)
2175
			{
2176
				$this_value = 0;
2177
				foreach ($context['alert_bits'] as $type => $bitvalue)
2178
				{
2179
					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...
2180
						$this_value |= $bitvalue;
2181
				}
2182
				if (!isset($context['alert_prefs'][$item_key]) || $context['alert_prefs'][$item_key] != $this_value)
2183
					$update_prefs[$item_key] = $this_value;
2184
			}
2185
		}
2186
2187
		if (!empty($_POST['opt_alert_timeout']))
2188
			$update_prefs['alert_timeout'] = $context['member']['alert_timeout'] = (int) $_POST['opt_alert_timeout'];
2189
2190
		if (!empty($_POST['notify_announcements']))
2191
			$update_prefs['announcements'] = $context['member']['notify_announcements'] = (int) $_POST['notify_announcements'];
2192
2193
		setNotifyPrefs((int) $memID, $update_prefs);
2194
		foreach ($update_prefs as $pref => $value)
2195
			$context['alert_prefs'][$pref] = $value;
2196
2197
		makeNotificationChanges($memID);
2198
2199
		$context['profile_updated'] = $txt['profile_updated_own'];
2200
	}
2201
2202
	createToken($context['token_check'], 'post');
2203
}
2204
2205
/**
2206
 * Marks all alerts as read for the specified user
2207
 *
2208
 * @param int $memID The ID of the member
2209
 */
2210
function alert_markread($memID)
2211
{
2212
	global $context, $db_show_debug, $smcFunc;
2213
2214
	// We do not want to output debug information here.
2215
	$db_show_debug = false;
2216
2217
	// We only want to output our little layer here.
2218
	$context['template_layers'] = array();
2219
	$context['sub_template'] = 'alerts_all_read';
2220
2221
	loadLanguage('Alerts');
2222
2223
	// Now we're all set up.
2224
	is_not_guest();
2225
	if (!$context['user']['is_owner'])
2226
		fatal_error('no_access');
2227
2228
	checkSession('get');
2229
2230
	// Assuming we're here, mark everything as read and head back.
2231
	// We only spit back the little layer because this should be called AJAXively.
2232
	$smcFunc['db_query']('', '
2233
		UPDATE {db_prefix}user_alerts
2234
		SET is_read = {int:now}
2235
		WHERE id_member = {int:current_member}
2236
			AND is_read = 0',
2237
		array(
2238
			'now' => time(),
2239
			'current_member' => $memID,
2240
		)
2241
	);
2242
2243
	updateMemberData($memID, array('alerts' => 0));
2244
}
2245
2246
/**
2247
 * Marks a group of alerts as un/read
2248
 *
2249
 * @param int $memID The user ID.
2250
 * @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.
2251
 * @param integer $read To mark as read or unread, 1 for read, 0 or any other value different than 1 for unread.
2252
 * @return integer How many alerts remain unread
2253
 */
2254
function alert_mark($memID, $toMark, $read = 0)
2255
{
2256
	global $smcFunc;
2257
2258
	if (empty($toMark) || empty($memID))
2259
		return false;
2260
2261
	$toMark = (array) $toMark;
2262
2263
	$smcFunc['db_query']('', '
2264
		UPDATE {db_prefix}user_alerts
2265
		SET is_read = {int:read}
2266
		WHERE id_alert IN({array_int:toMark})',
2267
		array(
2268
			'read' => $read == 1 ? time() : 0,
2269
			'toMark' => $toMark,
2270
		)
2271
	);
2272
2273
	// Gotta know how many unread alerts are left.
2274
	$count = alert_count($memID, true);
2275
2276
	updateMemberData($memID, array('alerts' => $count));
2277
2278
	// Might want to know this.
2279
	return $count;
2280
}
2281
2282
/**
2283
 * Deletes a single or a group of alerts by ID
2284
 *
2285
 * @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...
2286
 * @param bool|int $memID The user ID. Used to update the user unread alerts count.
2287
 * @return void|int If the $memID param is set, returns the new amount of unread alerts.
2288
 */
2289
function alert_delete($toDelete, $memID = false)
2290
{
2291
	global $smcFunc;
2292
2293
	if (empty($toDelete))
2294
		return false;
2295
2296
	$toDelete = (array) $toDelete;
2297
2298
	$smcFunc['db_query']('', '
2299
		DELETE FROM {db_prefix}user_alerts
2300
		WHERE id_alert IN({array_int:toDelete})',
2301
		array(
2302
			'toDelete' => $toDelete,
2303
		)
2304
	);
2305
2306
	// Gotta know how many unread alerts are left.
2307
	if ($memID)
2308
	{
2309
		$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

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

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