Issues (1061)

Sources/Profile-Modify.php (2 issues)

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 https://www.simplemachines.org
12
 * @copyright 2020 Simple Machines and individual contributors
13
 * @license https://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)
145
			{
146
				// Bad date!  Go try again - please?
147
				if (($value = strtotime($value)) === false)
148
				{
149
					$value = $cur_profile['date_registered'];
150
					return $txt['invalid_registration'] . ' ' . strftime('%d %b %Y ' . (strpos($user_info['time_format'], '%H') !== false ? '%I:%M:%S %p' : '%H:%M:%S'), forum_time(false));
151
				}
152
153
				// As long as it doesn't equal "N/A"...
154
				elseif ($value != $txt['not_applicable'] && $value != strtotime(strftime('%Y-%m-%d', $cur_profile['date_registered'] + ($user_info['time_offset'] + $modSettings['time_offset']) * 3600)))
155
					$value = $value - ($user_info['time_offset'] + $modSettings['time_offset']) * 3600;
156
157
				else
158
					$value = $cur_profile['date_registered'];
159
160
				return true;
161
			},
162
		),
163
		'email_address' => array(
164
			'type' => 'email',
165
			'label' => $txt['user_email_address'],
166
			'subtext' => $txt['valid_email'],
167
			'log_change' => true,
168
			'permission' => 'profile_password',
169
			'js_submit' => !empty($modSettings['send_validation_onChange']) ? '
170
	form_handle.addEventListener(\'submit\', function(event)
171
	{
172
		if (this.email_address.value != "' . (!empty($cur_profile['email_address']) ? $cur_profile['email_address'] : '') . '")
173
		{
174
			alert(' . JavaScriptEscape($txt['email_change_logout']) . ');
175
			return true;
176
		}
177
	}, false);' : '',
178
			'input_validate' => function(&$value)
179
			{
180
				global $context, $old_profile, $profile_vars, $sourcedir, $modSettings;
181
182
				if (strtolower($value) == strtolower($old_profile['email_address']))
183
					return false;
184
185
				$isValid = profileValidateEmail($value, $context['id_member']);
186
187
				// Do they need to revalidate? If so schedule the function!
188
				if ($isValid === true && !empty($modSettings['send_validation_onChange']) && !allowedTo('moderate_forum'))
189
				{
190
					require_once($sourcedir . '/Subs-Members.php');
191
					$profile_vars['validation_code'] = generateValidationCode();
192
					$profile_vars['is_activated'] = 2;
193
					$context['profile_execute_on_save'][] = 'profileSendActivation';
194
					unset($context['profile_execute_on_save']['reload_user']);
195
				}
196
197
				return $isValid;
198
			},
199
		),
200
		// Selecting group membership is a complicated one so we treat it separate!
201
		'id_group' => array(
202
			'type' => 'callback',
203
			'callback_func' => 'group_manage',
204
			'permission' => 'manage_membergroups',
205
			'preload' => 'profileLoadGroups',
206
			'log_change' => true,
207
			'input_validate' => 'profileSaveGroups',
208
		),
209
		'id_theme' => array(
210
			'type' => 'callback',
211
			'callback_func' => 'theme_pick',
212
			'permission' => 'profile_extra',
213
			'enabled' => $modSettings['theme_allow'] || allowedTo('admin_forum'),
214
			'preload' => function() use ($smcFunc, &$context, $cur_profile, $txt)
215
			{
216
				$request = $smcFunc['db_query']('', '
217
					SELECT value
218
					FROM {db_prefix}themes
219
					WHERE id_theme = {int:id_theme}
220
						AND variable = {string:variable}
221
					LIMIT 1', array(
222
						'id_theme' => $cur_profile['id_theme'],
223
						'variable' => 'name',
224
					)
225
				);
226
				list ($name) = $smcFunc['db_fetch_row']($request);
227
				$smcFunc['db_free_result']($request);
228
229
				$context['member']['theme'] = array(
230
					'id' => $cur_profile['id_theme'],
231
					'name' => empty($cur_profile['id_theme']) ? $txt['theme_forum_default'] : $name
232
				);
233
				return true;
234
			},
235
			'input_validate' => function(&$value)
236
			{
237
				$value = (int) $value;
238
				return true;
239
			},
240
		),
241
		'lngfile' => array(
242
			'type' => 'select',
243
			'options' => function() use (&$context)
244
			{
245
				return $context['profile_languages'];
246
			},
247
			'label' => $txt['preferred_language'],
248
			'permission' => 'profile_identity',
249
			'preload' => 'profileLoadLanguages',
250
			'enabled' => !empty($modSettings['userLanguage']),
251
			'value' => empty($cur_profile['lngfile']) ? $language : $cur_profile['lngfile'],
252
			'input_validate' => function(&$value) use (&$context, $cur_profile)
253
			{
254
				// Load the languages.
255
				profileLoadLanguages();
256
257
				if (isset($context['profile_languages'][$value]))
258
				{
259
					if ($context['user']['is_owner'] && empty($context['password_auth_failed']))
260
						$_SESSION['language'] = $value;
261
					return true;
262
				}
263
				else
264
				{
265
					$value = $cur_profile['lngfile'];
266
					return false;
267
				}
268
			},
269
		),
270
		// The username is not always editable - so adjust it as such.
271
		'member_name' => array(
272
			'type' => allowedTo('admin_forum') && isset($_GET['changeusername']) ? 'text' : 'label',
273
			'label' => $txt['username'],
274
			'subtext' => allowedTo('admin_forum') && !isset($_GET['changeusername']) ? '[<a href="' . $scripturl . '?action=profile;u=' . $context['id_member'] . ';area=account;changeusername" style="font-style: italic;">' . $txt['username_change'] . '</a>]' : '',
275
			'log_change' => true,
276
			'permission' => 'profile_identity',
277
			'prehtml' => allowedTo('admin_forum') && isset($_GET['changeusername']) ? '<div class="alert">' . $txt['username_warning'] . '</div>' : '',
278
			'input_validate' => function(&$value) use ($sourcedir, $context, $user_info, $cur_profile)
279
			{
280
				if (allowedTo('admin_forum'))
281
				{
282
					// We'll need this...
283
					require_once($sourcedir . '/Subs-Auth.php');
284
285
					// Maybe they are trying to change their password as well?
286
					$resetPassword = true;
287
					if (isset($_POST['passwrd1']) && $_POST['passwrd1'] != '' && isset($_POST['passwrd2']) && $_POST['passwrd1'] == $_POST['passwrd2'] && validatePassword($_POST['passwrd1'], $value, array($cur_profile['real_name'], $user_info['username'], $user_info['name'], $user_info['email'])) == null)
0 ignored issues
show
It seems like you are loosely comparing validatePassword($_POST[..., $user_info['email'])) of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
288
						$resetPassword = false;
289
290
					// Do the reset... this will send them an email too.
291
					if ($resetPassword)
292
						resetPassword($context['id_member'], $value);
293
					elseif ($value !== null)
294
					{
295
						validateUsername($context['id_member'], trim(preg_replace('~[\t\n\r \x0B\0' . ($context['utf8'] ? '\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}' : '\x00-\x08\x0B\x0C\x0E-\x19\xA0') . ']+~' . ($context['utf8'] ? 'u' : ''), ' ', $value)));
296
						updateMemberData($context['id_member'], array('member_name' => $value));
297
298
						// Call this here so any integrated systems will know about the name change (resetPassword() takes care of this if we're letting SMF generate the password)
299
						call_integration_hook('integrate_reset_pass', array($cur_profile['member_name'], $value, $_POST['passwrd1']));
300
					}
301
				}
302
				return false;
303
			},
304
		),
305
		'passwrd1' => array(
306
			'type' => 'password',
307
			'label' => $txt['choose_pass'],
308
			'subtext' => $txt['password_strength'],
309
			'size' => 20,
310
			'value' => '',
311
			'permission' => 'profile_password',
312
			'save_key' => 'passwd',
313
			// Note this will only work if passwrd2 also exists!
314
			'input_validate' => function(&$value) use ($sourcedir, $user_info, $smcFunc, $cur_profile)
315
			{
316
				// If we didn't try it then ignore it!
317
				if ($value == '')
318
					return false;
319
320
				// Do the two entries for the password even match?
321
				if (!isset($_POST['passwrd2']) || $value != $_POST['passwrd2'])
322
					return 'bad_new_password';
323
324
				// Let's get the validation function into play...
325
				require_once($sourcedir . '/Subs-Auth.php');
326
				$passwordErrors = validatePassword($value, $cur_profile['member_name'], array($cur_profile['real_name'], $user_info['username'], $user_info['name'], $user_info['email']));
327
328
				// Were there errors?
329
				if ($passwordErrors != null)
330
					return 'password_' . $passwordErrors;
331
332
				// Set up the new password variable... ready for storage.
333
				$value = hash_password($cur_profile['member_name'], un_htmlspecialchars($value));
334
335
				return true;
336
			},
337
		),
338
		'passwrd2' => array(
339
			'type' => 'password',
340
			'label' => $txt['verify_pass'],
341
			'size' => 20,
342
			'value' => '',
343
			'permission' => 'profile_password',
344
			'is_dummy' => true,
345
		),
346
		'personal_text' => array(
347
			'type' => 'text',
348
			'label' => $txt['personal_text'],
349
			'log_change' => true,
350
			'input_attr' => array('maxlength="50"'),
351
			'size' => 50,
352
			'permission' => 'profile_blurb',
353
			'input_validate' => function(&$value) use ($smcFunc)
354
			{
355
				if ($smcFunc['strlen']($value) > 50)
356
					return 'personal_text_too_long';
357
358
				return true;
359
			},
360
		),
361
		// This does ALL the pm settings
362
		'pm_prefs' => array(
363
			'type' => 'callback',
364
			'callback_func' => 'pm_settings',
365
			'permission' => 'pm_read',
366
			'preload' => function() use (&$context, $cur_profile)
367
			{
368
				$context['display_mode'] = $cur_profile['pm_prefs'] & 3;
369
				$context['receive_from'] = !empty($cur_profile['pm_receive_from']) ? $cur_profile['pm_receive_from'] : 0;
370
371
				return true;
372
			},
373
			'input_validate' => function(&$value) use (&$cur_profile, &$profile_vars)
374
			{
375
				// Simple validate and apply the two "sub settings"
376
				$value = max(min($value, 2), 0);
377
378
				$cur_profile['pm_receive_from'] = $profile_vars['pm_receive_from'] = max(min((int) $_POST['pm_receive_from'], 4), 0);
379
380
				return true;
381
			},
382
		),
383
		'posts' => array(
384
			'type' => 'int',
385
			'label' => $txt['profile_posts'],
386
			'log_change' => true,
387
			'size' => 7,
388
			'permission' => 'moderate_forum',
389
			'input_validate' => function(&$value)
390
			{
391
				if (!is_numeric($value))
392
					return 'digits_only';
393
				else
394
					$value = $value != '' ? strtr($value, array(',' => '', '.' => '', ' ' => '')) : 0;
395
				return true;
396
			},
397
		),
398
		'real_name' => array(
399
			'type' => allowedTo('profile_displayed_name_own') || allowedTo('profile_displayed_name_any') || allowedTo('moderate_forum') ? 'text' : 'label',
400
			'label' => $txt['name'],
401
			'subtext' => $txt['display_name_desc'],
402
			'log_change' => true,
403
			'input_attr' => array('maxlength="60"'),
404
			'permission' => 'profile_displayed_name',
405
			'enabled' => allowedTo('profile_displayed_name_own') || allowedTo('profile_displayed_name_any') || allowedTo('moderate_forum'),
406
			'input_validate' => function(&$value) use ($context, $smcFunc, $sourcedir, $cur_profile)
407
			{
408
				$value = trim(preg_replace('~[\t\n\r \x0B\0' . ($context['utf8'] ? '\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}' : '\x00-\x08\x0B\x0C\x0E-\x19\xA0') . ']+~' . ($context['utf8'] ? 'u' : ''), ' ', $value));
409
410
				if (trim($value) == '')
411
					return 'no_name';
412
				elseif ($smcFunc['strlen']($value) > 60)
413
					return 'name_too_long';
414
				elseif ($cur_profile['real_name'] != $value)
415
				{
416
					require_once($sourcedir . '/Subs-Members.php');
417
					if (isReservedName($value, $context['id_member']))
418
						return 'name_taken';
419
				}
420
				return true;
421
			},
422
		),
423
		'secret_question' => array(
424
			'type' => 'text',
425
			'label' => $txt['secret_question'],
426
			'subtext' => $txt['secret_desc'],
427
			'size' => 50,
428
			'permission' => 'profile_password',
429
		),
430
		'secret_answer' => array(
431
			'type' => 'text',
432
			'label' => $txt['secret_answer'],
433
			'subtext' => $txt['secret_desc2'],
434
			'size' => 20,
435
			'postinput' => '<span class="smalltext"><a href="' . $scripturl . '?action=helpadmin;help=secret_why_blank" onclick="return reqOverlayDiv(this.href);"><span class="main_icons help"></span> ' . $txt['secret_why_blank'] . '</a></span>',
436
			'value' => '',
437
			'permission' => 'profile_password',
438
			'input_validate' => function(&$value) use ($cur_profile)
439
			{
440
				$value = $value != '' ? hash_password($cur_profile['member_name'], $value) : '';
441
				return true;
442
			},
443
		),
444
		'signature' => array(
445
			'type' => 'callback',
446
			'callback_func' => 'signature_modify',
447
			'permission' => 'profile_signature',
448
			'enabled' => substr($modSettings['signature_settings'], 0, 1) == 1,
449
			'preload' => 'profileLoadSignatureData',
450
			'input_validate' => 'profileValidateSignature',
451
		),
452
		'show_online' => array(
453
			'type' => 'check',
454
			'label' => $txt['show_online'],
455
			'permission' => 'profile_identity',
456
			'enabled' => !empty($modSettings['allow_hideOnline']) || allowedTo('moderate_forum'),
457
		),
458
		'smiley_set' => array(
459
			'type' => 'callback',
460
			'callback_func' => 'smiley_pick',
461
			'enabled' => !empty($modSettings['smiley_sets_enable']),
462
			'permission' => 'profile_extra',
463
			'preload' => function() use ($modSettings, &$context, &$txt, $cur_profile, $smcFunc, $settings, $language)
464
			{
465
				$context['member']['smiley_set']['id'] = empty($cur_profile['smiley_set']) ? '' : $cur_profile['smiley_set'];
466
				$context['smiley_sets'] = explode(',', 'none,,' . $modSettings['smiley_sets_known']);
467
				$set_names = explode("\n", $txt['smileys_none'] . "\n" . $txt['smileys_forum_board_default'] . "\n" . $modSettings['smiley_sets_names']);
468
469
				$filenames = array();
470
				$result = $smcFunc['db_query']('', '
471
					SELECT f.filename, f.smiley_set
472
					FROM {db_prefix}smiley_files AS f
473
						JOIN {db_prefix}smileys AS s ON (s.id_smiley = f.id_smiley)
474
					WHERE s.code = {string:smiley}',
475
					array(
476
						'smiley' => ':)',
477
					)
478
				);
479
				while ($row = $smcFunc['db_fetch_assoc']($result))
480
					$filenames[$row['smiley_set']] = $row['filename'];
481
				$smcFunc['db_free_result']($result);
482
483
				// In case any sets don't contain a ':)' smiley
484
				$no_smiley_sets = array_diff(explode(',', $modSettings['smiley_sets_known']), array_keys($filenames));
485
				foreach ($no_smiley_sets as $set)
486
				{
487
					$allowedTypes = array('gif', 'png', 'jpg', 'jpeg', 'tiff', 'svg');
488
					$images = glob(implode('/', array($modSettings['smileys_dir'], $set, '*.{' . (implode(',', $allowedTypes) . '}'))), GLOB_BRACE);
489
490
					// Just use some image or other
491
					if (!empty($images))
492
					{
493
						$image = array_pop($images);
494
						$filenames[$set] = pathinfo($image, PATHINFO_BASENAME);
495
					}
496
					// No images at all? That's no good. Let the admin know, and quietly skip for this user.
497
					else
498
					{
499
						loadLanguage('Errors', $language);
500
						log_error(sprintf($txt['smiley_set_dir_not_found'], $set_names[array_search($set, $context['smiley_sets'])]));
501
502
						$context['smiley_sets'] = array_filter($context['smiley_sets'], function($v) use ($set)
503
							{
504
								return $v != $set;
505
							});
506
					}
507
				}
508
509
				foreach ($context['smiley_sets'] as $i => $set)
510
				{
511
					$context['smiley_sets'][$i] = array(
512
						'id' => $smcFunc['htmlspecialchars']($set),
513
						'name' => $smcFunc['htmlspecialchars']($set_names[$i]),
514
						'selected' => $set == $context['member']['smiley_set']['id']
515
					);
516
517
					if ($set === 'none')
518
						$context['smiley_sets'][$i]['preview'] = $settings['images_url'] . '/blank.png';
519
					elseif ($set === '')
520
					{
521
						$default_set = !empty($settings['smiley_sets_default']) ? $settings['smiley_sets_default'] : $modSettings['smiley_sets_default'];
522
						$context['smiley_sets'][$i]['preview'] = implode('/', array($modSettings['smileys_url'], $default_set, $filenames[$default_set]));
523
					}
524
					else
525
						$context['smiley_sets'][$i]['preview'] = implode('/', array($modSettings['smileys_url'], $set, $filenames[$set]));
526
527
					if ($context['smiley_sets'][$i]['selected'])
528
					{
529
						$context['member']['smiley_set']['name'] = $set_names[$i];
530
						$context['member']['smiley_set']['preview'] = $context['smiley_sets'][$i]['preview'];
531
					}
532
533
					$context['smiley_sets'][$i]['preview'] = $smcFunc['htmlspecialchars']($context['smiley_sets'][$i]['preview']);
534
				}
535
536
				return true;
537
			},
538
			'input_validate' => function(&$value)
539
			{
540
				global $modSettings;
541
542
				$smiley_sets = explode(',', $modSettings['smiley_sets_known']);
543
				if (!in_array($value, $smiley_sets) && $value != 'none')
544
					$value = '';
545
				return true;
546
			},
547
		),
548
		// Pretty much a dummy entry - it populates all the theme settings.
549
		'theme_settings' => array(
550
			'type' => 'callback',
551
			'callback_func' => 'theme_settings',
552
			'permission' => 'profile_extra',
553
			'is_dummy' => true,
554
			'preload' => function() use (&$context, $user_info, $modSettings)
555
			{
556
				loadLanguage('Settings');
557
558
				$context['allow_no_censored'] = false;
559
				if ($user_info['is_admin'] || $context['user']['is_owner'])
560
					$context['allow_no_censored'] = !empty($modSettings['allow_no_censored']);
561
562
				return true;
563
			},
564
		),
565
		'tfa' => array(
566
			'type' => 'callback',
567
			'callback_func' => 'tfa',
568
			'permission' => 'profile_password',
569
			'enabled' => !empty($modSettings['tfa_mode']),
570
			'preload' => function() use (&$context, $cur_profile)
571
			{
572
				$context['tfa_enabled'] = !empty($cur_profile['tfa_secret']);
573
574
				return true;
575
			},
576
		),
577
		'time_format' => array(
578
			'type' => 'callback',
579
			'callback_func' => 'timeformat_modify',
580
			'permission' => 'profile_extra',
581
			'preload' => function() use (&$context, $user_info, $txt, $cur_profile, $modSettings)
582
			{
583
				$context['easy_timeformats'] = array(
584
					array('format' => '', 'title' => $txt['timeformat_default']),
585
					array('format' => '%B %d, %Y, %I:%M:%S %p', 'title' => $txt['timeformat_easy1']),
586
					array('format' => '%B %d, %Y, %H:%M:%S', 'title' => $txt['timeformat_easy2']),
587
					array('format' => '%Y-%m-%d, %H:%M:%S', 'title' => $txt['timeformat_easy3']),
588
					array('format' => '%d %B %Y, %H:%M:%S', 'title' => $txt['timeformat_easy4']),
589
					array('format' => '%d-%m-%Y, %H:%M:%S', 'title' => $txt['timeformat_easy5'])
590
				);
591
592
				$context['member']['time_format'] = $cur_profile['time_format'];
593
				$context['current_forum_time'] = timeformat(time() - $user_info['time_offset'] * 3600, false);
594
				$context['current_forum_time_js'] = strftime('%Y,' . ((int) strftime('%m', time() + $modSettings['time_offset'] * 3600) - 1) . ',%d,%H,%M,%S', time() + $modSettings['time_offset'] * 3600);
595
				$context['current_forum_time_hour'] = (int) strftime('%H', forum_time(false));
596
				return true;
597
			},
598
		),
599
		'timezone' => array(
600
			'type' => 'select',
601
			'options' => smf_list_timezones(),
602
			'disabled_options' => array_filter(array_keys(smf_list_timezones()), 'is_int'),
603
			'permission' => 'profile_extra',
604
			'label' => $txt['timezone'],
605
			'value' => empty($cur_profile['timezone']) ? $modSettings['default_timezone'] : $cur_profile['timezone'],
606
			'input_validate' => function($value)
607
			{
608
				$tz = smf_list_timezones();
609
				if (!isset($tz[$value]))
610
					return 'bad_timezone';
611
612
				return true;
613
			},
614
		),
615
		'usertitle' => array(
616
			'type' => 'text',
617
			'label' => $txt['custom_title'],
618
			'log_change' => true,
619
			'input_attr' => array('maxlength="50"'),
620
			'size' => 50,
621
			'permission' => 'profile_title',
622
			'enabled' => !empty($modSettings['titlesEnable']),
623
			'input_validate' => function(&$value) use ($smcFunc)
624
			{
625
				if ($smcFunc['strlen']($value) > 50)
626
					return 'user_title_too_long';
627
628
				return true;
629
			},
630
		),
631
		'website_title' => array(
632
			'type' => 'text',
633
			'label' => $txt['website_title'],
634
			'subtext' => $txt['include_website_url'],
635
			'size' => 50,
636
			'permission' => 'profile_website',
637
			'link_with' => 'website',
638
		),
639
		'website_url' => array(
640
			'type' => 'url',
641
			'label' => $txt['website_url'],
642
			'subtext' => $txt['complete_url'],
643
			'size' => 50,
644
			'permission' => 'profile_website',
645
			// Fix the URL...
646
			'input_validate' => function(&$value)
647
			{
648
				if (strlen(trim($value)) > 0 && strpos($value, '://') === false)
649
					$value = 'http://' . $value;
650
				if (strlen($value) < 8 || (substr($value, 0, 7) !== 'http://' && substr($value, 0, 8) !== 'https://'))
651
					$value = '';
652
				$value = (string) validate_iri(sanitize_iri($value));
653
				return true;
654
			},
655
			'link_with' => 'website',
656
		),
657
	);
658
659
	call_integration_hook('integrate_load_profile_fields', array(&$profile_fields));
660
661
	$disabled_fields = !empty($modSettings['disabled_profile_fields']) ? explode(',', $modSettings['disabled_profile_fields']) : array();
662
	// For each of the above let's take out the bits which don't apply - to save memory and security!
663
	foreach ($profile_fields as $key => $field)
664
	{
665
		// Do we have permission to do this?
666
		if (isset($field['permission']) && !allowedTo(($context['user']['is_owner'] ? array($field['permission'] . '_own', $field['permission'] . '_any') : $field['permission'] . '_any')) && !allowedTo($field['permission']))
667
			unset($profile_fields[$key]);
668
669
		// Is it enabled?
670
		if (isset($field['enabled']) && !$field['enabled'])
671
			unset($profile_fields[$key]);
672
673
		// Is it specifically disabled?
674
		if (in_array($key, $disabled_fields) || (isset($field['link_with']) && in_array($field['link_with'], $disabled_fields)))
675
			unset($profile_fields[$key]);
676
	}
677
}
678
679
/**
680
 * Setup the context for a page load!
681
 *
682
 * @param array $fields The profile fields to display. Each item should correspond to an item in the $profile_fields array generated by loadProfileFields
683
 */
684
function setupProfileContext($fields)
685
{
686
	global $profile_fields, $context, $cur_profile, $txt;
687
688
	// Some default bits.
689
	$context['profile_prehtml'] = '';
690
	$context['profile_posthtml'] = '';
691
	$context['profile_javascript'] = '';
692
	$context['profile_onsubmit_javascript'] = '';
693
694
	call_integration_hook('integrate_setup_profile_context', array(&$fields));
695
696
	// Make sure we have this!
697
	loadProfileFields(true);
698
699
	// First check for any linked sets.
700
	foreach ($profile_fields as $key => $field)
701
		if (isset($field['link_with']) && in_array($field['link_with'], $fields))
702
			$fields[] = $key;
703
704
	$i = 0;
705
	$last_type = '';
706
	foreach ($fields as $key => $field)
707
	{
708
		if (isset($profile_fields[$field]))
709
		{
710
			// Shortcut.
711
			$cur_field = &$profile_fields[$field];
712
713
			// Does it have a preload and does that preload succeed?
714
			if (isset($cur_field['preload']) && !$cur_field['preload']())
715
				continue;
716
717
			// If this is anything but complex we need to do more cleaning!
718
			if ($cur_field['type'] != 'callback' && $cur_field['type'] != 'hidden')
719
			{
720
				if (!isset($cur_field['label']))
721
					$cur_field['label'] = isset($txt[$field]) ? $txt[$field] : $field;
722
723
				// Everything has a value!
724
				if (!isset($cur_field['value']))
725
					$cur_field['value'] = isset($cur_profile[$field]) ? $cur_profile[$field] : '';
726
727
				// Any input attributes?
728
				$cur_field['input_attr'] = !empty($cur_field['input_attr']) ? implode(',', $cur_field['input_attr']) : '';
729
			}
730
731
			// Was there an error with this field on posting?
732
			if (isset($context['profile_errors'][$field]))
733
				$cur_field['is_error'] = true;
734
735
			// Any javascript stuff?
736
			if (!empty($cur_field['js_submit']))
737
				$context['profile_onsubmit_javascript'] .= $cur_field['js_submit'];
738
			if (!empty($cur_field['js']))
739
				$context['profile_javascript'] .= $cur_field['js'];
740
741
			// Any template stuff?
742
			if (!empty($cur_field['prehtml']))
743
				$context['profile_prehtml'] .= $cur_field['prehtml'];
744
			if (!empty($cur_field['posthtml']))
745
				$context['profile_posthtml'] .= $cur_field['posthtml'];
746
747
			// Finally put it into context?
748
			if ($cur_field['type'] != 'hidden')
749
			{
750
				$last_type = $cur_field['type'];
751
				$context['profile_fields'][$field] = &$profile_fields[$field];
752
			}
753
		}
754
		// Bodge in a line break - without doing two in a row ;)
755
		elseif ($field == 'hr' && $last_type != 'hr' && $last_type != '')
756
		{
757
			$last_type = 'hr';
758
			$context['profile_fields'][$i++]['type'] = 'hr';
759
		}
760
	}
761
762
	// Some spicy JS.
763
	addInlineJavaScript('
764
	var form_handle = document.forms.creator;
765
	createEventListener(form_handle);
766
	' . (!empty($context['require_password']) ? '
767
	form_handle.addEventListener(\'submit\', function(event)
768
	{
769
		if (this.oldpasswrd.value == "")
770
		{
771
			event.preventDefault();
772
			alert(' . (JavaScriptEscape($txt['required_security_reasons'])) . ');
773
			return false;
774
		}
775
	}, false);' : ''), true);
776
777
	// Any onsubmit javascript?
778
	if (!empty($context['profile_onsubmit_javascript']))
779
		addInlineJavaScript($context['profile_onsubmit_javascript'], true);
780
781
	// Any totally custom stuff?
782
	if (!empty($context['profile_javascript']))
783
		addInlineJavaScript($context['profile_javascript'], true);
784
785
	// Free up some memory.
786
	unset($profile_fields);
787
}
788
789
/**
790
 * Save the profile changes.
791
 */
792
function saveProfileFields()
793
{
794
	global $profile_fields, $profile_vars, $context, $old_profile, $post_errors, $cur_profile;
795
796
	// Load them up.
797
	loadProfileFields();
798
799
	// This makes things easier...
800
	$old_profile = $cur_profile;
801
802
	// This allows variables to call activities when they save - by default just to reload their settings
803
	$context['profile_execute_on_save'] = array();
804
	if ($context['user']['is_owner'])
805
		$context['profile_execute_on_save']['reload_user'] = 'profileReloadUser';
806
807
	// Assume we log nothing.
808
	$context['log_changes'] = array();
809
810
	// Cycle through the profile fields working out what to do!
811
	foreach ($profile_fields as $key => $field)
812
	{
813
		if (!isset($_POST[$key]) || !empty($field['is_dummy']) || (isset($_POST['preview_signature']) && $key == 'signature'))
814
			continue;
815
816
		// What gets updated?
817
		$db_key = isset($field['save_key']) ? $field['save_key'] : $key;
818
819
		// Right - we have something that is enabled, we can act upon and has a value posted to it. Does it have a validation function?
820
		if (isset($field['input_validate']))
821
		{
822
			$is_valid = $field['input_validate']($_POST[$key]);
823
			// An error occurred - set it as such!
824
			if ($is_valid !== true)
825
			{
826
				// Is this an actual error?
827
				if ($is_valid !== false)
828
				{
829
					$post_errors[$key] = $is_valid;
830
					$profile_fields[$key]['is_error'] = $is_valid;
831
				}
832
				// Retain the old value.
833
				$cur_profile[$key] = $_POST[$key];
834
				continue;
835
			}
836
		}
837
838
		// Are we doing a cast?
839
		$field['cast_type'] = empty($field['cast_type']) ? $field['type'] : $field['cast_type'];
840
841
		// Finally, clean up certain types.
842
		if ($field['cast_type'] == 'int')
843
			$_POST[$key] = (int) $_POST[$key];
844
		elseif ($field['cast_type'] == 'float')
845
			$_POST[$key] = (float) $_POST[$key];
846
		elseif ($field['cast_type'] == 'check')
847
			$_POST[$key] = !empty($_POST[$key]) ? 1 : 0;
848
849
		// If we got here we're doing OK.
850
		if ($field['type'] != 'hidden' && (!isset($old_profile[$key]) || $_POST[$key] != $old_profile[$key]))
851
		{
852
			// Set the save variable.
853
			$profile_vars[$db_key] = $_POST[$key];
854
			// And update the user profile.
855
			$cur_profile[$key] = $_POST[$key];
856
857
			// Are we logging it?
858
			if (!empty($field['log_change']) && isset($old_profile[$key]))
859
				$context['log_changes'][$key] = array(
860
					'previous' => $old_profile[$key],
861
					'new' => $_POST[$key],
862
				);
863
		}
864
865
		// Logging group changes are a bit different...
866
		if ($key == 'id_group' && $field['log_change'])
867
		{
868
			profileLoadGroups();
869
870
			// Any changes to primary group?
871
			if ($_POST['id_group'] != $old_profile['id_group'])
872
			{
873
				$context['log_changes']['id_group'] = array(
874
					'previous' => !empty($old_profile[$key]) && isset($context['member_groups'][$old_profile[$key]]) ? $context['member_groups'][$old_profile[$key]]['name'] : '',
875
					'new' => !empty($_POST[$key]) && isset($context['member_groups'][$_POST[$key]]) ? $context['member_groups'][$_POST[$key]]['name'] : '',
876
				);
877
			}
878
879
			// Prepare additional groups for comparison.
880
			$additional_groups = array(
881
				'previous' => !empty($old_profile['additional_groups']) ? explode(',', $old_profile['additional_groups']) : array(),
882
				'new' => !empty($_POST['additional_groups']) ? array_diff($_POST['additional_groups'], array(0)) : array(),
883
			);
884
885
			sort($additional_groups['previous']);
886
			sort($additional_groups['new']);
887
888
			// What about additional groups?
889
			if ($additional_groups['previous'] != $additional_groups['new'])
890
			{
891
				foreach ($additional_groups as $type => $groups)
892
				{
893
					foreach ($groups as $id => $group)
894
					{
895
						if (isset($context['member_groups'][$group]))
896
							$additional_groups[$type][$id] = $context['member_groups'][$group]['name'];
897
						else
898
							unset($additional_groups[$type][$id]);
899
					}
900
					$additional_groups[$type] = implode(', ', $additional_groups[$type]);
901
				}
902
903
				$context['log_changes']['additional_groups'] = $additional_groups;
904
			}
905
		}
906
	}
907
908
	// @todo Temporary
909
	if ($context['user']['is_owner'])
910
		$changeOther = allowedTo(array('profile_extra_any', 'profile_extra_own'));
911
	else
912
		$changeOther = allowedTo('profile_extra_any');
913
	if ($changeOther && empty($post_errors))
914
	{
915
		makeThemeChanges($context['id_member'], isset($_POST['id_theme']) ? (int) $_POST['id_theme'] : $old_profile['id_theme']);
916
		if (!empty($_REQUEST['sa']))
917
		{
918
			$custom_fields_errors = makeCustomFieldChanges($context['id_member'], $_REQUEST['sa'], false, true);
919
920
			if (!empty($custom_fields_errors))
921
				$post_errors = array_merge($post_errors, $custom_fields_errors);
922
		}
923
	}
924
925
	// Free memory!
926
	unset($profile_fields);
927
}
928
929
/**
930
 * Save the profile changes
931
 *
932
 * @param array &$profile_vars The items to save
933
 * @param array &$post_errors An array of information about any errors that occurred
934
 * @param int $memID The ID of the member whose profile we're saving
935
 */
936
function saveProfileChanges(&$profile_vars, &$post_errors, $memID)
937
{
938
	global $user_profile, $context;
939
940
	// These make life easier....
941
	$old_profile = &$user_profile[$memID];
942
943
	// Permissions...
944
	if ($context['user']['is_owner'])
945
	{
946
		$changeOther = allowedTo(array('profile_extra_any', 'profile_extra_own', 'profile_website_any', 'profile_website_own', 'profile_signature_any', 'profile_signature_own'));
947
	}
948
	else
949
		$changeOther = allowedTo(array('profile_extra_any', 'profile_website_any', 'profile_signature_any'));
950
951
	// Arrays of all the changes - makes things easier.
952
	$profile_bools = array();
953
	$profile_ints = array();
954
	$profile_floats = array();
955
	$profile_strings = array(
956
		'buddy_list',
957
		'ignore_boards',
958
	);
959
960
	if (isset($_POST['sa']) && $_POST['sa'] == 'ignoreboards' && empty($_POST['ignore_brd']))
961
		$_POST['ignore_brd'] = array();
962
963
	unset($_POST['ignore_boards']); // Whatever it is set to is a dirty filthy thing.  Kinda like our minds.
964
	if (isset($_POST['ignore_brd']))
965
	{
966
		if (!is_array($_POST['ignore_brd']))
967
			$_POST['ignore_brd'] = array($_POST['ignore_brd']);
968
969
		foreach ($_POST['ignore_brd'] as $k => $d)
970
		{
971
			$d = (int) $d;
972
			if ($d != 0)
973
				$_POST['ignore_brd'][$k] = $d;
974
			else
975
				unset($_POST['ignore_brd'][$k]);
976
		}
977
		$_POST['ignore_boards'] = implode(',', $_POST['ignore_brd']);
978
		unset($_POST['ignore_brd']);
979
	}
980
981
	// Here's where we sort out all the 'other' values...
982
	if ($changeOther)
983
	{
984
		makeThemeChanges($memID, isset($_POST['id_theme']) ? (int) $_POST['id_theme'] : $old_profile['id_theme']);
985
		//makeAvatarChanges($memID, $post_errors);
986
987
		if (!empty($_REQUEST['sa']))
988
			makeCustomFieldChanges($memID, $_REQUEST['sa'], false);
989
990
		foreach ($profile_bools as $var)
991
			if (isset($_POST[$var]))
992
				$profile_vars[$var] = empty($_POST[$var]) ? '0' : '1';
993
		foreach ($profile_ints as $var)
994
			if (isset($_POST[$var]))
995
				$profile_vars[$var] = $_POST[$var] != '' ? (int) $_POST[$var] : '';
996
		foreach ($profile_floats as $var)
997
			if (isset($_POST[$var]))
998
				$profile_vars[$var] = (float) $_POST[$var];
999
		foreach ($profile_strings as $var)
1000
			if (isset($_POST[$var]))
1001
				$profile_vars[$var] = $_POST[$var];
1002
	}
1003
}
1004
1005
/**
1006
 * Make any theme changes that are sent with the profile.
1007
 *
1008
 * @param int $memID The ID of the user
1009
 * @param int $id_theme The ID of the theme
1010
 */
1011
function makeThemeChanges($memID, $id_theme)
1012
{
1013
	global $modSettings, $smcFunc, $context, $user_info;
1014
1015
	$reservedVars = array(
1016
		'actual_theme_url',
1017
		'actual_images_url',
1018
		'base_theme_dir',
1019
		'base_theme_url',
1020
		'default_images_url',
1021
		'default_theme_dir',
1022
		'default_theme_url',
1023
		'default_template',
1024
		'images_url',
1025
		'number_recent_posts',
1026
		'smiley_sets_default',
1027
		'theme_dir',
1028
		'theme_id',
1029
		'theme_layers',
1030
		'theme_templates',
1031
		'theme_url',
1032
	);
1033
1034
	// Can't change reserved vars.
1035
	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))
1036
		fatal_lang_error('no_access', false);
1037
1038
	// Don't allow any overriding of custom fields with default or non-default options.
1039
	$request = $smcFunc['db_query']('', '
1040
		SELECT col_name
1041
		FROM {db_prefix}custom_fields
1042
		WHERE active = {int:is_active}',
1043
		array(
1044
			'is_active' => 1,
1045
		)
1046
	);
1047
	$custom_fields = array();
1048
	while ($row = $smcFunc['db_fetch_assoc']($request))
1049
		$custom_fields[] = $row['col_name'];
1050
	$smcFunc['db_free_result']($request);
1051
1052
	// These are the theme changes...
1053
	$themeSetArray = array();
1054
	if (isset($_POST['options']) && is_array($_POST['options']))
1055
	{
1056
		foreach ($_POST['options'] as $opt => $val)
1057
		{
1058
			if (in_array($opt, $custom_fields))
1059
				continue;
1060
1061
			// These need to be controlled.
1062
			if ($opt == 'topics_per_page' || $opt == 'messages_per_page')
1063
				$val = max(0, min($val, 50));
1064
			// We don't set this per theme anymore.
1065
			elseif ($opt == 'allow_no_censored')
1066
				continue;
1067
1068
			$themeSetArray[] = array($memID, $id_theme, $opt, is_array($val) ? implode(',', $val) : $val);
1069
		}
1070
	}
1071
1072
	$erase_options = array();
1073
	if (isset($_POST['default_options']) && is_array($_POST['default_options']))
1074
		foreach ($_POST['default_options'] as $opt => $val)
1075
		{
1076
			if (in_array($opt, $custom_fields))
1077
				continue;
1078
1079
			// These need to be controlled.
1080
			if ($opt == 'topics_per_page' || $opt == 'messages_per_page')
1081
				$val = max(0, min($val, 50));
1082
			// Only let admins and owners change the censor.
1083
			elseif ($opt == 'allow_no_censored' && !$user_info['is_admin'] && !$context['user']['is_owner'])
1084
				continue;
1085
1086
			$themeSetArray[] = array($memID, 1, $opt, is_array($val) ? implode(',', $val) : $val);
1087
			$erase_options[] = $opt;
1088
		}
1089
1090
	// If themeSetArray isn't still empty, send it to the database.
1091
	if (empty($context['password_auth_failed']))
1092
	{
1093
		if (!empty($themeSetArray))
1094
		{
1095
			$smcFunc['db_insert']('replace',
1096
				'{db_prefix}themes',
1097
				array('id_member' => 'int', 'id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
1098
				$themeSetArray,
1099
				array('id_member', 'id_theme', 'variable')
1100
			);
1101
		}
1102
1103
		if (!empty($erase_options))
1104
		{
1105
			$smcFunc['db_query']('', '
1106
				DELETE FROM {db_prefix}themes
1107
				WHERE id_theme != {int:id_theme}
1108
					AND variable IN ({array_string:erase_variables})
1109
					AND id_member = {int:id_member}',
1110
				array(
1111
					'id_theme' => 1,
1112
					'id_member' => $memID,
1113
					'erase_variables' => $erase_options
1114
				)
1115
			);
1116
		}
1117
1118
		// Admins can choose any theme, even if it's not enabled...
1119
		$themes = allowedTo('admin_forum') ? explode(',', $modSettings['knownThemes']) : explode(',', $modSettings['enableThemes']);
1120
		foreach ($themes as $t)
1121
			cache_put_data('theme_settings-' . $t . ':' . $memID, null, 60);
1122
	}
1123
}
1124
1125
/**
1126
 * Make any notification changes that need to be made.
1127
 *
1128
 * @param int $memID The ID of the member
1129
 */
1130
function makeNotificationChanges($memID)
1131
{
1132
	global $smcFunc, $sourcedir;
1133
1134
	require_once($sourcedir . '/Subs-Notify.php');
1135
1136
	// Update the boards they are being notified on.
1137
	if (isset($_POST['edit_notify_boards']) && !empty($_POST['notify_boards']))
1138
	{
1139
		// Make sure only integers are deleted.
1140
		foreach ($_POST['notify_boards'] as $index => $id)
1141
			$_POST['notify_boards'][$index] = (int) $id;
1142
1143
		// id_board = 0 is reserved for topic notifications.
1144
		$_POST['notify_boards'] = array_diff($_POST['notify_boards'], array(0));
1145
1146
		$smcFunc['db_query']('', '
1147
			DELETE FROM {db_prefix}log_notify
1148
			WHERE id_board IN ({array_int:board_list})
1149
				AND id_member = {int:selected_member}',
1150
			array(
1151
				'board_list' => $_POST['notify_boards'],
1152
				'selected_member' => $memID,
1153
			)
1154
		);
1155
	}
1156
1157
	// We are editing topic notifications......
1158
	elseif (isset($_POST['edit_notify_topics']) && !empty($_POST['notify_topics']))
1159
	{
1160
		foreach ($_POST['notify_topics'] as $index => $id)
1161
			$_POST['notify_topics'][$index] = (int) $id;
1162
1163
		// Make sure there are no zeros left.
1164
		$_POST['notify_topics'] = array_diff($_POST['notify_topics'], array(0));
1165
1166
		$smcFunc['db_query']('', '
1167
			DELETE FROM {db_prefix}log_notify
1168
			WHERE id_topic IN ({array_int:topic_list})
1169
				AND id_member = {int:selected_member}',
1170
			array(
1171
				'topic_list' => $_POST['notify_topics'],
1172
				'selected_member' => $memID,
1173
			)
1174
		);
1175
		foreach ($_POST['notify_topics'] as $topic)
1176
			setNotifyPrefs($memID, array('topic_notify_' . $topic => 0));
1177
	}
1178
1179
	// We are removing topic preferences
1180
	elseif (isset($_POST['remove_notify_topics']) && !empty($_POST['notify_topics']))
1181
	{
1182
		$prefs = array();
1183
		foreach ($_POST['notify_topics'] as $topic)
1184
			$prefs[] = 'topic_notify_' . $topic;
1185
		deleteNotifyPrefs($memID, $prefs);
1186
	}
1187
1188
	// We are removing board preferences
1189
	elseif (isset($_POST['remove_notify_board']) && !empty($_POST['notify_boards']))
1190
	{
1191
		$prefs = array();
1192
		foreach ($_POST['notify_boards'] as $board)
1193
			$prefs[] = 'board_notify_' . $board;
1194
		deleteNotifyPrefs($memID, $prefs);
1195
	}
1196
}
1197
1198
/**
1199
 * Save any changes to the custom profile fields
1200
 *
1201
 * @param int $memID The ID of the member
1202
 * @param string $area The area of the profile these fields are in
1203
 * @param bool $sanitize = true Whether or not to sanitize the data
1204
 * @param bool $returnErrors Whether or not to return any error information
1205
 * @return void|array Returns nothing or returns an array of error info if $returnErrors is true
1206
 */
1207
function makeCustomFieldChanges($memID, $area, $sanitize = true, $returnErrors = false)
1208
{
1209
	global $context, $smcFunc, $user_profile, $user_info, $modSettings;
1210
	global $sourcedir;
1211
1212
	$errors = array();
1213
1214
	if ($sanitize && isset($_POST['customfield']))
1215
		$_POST['customfield'] = htmlspecialchars__recursive($_POST['customfield']);
1216
1217
	$where = $area == 'register' ? 'show_reg != 0' : 'show_profile = {string:area}';
1218
1219
	// Load the fields we are saving too - make sure we save valid data (etc).
1220
	$request = $smcFunc['db_query']('', '
1221
		SELECT col_name, field_name, field_desc, field_type, field_length, field_options, default_value, show_reg, mask, private
1222
		FROM {db_prefix}custom_fields
1223
		WHERE ' . $where . '
1224
			AND active = {int:is_active}',
1225
		array(
1226
			'is_active' => 1,
1227
			'area' => $area,
1228
		)
1229
	);
1230
	$changes = array();
1231
	$deletes = array();
1232
	$log_changes = array();
1233
	while ($row = $smcFunc['db_fetch_assoc']($request))
1234
	{
1235
		/* This means don't save if:
1236
			- The user is NOT an admin.
1237
			- The data is not freely viewable and editable by users.
1238
			- The data is not invisible to users but editable by the owner (or if it is the user is not the owner)
1239
			- The area isn't registration, and if it is that the field is not supposed to be shown there.
1240
		*/
1241
		if ($row['private'] != 0 && !allowedTo('admin_forum') && ($memID != $user_info['id'] || $row['private'] != 2) && ($area != 'register' || $row['show_reg'] == 0))
1242
			continue;
1243
1244
		// Validate the user data.
1245
		if ($row['field_type'] == 'check')
1246
			$value = isset($_POST['customfield'][$row['col_name']]) ? 1 : 0;
1247
		elseif ($row['field_type'] == 'select' || $row['field_type'] == 'radio')
1248
		{
1249
			$value = $row['default_value'];
1250
			foreach (explode(',', $row['field_options']) as $k => $v)
1251
				if (isset($_POST['customfield'][$row['col_name']]) && $_POST['customfield'][$row['col_name']] == $k)
1252
					$value = $v;
1253
		}
1254
		// Otherwise some form of text!
1255
		else
1256
		{
1257
			$value = isset($_POST['customfield'][$row['col_name']]) ? $_POST['customfield'][$row['col_name']] : '';
1258
1259
			if ($row['field_length'])
1260
				$value = $smcFunc['substr']($value, 0, $row['field_length']);
1261
1262
			// Any masks?
1263
			if ($row['field_type'] == 'text' && !empty($row['mask']) && $row['mask'] != 'none')
1264
			{
1265
				$value = $smcFunc['htmltrim']($value);
1266
				$valueReference = un_htmlspecialchars($value);
1267
1268
				// Try and avoid some checks. '0' could be a valid non-empty value.
1269
				if (empty($value) && !is_numeric($value))
1270
					$value = '';
1271
1272
				if ($row['mask'] == 'nohtml' && ($valueReference != strip_tags($valueReference) || $value != filter_var($value, FILTER_SANITIZE_STRING) || preg_match('/<(.+?)[\s]*\/?[\s]*>/si', $valueReference)))
1273
				{
1274
					if ($returnErrors)
1275
						$errors[] = 'custom_field_nohtml_fail';
1276
1277
					else
1278
						$value = '';
1279
				}
1280
				elseif ($row['mask'] == 'email' && !empty($value) && (!filter_var($value, FILTER_VALIDATE_EMAIL) || strlen($value) > 255))
1281
				{
1282
					if ($returnErrors)
1283
						$errors[] = 'custom_field_mail_fail';
1284
1285
					else
1286
						$value = '';
1287
				}
1288
				elseif ($row['mask'] == 'number')
1289
				{
1290
					$value = (int) $value;
1291
				}
1292
				elseif (substr($row['mask'], 0, 5) == 'regex' && trim($value) != '' && preg_match(substr($row['mask'], 5), $value) === 0)
1293
				{
1294
					if ($returnErrors)
1295
						$errors[] = 'custom_field_regex_fail';
1296
1297
					else
1298
						$value = '';
1299
				}
1300
1301
				unset($valueReference);
1302
			}
1303
		}
1304
1305
		if (!isset($user_profile[$memID]['options'][$row['col_name']]))
1306
			$user_profile[$memID]['options'][$row['col_name']] = '';
1307
1308
		// Did it change?
1309
		if ($user_profile[$memID]['options'][$row['col_name']] != $value)
1310
		{
1311
			$log_changes[] = array(
1312
				'action' => 'customfield_' . $row['col_name'],
1313
				'log_type' => 'user',
1314
				'extra' => array(
1315
					'previous' => !empty($user_profile[$memID]['options'][$row['col_name']]) ? $user_profile[$memID]['options'][$row['col_name']] : '',
1316
					'new' => $value,
1317
					'applicator' => $user_info['id'],
1318
					'member_affected' => $memID,
1319
				),
1320
			);
1321
			if (empty($value))
1322
			{
1323
				$deletes[] = array('id_theme' => 1, 'variable' => $row['col_name'], 'id_member' => $memID);
1324
				unset($user_profile[$memID]['options'][$row['col_name']]);
1325
			}
1326
			else
1327
			{
1328
				$changes[] = array(1, $row['col_name'], $value, $memID);
1329
				$user_profile[$memID]['options'][$row['col_name']] = $value;
1330
			}
1331
		}
1332
	}
1333
	$smcFunc['db_free_result']($request);
1334
1335
	$hook_errors = call_integration_hook('integrate_save_custom_profile_fields', array(&$changes, &$log_changes, &$errors, $returnErrors, $memID, $area, $sanitize, &$deletes));
1336
1337
	if (!empty($hook_errors) && is_array($hook_errors))
1338
		$errors = array_merge($errors, $hook_errors);
1339
1340
	// Make those changes!
1341
	if ((!empty($changes) || !empty($deletes)) && empty($context['password_auth_failed']) && empty($errors))
1342
	{
1343
		if (!empty($changes))
1344
			$smcFunc['db_insert']('replace',
1345
				'{db_prefix}themes',
1346
				array('id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534', 'id_member' => 'int'),
1347
				$changes,
1348
				array('id_theme', 'variable', 'id_member')
1349
			);
1350
		if (!empty($deletes))
1351
			foreach ($deletes as $delete)
1352
				$smcFunc['db_query']('', '
1353
					DELETE FROM {db_prefix}themes
1354
					WHERE id_theme = {int:id_theme}
1355
						AND variable = {string:variable}
1356
						AND id_member = {int:id_member}',
1357
					$delete
1358
				);
1359
		if (!empty($log_changes) && !empty($modSettings['modlog_enabled']))
1360
		{
1361
			require_once($sourcedir . '/Logging.php');
1362
			logActions($log_changes);
1363
		}
1364
	}
1365
1366
	if ($returnErrors)
1367
		return $errors;
1368
}
1369
1370
/**
1371
 * Show all the users buddies, as well as a add/delete interface.
1372
 *
1373
 * @param int $memID The ID of the member
1374
 */
1375
function editBuddyIgnoreLists($memID)
1376
{
1377
	global $context, $txt, $modSettings;
1378
1379
	// Do a quick check to ensure people aren't getting here illegally!
1380
	if (!$context['user']['is_owner'] || empty($modSettings['enable_buddylist']))
1381
		fatal_lang_error('no_access', false);
1382
1383
	// Can we email the user direct?
1384
	$context['can_moderate_forum'] = allowedTo('moderate_forum');
1385
	$context['can_send_email'] = allowedTo('moderate_forum');
1386
1387
	$subActions = array(
1388
		'buddies' => array('editBuddies', $txt['editBuddies']),
1389
		'ignore' => array('editIgnoreList', $txt['editIgnoreList']),
1390
	);
1391
1392
	$context['list_area'] = isset($_GET['sa']) && isset($subActions[$_GET['sa']]) ? $_GET['sa'] : 'buddies';
1393
1394
	// Create the tabs for the template.
1395
	$context[$context['profile_menu_name']]['tab_data'] = array(
1396
		'title' => $txt['editBuddyIgnoreLists'],
1397
		'description' => $txt['buddy_ignore_desc'],
1398
		'icon' => 'profile_hd.png',
1399
		'tabs' => array(
1400
			'buddies' => array(),
1401
			'ignore' => array(),
1402
		),
1403
	);
1404
1405
	loadJavaScriptFile('suggest.js', array('defer' => false, 'minimize' => true), 'smf_suggest');
1406
1407
	// Pass on to the actual function.
1408
	$context['sub_template'] = $subActions[$context['list_area']][0];
1409
	$call = call_helper($subActions[$context['list_area']][0], true);
1410
1411
	if (!empty($call))
1412
		call_user_func($call, $memID);
1413
}
1414
1415
/**
1416
 * Show all the users buddies, as well as a add/delete interface.
1417
 *
1418
 * @param int $memID The ID of the member
1419
 */
1420
function editBuddies($memID)
1421
{
1422
	global $txt, $scripturl, $settings, $modSettings;
1423
	global $context, $user_profile, $memberContext, $smcFunc;
1424
1425
	// For making changes!
1426
	$buddiesArray = explode(',', $user_profile[$memID]['buddy_list']);
1427
	foreach ($buddiesArray as $k => $dummy)
1428
		if ($dummy == '')
1429
			unset($buddiesArray[$k]);
1430
1431
	// Removing a buddy?
1432
	if (isset($_GET['remove']))
1433
	{
1434
		checkSession('get');
1435
1436
		call_integration_hook('integrate_remove_buddy', array($memID));
1437
1438
		$_SESSION['prf-save'] = $txt['could_not_remove_person'];
1439
1440
		// Heh, I'm lazy, do it the easy way...
1441
		foreach ($buddiesArray as $key => $buddy)
1442
			if ($buddy == (int) $_GET['remove'])
1443
			{
1444
				unset($buddiesArray[$key]);
1445
				$_SESSION['prf-save'] = true;
1446
			}
1447
1448
		// Make the changes.
1449
		$user_profile[$memID]['buddy_list'] = implode(',', $buddiesArray);
1450
		updateMemberData($memID, array('buddy_list' => $user_profile[$memID]['buddy_list']));
1451
1452
		// Redirect off the page because we don't like all this ugly query stuff to stick in the history.
1453
		redirectexit('action=profile;area=lists;sa=buddies;u=' . $memID);
1454
	}
1455
	elseif (isset($_POST['new_buddy']))
1456
	{
1457
		checkSession();
1458
1459
		// Prepare the string for extraction...
1460
		$_POST['new_buddy'] = strtr($smcFunc['htmlspecialchars']($_POST['new_buddy'], ENT_QUOTES), array('&quot;' => '"'));
1461
		preg_match_all('~"([^"]+)"~', $_POST['new_buddy'], $matches);
1462
		$new_buddies = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $_POST['new_buddy']))));
1463
1464
		foreach ($new_buddies as $k => $dummy)
1465
		{
1466
			$new_buddies[$k] = strtr(trim($new_buddies[$k]), array('\'' => '&#039;'));
1467
1468
			if (strlen($new_buddies[$k]) == 0 || in_array($new_buddies[$k], array($user_profile[$memID]['member_name'], $user_profile[$memID]['real_name'])))
1469
				unset($new_buddies[$k]);
1470
		}
1471
1472
		call_integration_hook('integrate_add_buddies', array($memID, &$new_buddies));
1473
1474
		$_SESSION['prf-save'] = $txt['could_not_add_person'];
1475
		if (!empty($new_buddies))
1476
		{
1477
			// Now find out the id_member of the buddy.
1478
			$request = $smcFunc['db_query']('', '
1479
				SELECT id_member
1480
				FROM {db_prefix}members
1481
				WHERE member_name IN ({array_string:new_buddies}) OR real_name IN ({array_string:new_buddies})
1482
				LIMIT {int:count_new_buddies}',
1483
				array(
1484
					'new_buddies' => $new_buddies,
1485
					'count_new_buddies' => count($new_buddies),
1486
				)
1487
			);
1488
1489
			if ($smcFunc['db_num_rows']($request) != 0)
1490
				$_SESSION['prf-save'] = true;
1491
1492
			// Add the new member to the buddies array.
1493
			while ($row = $smcFunc['db_fetch_assoc']($request))
1494
			{
1495
				if (in_array($row['id_member'], $buddiesArray))
1496
					continue;
1497
				else
1498
					$buddiesArray[] = (int) $row['id_member'];
1499
			}
1500
			$smcFunc['db_free_result']($request);
1501
1502
			// Now update the current users buddy list.
1503
			$user_profile[$memID]['buddy_list'] = implode(',', $buddiesArray);
1504
			updateMemberData($memID, array('buddy_list' => $user_profile[$memID]['buddy_list']));
1505
		}
1506
1507
		// Back to the buddy list!
1508
		redirectexit('action=profile;area=lists;sa=buddies;u=' . $memID);
1509
	}
1510
1511
	// Get all the users "buddies"...
1512
	$buddies = array();
1513
1514
	// Gotta load the custom profile fields names.
1515
	$request = $smcFunc['db_query']('', '
1516
		SELECT col_name, field_name, field_desc, field_type, bbc, enclose
1517
		FROM {db_prefix}custom_fields
1518
		WHERE active = {int:active}
1519
			AND private < {int:private_level}',
1520
		array(
1521
			'active' => 1,
1522
			'private_level' => 2,
1523
		)
1524
	);
1525
1526
	$context['custom_pf'] = array();
1527
	$disabled_fields = isset($modSettings['disabled_profile_fields']) ? array_flip(explode(',', $modSettings['disabled_profile_fields'])) : array();
1528
	while ($row = $smcFunc['db_fetch_assoc']($request))
1529
		if (!isset($disabled_fields[$row['col_name']]))
1530
			$context['custom_pf'][$row['col_name']] = array(
1531
				'label' => $row['field_name'],
1532
				'type' => $row['field_type'],
1533
				'bbc' => !empty($row['bbc']),
1534
				'enclose' => $row['enclose'],
1535
			);
1536
1537
	// Gotta disable the gender option.
1538
	if (isset($context['custom_pf']['cust_gender']) && $context['custom_pf']['cust_gender'] == 'None')
1539
		unset($context['custom_pf']['cust_gender']);
1540
1541
	$smcFunc['db_free_result']($request);
1542
1543
	if (!empty($buddiesArray))
1544
	{
1545
		$result = $smcFunc['db_query']('', '
1546
			SELECT id_member
1547
			FROM {db_prefix}members
1548
			WHERE id_member IN ({array_int:buddy_list})
1549
			ORDER BY real_name
1550
			LIMIT {int:buddy_list_count}',
1551
			array(
1552
				'buddy_list' => $buddiesArray,
1553
				'buddy_list_count' => substr_count($user_profile[$memID]['buddy_list'], ',') + 1,
1554
			)
1555
		);
1556
		while ($row = $smcFunc['db_fetch_assoc']($result))
1557
			$buddies[] = $row['id_member'];
1558
		$smcFunc['db_free_result']($result);
1559
	}
1560
1561
	$context['buddy_count'] = count($buddies);
1562
1563
	// Load all the members up.
1564
	loadMemberData($buddies, false, 'profile');
1565
1566
	// Setup the context for each buddy.
1567
	$context['buddies'] = array();
1568
	foreach ($buddies as $buddy)
1569
	{
1570
		loadMemberContext($buddy);
1571
		$context['buddies'][$buddy] = $memberContext[$buddy];
1572
1573
		// Make sure to load the appropriate fields for each user
1574
		if (!empty($context['custom_pf']))
1575
		{
1576
			foreach ($context['custom_pf'] as $key => $column)
1577
			{
1578
				// Don't show anything if there isn't anything to show.
1579
				if (!isset($context['buddies'][$buddy]['options'][$key]))
1580
				{
1581
					$context['buddies'][$buddy]['options'][$key] = '';
1582
					continue;
1583
				}
1584
1585
				if ($column['bbc'] && !empty($context['buddies'][$buddy]['options'][$key]))
1586
					$context['buddies'][$buddy]['options'][$key] = strip_tags(parse_bbc($context['buddies'][$buddy]['options'][$key]));
1587
1588
				elseif ($column['type'] == 'check')
1589
					$context['buddies'][$buddy]['options'][$key] = $context['buddies'][$buddy]['options'][$key] == 0 ? $txt['no'] : $txt['yes'];
1590
1591
				// Enclosing the user input within some other text?
1592
				if (!empty($column['enclose']) && !empty($context['buddies'][$buddy]['options'][$key]))
1593
					$context['buddies'][$buddy]['options'][$key] = strtr($column['enclose'], array(
1594
						'{SCRIPTURL}' => $scripturl,
1595
						'{IMAGES_URL}' => $settings['images_url'],
1596
						'{DEFAULT_IMAGES_URL}' => $settings['default_images_url'],
1597
						'{INPUT}' => $context['buddies'][$buddy]['options'][$key],
1598
					));
1599
			}
1600
		}
1601
	}
1602
1603
	if (isset($_SESSION['prf-save']))
1604
	{
1605
		if ($_SESSION['prf-save'] === true)
1606
			$context['saved_successful'] = true;
1607
		else
1608
			$context['saved_failed'] = $_SESSION['prf-save'];
1609
1610
		unset($_SESSION['prf-save']);
1611
	}
1612
1613
	call_integration_hook('integrate_view_buddies', array($memID));
1614
}
1615
1616
/**
1617
 * Allows the user to view their ignore list, as well as the option to manage members on it.
1618
 *
1619
 * @param int $memID The ID of the member
1620
 */
1621
function editIgnoreList($memID)
1622
{
1623
	global $txt;
1624
	global $context, $user_profile, $memberContext, $smcFunc;
1625
1626
	// For making changes!
1627
	$ignoreArray = explode(',', $user_profile[$memID]['pm_ignore_list']);
1628
	foreach ($ignoreArray as $k => $dummy)
1629
		if ($dummy == '')
1630
			unset($ignoreArray[$k]);
1631
1632
	// Removing a member from the ignore list?
1633
	if (isset($_GET['remove']))
1634
	{
1635
		checkSession('get');
1636
1637
		$_SESSION['prf-save'] = $txt['could_not_remove_person'];
1638
1639
		// Heh, I'm lazy, do it the easy way...
1640
		foreach ($ignoreArray as $key => $id_remove)
1641
			if ($id_remove == (int) $_GET['remove'])
1642
			{
1643
				unset($ignoreArray[$key]);
1644
				$_SESSION['prf-save'] = true;
1645
			}
1646
1647
		// Make the changes.
1648
		$user_profile[$memID]['pm_ignore_list'] = implode(',', $ignoreArray);
1649
		updateMemberData($memID, array('pm_ignore_list' => $user_profile[$memID]['pm_ignore_list']));
1650
1651
		// Redirect off the page because we don't like all this ugly query stuff to stick in the history.
1652
		redirectexit('action=profile;area=lists;sa=ignore;u=' . $memID);
1653
	}
1654
	elseif (isset($_POST['new_ignore']))
1655
	{
1656
		checkSession();
1657
		// Prepare the string for extraction...
1658
		$_POST['new_ignore'] = strtr($smcFunc['htmlspecialchars']($_POST['new_ignore'], ENT_QUOTES), array('&quot;' => '"'));
1659
		preg_match_all('~"([^"]+)"~', $_POST['new_ignore'], $matches);
1660
		$new_entries = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $_POST['new_ignore']))));
1661
1662
		foreach ($new_entries as $k => $dummy)
1663
		{
1664
			$new_entries[$k] = strtr(trim($new_entries[$k]), array('\'' => '&#039;'));
1665
1666
			if (strlen($new_entries[$k]) == 0 || in_array($new_entries[$k], array($user_profile[$memID]['member_name'], $user_profile[$memID]['real_name'])))
1667
				unset($new_entries[$k]);
1668
		}
1669
1670
		$_SESSION['prf-save'] = $txt['could_not_add_person'];
1671
		if (!empty($new_entries))
1672
		{
1673
			// Now find out the id_member for the members in question.
1674
			$request = $smcFunc['db_query']('', '
1675
				SELECT id_member
1676
				FROM {db_prefix}members
1677
				WHERE member_name IN ({array_string:new_entries}) OR real_name IN ({array_string:new_entries})
1678
				LIMIT {int:count_new_entries}',
1679
				array(
1680
					'new_entries' => $new_entries,
1681
					'count_new_entries' => count($new_entries),
1682
				)
1683
			);
1684
1685
			if ($smcFunc['db_num_rows']($request) != 0)
1686
				$_SESSION['prf-save'] = true;
1687
1688
			// Add the new member to the buddies array.
1689
			while ($row = $smcFunc['db_fetch_assoc']($request))
1690
			{
1691
				if (in_array($row['id_member'], $ignoreArray))
1692
					continue;
1693
				else
1694
					$ignoreArray[] = (int) $row['id_member'];
1695
			}
1696
			$smcFunc['db_free_result']($request);
1697
1698
			// Now update the current users buddy list.
1699
			$user_profile[$memID]['pm_ignore_list'] = implode(',', $ignoreArray);
1700
			updateMemberData($memID, array('pm_ignore_list' => $user_profile[$memID]['pm_ignore_list']));
1701
		}
1702
1703
		// Back to the list of pityful people!
1704
		redirectexit('action=profile;area=lists;sa=ignore;u=' . $memID);
1705
	}
1706
1707
	// Initialise the list of members we're ignoring.
1708
	$ignored = array();
1709
1710
	if (!empty($ignoreArray))
1711
	{
1712
		$result = $smcFunc['db_query']('', '
1713
			SELECT id_member
1714
			FROM {db_prefix}members
1715
			WHERE id_member IN ({array_int:ignore_list})
1716
			ORDER BY real_name
1717
			LIMIT {int:ignore_list_count}',
1718
			array(
1719
				'ignore_list' => $ignoreArray,
1720
				'ignore_list_count' => substr_count($user_profile[$memID]['pm_ignore_list'], ',') + 1,
1721
			)
1722
		);
1723
		while ($row = $smcFunc['db_fetch_assoc']($result))
1724
			$ignored[] = $row['id_member'];
1725
		$smcFunc['db_free_result']($result);
1726
	}
1727
1728
	$context['ignore_count'] = count($ignored);
1729
1730
	// Load all the members up.
1731
	loadMemberData($ignored, false, 'profile');
1732
1733
	// Setup the context for each buddy.
1734
	$context['ignore_list'] = array();
1735
	foreach ($ignored as $ignore_member)
1736
	{
1737
		loadMemberContext($ignore_member);
1738
		$context['ignore_list'][$ignore_member] = $memberContext[$ignore_member];
1739
	}
1740
1741
	if (isset($_SESSION['prf-save']))
1742
	{
1743
		if ($_SESSION['prf-save'] === true)
1744
			$context['saved_successful'] = true;
1745
		else
1746
			$context['saved_failed'] = $_SESSION['prf-save'];
1747
1748
		unset($_SESSION['prf-save']);
1749
	}
1750
}
1751
1752
/**
1753
 * Handles the account section of the profile
1754
 *
1755
 * @param int $memID The ID of the member
1756
 */
1757
function account($memID)
1758
{
1759
	global $context, $txt;
1760
1761
	loadThemeOptions($memID);
1762
	if (allowedTo(array('profile_identity_own', 'profile_identity_any', 'profile_password_own', 'profile_password_any')))
1763
		loadCustomFields($memID, 'account');
1764
1765
	$context['sub_template'] = 'edit_options';
1766
	$context['page_desc'] = $txt['account_info'];
1767
1768
	setupProfileContext(
1769
		array(
1770
			'member_name', 'real_name', 'date_registered', 'posts', 'lngfile', 'hr',
1771
			'id_group', 'hr',
1772
			'email_address', 'show_online', 'hr',
1773
			'tfa', 'hr',
1774
			'passwrd1', 'passwrd2', 'hr',
1775
			'secret_question', 'secret_answer',
1776
		)
1777
	);
1778
}
1779
1780
/**
1781
 * Handles the main "Forum Profile" section of the profile
1782
 *
1783
 * @param int $memID The ID of the member
1784
 */
1785
function forumProfile($memID)
1786
{
1787
	global $context, $txt;
1788
1789
	loadThemeOptions($memID);
1790
	if (allowedTo(array('profile_forum_own', 'profile_forum_any')))
1791
		loadCustomFields($memID, 'forumprofile');
1792
1793
	$context['sub_template'] = 'edit_options';
1794
	$context['page_desc'] = $txt['forumProfile_info'];
1795
	$context['show_preview_button'] = true;
1796
1797
	setupProfileContext(
1798
		array(
1799
			'avatar_choice', 'hr', 'personal_text', 'hr',
1800
			'bday1', 'usertitle', 'signature', 'hr',
1801
			'website_title', 'website_url',
1802
		)
1803
	);
1804
}
1805
1806
/**
1807
 * Recursive function to retrieve server-stored avatar files
1808
 *
1809
 * @param string $directory The directory to look for files in
1810
 * @param int $level How many levels we should go in the directory
1811
 * @return array An array of information about the files and directories found
1812
 */
1813
function getAvatars($directory, $level)
1814
{
1815
	global $context, $txt, $modSettings, $smcFunc;
1816
1817
	$result = array();
1818
1819
	// Open the directory..
1820
	$dir = dir($modSettings['avatar_directory'] . (!empty($directory) ? '/' : '') . $directory);
1821
	$dirs = array();
1822
	$files = array();
1823
1824
	if (!$dir)
1825
		return array();
1826
1827
	while ($line = $dir->read())
1828
	{
1829
		if (in_array($line, array('.', '..', 'blank.png', 'index.php')))
1830
			continue;
1831
1832
		if (is_dir($modSettings['avatar_directory'] . '/' . $directory . (!empty($directory) ? '/' : '') . $line))
1833
			$dirs[] = $line;
1834
		else
1835
			$files[] = $line;
1836
	}
1837
	$dir->close();
1838
1839
	// Sort the results...
1840
	natcasesort($dirs);
1841
	natcasesort($files);
1842
1843
	if ($level == 0)
1844
	{
1845
		$result[] = array(
1846
			'filename' => 'blank.png',
1847
			'checked' => in_array($context['member']['avatar']['server_pic'], array('', 'blank.png')),
1848
			'name' => $txt['no_pic'],
1849
			'is_dir' => false
1850
		);
1851
	}
1852
1853
	foreach ($dirs as $line)
1854
	{
1855
		$tmp = getAvatars($directory . (!empty($directory) ? '/' : '') . $line, $level + 1);
1856
		if (!empty($tmp))
1857
			$result[] = array(
1858
				'filename' => $smcFunc['htmlspecialchars']($line),
1859
				'checked' => strpos($context['member']['avatar']['server_pic'], $line . '/') !== false,
1860
				'name' => '[' . $smcFunc['htmlspecialchars'](str_replace('_', ' ', $line)) . ']',
1861
				'is_dir' => true,
1862
				'files' => $tmp
1863
			);
1864
		unset($tmp);
1865
	}
1866
1867
	foreach ($files as $line)
1868
	{
1869
		$filename = substr($line, 0, (strlen($line) - strlen(strrchr($line, '.'))));
1870
		$extension = substr(strrchr($line, '.'), 1);
1871
1872
		// Make sure it is an image.
1873
		if (strcasecmp($extension, 'gif') != 0 && strcasecmp($extension, 'jpg') != 0 && strcasecmp($extension, 'jpeg') != 0 && strcasecmp($extension, 'png') != 0 && strcasecmp($extension, 'bmp') != 0)
1874
			continue;
1875
1876
		$result[] = array(
1877
			'filename' => $smcFunc['htmlspecialchars']($line),
1878
			'checked' => $line == $context['member']['avatar']['server_pic'],
1879
			'name' => $smcFunc['htmlspecialchars'](str_replace('_', ' ', $filename)),
1880
			'is_dir' => false
1881
		);
1882
		if ($level == 1)
1883
			$context['avatar_list'][] = $directory . '/' . $line;
1884
	}
1885
1886
	return $result;
1887
}
1888
1889
/**
1890
 * Handles the "Look and Layout" section of the profile
1891
 *
1892
 * @param int $memID The ID of the member
1893
 */
1894
function theme($memID)
1895
{
1896
	global $txt, $context;
1897
1898
	loadTemplate('Settings');
1899
	loadSubTemplate('options');
1900
1901
	// Let mods hook into the theme options.
1902
	call_integration_hook('integrate_theme_options');
1903
1904
	loadThemeOptions($memID);
1905
	if (allowedTo(array('profile_extra_own', 'profile_extra_any')))
1906
		loadCustomFields($memID, 'theme');
1907
1908
	$context['sub_template'] = 'edit_options';
1909
	$context['page_desc'] = $txt['theme_info'];
1910
1911
	setupProfileContext(
1912
		array(
1913
			'id_theme', 'smiley_set', 'hr',
1914
			'time_format', 'timezone', 'hr',
1915
			'theme_settings',
1916
		)
1917
	);
1918
}
1919
1920
/**
1921
 * Display the notifications and settings for changes.
1922
 *
1923
 * @param int $memID The ID of the member
1924
 */
1925
function notification($memID)
1926
{
1927
	global $txt, $context;
1928
1929
	// Going to want this for consistency.
1930
	loadCSSFile('admin.css', array(), 'smf_admin');
1931
1932
	// This is just a bootstrap for everything else.
1933
	$sa = array(
1934
		'alerts' => 'alert_configuration',
1935
		'markread' => 'alert_markread',
1936
		'topics' => 'alert_notifications_topics',
1937
		'boards' => 'alert_notifications_boards',
1938
	);
1939
1940
	$subAction = !empty($_GET['sa']) && isset($sa[$_GET['sa']]) ? $_GET['sa'] : 'alerts';
1941
1942
	$context['sub_template'] = $sa[$subAction];
1943
	$context[$context['profile_menu_name']]['tab_data'] = array(
1944
		'title' => $txt['notification'],
1945
		'help' => '',
1946
		'description' => $txt['notification_info'],
1947
	);
1948
	$sa[$subAction]($memID);
1949
}
1950
1951
/**
1952
 * Handles configuration of alert preferences
1953
 *
1954
 * @param int $memID The ID of the member
1955
 * @param bool $defaultSettings If true, we are loading default options.
1956
 */
1957
function alert_configuration($memID, $defaultSettings = false)
1958
{
1959
	global $txt, $context, $modSettings, $smcFunc, $sourcedir;
1960
1961
	if (!isset($context['token_check']))
1962
		$context['token_check'] = 'profile-nt' . $memID;
1963
1964
	is_not_guest();
1965
	if (!$context['user']['is_owner'])
1966
		isAllowedTo('profile_extra_any');
1967
1968
	// Set the post action if we're coming from the profile...
1969
	if (!isset($context['action']))
1970
		$context['action'] = 'action=profile;area=notification;sa=alerts;u=' . $memID;
1971
1972
	// What options are set
1973
	loadThemeOptions($memID, $defaultSettings);
1974
	loadJavaScriptFile('alertSettings.js', array('minimize' => true), 'smf_alertSettings');
1975
1976
	// Now load all the values for this user.
1977
	require_once($sourcedir . '/Subs-Notify.php');
1978
	$prefs = getNotifyPrefs($memID, '', $memID != 0);
1979
1980
	$context['alert_prefs'] = !empty($prefs[$memID]) ? $prefs[$memID] : array();
1981
1982
	$context['member'] += array(
1983
		'alert_timeout' => isset($context['alert_prefs']['alert_timeout']) ? $context['alert_prefs']['alert_timeout'] : 10,
1984
		'notify_announcements' => isset($context['alert_prefs']['announcements']) ? $context['alert_prefs']['announcements'] : 0,
1985
	);
1986
1987
	// Now for the exciting stuff.
1988
	// We have groups of items, each item has both an alert and an email key as well as an optional help string.
1989
	// Valid values for these keys are 'always', 'yes', 'never'; if using always or never you should add a help string.
1990
	$alert_types = array(
1991
		'board' => array(
1992
			'topic_notify' => array('alert' => 'yes', 'email' => 'yes'),
1993
			'board_notify' => array('alert' => 'yes', 'email' => 'yes'),
1994
		),
1995
		'msg' => array(
1996
			'msg_mention' => array('alert' => 'yes', 'email' => 'yes'),
1997
			'msg_quote' => array('alert' => 'yes', 'email' => 'yes'),
1998
			'msg_like' => array('alert' => 'yes', 'email' => 'never'),
1999
			'unapproved_reply' => array('alert' => 'yes', 'email' => 'yes'),
2000
		),
2001
		'pm' => array(
2002
			'pm_new' => array('alert' => 'never', 'email' => 'yes', 'help' => 'alert_pm_new', 'permission' => array('name' => 'pm_read', 'is_board' => false)),
2003
			'pm_reply' => array('alert' => 'never', 'email' => 'yes', 'help' => 'alert_pm_new', 'permission' => array('name' => 'pm_send', 'is_board' => false)),
2004
		),
2005
		'groupr' => array(
2006
			'groupr_approved' => array('alert' => 'yes', 'email' => 'yes'),
2007
			'groupr_rejected' => array('alert' => 'yes', 'email' => 'yes'),
2008
		),
2009
		'moderation' => array(
2010
			'unapproved_attachment' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'approve_posts', 'is_board' => true)),
2011
			'unapproved_post' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'approve_posts', 'is_board' => true)),
2012
			'msg_report' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_board', 'is_board' => true)),
2013
			'msg_report_reply' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_board', 'is_board' => true)),
2014
			'member_report' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_forum', 'is_board' => false)),
2015
			'member_report_reply' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_forum', 'is_board' => false)),
2016
		),
2017
		'members' => array(
2018
			'member_register' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_forum', 'is_board' => false)),
2019
			'request_group' => array('alert' => 'yes', 'email' => 'yes'),
2020
			'warn_any' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'issue_warning', 'is_board' => false)),
2021
			'buddy_request' => array('alert' => 'yes', 'email' => 'never'),
2022
			'birthday' => array('alert' => 'yes', 'email' => 'yes'),
2023
		),
2024
		'calendar' => array(
2025
			'event_new' => array('alert' => 'yes', 'email' => 'yes', 'help' => 'alert_event_new'),
2026
		),
2027
		'paidsubs' => array(
2028
			'paidsubs_expiring' => array('alert' => 'yes', 'email' => 'yes'),
2029
		),
2030
	);
2031
	$group_options = array(
2032
		'board' => array(
2033
			array('check', 'msg_auto_notify', 'label' => 'after'),
2034
			array('check', 'msg_receive_body', 'label' => 'after'),
2035
			array('select', 'msg_notify_pref', 'label' => 'before', 'opts' => array(
2036
				0 => $txt['alert_opt_msg_notify_pref_never'],
2037
				1 => $txt['alert_opt_msg_notify_pref_instant'],
2038
				2 => $txt['alert_opt_msg_notify_pref_first'],
2039
				3 => $txt['alert_opt_msg_notify_pref_daily'],
2040
				4 => $txt['alert_opt_msg_notify_pref_weekly'],
2041
			)),
2042
			array('select', 'msg_notify_type', 'label' => 'before', 'opts' => array(
2043
				1 => $txt['notify_send_type_everything'],
2044
				2 => $txt['notify_send_type_everything_own'],
2045
				3 => $txt['notify_send_type_only_replies'],
2046
				4 => $txt['notify_send_type_nothing'],
2047
			)),
2048
		),
2049
		'pm' => array(
2050
			array('select', 'pm_notify', 'label' => 'before', 'opts' => array(
2051
				1 => $txt['email_notify_all'],
2052
				2 => $txt['email_notify_buddies'],
2053
			)),
2054
		),
2055
	);
2056
2057
	// There are certain things that are disabled at the group level.
2058
	if (empty($modSettings['cal_enabled']))
2059
		unset($alert_types['calendar']);
2060
2061
	// Disable paid subscriptions at group level if they're disabled
2062
	if (empty($modSettings['paid_enabled']))
2063
		unset($alert_types['paidsubs']);
2064
2065
	// Disable membergroup requests at group level if they're disabled
2066
	if (empty($modSettings['show_group_membership']))
2067
		unset($alert_types['groupr'], $alert_types['members']['request_group']);
2068
2069
	// Disable mentions if they're disabled
2070
	if (empty($modSettings['enable_mentions']))
2071
		unset($alert_types['msg']['msg_mention']);
2072
2073
	// Disable likes if they're disabled
2074
	if (empty($modSettings['enable_likes']))
2075
		unset($alert_types['msg']['msg_like']);
2076
2077
	// Disable buddy requests if they're disabled
2078
	if (empty($modSettings['enable_buddylist']))
2079
		unset($alert_types['members']['buddy_request']);
2080
2081
	// Now, now, we could pass this through global but we should really get into the habit of
2082
	// passing content to hooks, not expecting hooks to splatter everything everywhere.
2083
	call_integration_hook('integrate_alert_types', array(&$alert_types, &$group_options));
2084
2085
	// Now we have to do some permissions testing - but only if we're not loading this from the admin center
2086
	if (!empty($memID))
2087
	{
2088
		require_once($sourcedir . '/Subs-Members.php');
2089
		$perms_cache = array();
2090
		$request = $smcFunc['db_query']('', '
2091
			SELECT COUNT(*)
2092
			FROM {db_prefix}group_moderators
2093
			WHERE id_member = {int:memID}',
2094
			array(
2095
				'memID' => $memID,
2096
			)
2097
		);
2098
2099
		list ($can_mod) = $smcFunc['db_fetch_row']($request);
2100
2101
		if (!isset($perms_cache['manage_membergroups']))
2102
		{
2103
			$members = membersAllowedTo('manage_membergroups');
2104
			$perms_cache['manage_membergroups'] = in_array($memID, $members);
2105
		}
2106
2107
		if (!($perms_cache['manage_membergroups'] || $can_mod != 0))
2108
			unset($alert_types['members']['request_group']);
2109
2110
		foreach ($alert_types as $group => $items)
2111
		{
2112
			foreach ($items as $alert_key => $alert_value)
2113
			{
2114
				if (!isset($alert_value['permission']))
2115
					continue;
2116
				if (!isset($perms_cache[$alert_value['permission']['name']]))
2117
				{
2118
					$in_board = !empty($alert_value['permission']['is_board']) ? 0 : null;
2119
					$members = membersAllowedTo($alert_value['permission']['name'], $in_board);
2120
					$perms_cache[$alert_value['permission']['name']] = in_array($memID, $members);
2121
				}
2122
2123
				if (!$perms_cache[$alert_value['permission']['name']])
2124
					unset ($alert_types[$group][$alert_key]);
2125
			}
2126
2127
			if (empty($alert_types[$group]))
2128
				unset ($alert_types[$group]);
2129
		}
2130
	}
2131
2132
	// And finally, exporting it to be useful later.
2133
	$context['alert_types'] = $alert_types;
2134
	$context['alert_group_options'] = $group_options;
2135
2136
	$context['alert_bits'] = array(
2137
		'alert' => 0x01,
2138
		'email' => 0x02,
2139
	);
2140
2141
	if (isset($_POST['notify_submit']))
2142
	{
2143
		checkSession();
2144
		validateToken($context['token_check'], 'post');
2145
2146
		// We need to step through the list of valid settings and figure out what the user has set.
2147
		$update_prefs = array();
2148
2149
		// Now the group level options
2150
		foreach ($context['alert_group_options'] as $opt_group => $group)
2151
		{
2152
			foreach ($group as $this_option)
2153
			{
2154
				switch ($this_option[0])
2155
				{
2156
					case 'check':
2157
						$update_prefs[$this_option[1]] = !empty($_POST['opt_' . $this_option[1]]) ? 1 : 0;
2158
						break;
2159
					case 'select':
2160
						if (isset($_POST['opt_' . $this_option[1]], $this_option['opts'][$_POST['opt_' . $this_option[1]]]))
2161
							$update_prefs[$this_option[1]] = $_POST['opt_' . $this_option[1]];
2162
						else
2163
						{
2164
							// We didn't have a sane value. Let's grab the first item from the possibles.
2165
							$keys = array_keys($this_option['opts']);
2166
							$first = array_shift($keys);
2167
							$update_prefs[$this_option[1]] = $first;
2168
						}
2169
						break;
2170
				}
2171
			}
2172
		}
2173
2174
		// Now the individual options
2175
		foreach ($context['alert_types'] as $alert_group => $items)
2176
		{
2177
			foreach ($items as $item_key => $this_options)
2178
			{
2179
				$this_value = 0;
2180
				foreach ($context['alert_bits'] as $type => $bitvalue)
2181
				{
2182
					if ($this_options[$type] == 'yes' && !empty($_POST[$type . '_' . $item_key]) || $this_options[$type] == 'always')
2183
						$this_value |= $bitvalue;
2184
				}
2185
2186
				$update_prefs[$item_key] = $this_value;
2187
			}
2188
		}
2189
2190
		if (isset($_POST['opt_alert_timeout']))
2191
			$update_prefs['alert_timeout'] = $context['member']['alert_timeout'] = (int) $_POST['opt_alert_timeout'];
2192
		else
2193
			$update_prefs['alert_timeout'] = $context['alert_prefs']['alert_timeout'];
2194
2195
		if (isset($_POST['notify_announcements']))
2196
			$update_prefs['announcements'] = $context['member']['notify_announcements'] = (int) $_POST['notify_announcements'];
2197
		else
2198
			$update_prefs['announcements'] = $context['alert_prefs']['announcements'];
2199
2200
		setNotifyPrefs((int) $memID, $update_prefs);
2201
		foreach ($update_prefs as $pref => $value)
2202
			$context['alert_prefs'][$pref] = $value;
2203
2204
		makeNotificationChanges($memID);
2205
2206
		$context['profile_updated'] = $txt['profile_updated_own'];
2207
	}
2208
2209
	createToken($context['token_check'], 'post');
2210
}
2211
2212
/**
2213
 * Marks all alerts as read for the specified user
2214
 *
2215
 * @param int $memID The ID of the member
2216
 */
2217
function alert_markread($memID)
2218
{
2219
	global $context, $db_show_debug, $smcFunc;
2220
2221
	// We do not want to output debug information here.
2222
	$db_show_debug = false;
2223
2224
	// We only want to output our little layer here.
2225
	$context['template_layers'] = array();
2226
	$context['sub_template'] = 'alerts_all_read';
2227
2228
	loadLanguage('Alerts');
2229
2230
	// Now we're all set up.
2231
	is_not_guest();
2232
	if (!$context['user']['is_owner'])
2233
		fatal_error('no_access');
2234
2235
	checkSession('get');
2236
2237
	// Assuming we're here, mark everything as read and head back.
2238
	// We only spit back the little layer because this should be called AJAXively.
2239
	$smcFunc['db_query']('', '
2240
		UPDATE {db_prefix}user_alerts
2241
		SET is_read = {int:now}
2242
		WHERE id_member = {int:current_member}
2243
			AND is_read = 0',
2244
		array(
2245
			'now' => time(),
2246
			'current_member' => $memID,
2247
		)
2248
	);
2249
2250
	updateMemberData($memID, array('alerts' => 0));
2251
}
2252
2253
/**
2254
 * Marks a group of alerts as un/read
2255
 *
2256
 * @param int $memID The user ID.
2257
 * @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.
2258
 * @param integer $read To mark as read or unread, 1 for read, 0 or any other value different than 1 for unread.
2259
 * @return integer How many alerts remain unread
2260
 */
2261
function alert_mark($memID, $toMark, $read = 0)
2262
{
2263
	global $smcFunc;
2264
2265
	if (empty($toMark) || empty($memID))
2266
		return false;
2267
2268
	$toMark = (array) $toMark;
2269
2270
	$smcFunc['db_query']('', '
2271
		UPDATE {db_prefix}user_alerts
2272
		SET is_read = {int:read}
2273
		WHERE id_alert IN({array_int:toMark})',
2274
		array(
2275
			'read' => $read == 1 ? time() : 0,
2276
			'toMark' => $toMark,
2277
		)
2278
	);
2279
2280
	// Gotta know how many unread alerts are left.
2281
	$count = alert_count($memID, true);
2282
2283
	updateMemberData($memID, array('alerts' => $count));
2284
2285
	// Might want to know this.
2286
	return $count;
2287
}
2288
2289
/**
2290
 * Deletes a single or a group of alerts by ID
2291
 *
2292
 * @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.
2293
 * @param bool|int $memID The user ID. Used to update the user unread alerts count.
2294
 * @return void|int If the $memID param is set, returns the new amount of unread alerts.
2295
 */
2296
function alert_delete($toDelete, $memID = false)
2297
{
2298
	global $smcFunc;
2299
2300
	if (empty($toDelete))
2301
		return false;
2302
2303
	$toDelete = (array) $toDelete;
2304
2305
	$smcFunc['db_query']('', '
2306
		DELETE FROM {db_prefix}user_alerts
2307
		WHERE id_alert IN({array_int:toDelete})',
2308
		array(
2309
			'toDelete' => $toDelete,
2310
		)
2311
	);
2312
2313
	// Gotta know how many unread alerts are left.
2314
	if ($memID)
2315
	{
2316
		$count = alert_count($memID, true);
2317
2318
		updateMemberData($memID, array('alerts' => $count));
2319
2320
		// Might want to know this.
2321
		return $count;
2322
	}
2323
}
2324
2325
/**
2326
 * Deletes all the alerts that a user has already read.
2327
 *
2328
 * @param int $memID The user ID. Defaults to the current user's ID.
2329
 */
2330
function alert_purge($memID = 0)
2331
{
2332
	global $smcFunc, $user_info;
2333
2334
	$memID = !empty($memID) && is_int($memID) ? $memID : $user_info['id'];
2335
2336
	$smcFunc['db_query']('', '
2337
		DELETE FROM {db_prefix}user_alerts
2338
		WHERE id_member = {int:memID}
2339
			AND is_read > 0',
2340
		array(
2341
			'memID' => $memID,
2342
		)
2343
	);
2344
}
2345
2346
/**
2347
 * Counts how many alerts a user has - either unread or all depending on $unread
2348
 * We can't use db_num_rows here, as we have to determine what boards the user can see
2349
 * Possibly in future versions as database support for json is mainstream, we can simplify this.
2350
 *
2351
 * @param int $memID The user ID.
2352
 * @param bool $unread Whether to only count unread alerts.
2353
 * @return int The number of requested alerts
2354
 */
2355
function alert_count($memID, $unread = false)
2356
{
2357
	global $smcFunc, $user_info;
2358
2359
	if (empty($memID))
2360
		return false;
2361
2362
	$alerts = array();
2363
	$possible_topics = array();
2364
	$possible_msgs = array();
2365
	$possible_attachments = array();
2366
2367
	// We have to do this the slow way as to iterate over all possible boards the user can see.
2368
	$request = $smcFunc['db_query']('', '
2369
		SELECT id_alert, content_id, content_type, content_action
2370
		FROM {db_prefix}user_alerts
2371
		WHERE id_member = {int:id_member}
2372
			' . ($unread ? '
2373
			AND is_read = 0' : ''),
2374
		array(
2375
			'id_member' => $memID,
2376
		)
2377
	);
2378
	// First we dump alerts and possible boards information out.
2379
	while ($row = $smcFunc['db_fetch_assoc']($request))
2380
	{
2381
		$alerts[$row['id_alert']] = $row;
2382
2383
		// For these types, we need to check whether they can actually see the content.
2384
		if ($row['content_type'] == 'msg')
2385
		{
2386
			$alerts[$row['id_alert']]['visible'] = false;
2387
			$possible_msgs[$row['id_alert']] = $row['content_id'];
2388
		}
2389
		elseif (in_array($row['content_type'], array('topic', 'board')))
2390
		{
2391
			$alerts[$row['id_alert']]['visible'] = false;
2392
			$possible_topics[$row['id_alert']] = $row['content_id'];
2393
		}
2394
		// For the rest, they can always see it.
2395
		else
2396
			$alerts[$row['id_alert']]['visible'] = true;
2397
	}
2398
	$smcFunc['db_free_result']($request);
2399
2400
	// If we need to check board access, use the correct board access filter for the member in question.
2401
	if ((!isset($user_info['query_see_board']) || $user_info['id'] != $memID) && (!empty($possible_msgs) || !empty($possible_topics)))
2402
		$qb = build_query_board($memID);
2403
	else
2404
	{
2405
		$qb['query_see_topic_board'] = '{query_see_topic_board}';
2406
		$qb['query_see_message_board'] = '{query_see_message_board}';
2407
	}
2408
2409
	// We want only the stuff they can see.
2410
	if (!empty($possible_msgs))
2411
	{
2412
		$flipped_msgs = array();
2413
		foreach ($possible_msgs as $id_alert => $id_msg)
2414
		{
2415
			if (!isset($flipped_msgs[$id_msg]))
2416
				$flipped_msgs[$id_msg] = array();
2417
2418
			$flipped_msgs[$id_msg][] = $id_alert;
2419
		}
2420
2421
		$request = $smcFunc['db_query']('', '
2422
			SELECT m.id_msg
2423
			FROM {db_prefix}messages AS m
2424
			WHERE ' . $qb['query_see_message_board'] . '
2425
				AND m.id_msg IN ({array_int:msgs})',
2426
			array(
2427
				'msgs' => $possible_msgs,
2428
			)
2429
		);
2430
		while ($row = $smcFunc['db_fetch_assoc']($request))
2431
		{
2432
			foreach ($flipped_msgs[$row['id_msg']] as $id_alert)
2433
				$alerts[$id_alert]['visible'] = true;
2434
		}
2435
		$smcFunc['db_free_result']($request);
2436
	}
2437
	if (!empty($possible_topics))
2438
	{
2439
		$flipped_topics = array();
2440
		foreach ($possible_topics as $id_alert => $id_topic)
2441
		{
2442
			if (!isset($flipped_topics[$id_topic]))
2443
				$flipped_topics[$id_topic] = array();
2444
2445
			$flipped_topics[$id_topic][] = $id_alert;
2446
		}
2447
2448
		$request = $smcFunc['db_query']('', '
2449
			SELECT t.id_topic
2450
			FROM {db_prefix}topics AS t
2451
			WHERE ' . $qb['query_see_topic_board'] . '
2452
				AND t.id_topic IN ({array_int:topics})',
2453
			array(
2454
				'topics' => $possible_topics,
2455
			)
2456
		);
2457
		while ($row = $smcFunc['db_fetch_assoc']($request))
2458
		{
2459
			foreach ($flipped_topics[$row['id_topic']] as $id_alert)
2460
				$alerts[$id_alert]['visible'] = true;
2461
		}
2462
		$smcFunc['db_free_result']($request);
2463
	}
2464
2465
	// Now check alerts again and remove any they can't see.
2466
	foreach ($alerts as $id_alert => $alert)
2467
	{
2468
		if (!$alert['visible'])
2469
			unset($alerts[$id_alert]);
2470
	}
2471
2472
	return count($alerts);
2473
}
2474
2475
/**
2476
 * Handles alerts related to topics and posts
2477
 *
2478
 * @param int $memID The ID of the member
2479
 */
2480
function alert_notifications_topics($memID)
2481
{
2482
	global $txt, $scripturl, $context, $modSettings, $sourcedir;
2483
2484
	// Because of the way this stuff works, we want to do this ourselves.
2485
	if (isset($_POST['edit_notify_topics']) || isset($_POST['remove_notify_topics']))
2486
	{
2487
		checkSession();
2488
		validateToken(str_replace('%u', $memID, 'profile-nt%u'), 'post');
2489
2490
		makeNotificationChanges($memID);
2491
		$context['profile_updated'] = $txt['profile_updated_own'];
2492
	}
2493
2494
	// Now set up for the token check.
2495
	$context['token_check'] = str_replace('%u', $memID, 'profile-nt%u');
2496
	createToken($context['token_check'], 'post');
2497
2498
	// Gonna want this for the list.
2499
	require_once($sourcedir . '/Subs-List.php');
2500
2501
	// Do the topic notifications.
2502
	$listOptions = array(
2503
		'id' => 'topic_notification_list',
2504
		'width' => '100%',
2505
		'items_per_page' => $modSettings['defaultMaxListItems'],
2506
		'no_items_label' => $txt['notifications_topics_none'] . '<br><br>' . $txt['notifications_topics_howto'],
2507
		'no_items_align' => 'left',
2508
		'base_href' => $scripturl . '?action=profile;u=' . $memID . ';area=notification;sa=topics',
2509
		'default_sort_col' => 'last_post',
2510
		'get_items' => array(
2511
			'function' => 'list_getTopicNotifications',
2512
			'params' => array(
2513
				$memID,
2514
			),
2515
		),
2516
		'get_count' => array(
2517
			'function' => 'list_getTopicNotificationCount',
2518
			'params' => array(
2519
				$memID,
2520
			),
2521
		),
2522
		'columns' => array(
2523
			'subject' => array(
2524
				'header' => array(
2525
					'value' => $txt['notifications_topics'],
2526
					'class' => 'lefttext',
2527
				),
2528
				'data' => array(
2529
					'function' => function($topic) use ($txt)
2530
					{
2531
						$link = $topic['link'];
2532
2533
						if ($topic['new'])
2534
							$link .= ' <a href="' . $topic['new_href'] . '" class="new_posts">' . $txt['new'] . '</a>';
2535
2536
						$link .= '<br><span class="smalltext"><em>' . $txt['in'] . ' ' . $topic['board_link'] . '</em></span>';
2537
2538
						return $link;
2539
					},
2540
				),
2541
				'sort' => array(
2542
					'default' => 'ms.subject',
2543
					'reverse' => 'ms.subject DESC',
2544
				),
2545
			),
2546
			'started_by' => array(
2547
				'header' => array(
2548
					'value' => $txt['started_by'],
2549
					'class' => 'lefttext',
2550
				),
2551
				'data' => array(
2552
					'db' => 'poster_link',
2553
				),
2554
				'sort' => array(
2555
					'default' => 'real_name_col',
2556
					'reverse' => 'real_name_col DESC',
2557
				),
2558
			),
2559
			'last_post' => array(
2560
				'header' => array(
2561
					'value' => $txt['last_post'],
2562
					'class' => 'lefttext',
2563
				),
2564
				'data' => array(
2565
					'sprintf' => array(
2566
						'format' => '<span class="smalltext">%1$s<br>' . $txt['by'] . ' %2$s</span>',
2567
						'params' => array(
2568
							'updated' => false,
2569
							'poster_updated_link' => false,
2570
						),
2571
					),
2572
				),
2573
				'sort' => array(
2574
					'default' => 'ml.id_msg DESC',
2575
					'reverse' => 'ml.id_msg',
2576
				),
2577
			),
2578
			'alert' => array(
2579
				'header' => array(
2580
					'value' => $txt['notify_what_how'],
2581
					'class' => 'lefttext',
2582
				),
2583
				'data' => array(
2584
					'function' => function($topic) use ($txt)
2585
					{
2586
						$pref = $topic['notify_pref'];
2587
						$mode = !empty($topic['unwatched']) ? 0 : ($pref & 0x02 ? 3 : ($pref & 0x01 ? 2 : 1));
2588
						return $txt['notify_topic_' . $mode];
2589
					},
2590
				),
2591
			),
2592
			'delete' => array(
2593
				'header' => array(
2594
					'value' => '<input type="checkbox" onclick="invertAll(this, this.form);">',
2595
					'style' => 'width: 4%;',
2596
					'class' => 'centercol',
2597
				),
2598
				'data' => array(
2599
					'sprintf' => array(
2600
						'format' => '<input type="checkbox" name="notify_topics[]" value="%1$d">',
2601
						'params' => array(
2602
							'id' => false,
2603
						),
2604
					),
2605
					'class' => 'centercol',
2606
				),
2607
			),
2608
		),
2609
		'form' => array(
2610
			'href' => $scripturl . '?action=profile;area=notification;sa=topics',
2611
			'include_sort' => true,
2612
			'include_start' => true,
2613
			'hidden_fields' => array(
2614
				'u' => $memID,
2615
				'sa' => $context['menu_item_selected'],
2616
				$context['session_var'] => $context['session_id'],
2617
			),
2618
			'token' => $context['token_check'],
2619
		),
2620
		'additional_rows' => array(
2621
			array(
2622
				'position' => 'bottom_of_list',
2623
				'value' => '<input type="submit" name="edit_notify_topics" value="' . $txt['notifications_update'] . '" class="button" />
2624
							<input type="submit" name="remove_notify_topics" value="' . $txt['notification_remove_pref'] . '" class="button" />',
2625
				'class' => 'floatright',
2626
			),
2627
		),
2628
	);
2629
2630
	// Create the notification list.
2631
	createList($listOptions);
2632
}
2633
2634
/**
2635
 * Handles preferences related to board-level notifications
2636
 *
2637
 * @param int $memID The ID of the member
2638
 */
2639
function alert_notifications_boards($memID)
2640
{
2641
	global $txt, $scripturl, $context, $sourcedir;
2642
2643
	// Because of the way this stuff works, we want to do this ourselves.
2644
	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...
2645
	{
2646
		checkSession();
2647
		validateToken(str_replace('%u', $memID, 'profile-nt%u'), 'post');
2648
2649
		makeNotificationChanges($memID);
2650
		$context['profile_updated'] = $txt['profile_updated_own'];
2651
	}
2652
2653
	// Now set up for the token check.
2654
	$context['token_check'] = str_replace('%u', $memID, 'profile-nt%u');
2655
	createToken($context['token_check'], 'post');
2656
2657
	// Gonna want this for the list.
2658
	require_once($sourcedir . '/Subs-List.php');
2659
2660
	// Fine, start with the board list.
2661
	$listOptions = array(
2662
		'id' => 'board_notification_list',
2663
		'width' => '100%',
2664
		'no_items_label' => $txt['notifications_boards_none'] . '<br><br>' . $txt['notifications_boards_howto'],
2665
		'no_items_align' => 'left',
2666
		'base_href' => $scripturl . '?action=profile;u=' . $memID . ';area=notification;sa=boards',
2667
		'default_sort_col' => 'board_name',
2668
		'get_items' => array(
2669
			'function' => 'list_getBoardNotifications',
2670
			'params' => array(
2671
				$memID,
2672
			),
2673
		),
2674
		'columns' => array(
2675
			'board_name' => array(
2676
				'header' => array(
2677
					'value' => $txt['notifications_boards'],
2678
					'class' => 'lefttext',
2679
				),
2680
				'data' => array(
2681
					'function' => function($board) use ($txt)
2682
					{
2683
						$link = $board['link'];
2684
2685
						if ($board['new'])
2686
							$link .= ' <a href="' . $board['href'] . '" class="new_posts">' . $txt['new'] . '</a>';
2687
2688
						return $link;
2689
					},
2690
				),
2691
				'sort' => array(
2692
					'default' => 'name',
2693
					'reverse' => 'name DESC',
2694
				),
2695
			),
2696
			'alert' => array(
2697
				'header' => array(
2698
					'value' => $txt['notify_what_how'],
2699
					'class' => 'lefttext',
2700
				),
2701
				'data' => array(
2702
					'function' => function($board) use ($txt)
2703
					{
2704
						$pref = $board['notify_pref'];
2705
						$mode = $pref & 0x02 ? 3 : ($pref & 0x01 ? 2 : 1);
2706
						return $txt['notify_board_' . $mode];
2707
					},
2708
				),
2709
			),
2710
			'delete' => array(
2711
				'header' => array(
2712
					'value' => '<input type="checkbox" onclick="invertAll(this, this.form);">',
2713
					'style' => 'width: 4%;',
2714
					'class' => 'centercol',
2715
				),
2716
				'data' => array(
2717
					'sprintf' => array(
2718
						'format' => '<input type="checkbox" name="notify_boards[]" value="%1$d">',
2719
						'params' => array(
2720
							'id' => false,
2721
						),
2722
					),
2723
					'class' => 'centercol',
2724
				),
2725
			),
2726
		),
2727
		'form' => array(
2728
			'href' => $scripturl . '?action=profile;area=notification;sa=boards',
2729
			'include_sort' => true,
2730
			'include_start' => true,
2731
			'hidden_fields' => array(
2732
				'u' => $memID,
2733
				'sa' => $context['menu_item_selected'],
2734
				$context['session_var'] => $context['session_id'],
2735
			),
2736
			'token' => $context['token_check'],
2737
		),
2738
		'additional_rows' => array(
2739
			array(
2740
				'position' => 'bottom_of_list',
2741
				'value' => '<input type="submit" name="edit_notify_boards" value="' . $txt['notifications_update'] . '" class="button">
2742
							<input type="submit" name="remove_notify_boards" value="' . $txt['notification_remove_pref'] . '" class="button" />',
2743
				'class' => 'floatright',
2744
			),
2745
		),
2746
	);
2747
2748
	// Create the board notification list.
2749
	createList($listOptions);
2750
}
2751
2752
/**
2753
 * Determins how many topics a user has requested notifications for
2754
 *
2755
 * @param int $memID The ID of the member
2756
 * @return int The number of topic notifications for this user
2757
 */
2758
function list_getTopicNotificationCount($memID)
2759
{
2760
	global $smcFunc, $user_info, $modSettings;
2761
2762
	$request = $smcFunc['db_query']('', '
2763
		SELECT COUNT(*)
2764
		FROM {db_prefix}log_notify AS ln' . (!$modSettings['postmod_active'] && $user_info['query_see_board'] === '1=1' ? '' : '
2765
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ln.id_topic)') . '
2766
		WHERE ln.id_member = {int:selected_member}' . ($user_info['query_see_topic_board'] === '1=1' ? '' : '
2767
			AND {query_see_topic_board}') . ($modSettings['postmod_active'] ? '
2768
			AND t.approved = {int:is_approved}' : ''),
2769
		array(
2770
			'selected_member' => $memID,
2771
			'is_approved' => 1,
2772
		)
2773
	);
2774
	list ($totalNotifications) = $smcFunc['db_fetch_row']($request);
2775
	$smcFunc['db_free_result']($request);
2776
2777
	return (int) $totalNotifications;
2778
}
2779
2780
/**
2781
 * Gets information about all the topics a user has requested notifications for. Callback for the list in alert_notifications_topics
2782
 *
2783
 * @param int $start Which item to start with (for pagination purposes)
2784
 * @param int $items_per_page How many items to display on each page
2785
 * @param string $sort A string indicating how to sort the results
2786
 * @param int $memID The ID of the member
2787
 * @return array An array of information about the topics a user has subscribed to
2788
 */
2789
function list_getTopicNotifications($start, $items_per_page, $sort, $memID)
2790
{
2791
	global $smcFunc, $scripturl, $user_info, $modSettings, $sourcedir;
2792
2793
	require_once($sourcedir . '/Subs-Notify.php');
2794
	$prefs = getNotifyPrefs($memID);
2795
	$prefs = isset($prefs[$memID]) ? $prefs[$memID] : array();
2796
2797
	// All the topics with notification on...
2798
	$request = $smcFunc['db_query']('', '
2799
		SELECT
2800
			COALESCE(lt.id_msg, lmr.id_msg, -1) + 1 AS new_from, b.id_board, b.name,
2801
			t.id_topic, ms.subject, ms.id_member, COALESCE(mem.real_name, ms.poster_name) AS real_name_col,
2802
			ml.id_msg_modified, ml.poster_time, ml.id_member AS id_member_updated,
2803
			COALESCE(mem2.real_name, ml.poster_name) AS last_real_name,
2804
			lt.unwatched
2805
		FROM {db_prefix}log_notify AS ln
2806
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ln.id_topic' . ($modSettings['postmod_active'] ? ' AND t.approved = {int:is_approved}' : '') . ')
2807
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board AND {query_see_board})
2808
			INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
2809
			INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
2810
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ms.id_member)
2811
			LEFT JOIN {db_prefix}members AS mem2 ON (mem2.id_member = ml.id_member)
2812
			LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
2813
			LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = b.id_board AND lmr.id_member = {int:current_member})
2814
		WHERE ln.id_member = {int:selected_member}
2815
		ORDER BY {raw:sort}
2816
		LIMIT {int:offset}, {int:items_per_page}',
2817
		array(
2818
			'current_member' => $user_info['id'],
2819
			'is_approved' => 1,
2820
			'selected_member' => $memID,
2821
			'sort' => $sort,
2822
			'offset' => $start,
2823
			'items_per_page' => $items_per_page,
2824
		)
2825
	);
2826
	$notification_topics = array();
2827
	while ($row = $smcFunc['db_fetch_assoc']($request))
2828
	{
2829
		censorText($row['subject']);
2830
2831
		$notification_topics[] = array(
2832
			'id' => $row['id_topic'],
2833
			'poster_link' => empty($row['id_member']) ? $row['real_name_col'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name_col'] . '</a>',
2834
			'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>',
2835
			'subject' => $row['subject'],
2836
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
2837
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['subject'] . '</a>',
2838
			'new' => $row['new_from'] <= $row['id_msg_modified'],
2839
			'new_from' => $row['new_from'],
2840
			'updated' => timeformat($row['poster_time']),
2841
			'new_href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['new_from'] . '#new',
2842
			'new_link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['new_from'] . '#new">' . $row['subject'] . '</a>',
2843
			'board_link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['name'] . '</a>',
2844
			'notify_pref' => isset($prefs['topic_notify_' . $row['id_topic']]) ? $prefs['topic_notify_' . $row['id_topic']] : (!empty($prefs['topic_notify']) ? $prefs['topic_notify'] : 0),
2845
			'unwatched' => $row['unwatched'],
2846
		);
2847
	}
2848
	$smcFunc['db_free_result']($request);
2849
2850
	return $notification_topics;
2851
}
2852
2853
/**
2854
 * Gets information about all the boards a user has requested notifications for. Callback for the list in alert_notifications_boards
2855
 *
2856
 * @param int $start Which item to start with (not used here)
2857
 * @param int $items_per_page How many items to show on each page (not used here)
2858
 * @param string $sort A string indicating how to sort the results
2859
 * @param int $memID The ID of the member
2860
 * @return array An array of information about all the boards a user is subscribed to
2861
 */
2862
function list_getBoardNotifications($start, $items_per_page, $sort, $memID)
2863
{
2864
	global $smcFunc, $scripturl, $user_info, $sourcedir;
2865
2866
	require_once($sourcedir . '/Subs-Notify.php');
2867
	$prefs = getNotifyPrefs($memID);
2868
	$prefs = isset($prefs[$memID]) ? $prefs[$memID] : array();
2869
2870
	$request = $smcFunc['db_query']('', '
2871
		SELECT b.id_board, b.name, COALESCE(lb.id_msg, 0) AS board_read, b.id_msg_updated
2872
		FROM {db_prefix}log_notify AS ln
2873
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = ln.id_board)
2874
			LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = b.id_board AND lb.id_member = {int:current_member})
2875
		WHERE ln.id_member = {int:selected_member}
2876
			AND {query_see_board}
2877
		ORDER BY {raw:sort}',
2878
		array(
2879
			'current_member' => $user_info['id'],
2880
			'selected_member' => $memID,
2881
			'sort' => $sort,
2882
		)
2883
	);
2884
	$notification_boards = array();
2885
	while ($row = $smcFunc['db_fetch_assoc']($request))
2886
		$notification_boards[] = array(
2887
			'id' => $row['id_board'],
2888
			'name' => $row['name'],
2889
			'href' => $scripturl . '?board=' . $row['id_board'] . '.0',
2890
			'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['name'] . '</a>',
2891
			'new' => $row['board_read'] < $row['id_msg_updated'],
2892
			'notify_pref' => isset($prefs['board_notify_' . $row['id_board']]) ? $prefs['board_notify_' . $row['id_board']] : (!empty($prefs['board_notify']) ? $prefs['board_notify'] : 0),
2893
		);
2894
	$smcFunc['db_free_result']($request);
2895
2896
	return $notification_boards;
2897
}
2898
2899
/**
2900
 * Loads the theme options for a user
2901
 *
2902
 * @param int $memID The ID of the member
2903
 * @param bool $defaultSettings If true, we are loading default options.
2904
 */
2905
function loadThemeOptions($memID, $defaultSettings = false)
2906
{
2907
	global $context, $options, $cur_profile, $smcFunc;
2908
2909
	if (isset($_POST['default_options']))
2910
		$_POST['options'] = isset($_POST['options']) ? $_POST['options'] + $_POST['default_options'] : $_POST['default_options'];
2911
2912
	if ($context['user']['is_owner'])
2913
	{
2914
		$context['member']['options'] = $options;
2915
		if (isset($_POST['options']) && is_array($_POST['options']))
2916
			foreach ($_POST['options'] as $k => $v)
2917
				$context['member']['options'][$k] = $v;
2918
	}
2919
	else
2920
	{
2921
		$request = $smcFunc['db_query']('', '
2922
			SELECT id_member, variable, value
2923
			FROM {db_prefix}themes
2924
			WHERE id_theme IN (1, {int:member_theme})
2925
				AND id_member IN (-1, {int:selected_member})',
2926
			array(
2927
				'member_theme' => !isset($cur_profile['id_theme']) && !empty($defaultSettings) ? 0 : (int) $cur_profile['id_theme'],
2928
				'selected_member' => $memID,
2929
			)
2930
		);
2931
		$temp = array();
2932
		while ($row = $smcFunc['db_fetch_assoc']($request))
2933
		{
2934
			if ($row['id_member'] == -1)
2935
			{
2936
				$temp[$row['variable']] = $row['value'];
2937
				continue;
2938
			}
2939
2940
			if (isset($_POST['options'][$row['variable']]))
2941
				$row['value'] = $_POST['options'][$row['variable']];
2942
			$context['member']['options'][$row['variable']] = $row['value'];
2943
		}
2944
		$smcFunc['db_free_result']($request);
2945
2946
		// Load up the default theme options for any missing.
2947
		foreach ($temp as $k => $v)
2948
		{
2949
			if (!isset($context['member']['options'][$k]))
2950
				$context['member']['options'][$k] = $v;
2951
		}
2952
	}
2953
}
2954
2955
/**
2956
 * Handles the "ignored boards" section of the profile (if enabled)
2957
 *
2958
 * @param int $memID The ID of the member
2959
 */
2960
function ignoreboards($memID)
2961
{
2962
	global $context, $modSettings, $smcFunc, $cur_profile, $sourcedir;
2963
2964
	// Have the admins enabled this option?
2965
	if (empty($modSettings['allow_ignore_boards']))
2966
		fatal_lang_error('ignoreboards_disallowed', 'user');
2967
2968
	// Find all the boards this user is allowed to see.
2969
	$request = $smcFunc['db_query']('order_by_board_order', '
2970
		SELECT b.id_cat, c.name AS cat_name, b.id_board, b.name, b.child_level,
2971
			' . (!empty($cur_profile['ignore_boards']) ? 'b.id_board IN ({array_int:ignore_boards})' : '0') . ' AS is_ignored
2972
		FROM {db_prefix}boards AS b
2973
			LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
2974
		WHERE {query_see_board}
2975
			AND redirect = {string:empty_string}',
2976
		array(
2977
			'ignore_boards' => !empty($cur_profile['ignore_boards']) ? explode(',', $cur_profile['ignore_boards']) : array(),
2978
			'empty_string' => '',
2979
		)
2980
	);
2981
	$context['num_boards'] = $smcFunc['db_num_rows']($request);
2982
	$context['categories'] = array();
2983
	while ($row = $smcFunc['db_fetch_assoc']($request))
2984
	{
2985
		// This category hasn't been set up yet..
2986
		if (!isset($context['categories'][$row['id_cat']]))
2987
			$context['categories'][$row['id_cat']] = array(
2988
				'id' => $row['id_cat'],
2989
				'name' => $row['cat_name'],
2990
				'boards' => array()
2991
			);
2992
2993
		// Set this board up, and let the template know when it's a child.  (indent them..)
2994
		$context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array(
2995
			'id' => $row['id_board'],
2996
			'name' => $row['name'],
2997
			'child_level' => $row['child_level'],
2998
			'selected' => $row['is_ignored'],
2999
		);
3000
	}
3001
	$smcFunc['db_free_result']($request);
3002
3003
	require_once($sourcedir . '/Subs-Boards.php');
3004
	sortCategories($context['categories']);
3005
3006
	// Now, let's sort the list of categories into the boards for templates that like that.
3007
	$temp_boards = array();
3008
	foreach ($context['categories'] as $category)
3009
	{
3010
		// Include a list of boards per category for easy toggling.
3011
		$context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']);
3012
3013
		$temp_boards[] = array(
3014
			'name' => $category['name'],
3015
			'child_ids' => array_keys($category['boards'])
3016
		);
3017
		$temp_boards = array_merge($temp_boards, array_values($category['boards']));
3018
	}
3019
3020
	$max_boards = ceil(count($temp_boards) / 2);
3021
	if ($max_boards == 1)
3022
		$max_boards = 2;
3023
3024
	// Now, alternate them so they can be shown left and right ;).
3025
	$context['board_columns'] = array();
3026
	for ($i = 0; $i < $max_boards; $i++)
3027
	{
3028
		$context['board_columns'][] = $temp_boards[$i];
3029
		if (isset($temp_boards[$i + $max_boards]))
3030
			$context['board_columns'][] = $temp_boards[$i + $max_boards];
3031
		else
3032
			$context['board_columns'][] = array();
3033
	}
3034
3035
	loadThemeOptions($memID);
3036
}
3037
3038
/**
3039
 * Load all the languages for the profile
3040
 * .
3041
 * @return bool Whether or not the forum has multiple languages installed
3042
 */
3043
function profileLoadLanguages()
3044
{
3045
	global $context;
3046
3047
	$context['profile_languages'] = array();
3048
3049
	// Get our languages!
3050
	getLanguages();
3051
3052
	// Setup our languages.
3053
	foreach ($context['languages'] as $lang)
3054
	{
3055
		$context['profile_languages'][$lang['filename']] = strtr($lang['name'], array('-utf8' => ''));
3056
	}
3057
	ksort($context['profile_languages']);
3058
3059
	// Return whether we should proceed with this.
3060
	return count($context['profile_languages']) > 1 ? true : false;
3061
}
3062
3063
/**
3064
 * Handles the "manage groups" section of the profile
3065
 *
3066
 * @return true Always returns true
3067
 */
3068
function profileLoadGroups()
3069
{
3070
	global $cur_profile, $txt, $context, $smcFunc, $user_settings;
3071
3072
	$context['member_groups'] = array(
3073
		0 => array(
3074
			'id' => 0,
3075
			'name' => $txt['no_primary_membergroup'],
3076
			'is_primary' => $cur_profile['id_group'] == 0,
3077
			'can_be_additional' => false,
3078
			'can_be_primary' => true,
3079
		)
3080
	);
3081
	$curGroups = explode(',', $cur_profile['additional_groups']);
3082
3083
	// Load membergroups, but only those groups the user can assign.
3084
	$request = $smcFunc['db_query']('', '
3085
		SELECT group_name, id_group, hidden
3086
		FROM {db_prefix}membergroups
3087
		WHERE id_group != {int:moderator_group}
3088
			AND min_posts = {int:min_posts}' . (allowedTo('admin_forum') ? '' : '
3089
			AND group_type != {int:is_protected}') . '
3090
		ORDER BY min_posts, CASE WHEN id_group < {int:newbie_group} THEN id_group ELSE 4 END, group_name',
3091
		array(
3092
			'moderator_group' => 3,
3093
			'min_posts' => -1,
3094
			'is_protected' => 1,
3095
			'newbie_group' => 4,
3096
		)
3097
	);
3098
	while ($row = $smcFunc['db_fetch_assoc']($request))
3099
	{
3100
		// We should skip the administrator group if they don't have the admin_forum permission!
3101
		if ($row['id_group'] == 1 && !allowedTo('admin_forum'))
3102
			continue;
3103
3104
		$context['member_groups'][$row['id_group']] = array(
3105
			'id' => $row['id_group'],
3106
			'name' => $row['group_name'],
3107
			'is_primary' => $cur_profile['id_group'] == $row['id_group'],
3108
			'is_additional' => in_array($row['id_group'], $curGroups),
3109
			'can_be_additional' => true,
3110
			'can_be_primary' => $row['hidden'] != 2,
3111
		);
3112
	}
3113
	$smcFunc['db_free_result']($request);
3114
3115
	$context['member']['group_id'] = $user_settings['id_group'];
3116
3117
	return true;
3118
}
3119
3120
/**
3121
 * Load key signature context data.
3122
 *
3123
 * @return true Always returns true
3124
 */
3125
function profileLoadSignatureData()
3126
{
3127
	global $modSettings, $context, $txt, $cur_profile, $memberContext;
3128
3129
	// Signature limits.
3130
	list ($sig_limits, $sig_bbc) = explode(':', $modSettings['signature_settings']);
3131
	$sig_limits = explode(',', $sig_limits);
3132
3133
	$context['signature_enabled'] = isset($sig_limits[0]) ? $sig_limits[0] : 0;
3134
	$context['signature_limits'] = array(
3135
		'max_length' => isset($sig_limits[1]) ? $sig_limits[1] : 0,
3136
		'max_lines' => isset($sig_limits[2]) ? $sig_limits[2] : 0,
3137
		'max_images' => isset($sig_limits[3]) ? $sig_limits[3] : 0,
3138
		'max_smileys' => isset($sig_limits[4]) ? $sig_limits[4] : 0,
3139
		'max_image_width' => isset($sig_limits[5]) ? $sig_limits[5] : 0,
3140
		'max_image_height' => isset($sig_limits[6]) ? $sig_limits[6] : 0,
3141
		'max_font_size' => isset($sig_limits[7]) ? $sig_limits[7] : 0,
3142
		'bbc' => !empty($sig_bbc) ? explode(',', $sig_bbc) : array(),
3143
	);
3144
	// Kept this line in for backwards compatibility!
3145
	$context['max_signature_length'] = $context['signature_limits']['max_length'];
3146
	// Warning message for signature image limits?
3147
	$context['signature_warning'] = '';
3148
	if ($context['signature_limits']['max_image_width'] && $context['signature_limits']['max_image_height'])
3149
		$context['signature_warning'] = sprintf($txt['profile_error_signature_max_image_size'], $context['signature_limits']['max_image_width'], $context['signature_limits']['max_image_height']);
3150
	elseif ($context['signature_limits']['max_image_width'] || $context['signature_limits']['max_image_height'])
3151
		$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']);
3152
3153
	$context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && (function_exists('pspell_new') || (function_exists('enchant_broker_init') && ($txt['lang_character_set'] == 'UTF-8' || function_exists('iconv'))));
3154
3155
	if (empty($context['do_preview']))
3156
		$context['member']['signature'] = empty($cur_profile['signature']) ? '' : str_replace(array('<br>', '<', '>', '"', '\''), array("\n", '&lt;', '&gt;', '&quot;', '&#039;'), $cur_profile['signature']);
3157
	else
3158
	{
3159
		$signature = !empty($_POST['signature']) ? $_POST['signature'] : '';
3160
		$validation = profileValidateSignature($signature);
3161
		if (empty($context['post_errors']))
3162
		{
3163
			loadLanguage('Errors');
3164
			$context['post_errors'] = array();
3165
		}
3166
		$context['post_errors'][] = 'signature_not_yet_saved';
3167
		if ($validation !== true && $validation !== false)
3168
			$context['post_errors'][] = $validation;
3169
3170
		censorText($context['member']['signature']);
3171
		$context['member']['current_signature'] = $context['member']['signature'];
3172
		censorText($signature);
3173
		$context['member']['signature_preview'] = parse_bbc($signature, true, 'sig' . $memberContext[$context['id_member']]);
3174
		$context['member']['signature'] = $_POST['signature'];
3175
	}
3176
3177
	// Load the spell checker?
3178
	if ($context['show_spellchecking'])
3179
		loadJavaScriptFile('spellcheck.js', array('defer' => false, 'minimize' => true), 'smf_spellcheck');
3180
3181
	return true;
3182
}
3183
3184
/**
3185
 * Load avatar context data.
3186
 *
3187
 * @return true Always returns true
3188
 */
3189
function profileLoadAvatarData()
3190
{
3191
	global $context, $cur_profile, $modSettings, $scripturl;
3192
3193
	$context['avatar_url'] = $modSettings['avatar_url'];
3194
3195
	// Default context.
3196
	$context['member']['avatar'] += array(
3197
		'custom' => stristr($cur_profile['avatar'], 'http://') || stristr($cur_profile['avatar'], 'https://') ? $cur_profile['avatar'] : 'http://',
3198
		'selection' => $cur_profile['avatar'] == '' || (stristr($cur_profile['avatar'], 'http://') || stristr($cur_profile['avatar'], 'https://')) ? '' : $cur_profile['avatar'],
3199
		'allow_server_stored' => (empty($modSettings['gravatarEnabled']) || empty($modSettings['gravatarOverride'])) && (allowedTo('profile_server_avatar') || (!$context['user']['is_owner'] && allowedTo('profile_extra_any'))),
3200
		'allow_upload' => (empty($modSettings['gravatarEnabled']) || empty($modSettings['gravatarOverride'])) && (allowedTo('profile_upload_avatar') || (!$context['user']['is_owner'] && allowedTo('profile_extra_any'))),
3201
		'allow_external' => (empty($modSettings['gravatarEnabled']) || empty($modSettings['gravatarOverride'])) && (allowedTo('profile_remote_avatar') || (!$context['user']['is_owner'] && allowedTo('profile_extra_any'))),
3202
		'allow_gravatar' => !empty($modSettings['gravatarEnabled']) || !empty($modSettings['gravatarOverride']),
3203
	);
3204
3205
	if ($context['member']['avatar']['allow_gravatar'] && (stristr($cur_profile['avatar'], 'gravatar://') || !empty($modSettings['gravatarOverride'])))
3206
	{
3207
		$context['member']['avatar'] += array(
3208
			'choice' => 'gravatar',
3209
			'server_pic' => 'blank.png',
3210
			'external' => $cur_profile['avatar'] == 'gravatar://' || empty($modSettings['gravatarAllowExtraEmail']) || !empty($modSettings['gravatarOverride']) ? $cur_profile['email_address'] : substr($cur_profile['avatar'], 11)
3211
		);
3212
		$context['member']['avatar']['href'] = get_gravatar_url($context['member']['avatar']['external']);
3213
	}
3214
	elseif ($cur_profile['avatar'] == '' && $cur_profile['id_attach'] > 0 && $context['member']['avatar']['allow_upload'])
3215
	{
3216
		$context['member']['avatar'] += array(
3217
			'choice' => 'upload',
3218
			'server_pic' => 'blank.png',
3219
			'external' => 'http://'
3220
		);
3221
		$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'];
3222
	}
3223
	// Use "avatar_original" here so we show what the user entered even if the image proxy is enabled
3224
	elseif ((stristr($cur_profile['avatar'], 'http://') || stristr($cur_profile['avatar'], 'https://')) && $context['member']['avatar']['allow_external'])
3225
		$context['member']['avatar'] += array(
3226
			'choice' => 'external',
3227
			'server_pic' => 'blank.png',
3228
			'external' => $cur_profile['avatar_original']
3229
		);
3230
	elseif ($cur_profile['avatar'] != '' && file_exists($modSettings['avatar_directory'] . '/' . $cur_profile['avatar']) && $context['member']['avatar']['allow_server_stored'])
3231
		$context['member']['avatar'] += array(
3232
			'choice' => 'server_stored',
3233
			'server_pic' => $cur_profile['avatar'] == '' ? 'blank.png' : $cur_profile['avatar'],
3234
			'external' => 'http://'
3235
		);
3236
	else
3237
		$context['member']['avatar'] += array(
3238
			'choice' => 'none',
3239
			'server_pic' => 'blank.png',
3240
			'external' => 'http://'
3241
		);
3242
3243
	// Get a list of all the avatars.
3244
	if ($context['member']['avatar']['allow_server_stored'])
3245
	{
3246
		$context['avatar_list'] = array();
3247
		$context['avatars'] = is_dir($modSettings['avatar_directory']) ? getAvatars('', 0) : array();
3248
	}
3249
	else
3250
		$context['avatars'] = array();
3251
3252
	// Second level selected avatar...
3253
	$context['avatar_selected'] = substr(strrchr($context['member']['avatar']['server_pic'], '/'), 1);
3254
	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']);
3255
}
3256
3257
/**
3258
 * Save a members group.
3259
 *
3260
 * @param int &$value The ID of the (new) primary group
3261
 * @return true Always returns true
3262
 */
3263
function profileSaveGroups(&$value)
3264
{
3265
	global $profile_vars, $old_profile, $context, $smcFunc, $cur_profile;
3266
3267
	// Do we need to protect some groups?
3268
	if (!allowedTo('admin_forum'))
3269
	{
3270
		$request = $smcFunc['db_query']('', '
3271
			SELECT id_group
3272
			FROM {db_prefix}membergroups
3273
			WHERE group_type = {int:is_protected}',
3274
			array(
3275
				'is_protected' => 1,
3276
			)
3277
		);
3278
		$protected_groups = array(1);
3279
		while ($row = $smcFunc['db_fetch_assoc']($request))
3280
			$protected_groups[] = $row['id_group'];
3281
		$smcFunc['db_free_result']($request);
3282
3283
		$protected_groups = array_unique($protected_groups);
3284
	}
3285
3286
	// The account page allows the change of your id_group - but not to a protected group!
3287
	if (empty($protected_groups) || count(array_intersect(array((int) $value, $old_profile['id_group']), $protected_groups)) == 0)
3288
		$value = (int) $value;
3289
	// ... otherwise it's the old group sir.
3290
	else
3291
		$value = $old_profile['id_group'];
3292
3293
	// Find the additional membergroups (if any)
3294
	if (isset($_POST['additional_groups']) && is_array($_POST['additional_groups']))
3295
	{
3296
		$additional_groups = array();
3297
		foreach ($_POST['additional_groups'] as $group_id)
3298
		{
3299
			$group_id = (int) $group_id;
3300
			if (!empty($group_id) && (empty($protected_groups) || !in_array($group_id, $protected_groups)))
3301
				$additional_groups[] = $group_id;
3302
		}
3303
3304
		// Put the protected groups back in there if you don't have permission to take them away.
3305
		$old_additional_groups = explode(',', $old_profile['additional_groups']);
3306
		foreach ($old_additional_groups as $group_id)
3307
		{
3308
			if (!empty($protected_groups) && in_array($group_id, $protected_groups))
3309
				$additional_groups[] = $group_id;
3310
		}
3311
3312
		if (implode(',', $additional_groups) !== $old_profile['additional_groups'])
3313
		{
3314
			$profile_vars['additional_groups'] = implode(',', $additional_groups);
3315
			$cur_profile['additional_groups'] = implode(',', $additional_groups);
3316
		}
3317
	}
3318
3319
	// Too often, people remove delete their own account, or something.
3320
	if (in_array(1, explode(',', $old_profile['additional_groups'])) || $old_profile['id_group'] == 1)
3321
	{
3322
		$stillAdmin = $value == 1 || (isset($additional_groups) && in_array(1, $additional_groups));
3323
3324
		// If they would no longer be an admin, look for any other...
3325
		if (!$stillAdmin)
3326
		{
3327
			$request = $smcFunc['db_query']('', '
3328
				SELECT id_member
3329
				FROM {db_prefix}members
3330
				WHERE (id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0)
3331
					AND id_member != {int:selected_member}
3332
				LIMIT 1',
3333
				array(
3334
					'admin_group' => 1,
3335
					'selected_member' => $context['id_member'],
3336
				)
3337
			);
3338
			list ($another) = $smcFunc['db_fetch_row']($request);
3339
			$smcFunc['db_free_result']($request);
3340
3341
			if (empty($another))
3342
				fatal_lang_error('at_least_one_admin', 'critical');
3343
		}
3344
	}
3345
3346
	// If we are changing group status, update permission cache as necessary.
3347
	if ($value != $old_profile['id_group'] || isset($profile_vars['additional_groups']))
3348
	{
3349
		if ($context['user']['is_owner'])
3350
			$_SESSION['mc']['time'] = 0;
3351
		else
3352
			updateSettings(array('settings_updated' => time()));
3353
	}
3354
3355
	// Announce to any hooks that we have changed groups, but don't allow them to change it.
3356
	call_integration_hook('integrate_profile_profileSaveGroups', array($value, $additional_groups));
3357
3358
	return true;
3359
}
3360
3361
/**
3362
 * The avatar is incredibly complicated, what with the options... and what not.
3363
 *
3364
 * @todo argh, the avatar here. Take this out of here!
3365
 *
3366
 * @param string &$value What kind of avatar we're expecting. Can be 'none', 'server_stored', 'gravatar', 'external' or 'upload'
3367
 * @return bool|string False if success (or if memID is empty and password authentication failed), otherwise a string indicating what error occurred
3368
 */
3369
function profileSaveAvatarData(&$value)
3370
{
3371
	global $modSettings, $sourcedir, $smcFunc, $profile_vars, $cur_profile, $context;
3372
3373
	$memID = $context['id_member'];
3374
	$context['max_external_size_url'] = 255;
3375
3376
	if (empty($memID) && !empty($context['password_auth_failed']))
3377
		return false;
3378
3379
	require_once($sourcedir . '/ManageAttachments.php');
3380
3381
	call_integration_hook('before_profile_save_avatar', array(&$value));
3382
3383
	// External url too large
3384
	if ($value == 'external' && allowedTo('profile_remote_avatar') && strlen($_POST['userpicpersonal']) > $context['max_external_size_url'])
3385
		return 'bad_avatar_url_too_long';
3386
3387
	// We're going to put this on a nice custom dir.
3388
	$uploadDir = $modSettings['custom_avatar_dir'];
3389
	$id_folder = 1;
3390
3391
	$downloadedExternalAvatar = false;
3392
	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']))
3393
	{
3394
		if (!is_writable($uploadDir))
3395
			fatal_lang_error('attachments_no_write', 'critical');
3396
3397
		$url = parse_url($_POST['userpicpersonal']);
3398
		$contents = fetch_web_data($url['scheme'] . '://' . $url['host'] . (empty($url['port']) ? '' : ':' . $url['port']) . str_replace(' ', '%20', trim($url['path'])));
3399
3400
		$new_filename = $uploadDir . '/' . getAttachmentFilename('avatar_tmp_' . $memID, false, null, true);
3401
		if ($contents != false && $tmpAvatar = fopen($new_filename, 'wb'))
3402
		{
3403
			fwrite($tmpAvatar, $contents);
3404
			fclose($tmpAvatar);
3405
3406
			$downloadedExternalAvatar = true;
3407
			$_FILES['attachment']['tmp_name'] = $new_filename;
3408
		}
3409
	}
3410
3411
	// Removes whatever attachment there was before updating
3412
	if ($value == 'none')
3413
	{
3414
		$profile_vars['avatar'] = '';
3415
3416
		// Reset the attach ID.
3417
		$cur_profile['id_attach'] = 0;
3418
		$cur_profile['attachment_type'] = 0;
3419
		$cur_profile['filename'] = '';
3420
3421
		removeAttachments(array('id_member' => $memID));
3422
	}
3423
3424
	// An avatar from the server-stored galleries.
3425
	elseif ($value == 'server_stored' && allowedTo('profile_server_avatar'))
3426
	{
3427
		$profile_vars['avatar'] = strtr(empty($_POST['file']) ? (empty($_POST['cat']) ? '' : $_POST['cat']) : $_POST['file'], array('&amp;' => '&'));
3428
		$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']) : '';
3429
3430
		// Clear current profile...
3431
		$cur_profile['id_attach'] = 0;
3432
		$cur_profile['attachment_type'] = 0;
3433
		$cur_profile['filename'] = '';
3434
3435
		// Get rid of their old avatar. (if uploaded.)
3436
		removeAttachments(array('id_member' => $memID));
3437
	}
3438
	elseif ($value == 'gravatar' && !empty($modSettings['gravatarEnabled']))
3439
	{
3440
		// 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.
3441
		if (empty($_POST['gravatarEmail']) || empty($modSettings['gravatarAllowExtraEmail']) || !filter_var($_POST['gravatarEmail'], FILTER_VALIDATE_EMAIL))
3442
			$profile_vars['avatar'] = 'gravatar://';
3443
		else
3444
			$profile_vars['avatar'] = 'gravatar://' . ($_POST['gravatarEmail'] != $cur_profile['email_address'] ? $_POST['gravatarEmail'] : '');
3445
3446
		// Get rid of their old avatar. (if uploaded.)
3447
		removeAttachments(array('id_member' => $memID));
3448
	}
3449
	elseif ($value == 'external' && allowedTo('profile_remote_avatar') && (stripos($_POST['userpicpersonal'], 'http://') === 0 || stripos($_POST['userpicpersonal'], 'https://') === 0) && empty($modSettings['avatar_download_external']))
3450
	{
3451
		// We need these clean...
3452
		$cur_profile['id_attach'] = 0;
3453
		$cur_profile['attachment_type'] = 0;
3454
		$cur_profile['filename'] = '';
3455
3456
		// Remove any attached avatar...
3457
		removeAttachments(array('id_member' => $memID));
3458
3459
		$profile_vars['avatar'] = str_replace(' ', '%20', preg_replace('~action(?:=|%3d)(?!dlattach)~i', 'action-', $_POST['userpicpersonal']));
3460
		$mime_valid = check_mime_type($profile_vars['avatar'], 'image/', true);
3461
3462
		if ($profile_vars['avatar'] == 'http://' || $profile_vars['avatar'] == 'http:///')
3463
			$profile_vars['avatar'] = '';
3464
		// Trying to make us do something we'll regret?
3465
		elseif (substr($profile_vars['avatar'], 0, 7) != 'http://' && substr($profile_vars['avatar'], 0, 8) != 'https://')
3466
			return 'bad_avatar_invalid_url';
3467
		elseif (empty($mime_valid))
3468
			return 'bad_avatar';
3469
		// Should we check dimensions?
3470
		elseif (!empty($modSettings['avatar_max_height_external']) || !empty($modSettings['avatar_max_width_external']))
3471
		{
3472
			// Now let's validate the avatar.
3473
			$sizes = url_image_size($profile_vars['avatar']);
3474
3475
			if (is_array($sizes) && (($sizes[0] > $modSettings['avatar_max_width_external']
3476
				&& !empty($modSettings['avatar_max_width_external'])) || ($sizes[1] > $modSettings['avatar_max_height_external']
3477
				&& !empty($modSettings['avatar_max_height_external']))))
3478
			{
3479
				// Houston, we have a problem. The avatar is too large!!
3480
				if ($modSettings['avatar_action_too_large'] == 'option_refuse')
3481
					return 'bad_avatar_too_large';
3482
				elseif ($modSettings['avatar_action_too_large'] == 'option_download_and_resize')
3483
				{
3484
					// @todo remove this if appropriate
3485
					require_once($sourcedir . '/Subs-Graphics.php');
3486
					if (downloadAvatar($profile_vars['avatar'], $memID, $modSettings['avatar_max_width_external'], $modSettings['avatar_max_height_external']))
3487
					{
3488
						$profile_vars['avatar'] = '';
3489
						$cur_profile['id_attach'] = $modSettings['new_avatar_data']['id'];
3490
						$cur_profile['filename'] = $modSettings['new_avatar_data']['filename'];
3491
						$cur_profile['attachment_type'] = $modSettings['new_avatar_data']['type'];
3492
					}
3493
					else
3494
						return 'bad_avatar';
3495
				}
3496
			}
3497
		}
3498
	}
3499
3500
	elseif (($value == 'upload' && allowedTo('profile_upload_avatar')) || $downloadedExternalAvatar)
3501
	{
3502
		if ((isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') || $downloadedExternalAvatar)
3503
		{
3504
			// Get the dimensions of the image.
3505
			if (!$downloadedExternalAvatar)
3506
			{
3507
				if (!is_writable($uploadDir))
3508
					fatal_lang_error('avatars_no_write', 'critical');
3509
3510
				$new_filename = $uploadDir . '/' . getAttachmentFilename('avatar_tmp_' . $memID, false, null, true);
3511
				if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $new_filename))
3512
					fatal_lang_error('attach_timeout', 'critical');
3513
3514
				$_FILES['attachment']['tmp_name'] = $new_filename;
3515
			}
3516
3517
			$mime_valid = check_mime_type($_FILES['attachment']['tmp_name'], 'image/', true);
3518
			$sizes = empty($mime_valid) ? false : @getimagesize($_FILES['attachment']['tmp_name']);
3519
3520
			// No size, then it's probably not a valid pic.
3521
			if ($sizes === false)
3522
			{
3523
				@unlink($_FILES['attachment']['tmp_name']);
3524
				return 'bad_avatar';
3525
			}
3526
			// Check whether the image is too large.
3527
			elseif ((!empty($modSettings['avatar_max_width_upload']) && $sizes[0] > $modSettings['avatar_max_width_upload'])
3528
				|| (!empty($modSettings['avatar_max_height_upload']) && $sizes[1] > $modSettings['avatar_max_height_upload']))
3529
			{
3530
				if (!empty($modSettings['avatar_resize_upload']))
3531
				{
3532
					// Attempt to chmod it.
3533
					smf_chmod($_FILES['attachment']['tmp_name'], 0644);
3534
3535
					// @todo remove this require when appropriate
3536
					require_once($sourcedir . '/Subs-Graphics.php');
3537
					if (!downloadAvatar($_FILES['attachment']['tmp_name'], $memID, $modSettings['avatar_max_width_upload'], $modSettings['avatar_max_height_upload']))
3538
					{
3539
						@unlink($_FILES['attachment']['tmp_name']);
3540
						return 'bad_avatar';
3541
					}
3542
3543
					// Reset attachment avatar data.
3544
					$cur_profile['id_attach'] = $modSettings['new_avatar_data']['id'];
3545
					$cur_profile['filename'] = $modSettings['new_avatar_data']['filename'];
3546
					$cur_profile['attachment_type'] = $modSettings['new_avatar_data']['type'];
3547
				}
3548
3549
				// Admin doesn't want to resize large avatars, can't do much about it but to tell you to use a different one :(
3550
				else
3551
				{
3552
					@unlink($_FILES['attachment']['tmp_name']);
3553
					return 'bad_avatar_too_large';
3554
				}
3555
			}
3556
3557
			// So far, so good, checks lies ahead!
3558
			elseif (is_array($sizes))
3559
			{
3560
				// Now try to find an infection.
3561
				require_once($sourcedir . '/Subs-Graphics.php');
3562
				if (!checkImageContents($_FILES['attachment']['tmp_name'], !empty($modSettings['avatar_paranoid'])))
3563
				{
3564
					// It's bad. Try to re-encode the contents?
3565
					if (empty($modSettings['avatar_reencode']) || (!reencodeImage($_FILES['attachment']['tmp_name'], $sizes[2])))
3566
					{
3567
						@unlink($_FILES['attachment']['tmp_name']);
3568
						return 'bad_avatar_fail_reencode';
3569
					}
3570
					// We were successful. However, at what price?
3571
					$sizes = @getimagesize($_FILES['attachment']['tmp_name']);
3572
					// Hard to believe this would happen, but can you bet?
3573
					if ($sizes === false)
3574
					{
3575
						@unlink($_FILES['attachment']['tmp_name']);
3576
						return 'bad_avatar';
3577
					}
3578
				}
3579
3580
				$extensions = array(
3581
					'1' => 'gif',
3582
					'2' => 'jpg',
3583
					'3' => 'png',
3584
					'6' => 'bmp'
3585
				);
3586
3587
				$extension = isset($extensions[$sizes[2]]) ? $extensions[$sizes[2]] : 'bmp';
3588
				$mime_type = 'image/' . ($extension === 'jpg' ? 'jpeg' : ($extension === 'bmp' ? 'x-ms-bmp' : $extension));
3589
				$destName = 'avatar_' . $memID . '_' . time() . '.' . $extension;
3590
				list ($width, $height) = getimagesize($_FILES['attachment']['tmp_name']);
3591
				$file_hash = '';
3592
3593
				// Remove previous attachments this member might have had.
3594
				removeAttachments(array('id_member' => $memID));
3595
3596
				$cur_profile['id_attach'] = $smcFunc['db_insert']('',
3597
					'{db_prefix}attachments',
3598
					array(
3599
						'id_member' => 'int', 'attachment_type' => 'int', 'filename' => 'string', 'file_hash' => 'string', 'fileext' => 'string', 'size' => 'int',
3600
						'width' => 'int', 'height' => 'int', 'mime_type' => 'string', 'id_folder' => 'int',
3601
					),
3602
					array(
3603
						$memID, 1, $destName, $file_hash, $extension, filesize($_FILES['attachment']['tmp_name']),
3604
						(int) $width, (int) $height, $mime_type, $id_folder,
3605
					),
3606
					array('id_attach'),
3607
					1
3608
				);
3609
3610
				$cur_profile['filename'] = $destName;
3611
				$cur_profile['attachment_type'] = 1;
3612
3613
				$destinationPath = $uploadDir . '/' . (empty($file_hash) ? $destName : $cur_profile['id_attach'] . '_' . $file_hash . '.dat');
3614
				if (!rename($_FILES['attachment']['tmp_name'], $destinationPath))
3615
				{
3616
					// I guess a man can try.
3617
					removeAttachments(array('id_member' => $memID));
3618
					fatal_lang_error('attach_timeout', 'critical');
3619
				}
3620
3621
				// Attempt to chmod it.
3622
				smf_chmod($uploadDir . '/' . $destinationPath, 0644);
3623
			}
3624
			$profile_vars['avatar'] = '';
3625
3626
			// Delete any temporary file.
3627
			if (file_exists($_FILES['attachment']['tmp_name']))
3628
				@unlink($_FILES['attachment']['tmp_name']);
3629
		}
3630
		// Selected the upload avatar option and had one already uploaded before or didn't upload one.
3631
		else
3632
			$profile_vars['avatar'] = '';
3633
	}
3634
	elseif ($value == 'gravatar' && allowedTo('profile_gravatar_avatar'))
3635
		$profile_vars['avatar'] = 'gravatar://www.gravatar.com/avatar/' . md5(strtolower(trim($cur_profile['email_address'])));
3636
3637
	else
3638
		$profile_vars['avatar'] = '';
3639
3640
	// Setup the profile variables so it shows things right on display!
3641
	$cur_profile['avatar'] = $profile_vars['avatar'];
3642
3643
	call_integration_hook('after_profile_save_avatar');
3644
3645
	return false;
3646
}
3647
3648
/**
3649
 * Validate the signature
3650
 *
3651
 * @param string &$value The new signature
3652
 * @return bool|string True if the signature passes the checks, otherwise a string indicating what the problem is
3653
 */
3654
function profileValidateSignature(&$value)
3655
{
3656
	global $sourcedir, $modSettings, $smcFunc, $txt;
3657
3658
	require_once($sourcedir . '/Subs-Post.php');
3659
3660
	// Admins can do whatever they hell they want!
3661
	if (!allowedTo('admin_forum'))
3662
	{
3663
		// Load all the signature limits.
3664
		list ($sig_limits, $sig_bbc) = explode(':', $modSettings['signature_settings']);
3665
		$sig_limits = explode(',', $sig_limits);
3666
		$disabledTags = !empty($sig_bbc) ? explode(',', $sig_bbc) : array();
3667
3668
		$unparsed_signature = strtr(un_htmlspecialchars($value), array("\r" => '', '&#039' => '\''));
3669
3670
		// Too many lines?
3671
		if (!empty($sig_limits[2]) && substr_count($unparsed_signature, "\n") >= $sig_limits[2])
3672
		{
3673
			$txt['profile_error_signature_max_lines'] = sprintf($txt['profile_error_signature_max_lines'], $sig_limits[2]);
3674
			return 'signature_max_lines';
3675
		}
3676
3677
		// Too many images?!
3678
		if (!empty($sig_limits[3]) && (substr_count(strtolower($unparsed_signature), '[img') + substr_count(strtolower($unparsed_signature), '<img')) > $sig_limits[3])
3679
		{
3680
			$txt['profile_error_signature_max_image_count'] = sprintf($txt['profile_error_signature_max_image_count'], $sig_limits[3]);
3681
			return 'signature_max_image_count';
3682
		}
3683
3684
		// What about too many smileys!
3685
		$smiley_parsed = $unparsed_signature;
3686
		parsesmileys($smiley_parsed);
3687
		$smiley_count = substr_count(strtolower($smiley_parsed), '<img') - substr_count(strtolower($unparsed_signature), '<img');
3688
		if (!empty($sig_limits[4]) && $sig_limits[4] == -1 && $smiley_count > 0)
3689
			return 'signature_allow_smileys';
3690
		elseif (!empty($sig_limits[4]) && $sig_limits[4] > 0 && $smiley_count > $sig_limits[4])
3691
		{
3692
			$txt['profile_error_signature_max_smileys'] = sprintf($txt['profile_error_signature_max_smileys'], $sig_limits[4]);
3693
			return 'signature_max_smileys';
3694
		}
3695
3696
		// Maybe we are abusing font sizes?
3697
		if (!empty($sig_limits[7]) && preg_match_all('~\[size=([\d\.]+)?(px|pt|em|x-large|larger)~i', $unparsed_signature, $matches) !== false && isset($matches[2]))
3698
		{
3699
			foreach ($matches[1] as $ind => $size)
3700
			{
3701
				$limit_broke = 0;
3702
				// Attempt to allow all sizes of abuse, so to speak.
3703
				if ($matches[2][$ind] == 'px' && $size > $sig_limits[7])
3704
					$limit_broke = $sig_limits[7] . 'px';
3705
				elseif ($matches[2][$ind] == 'pt' && $size > ($sig_limits[7] * 0.75))
3706
					$limit_broke = ((int) $sig_limits[7] * 0.75) . 'pt';
3707
				elseif ($matches[2][$ind] == 'em' && $size > ((float) $sig_limits[7] / 16))
3708
					$limit_broke = ((float) $sig_limits[7] / 16) . 'em';
3709
				elseif ($matches[2][$ind] != 'px' && $matches[2][$ind] != 'pt' && $matches[2][$ind] != 'em' && $sig_limits[7] < 18)
3710
					$limit_broke = 'large';
3711
3712
				if ($limit_broke)
3713
				{
3714
					$txt['profile_error_signature_max_font_size'] = sprintf($txt['profile_error_signature_max_font_size'], $limit_broke);
3715
					return 'signature_max_font_size';
3716
				}
3717
			}
3718
		}
3719
3720
		// The difficult one - image sizes! Don't error on this - just fix it.
3721
		if ((!empty($sig_limits[5]) || !empty($sig_limits[6])))
3722
		{
3723
			// Get all BBC tags...
3724
			preg_match_all('~\[img(\s+width=([\d]+))?(\s+height=([\d]+))?(\s+width=([\d]+))?\s*\](?:<br>)*([^<">]+?)(?:<br>)*\[/img\]~i', $unparsed_signature, $matches);
3725
			// ... and all HTML ones.
3726
			preg_match_all('~<img\s+src=(?:")?((?:http://|ftp://|https://|ftps://).+?)(?:")?(?:\s+alt=(?:")?(.*?)(?:")?)?(?:\s?/)?' . '>~i', $unparsed_signature, $matches2, PREG_PATTERN_ORDER);
3727
			// And stick the HTML in the BBC.
3728
			if (!empty($matches2))
3729
			{
3730
				foreach ($matches2[0] as $ind => $dummy)
3731
				{
3732
					$matches[0][] = $matches2[0][$ind];
3733
					$matches[1][] = '';
3734
					$matches[2][] = '';
3735
					$matches[3][] = '';
3736
					$matches[4][] = '';
3737
					$matches[5][] = '';
3738
					$matches[6][] = '';
3739
					$matches[7][] = $matches2[1][$ind];
3740
				}
3741
			}
3742
3743
			$replaces = array();
3744
			// Try to find all the images!
3745
			if (!empty($matches))
3746
			{
3747
				foreach ($matches[0] as $key => $image)
3748
				{
3749
					$width = -1;
3750
					$height = -1;
3751
3752
					// Does it have predefined restraints? Width first.
3753
					if ($matches[6][$key])
3754
						$matches[2][$key] = $matches[6][$key];
3755
					if ($matches[2][$key] && $sig_limits[5] && $matches[2][$key] > $sig_limits[5])
3756
					{
3757
						$width = $sig_limits[5];
3758
						$matches[4][$key] = $matches[4][$key] * ($width / $matches[2][$key]);
3759
					}
3760
					elseif ($matches[2][$key])
3761
						$width = $matches[2][$key];
3762
					// ... and height.
3763
					if ($matches[4][$key] && $sig_limits[6] && $matches[4][$key] > $sig_limits[6])
3764
					{
3765
						$height = $sig_limits[6];
3766
						if ($width != -1)
3767
							$width = $width * ($height / $matches[4][$key]);
3768
					}
3769
					elseif ($matches[4][$key])
3770
						$height = $matches[4][$key];
3771
3772
					// If the dimensions are still not fixed - we need to check the actual image.
3773
					if (($width == -1 && $sig_limits[5]) || ($height == -1 && $sig_limits[6]))
3774
					{
3775
						$sizes = url_image_size($matches[7][$key]);
3776
						if (is_array($sizes))
3777
						{
3778
							// Too wide?
3779
							if ($sizes[0] > $sig_limits[5] && $sig_limits[5])
3780
							{
3781
								$width = $sig_limits[5];
3782
								$sizes[1] = $sizes[1] * ($width / $sizes[0]);
3783
							}
3784
							// Too high?
3785
							if ($sizes[1] > $sig_limits[6] && $sig_limits[6])
3786
							{
3787
								$height = $sig_limits[6];
3788
								if ($width == -1)
3789
									$width = $sizes[0];
3790
								$width = $width * ($height / $sizes[1]);
3791
							}
3792
							elseif ($width != -1)
3793
								$height = $sizes[1];
3794
						}
3795
					}
3796
3797
					// Did we come up with some changes? If so remake the string.
3798
					if ($width != -1 || $height != -1)
3799
						$replaces[$image] = '[img' . ($width != -1 ? ' width=' . round($width) : '') . ($height != -1 ? ' height=' . round($height) : '') . ']' . $matches[7][$key] . '[/img]';
3800
				}
3801
				if (!empty($replaces))
3802
					$value = str_replace(array_keys($replaces), array_values($replaces), $value);
3803
			}
3804
		}
3805
3806
		// Any disabled BBC?
3807
		$disabledSigBBC = implode('|', $disabledTags);
3808
		if (!empty($disabledSigBBC))
3809
		{
3810
			if (preg_match('~\[(' . $disabledSigBBC . '[ =\]/])~i', $unparsed_signature, $matches) !== false && isset($matches[1]))
3811
			{
3812
				$disabledTags = array_unique($disabledTags);
3813
				$txt['profile_error_signature_disabled_bbc'] = sprintf($txt['profile_error_signature_disabled_bbc'], implode(', ', $disabledTags));
3814
				return 'signature_disabled_bbc';
3815
			}
3816
		}
3817
	}
3818
3819
	preparsecode($value);
3820
3821
	// Too long?
3822
	if (!allowedTo('admin_forum') && !empty($sig_limits[1]) && $smcFunc['strlen'](str_replace('<br>', "\n", $value)) > $sig_limits[1])
3823
	{
3824
		$_POST['signature'] = trim($smcFunc['htmlspecialchars'](str_replace('<br>', "\n", $value), ENT_QUOTES));
3825
		$txt['profile_error_signature_max_length'] = sprintf($txt['profile_error_signature_max_length'], $sig_limits[1]);
3826
		return 'signature_max_length';
3827
	}
3828
3829
	return true;
3830
}
3831
3832
/**
3833
 * Validate an email address.
3834
 *
3835
 * @param string $email The email address to validate
3836
 * @param int $memID The ID of the member (used to prevent false positives from the current user)
3837
 * @return bool|string True if the email is valid, otherwise a string indicating what the problem is
3838
 */
3839
function profileValidateEmail($email, $memID = 0)
3840
{
3841
	global $smcFunc;
3842
3843
	$email = strtr($email, array('&#039;' => '\''));
3844
3845
	// Check the name and email for validity.
3846
	if (trim($email) == '')
3847
		return 'no_email';
3848
	if (!filter_var($email, FILTER_VALIDATE_EMAIL))
3849
		return 'bad_email';
3850
3851
	// Email addresses should be and stay unique.
3852
	$request = $smcFunc['db_query']('', '
3853
		SELECT id_member
3854
		FROM {db_prefix}members
3855
		WHERE ' . ($memID != 0 ? 'id_member != {int:selected_member} AND ' : '') . '
3856
			email_address = {string:email_address}
3857
		LIMIT 1',
3858
		array(
3859
			'selected_member' => $memID,
3860
			'email_address' => $email,
3861
		)
3862
	);
3863
3864
	if ($smcFunc['db_num_rows']($request) > 0)
3865
		return 'email_taken';
3866
	$smcFunc['db_free_result']($request);
3867
3868
	return true;
3869
}
3870
3871
/**
3872
 * Reload a user's settings.
3873
 */
3874
function profileReloadUser()
3875
{
3876
	global $modSettings, $context, $cur_profile;
3877
3878
	if (isset($_POST['passwrd2']) && $_POST['passwrd2'] != '')
3879
		setLoginCookie(60 * $modSettings['cookieTime'], $context['id_member'], hash_salt($_POST['passwrd1'], $cur_profile['password_salt']));
3880
3881
	loadUserSettings();
3882
	writeLog();
3883
}
3884
3885
/**
3886
 * Send the user a new activation email if they need to reactivate!
3887
 */
3888
function profileSendActivation()
3889
{
3890
	global $sourcedir, $profile_vars, $context, $scripturl, $smcFunc, $cookiename, $cur_profile, $language, $modSettings;
3891
3892
	require_once($sourcedir . '/Subs-Post.php');
3893
3894
	// Shouldn't happen but just in case.
3895
	if (empty($profile_vars['email_address']))
3896
		return;
3897
3898
	$replacements = array(
3899
		'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $context['id_member'] . ';code=' . $profile_vars['validation_code'],
3900
		'ACTIVATIONCODE' => $profile_vars['validation_code'],
3901
		'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $context['id_member'],
3902
	);
3903
3904
	// Send off the email.
3905
	$emaildata = loadEmailTemplate('activate_reactivate', $replacements, empty($cur_profile['lngfile']) || empty($modSettings['userLanguage']) ? $language : $cur_profile['lngfile']);
3906
	sendmail($profile_vars['email_address'], $emaildata['subject'], $emaildata['body'], null, 'reactivate', $emaildata['is_html'], 0);
3907
3908
	// Log the user out.
3909
	$smcFunc['db_query']('', '
3910
		DELETE FROM {db_prefix}log_online
3911
		WHERE id_member = {int:selected_member}',
3912
		array(
3913
			'selected_member' => $context['id_member'],
3914
		)
3915
	);
3916
	$_SESSION['log_time'] = 0;
3917
	$_SESSION['login_' . $cookiename] = $smcFunc['json_encode'](array(0, '', 0));
3918
3919
	if (isset($_COOKIE[$cookiename]))
3920
		$_COOKIE[$cookiename] = '';
3921
3922
	loadUserSettings();
3923
3924
	$context['user']['is_logged'] = false;
3925
	$context['user']['is_guest'] = true;
3926
3927
	redirectexit('action=sendactivation');
3928
}
3929
3930
/**
3931
 * Function to allow the user to choose group membership etc...
3932
 *
3933
 * @param int $memID The ID of the member
3934
 */
3935
function groupMembership($memID)
3936
{
3937
	global $txt, $user_profile, $context, $smcFunc;
3938
3939
	$curMember = $user_profile[$memID];
3940
	$context['primary_group'] = $curMember['id_group'];
3941
3942
	// Can they manage groups?
3943
	$context['can_manage_membergroups'] = allowedTo('manage_membergroups');
3944
	$context['can_manage_protected'] = allowedTo('admin_forum');
3945
	$context['can_edit_primary'] = $context['can_manage_protected'];
3946
	$context['update_message'] = isset($_GET['msg']) && isset($txt['group_membership_msg_' . $_GET['msg']]) ? $txt['group_membership_msg_' . $_GET['msg']] : '';
3947
3948
	// Get all the groups this user is a member of.
3949
	$groups = explode(',', $curMember['additional_groups']);
3950
	$groups[] = $curMember['id_group'];
3951
3952
	// Ensure the query doesn't croak!
3953
	if (empty($groups))
3954
		$groups = array(0);
3955
	// Just to be sure...
3956
	foreach ($groups as $k => $v)
3957
		$groups[$k] = (int) $v;
3958
3959
	// Get all the membergroups they can join.
3960
	$request = $smcFunc['db_query']('', '
3961
		SELECT mg.id_group, mg.group_name, mg.description, mg.group_type, mg.online_color, mg.hidden,
3962
			COALESCE(lgr.id_member, 0) AS pending
3963
		FROM {db_prefix}membergroups AS mg
3964
			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})
3965
		WHERE (mg.id_group IN ({array_int:group_list})
3966
			OR mg.group_type > {int:nonjoin_group_id})
3967
			AND mg.min_posts = {int:min_posts}
3968
			AND mg.id_group != {int:moderator_group}
3969
		ORDER BY group_name',
3970
		array(
3971
			'group_list' => $groups,
3972
			'selected_member' => $memID,
3973
			'status_open' => 0,
3974
			'nonjoin_group_id' => 1,
3975
			'min_posts' => -1,
3976
			'moderator_group' => 3,
3977
		)
3978
	);
3979
	// This beast will be our group holder.
3980
	$context['groups'] = array(
3981
		'member' => array(),
3982
		'available' => array()
3983
	);
3984
	while ($row = $smcFunc['db_fetch_assoc']($request))
3985
	{
3986
		// Can they edit their primary group?
3987
		if (($row['id_group'] == $context['primary_group'] && $row['group_type'] > 1) || ($row['hidden'] != 2 && $context['primary_group'] == 0 && in_array($row['id_group'], $groups)))
3988
			$context['can_edit_primary'] = true;
3989
3990
		// If they can't manage (protected) groups, and it's not publically joinable or already assigned, they can't see it.
3991
		if (((!$context['can_manage_protected'] && $row['group_type'] == 1) || (!$context['can_manage_membergroups'] && $row['group_type'] == 0)) && $row['id_group'] != $context['primary_group'])
3992
			continue;
3993
3994
		$context['groups'][in_array($row['id_group'], $groups) ? 'member' : 'available'][$row['id_group']] = array(
3995
			'id' => $row['id_group'],
3996
			'name' => $row['group_name'],
3997
			'desc' => $row['description'],
3998
			'color' => $row['online_color'],
3999
			'type' => $row['group_type'],
4000
			'pending' => $row['pending'],
4001
			'is_primary' => $row['id_group'] == $context['primary_group'],
4002
			'can_be_primary' => $row['hidden'] != 2,
4003
			// Anything more than this needs to be done through account settings for security.
4004
			'can_leave' => $row['id_group'] != 1 && $row['group_type'] > 1 ? true : false,
4005
		);
4006
	}
4007
	$smcFunc['db_free_result']($request);
4008
4009
	// Add registered members on the end.
4010
	$context['groups']['member'][0] = array(
4011
		'id' => 0,
4012
		'name' => $txt['regular_members'],
4013
		'desc' => $txt['regular_members_desc'],
4014
		'type' => 0,
4015
		'is_primary' => $context['primary_group'] == 0 ? true : false,
4016
		'can_be_primary' => true,
4017
		'can_leave' => 0,
4018
	);
4019
4020
	// No changing primary one unless you have enough groups!
4021
	if (count($context['groups']['member']) < 2)
4022
		$context['can_edit_primary'] = false;
4023
4024
	// In the special case that someone is requesting membership of a group, setup some special context vars.
4025
	if (isset($_REQUEST['request']) && isset($context['groups']['available'][(int) $_REQUEST['request']]) && $context['groups']['available'][(int) $_REQUEST['request']]['type'] == 2)
4026
		$context['group_request'] = $context['groups']['available'][(int) $_REQUEST['request']];
4027
}
4028
4029
/**
4030
 * This function actually makes all the group changes
4031
 *
4032
 * @param array $profile_vars The profile variables
4033
 * @param array $post_errors Any errors that have occurred
4034
 * @param int $memID The ID of the member
4035
 * @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
4036
 */
4037
function groupMembership2($profile_vars, $post_errors, $memID)
4038
{
4039
	global $user_info, $context, $user_profile, $modSettings, $smcFunc;
4040
4041
	// Let's be extra cautious...
4042
	if (!$context['user']['is_owner'] || empty($modSettings['show_group_membership']))
4043
		isAllowedTo('manage_membergroups');
4044
	if (!isset($_REQUEST['gid']) && !isset($_POST['primary']))
4045
		fatal_lang_error('no_access', false);
4046
4047
	checkSession(isset($_GET['gid']) ? 'get' : 'post');
4048
4049
	$old_profile = &$user_profile[$memID];
4050
	$context['can_manage_membergroups'] = allowedTo('manage_membergroups');
4051
	$context['can_manage_protected'] = allowedTo('admin_forum');
4052
4053
	// By default the new primary is the old one.
4054
	$newPrimary = $old_profile['id_group'];
4055
	$addGroups = array_flip(explode(',', $old_profile['additional_groups']));
4056
	$canChangePrimary = $old_profile['id_group'] == 0 ? 1 : 0;
4057
	$changeType = isset($_POST['primary']) ? 'primary' : (isset($_POST['req']) ? 'request' : 'free');
4058
4059
	// One way or another, we have a target group in mind...
4060
	$group_id = isset($_REQUEST['gid']) ? (int) $_REQUEST['gid'] : (int) $_POST['primary'];
4061
	$foundTarget = $changeType == 'primary' && $group_id == 0 ? true : false;
4062
4063
	// Sanity check!!
4064
	if ($group_id == 1)
4065
		isAllowedTo('admin_forum');
4066
	// Protected groups too!
4067
	else
4068
	{
4069
		$request = $smcFunc['db_query']('', '
4070
			SELECT group_type
4071
			FROM {db_prefix}membergroups
4072
			WHERE id_group = {int:current_group}
4073
			LIMIT {int:limit}',
4074
			array(
4075
				'current_group' => $group_id,
4076
				'limit' => 1,
4077
			)
4078
		);
4079
		list ($is_protected) = $smcFunc['db_fetch_row']($request);
4080
		$smcFunc['db_free_result']($request);
4081
4082
		if ($is_protected == 1)
4083
			isAllowedTo('admin_forum');
4084
	}
4085
4086
	// What ever we are doing, we need to determine if changing primary is possible!
4087
	$request = $smcFunc['db_query']('', '
4088
		SELECT id_group, group_type, hidden, group_name
4089
		FROM {db_prefix}membergroups
4090
		WHERE id_group IN ({int:group_list}, {int:current_group})',
4091
		array(
4092
			'group_list' => $group_id,
4093
			'current_group' => $old_profile['id_group'],
4094
		)
4095
	);
4096
	while ($row = $smcFunc['db_fetch_assoc']($request))
4097
	{
4098
		// Is this the new group?
4099
		if ($row['id_group'] == $group_id)
4100
		{
4101
			$foundTarget = true;
4102
			$group_name = $row['group_name'];
4103
4104
			// Does the group type match what we're doing - are we trying to request a non-requestable group?
4105
			if ($changeType == 'request' && $row['group_type'] != 2)
4106
				fatal_lang_error('no_access', false);
4107
			// What about leaving a requestable group we are not a member of?
4108
			elseif ($changeType == 'free' && $row['group_type'] == 2 && $old_profile['id_group'] != $row['id_group'] && !isset($addGroups[$row['id_group']]))
4109
				fatal_lang_error('no_access', false);
4110
			elseif ($changeType == 'free' && $row['group_type'] != 3 && $row['group_type'] != 2)
4111
				fatal_lang_error('no_access', false);
4112
4113
			// We can't change the primary group if this is hidden!
4114
			if ($row['hidden'] == 2)
4115
				$canChangePrimary = false;
4116
		}
4117
4118
		// If this is their old primary, can we change it?
4119
		if ($row['id_group'] == $old_profile['id_group'] && ($row['group_type'] > 1 || $context['can_manage_membergroups']) && $canChangePrimary !== false)
4120
			$canChangePrimary = 1;
4121
4122
		// If we are not doing a force primary move, don't do it automatically if current primary is not 0.
4123
		if ($changeType != 'primary' && $old_profile['id_group'] != 0)
4124
			$canChangePrimary = false;
4125
4126
		// If this is the one we are acting on, can we even act?
4127
		if ((!$context['can_manage_protected'] && $row['group_type'] == 1) || (!$context['can_manage_membergroups'] && $row['group_type'] == 0))
4128
			$canChangePrimary = false;
4129
	}
4130
	$smcFunc['db_free_result']($request);
4131
4132
	// Didn't find the target?
4133
	if (!$foundTarget)
4134
		fatal_lang_error('no_access', false);
4135
4136
	// Final security check, don't allow users to promote themselves to admin.
4137
	if ($context['can_manage_membergroups'] && !allowedTo('admin_forum'))
4138
	{
4139
		$request = $smcFunc['db_query']('', '
4140
			SELECT COUNT(permission)
4141
			FROM {db_prefix}permissions
4142
			WHERE id_group = {int:selected_group}
4143
				AND permission = {string:admin_forum}
4144
				AND add_deny = {int:not_denied}',
4145
			array(
4146
				'selected_group' => $group_id,
4147
				'not_denied' => 1,
4148
				'admin_forum' => 'admin_forum',
4149
			)
4150
		);
4151
		list ($disallow) = $smcFunc['db_fetch_row']($request);
4152
		$smcFunc['db_free_result']($request);
4153
4154
		if ($disallow)
4155
			isAllowedTo('admin_forum');
4156
	}
4157
4158
	// If we're requesting, add the note then return.
4159
	if ($changeType == 'request')
4160
	{
4161
		$request = $smcFunc['db_query']('', '
4162
			SELECT id_member
4163
			FROM {db_prefix}log_group_requests
4164
			WHERE id_member = {int:selected_member}
4165
				AND id_group = {int:selected_group}
4166
				AND status = {int:status_open}',
4167
			array(
4168
				'selected_member' => $memID,
4169
				'selected_group' => $group_id,
4170
				'status_open' => 0,
4171
			)
4172
		);
4173
		if ($smcFunc['db_num_rows']($request) != 0)
4174
			fatal_lang_error('profile_error_already_requested_group');
4175
		$smcFunc['db_free_result']($request);
4176
4177
		// Log the request.
4178
		$smcFunc['db_insert']('',
4179
			'{db_prefix}log_group_requests',
4180
			array(
4181
				'id_member' => 'int', 'id_group' => 'int', 'time_applied' => 'int', 'reason' => 'string-65534',
4182
				'status' => 'int', 'id_member_acted' => 'int', 'member_name_acted' => 'string', 'time_acted' => 'int', 'act_reason' => 'string',
4183
			),
4184
			array(
4185
				$memID, $group_id, time(), $_POST['reason'],
4186
				0, 0, '', 0, '',
4187
			),
4188
			array('id_request')
4189
		);
4190
4191
		// Set up some data for our background task...
4192
		$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()));
4193
4194
		// Add a background task to handle notifying people of this request
4195
		$smcFunc['db_insert']('insert', '{db_prefix}background_tasks',
4196
			array('task_file' => 'string-255', 'task_class' => 'string-255', 'task_data' => 'string', 'claimed_time' => 'int'),
4197
			array('$sourcedir/tasks/GroupReq-Notify.php', 'GroupReq_Notify_Background', $data, 0), array()
4198
		);
4199
4200
		return $changeType;
4201
	}
4202
	// Otherwise we are leaving/joining a group.
4203
	elseif ($changeType == 'free')
4204
	{
4205
		// Are we leaving?
4206
		if ($old_profile['id_group'] == $group_id || isset($addGroups[$group_id]))
4207
		{
4208
			if ($old_profile['id_group'] == $group_id)
4209
				$newPrimary = 0;
4210
			else
4211
				unset($addGroups[$group_id]);
4212
		}
4213
		// ... if not, must be joining.
4214
		else
4215
		{
4216
			// Can we change the primary, and do we want to?
4217
			if ($canChangePrimary)
4218
			{
4219
				if ($old_profile['id_group'] != 0)
4220
					$addGroups[$old_profile['id_group']] = -1;
4221
				$newPrimary = $group_id;
4222
			}
4223
			// Otherwise it's an additional group...
4224
			else
4225
				$addGroups[$group_id] = -1;
4226
		}
4227
	}
4228
	// Finally, we must be setting the primary.
4229
	elseif ($canChangePrimary)
4230
	{
4231
		if ($old_profile['id_group'] != 0)
4232
			$addGroups[$old_profile['id_group']] = -1;
4233
		if (isset($addGroups[$group_id]))
4234
			unset($addGroups[$group_id]);
4235
		$newPrimary = $group_id;
4236
	}
4237
4238
	// Finally, we can make the changes!
4239
	foreach ($addGroups as $id => $dummy)
4240
		if (empty($id))
4241
			unset($addGroups[$id]);
4242
	$addGroups = implode(',', array_flip($addGroups));
4243
4244
	// Ensure that we don't cache permissions if the group is changing.
4245
	if ($context['user']['is_owner'])
4246
		$_SESSION['mc']['time'] = 0;
4247
	else
4248
		updateSettings(array('settings_updated' => time()));
4249
4250
	updateMemberData($memID, array('id_group' => $newPrimary, 'additional_groups' => $addGroups));
4251
4252
	return $changeType;
4253
}
4254
4255
/**
4256
 * Provides interface to setup Two Factor Auth in SMF
4257
 *
4258
 * @param int $memID The ID of the member
4259
 */
4260
function tfasetup($memID)
4261
{
4262
	global $user_info, $context, $user_settings, $sourcedir, $modSettings, $smcFunc;
4263
4264
	require_once($sourcedir . '/Class-TOTP.php');
4265
	require_once($sourcedir . '/Subs-Auth.php');
4266
4267
	// load JS lib for QR
4268
	loadJavaScriptFile('qrcode.js', array('force_current' => false, 'validate' => true));
4269
4270
	// If TFA has not been setup, allow them to set it up
4271
	if (empty($user_settings['tfa_secret']) && $context['user']['is_owner'])
4272
	{
4273
		// Check to ensure we're forcing SSL for authentication
4274
		if (!empty($modSettings['force_ssl']) && empty($maintenance) && !httpsOn())
4275
			fatal_lang_error('login_ssl_required', false);
4276
4277
		// In some cases (forced 2FA or backup code) they would be forced to be redirected here,
4278
		// we do not want too much AJAX to confuse them.
4279
		if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && !isset($_REQUEST['backup']) && !isset($_REQUEST['forced']))
4280
		{
4281
			$context['from_ajax'] = true;
4282
			$context['template_layers'] = array();
4283
		}
4284
4285
		// When the code is being sent, verify to make sure the user got it right
4286
		if (!empty($_REQUEST['save']) && !empty($_SESSION['tfa_secret']))
4287
		{
4288
			$code = $_POST['tfa_code'];
4289
			$totp = new \TOTP\Auth($_SESSION['tfa_secret']);
4290
			$totp->setRange(1);
4291
			$valid_code = strlen($code) == $totp->getCodeLength() && $totp->validateCode($code);
4292
4293
			if (empty($context['password_auth_failed']) && $valid_code)
4294
			{
4295
				$backup = substr(sha1($smcFunc['random_int']()), 0, 16);
4296
				$backup_encrypted = hash_password($user_settings['member_name'], $backup);
4297
4298
				updateMemberData($memID, array(
4299
					'tfa_secret' => $_SESSION['tfa_secret'],
4300
					'tfa_backup' => $backup_encrypted,
4301
				));
4302
4303
				setTFACookie(3153600, $memID, hash_salt($backup_encrypted, $user_settings['password_salt']));
4304
4305
				unset($_SESSION['tfa_secret']);
4306
4307
				$context['tfa_backup'] = $backup;
4308
				$context['sub_template'] = 'tfasetup_backup';
4309
4310
				return;
4311
			}
4312
			else
4313
			{
4314
				$context['tfa_secret'] = $_SESSION['tfa_secret'];
4315
				$context['tfa_error'] = !$valid_code;
4316
				$context['tfa_pass_value'] = $_POST['oldpasswrd'];
4317
				$context['tfa_value'] = $_POST['tfa_code'];
4318
			}
4319
		}
4320
		else
4321
		{
4322
			$totp = new \TOTP\Auth();
4323
			$secret = $totp->generateCode();
4324
			$_SESSION['tfa_secret'] = $secret;
4325
			$context['tfa_secret'] = $secret;
4326
			$context['tfa_backup'] = isset($_REQUEST['backup']);
4327
		}
4328
4329
		$context['tfa_qr_url'] = $totp->getQrCodeUrl($context['forum_name'] . ':' . $user_info['name'], $context['tfa_secret']);
4330
	}
4331
	else
4332
		redirectexit('action=profile;area=account;u=' . $memID);
4333
}
4334
4335
/**
4336
 * Provides interface to disable two-factor authentication in SMF
4337
 *
4338
 * @param int $memID The ID of the member
4339
 */
4340
function tfadisable($memID)
4341
{
4342
	global $context, $modSettings, $smcFunc, $user_settings;
4343
4344
	if (!empty($user_settings['tfa_secret']))
4345
	{
4346
		// Bail if we're forcing SSL for authentication and the network connection isn't secure.
4347
		if (!empty($modSettings['force_ssl']) && !httpsOn())
4348
			fatal_lang_error('login_ssl_required', false);
4349
4350
		// The admin giveth...
4351
		elseif ($modSettings['tfa_mode'] == 3 && $context['user']['is_owner'])
4352
			fatal_lang_error('cannot_disable_tfa', false);
4353
		elseif ($modSettings['tfa_mode'] == 2 && $context['user']['is_owner'])
4354
		{
4355
			$groups = array($user_settings['id_group']);
4356
			if (!empty($user_settings['additional_groups']))
4357
				$groups = array_unique(array_merge($groups, explode(',', $user_settings['additional_groups'])));
4358
4359
			$request = $smcFunc['db_query']('', '
4360
				SELECT id_group
4361
				FROM {db_prefix}membergroups
4362
				WHERE tfa_required = {int:tfa_required}
4363
					AND id_group IN ({array_int:groups})',
4364
				array(
4365
					'tfa_required' => 1,
4366
					'groups' => $groups,
4367
				)
4368
			);
4369
			$tfa_required_groups = $smcFunc['db_num_rows']($request);
4370
			$smcFunc['db_free_result']($request);
4371
4372
			// They belong to a membergroup that requires tfa.
4373
			if (!empty($tfa_required_groups))
4374
				fatal_lang_error('cannot_disable_tfa2', false);
4375
		}
4376
	}
4377
	else
4378
		redirectexit('action=profile;area=account;u=' . $memID);
4379
}
4380
4381
?>