Completed
Push — patch_1-1-7 ( 4638d6...31ac10 )
by Emanuele
11:55 queued 15s
created

getMemberNotificationsProfile()   B

Complexity

Conditions 11
Paths 45

Size

Total Lines 47
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 26
nc 45
nop 1
dl 0
loc 47
rs 7.3166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Functions to support the profile controller
5
 *
6
 * @name      ElkArte Forum
7
 * @copyright ElkArte Forum contributors
8
 * @license   BSD http://opensource.org/licenses/BSD-3-Clause
9
 *
10
 * This file contains code covered by:
11
 * copyright:	2011 Simple Machines (http://www.simplemachines.org)
12
 * license:  	BSD, See included LICENSE.TXT for terms and conditions.
13
 *
14
 * @version 1.1.7
15
 *
16
 */
17
18
/**
19
 * Find the ID of the "current" member
20
 *
21
 * @param boolean $fatal if the function ends in a fatal error in case of problems (default true)
22
 * @param boolean $reload_id if true the already set value is ignored (default false)
23
 *
24
 * @return int if no error.  May return false in case of problems only if $fatal is set to false
25
 * @throws Elk_Exception not_a_user
26
 */
27
function currentMemberID($fatal = true, $reload_id = false)
28
{
29
	global $user_info;
30
	static $memID;
31
32
	// If we already know who we're dealing with
33
	if (isset($memID) && !$reload_id)
34
		return $memID;
35
36
	// Did we get the user by name...
37
	if (isset($_REQUEST['user']))
38
		$memberResult = loadMemberData($_REQUEST['user'], true, 'profile');
39
	// ... or by id_member?
40
	elseif (!empty($_REQUEST['u']))
41
		$memberResult = loadMemberData((int) $_REQUEST['u'], false, 'profile');
42
	// If it was just ?action=profile, edit your own profile.
43
	else
44
		$memberResult = loadMemberData($user_info['id'], false, 'profile');
45
46
	// Check if loadMemberData() has returned a valid result.
47
	if (!is_array($memberResult))
48
	{
49
		// Members only...
50
		is_not_guest('', $fatal);
51
52
		if ($fatal)
53
			throw new Elk_Exception('not_a_user', false);
54
		else
55
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type integer.
Loading history...
56
	}
57
58
	// If all went well, we have a valid member ID!
59
	list ($memID) = $memberResult;
60
61
	return $memID;
62
}
63
64
/**
65
 * Setup the context for a page load!
66
 *
67
 * @param mixed[] $fields
68
 * @param string $hook a string that represent the hook that can be used to operate on $fields
69
 */
70
function setupProfileContext($fields, $hook = '')
71
{
72
	global $profile_fields, $context, $cur_profile, $txt;
73
74
	if (!empty($hook))
75
		call_integration_hook('integrate_' . $hook . '_profile_fields', array(&$fields));
76
77
	// Make sure we have this!
78
	loadProfileFields(true);
79
80
	// First check for any linked sets.
81
	foreach ($profile_fields as $key => $field)
82
		if (isset($field['link_with']) && in_array($field['link_with'], $fields))
83
			$fields[] = $key;
84
85
	// Some default bits.
86
	$context['profile_prehtml'] = '';
87
	$context['profile_posthtml'] = '';
88
	$context['profile_onsubmit_javascript'] = '';
89
90
	$i = 0;
91
	$last_type = '';
92
	foreach ($fields as $key => $field)
93
	{
94
		if (isset($profile_fields[$field]))
95
		{
96
			// Shortcut.
97
			$cur_field = &$profile_fields[$field];
98
99
			// Does it have a preload and does that preload succeed?
100
			if (isset($cur_field['preload']) && !$cur_field['preload']())
101
				continue;
102
103
			// If this is anything but complex we need to do more cleaning!
104
			if ($cur_field['type'] !== 'callback' && $cur_field['type'] !== 'hidden')
105
			{
106
				if (!isset($cur_field['label']))
107
					$cur_field['label'] = isset($txt[$field]) ? $txt[$field] : $field;
108
109
				// Everything has a value!
110
				if (!isset($cur_field['value']))
111
					$cur_field['value'] = isset($cur_profile[$field]) ? $cur_profile[$field] : '';
112
113
				// Any input attributes?
114
				$cur_field['input_attr'] = !empty($cur_field['input_attr']) ? implode(',', $cur_field['input_attr']) : '';
115
			}
116
117
			// Was there an error with this field on posting?
118
			if (isset($context['post_errors'][$field]))
119
				$cur_field['is_error'] = true;
120
121
			// Any javascript stuff?
122
			if (!empty($cur_field['js_submit']))
123
				$context['profile_onsubmit_javascript'] .= $cur_field['js_submit'];
124
			if (!empty($cur_field['js']))
125
				addInlineJavascript($cur_field['js']);
126
			if (!empty($cur_field['js_load']))
127
				loadJavascriptFile($cur_field['js_load']);
128
129
			// Any template stuff?
130
			if (!empty($cur_field['prehtml']))
131
				$context['profile_prehtml'] .= $cur_field['prehtml'];
132
			if (!empty($cur_field['posthtml']))
133
				$context['profile_posthtml'] .= $cur_field['posthtml'];
134
135
			// Finally put it into context?
136
			if ($cur_field['type'] !== 'hidden')
137
			{
138
				$last_type = $cur_field['type'];
139
				$context['profile_fields'][$field] = &$profile_fields[$field];
140
			}
141
		}
142
		// Bodge in a line break - without doing two in a row ;)
143
		elseif ($field === 'hr' && $last_type !== 'hr' && $last_type != '')
144
		{
145
			$last_type = 'hr';
146
			$context['profile_fields'][$i++]['type'] = 'hr';
147
		}
148
	}
149
150
	// Free up some memory.
151
	unset($profile_fields);
152
}
153
154
/**
155
 * Load any custom fields for this area.
156
 * No area means load all, 'summary' loads all public ones.
157
 *
158
 * @param int $memID
159
 * @param string $area = 'summary'
160
 * @param mixed[] $custom_fields = array()
161
 */
162
function loadCustomFields($memID, $area = 'summary', array $custom_fields = array())
163
{
164
	global $context, $txt, $user_profile, $user_info, $settings, $scripturl;
165
166
	$db = database();
167
168
	// Get the right restrictions in place...
169
	$where = 'active = 1';
170
	if (!allowedTo('admin_forum') && $area !== 'register')
171
	{
172
		// If it's the owner they can see two types of private fields, regardless.
173
		if ($memID == $user_info['id'])
174
			$where .= $area === 'summary' ? ' AND private < 3' : ' AND (private = 0 OR private = 2)';
175
		else
176
			$where .= $area === 'summary' ? ' AND private < 2' : ' AND private = 0';
177
	}
178
179
	if ($area === 'register')
180
		$where .= ' AND show_reg != 0';
181
	elseif ($area !== 'summary')
182
		$where .= ' AND show_profile = {string:area}';
183
184
	// Load all the relevant fields - and data.
185
	// The fully-qualified name for rows is here because it's a reserved word in Mariadb 10.2.4+ and quoting would be different for MySQL/Mariadb and PSQL
186
	$request = $db->query('', '
187
		SELECT
188
			col_name, field_name, field_desc, field_type, show_reg, field_length, field_options,
189
			default_value, bbc, enclose, placement, mask, vieworder, {db_prefix}custom_fields.rows, cols
190
		FROM {db_prefix}custom_fields
191
		WHERE ' . $where . '
192
		ORDER BY vieworder ASC',
193
		array(
194
			'area' => $area,
195
		)
196
	);
197
	$context['custom_fields'] = array();
198
	$context['custom_fields_required'] = false;
199
	$bbc_parser = \BBC\ParserWrapper::instance();
200
	while ($row = $db->fetch_assoc($request))
201
	{
202
		// Shortcut.
203
		$exists = $memID && isset($user_profile[$memID], $user_profile[$memID]['options'][$row['col_name']]);
204
		$value = $exists ? $user_profile[$memID]['options'][$row['col_name']] : $row['default_value'];
205
206
		// If this was submitted already then make the value the posted version.
207
		if (!empty($custom_fields) && isset($custom_fields[$row['col_name']]))
208
		{
209
			$value = Util::htmlspecialchars($custom_fields[$row['col_name']]);
210
			if (in_array($row['field_type'], array('select', 'radio')))
211
			{
212
				$options = explode(',', $row['field_options']);
213
				$value = isset($options[$value]) ? $options[$value] : '';
214
			}
215
		}
216
217
		// HTML for the input form.
218
		$output_html = $value;
219
220
		// Checkbox inputs
221
		if ($row['field_type'] === 'check')
222
		{
223
			$true = (bool) $value;
224
			$input_html = '<input id="' . $row['col_name'] . '" type="checkbox" name="customfield[' . $row['col_name'] . ']" ' . ($true ? 'checked="checked"' : '') . ' class="input_check" />';
225
			$output_html = $true ? $txt['yes'] : $txt['no'];
226
		}
227
		// A select list
228
		elseif ($row['field_type'] === 'select')
229
		{
230
			$input_html = '<select id="' . $row['col_name'] . '" name="customfield[' . $row['col_name'] . ']"><option value=""' . ($row['default_value'] === 'no_default' ? ' selected="selected"' : '') . '></option>';
231
			$options = explode(',', $row['field_options']);
232
233
			foreach ($options as $k => $v)
234
			{
235
				$true = ($value == $v);
236
				$input_html .= '<option value="' . $k . '"' . ($true ? ' selected="selected"' : '') . '>' . $v . '</option>';
237
				if ($true)
238
				{
239
					$key = $k;
240
					$output_html = $v;
241
				}
242
			}
243
244
			$input_html .= '</select>';
245
		}
246
		// Radio buttons
247
		elseif ($row['field_type'] === 'radio')
248
		{
249
			$input_html = '<fieldset>';
250
			$options = explode(',', $row['field_options']);
251
252
			foreach ($options as $k => $v)
253
			{
254
				$true = ($value == $v);
255
				$input_html .= '<label for="customfield_' . $row['col_name'] . '_' . $k . '"><input type="radio" name="customfield[' . $row['col_name'] . ']" class="input_radio" id="customfield_' . $row['col_name'] . '_' . $k . '" value="' . $k . '" ' . ($true ? 'checked="checked"' : '') . ' />' . $v . '</label><br />';
256
				if ($true)
257
				{
258
					$key = $k;
259
					$output_html = $v;
260
				}
261
			}
262
			$input_html .= '</fieldset>';
263
		}
264
		// A standard input field, including some html5 variants
265
		elseif (in_array($row['field_type'], array('text', 'url', 'search', 'date', 'email', 'color')))
266
		{
267
			$input_html = '<input id="' . $row['col_name'] . '" type="' . $row['field_type'] . '" name="customfield[' . $row['col_name'] . ']" ' . ($row['field_length'] != 0 ? 'maxlength="' . $row['field_length'] . '"' : '') . ' size="' . ($row['field_length'] == 0 || $row['field_length'] >= 50 ? 50 : ($row['field_length'] > 30 ? 30 : ($row['field_length'] > 10 ? 20 : 10))) . '" value="' . $value . '" class="input_text" />';
268
		}
269
		// Only thing left, a textbox for you
270
		else
271
		{
272
			$input_html = '<textarea id="' . $row['col_name'] . '" name="customfield[' . $row['col_name'] . ']" ' . (!empty($rows) ? 'rows="' . $row['rows'] . '"' : '') . ' ' . (!empty($cols) ? 'cols="' . $row['cols'] . '"' : '') . '>' . $value . '</textarea>';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $rows does not exist. Did you maybe mean $row?
Loading history...
Comprehensibility Best Practice introduced by
The variable $cols seems to never exist and therefore empty should always be true.
Loading history...
273
		}
274
275
		// Parse BBCode
276
		if ($row['bbc'])
277
			$output_html = $bbc_parser->parseCustomFields($output_html);
278
		// Allow for newlines at least
279
		elseif ($row['field_type'] === 'textarea')
280
			$output_html = strtr($output_html, array("\n" => '<br />'));
281
282
		// Enclosing the user input within some other text?
283
		if (!empty($row['enclose']) && !empty($output_html))
284
		{
285
			$replacements = array(
286
				'{SCRIPTURL}' => $scripturl,
287
				'{IMAGES_URL}' => $settings['images_url'],
288
				'{DEFAULT_IMAGES_URL}' => $settings['default_images_url'],
289
				'{INPUT}' => $output_html,
290
			);
291
			if (in_array($row['field_type'], array('radio', 'select')))
292
			{
293
				$replacements['{KEY}'] = $row['col_name'] . '_' . $key;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $key does not seem to be defined for all execution paths leading up to this point.
Loading history...
294
			}
295
			$output_html = strtr($row['enclose'], $replacements);
296
		}
297
298
		$context['custom_fields_required'] = $context['custom_fields_required'] || $row['show_reg'];
299
		$valid_areas = array('register', 'account', 'forumprofile', 'theme');
300
301
		if (!in_array($area, $valid_areas) && ($value === '' || $value === 'no_default'))
302
		{
303
			continue;
304
		}
305
		$context['custom_fields'][] = array(
306
			'name' => $row['field_name'],
307
			'desc' => $row['field_desc'],
308
			'field_type' => $row['field_type'],
309
			'input_html' => $input_html,
310
			'output_html' => $output_html,
311
			'placement' => $row['placement'],
312
			'colname' => $row['col_name'],
313
			'value' => $value,
314
			'show_reg' => $row['show_reg'],
315
			'field_length' => $row['field_length'],
316
			'mask' => $row['mask'],
317
		);
318
	}
319
320
	$db->free_result($request);
321
322
	call_integration_hook('integrate_load_custom_profile_fields', array($memID, $area));
323
}
324
325
/**
326
 * This defines every profile field known to man.
327
 *
328
 * @param bool $force_reload = false
329
 */
330
function loadProfileFields($force_reload = false)
331
{
332
	global $context, $profile_fields, $txt, $scripturl, $modSettings, $user_info, $cur_profile, $language, $settings;
333
334
	// Don't load this twice!
335
	if (!empty($profile_fields) && !$force_reload)
336
		return;
337
338
	/**
339
	 * This horrific array defines all the profile fields in the whole world!
340
	 * In general each "field" has one array - the key of which is the database
341
	 * column name associated with said field.
342
	 *
343
	 * Each item can have the following attributes:
344
	 *
345
	 * string $type: The type of field this is - valid types are:
346
	 *   - callback: This is a field which has its own callback mechanism for templating.
347
	 *   - check:    A simple checkbox.
348
	 *   - hidden:   This doesn't have any visual aspects but may have some validity.
349
	 *   - password: A password box.
350
	 *   - select:   A select box.
351
	 *   - text:     A string of some description.
352
	 *
353
	 * string $label:       The label for this item - default will be $txt[$key] if this isn't set.
354
	 * string $subtext:     The subtext (Small label) for this item.
355
	 * int $size:           Optional size for a text area.
356
	 * array $input_attr:   An array of text strings to be added to the input box for this item.
357
	 * string $value:       The value of the item. If not set $cur_profile[$key] is assumed.
358
	 * string $permission:  Permission required for this item (Excluded _any/_own suffix which is applied automatically).
359
	 * func $input_validate: A runtime function which validates the element before going to the database. It is passed
360
	 *                       the relevant $_POST element if it exists and should be treated like a reference.
361
	 *
362
	 * Return types:
363
	 *   - true:          Element can be stored.
364
	 *   - false:         Skip this element.
365
	 *   - a text string: An error occurred - this is the error message.
366
	 *
367
	 * function $preload: A function that is used to load data required for this element to be displayed. Must return
368
	 *                    true to be displayed at all.
369
	 *
370
	 * string $cast_type: If set casts the element to a certain type. Valid types (bool, int, float).
371
	 * string $save_key:  If the index of this element isn't the database column name it can be overridden with this string.
372
	 * bool $is_dummy:    If set then nothing is acted upon for this element.
373
	 * bool $enabled:     A test to determine whether this is even available - if not is unset.
374
	 * string $link_with: Key which links this field to an overall set.
375
	 *
376
	 * string $js_submit: javascript to add inside the function checkProfileSubmit() in the template
377
	 * string $js:        javascript to add to the page in general
378
	 * string $js_load:   filename of js to be loaded with loadJavasciptFile
379
	 *
380
	 * Note that all elements that have a custom input_validate must ensure they set the value of $cur_profile correct to enable
381
	 * the changes to be displayed correctly on submit of the form.
382
	 */
383
384
	$profile_fields = array(
385
		'avatar_choice' => array(
386
			'type' => 'callback',
387
			'callback_func' => 'avatar_select',
388
			// This handles the permissions too.
389
			'preload' => 'profileLoadAvatarData',
390
			'input_validate' => 'profileSaveAvatarData',
391
			'save_key' => 'avatar',
392
		),
393
		'bday1' => array(
394
			'type' => 'callback',
395
			'callback_func' => 'birthdate',
396
			'permission' => 'profile_extra',
397
			'preload' => function () {
398
				global $cur_profile, $context;
399
400
				// Split up the birth date....
401
				list ($uyear, $umonth, $uday) = explode('-', empty($cur_profile['birthdate']) || $cur_profile['birthdate'] === '0001-01-01' ? '0000-00-00' : $cur_profile['birthdate']);
402
				$context['member']['birth_date'] = array(
403
					'year' => $uyear === '0004' ? '0000' : $uyear,
404
					'month' => $umonth,
405
					'day' => $uday,
406
				);
407
408
				return true;
409
			},
410
			'input_validate' => function (&$value) {
411
				global $profile_vars, $cur_profile;
412
413
				if (isset($_POST['bday2'], $_POST['bday3']) && $value > 0 && $_POST['bday2'] > 0)
414
				{
415
					// Set to blank?
416
					if ((int) $_POST['bday3'] == 1 && (int) $_POST['bday2'] == 1 && (int) $value == 1)
417
						$value = '0001-01-01';
418
					else
419
						$value = checkdate($value, $_POST['bday2'], $_POST['bday3'] < 4 ? 4 : $_POST['bday3']) ? sprintf('%04d-%02d-%02d', $_POST['bday3'] < 4 ? 4 : $_POST['bday3'], $_POST['bday1'], $_POST['bday2']) : '0001-01-01';
420
				}
421
				else
422
					$value = '0001-01-01';
423
424
				$profile_vars['birthdate'] = $value;
425
				$cur_profile['birthdate'] = $value;
426
				return false;
427
			},
428
		),
429
		// Setting the birth date the old style way?
430
		'birthdate' => array(
431
			'type' => 'hidden',
432
			'permission' => 'profile_extra',
433
			'input_validate' => function (&$value) {
434
				global $cur_profile;
435
436
				// @todo Should we check for this year and tell them they made a mistake :P? (based on coppa at least?)
437
				if (preg_match('/(\d{4})[\-\., ](\d{2})[\-\., ](\d{2})/', $value, $dates) === 1)
438
				{
439
					$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]) : '0001-01-01';
440
					return true;
441
				}
442
				else
443
				{
444
					$value = empty($cur_profile['birthdate']) ? '0001-01-01' : $cur_profile['birthdate'];
445
					return false;
446
				}
447
			},
448
		),
449
		'date_registered' => array(
450
			'type' => 'date',
451
			'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),
452
			'label' => $txt['date_registered'],
453
			'log_change' => true,
454
			'permission' => 'moderate_forum',
455
			'input_validate' => function (&$value) {
456
				global $txt, $user_info, $modSettings, $cur_profile;
457
458
				// Bad date!  Go try again - please?
459
				if (($value = strtotime($value)) === -1)
460
				{
461
					$value = $cur_profile['date_registered'];
462
					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));
463
				}
464
				// As long as it doesn't equal "N/A"...
465
				elseif ($value != $txt['not_applicable'] && $value != strtotime(strftime('%Y-%m-%d', $cur_profile['date_registered'] + ($user_info['time_offset'] + $modSettings['time_offset']) * 3600)))
466
					$value = $value - ($user_info['time_offset'] + $modSettings['time_offset']) * 3600;
467
				else
468
					$value = $cur_profile['date_registered'];
469
470
				return true;
471
			},
472
		),
473
		'email_address' => array(
474
			'type' => 'email',
475
			'label' => $txt['user_email_address'],
476
			'subtext' => $txt['valid_email'],
477
			'log_change' => true,
478
			'permission' => 'profile_identity',
479
			'input_validate' => function (&$value) {
480
				global $context, $old_profile, $profile_vars, $modSettings;
481
482
				if (strtolower($value) == strtolower($old_profile['email_address']))
483
					return false;
484
485
				$isValid = profileValidateEmail($value, $context['id_member']);
486
487
				// Do they need to re-validate? If so schedule the function!
488
				if ($isValid === true && !empty($modSettings['send_validation_onChange']) && !allowedTo('moderate_forum'))
489
				{
490
					require_once(SUBSDIR . '/Auth.subs.php');
491
					$old_profile['validation_code'] = generateValidationCode(14);
492
					$profile_vars['validation_code'] = substr(hash('sha256', $old_profile['validation_code']), 0, 10);
493
					$profile_vars['is_activated'] = 2;
494
					$context['profile_execute_on_save'][] = 'profileSendActivation';
495
					unset($context['profile_execute_on_save']['reload_user']);
496
				}
497
498
				return $isValid;
499
			},
500
		),
501
		'hide_email' => array(
502
			'type' => 'check',
503
			'value' => empty($cur_profile['hide_email']) ? true : false,
504
			'label' => $txt['allow_user_email'],
505
			'permission' => 'profile_identity',
506
			'input_validate' => function (&$value) {
507
				$value = $value == 0 ? 1 : 0;
508
509
				return true;
510
			},
511
		),
512
		// Selecting group membership is a complicated one so we treat it separate!
513
		'id_group' => array(
514
			'type' => 'callback',
515
			'callback_func' => 'group_manage',
516
			'permission' => 'manage_membergroups',
517
			'preload' => 'profileLoadGroups',
518
			'log_change' => true,
519
			'input_validate' => 'profileSaveGroups',
520
		),
521
		'id_theme' => array(
522
			'type' => 'callback',
523
			'callback_func' => 'theme_pick',
524
			'permission' => 'profile_extra',
525
			'enabled' => empty($settings['disable_user_variant']) || !empty($modSettings['theme_allow']) || allowedTo('admin_forum'),
526
			'preload' => function () {
527
				global $context, $cur_profile, $txt;
528
529
				$db = database();
530
531
				$request = $db->query('', '
532
					SELECT value
533
					FROM {db_prefix}themes
534
					WHERE id_theme = {int:id_theme}
535
						AND variable = {string:variable}
536
					LIMIT 1', array(
537
						'id_theme' => $cur_profile['id_theme'],
538
						'variable' => 'name',
539
					)
540
				);
541
				list ($name) = $db->fetch_row($request);
542
				$db->free_result($request);
543
544
				$context['member']['theme'] = array(
545
					'id' => $cur_profile['id_theme'],
546
					'name' => empty($cur_profile['id_theme']) ? $txt['theme_forum_default'] : $name
547
				);
548
				return true;
549
			},
550
			'input_validate' => function (&$value) {
551
				$value = (int) $value;
552
				return true;
553
			},
554
		),
555
		'karma_good' => array(
556
			'type' => 'callback',
557
			'callback_func' => 'karma_modify',
558
			'permission' => 'admin_forum',
559
			// Set karma_bad too!
560
			'input_validate' => function (&$value) {
561
				global $profile_vars, $cur_profile;
562
563
				$value = (int) $value;
564
				if (isset($_POST['karma_bad']))
565
				{
566
					$profile_vars['karma_bad'] = $_POST['karma_bad'] != '' ? (int) $_POST['karma_bad'] : 0;
567
					$cur_profile['karma_bad'] = $_POST['karma_bad'] != '' ? (int) $_POST['karma_bad'] : 0;
568
				}
569
				return true;
570
			},
571
			'preload' => function () {
572
				global $context, $cur_profile;
573
574
				$context['member']['karma']['good'] = $cur_profile['karma_good'];
575
				$context['member']['karma']['bad'] = $cur_profile['karma_bad'];
576
577
				return true;
578
			},
579
			'enabled' => !empty($modSettings['karmaMode']),
580
		),
581
		'lngfile' => array(
582
			'type' => 'select',
583
			'options' => 'return $context[\'profile_languages\'];',
584
			'label' => $txt['preferred_language'],
585
			'permission' => 'profile_identity',
586
			'preload' => 'profileLoadLanguages',
587
			'enabled' => !empty($modSettings['userLanguage']),
588
			'value' => empty($cur_profile['lngfile']) ? $language : $cur_profile['lngfile'],
589
			'input_validate' => function (&$value) {
590
				global $context, $cur_profile;
591
592
				// Load the languages.
593
				profileLoadLanguages();
594
595
				if (isset($context['profile_languages'][$value]))
596
				{
597
					if ($context['user']['is_owner'] && empty($context['password_auth_failed']))
598
						$_SESSION['language'] = $value;
599
					return true;
600
				}
601
				else
602
				{
603
					$value = $cur_profile['lngfile'];
604
					return false;
605
				}
606
			},
607
		),
608
		// The username is not always editable - so adjust it as such.
609
		'member_name' => array(
610
			'type' => allowedTo('admin_forum') && isset($_GET['changeusername']) ? 'text' : 'label',
611
			'label' => $txt['username'],
612
			'subtext' => allowedTo('admin_forum') && !isset($_GET['changeusername']) ? '[<a href="' . $scripturl . '?action=profile;u=' . $context['id_member'] . ';area=account;changeusername" class="em">' . $txt['username_change'] . '</a>]' : '',
613
			'log_change' => true,
614
			'permission' => 'profile_identity',
615
			'prehtml' => allowedTo('admin_forum') && isset($_GET['changeusername']) ? '<div class="warningbox">' . $txt['username_warning'] . '</div>' : '',
616
			'input_validate' => function (&$value) {
617
				global $context, $user_info, $cur_profile;
618
619
				if (allowedTo('admin_forum'))
620
				{
621
					// We'll need this...
622
					require_once(SUBSDIR . '/Auth.subs.php');
623
624
					// Maybe they are trying to change their password as well?
625
					$resetPassword = true;
626
					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
introduced by
The condition validatePassword($_POST[...nfo['email'])) === null is always false.
Loading history...
627
					{
628
						$resetPassword = false;
629
					}
630
631
					// Do the reset... this will send them an email too.
632
					if ($resetPassword)
0 ignored issues
show
introduced by
The condition $resetPassword is always true.
Loading history...
633
					{
634
						resetPassword($context['id_member'], $value);
635
					}
636
					elseif ($value !== null)
637
					{
638
						$errors = ElkArte\Errors\ErrorContext::context('change_username', 0);
639
640
						validateUsername($context['id_member'], $value, 'change_username');
641
642
						// No errors we can proceed normally
643
						if (!$errors->hasErrors())
644
							updateMemberData($context['id_member'], array('member_name' => $value));
645
						else
646
						{
647
							// If there are "important" errors and you are not an admin: log the first error
648
							// Otherwise grab all of them and do not log anything
649
							$error_severity = $errors->hasErrors(1) && !$user_info['is_admin'] ? 1 : null;
650
							foreach ($errors->prepareErrors($error_severity) as $error)
651
								throw new Elk_Exception($error, $error_severity === null ? false : 'general');
652
						}
653
					}
654
				}
655
				return false;
656
			},
657
		),
658
		'passwrd1' => array(
659
			'type' => 'password',
660
			'label' => ucwords($txt['choose_pass']),
661
			'subtext' => $txt['password_strength'],
662
			'size' => 20,
663
			'value' => '',
664
			'enabled' => empty($cur_profile['openid_uri']),
665
			'permission' => 'profile_identity',
666
			'save_key' => 'passwd',
667
			// Note this will only work if passwrd2 also exists!
668
			'input_validate' => function (&$value) {
669
				global $user_info, $cur_profile;
670
671
				// If we didn't try it then ignore it!
672
				if ($value == '')
673
					return false;
674
675
				// Do the two entries for the password even match?
676
				if (!isset($_POST['passwrd2']) || $value != $_POST['passwrd2'])
677
					return 'bad_new_password';
678
679
				// Let's get the validation function into play...
680
				require_once(SUBSDIR . '/Auth.subs.php');
681
				$passwordErrors = validatePassword($value, $cur_profile['member_name'], array($cur_profile['real_name'], $user_info['username'], $user_info['name'], $user_info['email']));
682
683
				// Were there errors?
684
				if ($passwordErrors !== null)
0 ignored issues
show
introduced by
The condition $passwordErrors !== null is always true.
Loading history...
685
					return 'password_' . $passwordErrors;
686
687
				// Set up the new password variable... ready for storage.
688
				require_once(SUBSDIR . '/Auth.subs.php');
689
				$value = validateLoginPassword($value, '', $cur_profile['member_name'], true);
690
				return true;
691
			},
692
		),
693
		'passwrd2' => array(
694
			'type' => 'password',
695
			'label' => ucwords($txt['verify_pass']),
696
			'enabled' => empty($cur_profile['openid_uri']),
697
			'size' => 20,
698
			'value' => '',
699
			'permission' => 'profile_identity',
700
			'is_dummy' => true,
701
		),
702
		'enable_otp' => array(
703
			'type' => 'check',
704
			'value' => empty($cur_profile['enable_otp']) ? false : true,
705
			'subtext' => $txt['otp_enabled_help'],
706
			'label' => $txt['otp_enabled'],
707
			'permission' => 'profile_identity',
708
		),
709
		'otp_secret' => array(
710
			'type' => 'text',
711
			'label' => ucwords($txt['otp_token']),
712
			'subtext' => $txt['otp_token_help'],
713
			'enabled' => empty($cur_profile['openid_uri']),
714
			'size' => 20,
715
			'value' => empty($cur_profile['otp_secret']) ? '' : $cur_profile['otp_secret'],
716
			'postinput' => '<div style="display: inline-block;"><input type="button" value="' . $txt['otp_generate'] . '" onclick="generateSecret();"></div><div id="qrcode"></div>',
717
			'permission' => 'profile_identity',
718
		),
719
		// This does contact-related settings
720
		'receive_from' => array(
721
			'type' => 'select',
722
			'options' => array(
723
				$txt['receive_from_everyone'],
724
				$txt['receive_from_ignore'],
725
				$txt['receive_from_buddies'],
726
				$txt['receive_from_admins'],
727
			),
728
			'subtext' => $txt['receive_from_description'],
729
			'value' => empty($cur_profile['receive_from']) ? 0 : $cur_profile['receive_from'],
730
			'input_validate' => function (&$value) {
731
				global $cur_profile, $profile_vars;
732
733
				// Simple validate and apply the two "sub settings"
734
				$value = max(min($value, 3), 0);
735
736
				$cur_profile['receive_from'] = $profile_vars['receive_from'] = max(min((int) $_POST['receive_from'], 4), 0);
737
738
				return true;
739
			},
740
		),
741
		// This does ALL the pm settings
742
		'pm_settings' => array(
743
			'type' => 'callback',
744
			'callback_func' => 'pm_settings',
745
			'permission' => 'pm_read',
746
			'save_key' => 'pm_prefs',
747
			'preload' => function () {
748
				global $context, $cur_profile;
749
750
				$context['display_mode'] = $cur_profile['pm_prefs'] & 3;
751
				$context['send_email'] = $cur_profile['pm_email_notify'];
752
753
				return true;
754
			},
755
			'input_validate' => function (&$value) {
756
				global $cur_profile, $profile_vars;
757
758
				// Simple validate and apply the two "sub settings"
759
				$value = max(min($value, 2), 0);
760
761
				$cur_profile['pm_email_notify'] = $profile_vars['pm_email_notify'] = max(min((int) $_POST['pm_email_notify'], 2), 0);
762
763
				return true;
764
			},
765
		),
766
		'posts' => array(
767
			'type' => 'int',
768
			'label' => $txt['profile_posts'],
769
			'log_change' => true,
770
			'size' => 7,
771
			'permission' => 'moderate_forum',
772
			'input_validate' => function (&$value) {
773
				if (!is_numeric($value))
774
					return 'digits_only';
775
				else
776
					$value = $value != '' ? strtr($value, array(',' => '', '.' => '', ' ' => '')) : 0;
777
				return true;
778
			},
779
		),
780
		'real_name' => array(
781
			'type' => !empty($modSettings['allow_editDisplayName']) || allowedTo('moderate_forum') ? 'text' : 'label',
782
			'label' => $txt['name'],
783
			'subtext' => $txt['display_name_desc'],
784
			'log_change' => true,
785
			'input_attr' => array('maxlength="60"'),
786
			'permission' => 'profile_identity',
787
			'enabled' => !empty($modSettings['allow_editDisplayName']) || allowedTo('moderate_forum'),
788
			'input_validate' => function (&$value) {
789
				global $context, $cur_profile;
790
791
				$value = trim(preg_replace('~[\s]~u', ' ', $value));
792
793
				if (trim($value) == '')
794
					return 'no_name';
795
				elseif (Util::strlen($value) > 60)
796
					return 'name_too_long';
797
				elseif ($cur_profile['real_name'] != $value)
798
				{
799
					require_once(SUBSDIR . '/Members.subs.php');
800
					if (isReservedName($value, $context['id_member']))
801
						return 'name_taken';
802
				}
803
				return true;
804
			},
805
		),
806
		'secret_question' => array(
807
			'type' => 'text',
808
			'label' => $txt['secret_question'],
809
			'subtext' => $txt['secret_desc'],
810
			'size' => 50,
811
			'permission' => 'profile_identity',
812
		),
813
		'secret_answer' => array(
814
			'type' => 'text',
815
			'label' => $txt['secret_answer'],
816
			'subtext' => $txt['secret_desc2'],
817
			'size' => 20,
818
			'postinput' => '<span class="smalltext" style="margin-left: 4ex;">[<a href="' . $scripturl . '?action=quickhelp;help=secret_why_blank" onclick="return reqOverlayDiv(this.href);">' . $txt['secret_why_blank'] . '</a>]</span>',
819
			'value' => '',
820
			'permission' => 'profile_identity',
821
			'input_validate' => function (&$value) {
822
				global $cur_profile;
823
824
				if (empty($value))
825
				{
826
					require_once(SUBSDIR . '/Members.subs.php');
827
					$member = getBasicMemberData($cur_profile['id_member'], array('authentication' => true));
828
829
					// No previous answer was saved, so that\'s all good
830
					if (empty($member['secret_answer']))
831
					{
832
						return true;
833
					}
834
					// There is a previous secret answer to the secret question, so let\'s put it back in the db...
835
					else
836
					{
837
						$value = $member['secret_answer'];
838
						// We have to tell the code is an error otherwise an empty value will go into the db
839
						return false;
840
					}
841
				}
842
				$value = $value != '' ? md5($value) : '';
843
				return true;
844
			},
845
		),
846
		'signature' => array(
847
			'type' => 'callback',
848
			'callback_func' => 'signature_modify',
849
			'permission' => 'profile_extra',
850
			'enabled' => substr($modSettings['signature_settings'], 0, 1) == 1,
851
			'preload' => 'profileLoadSignatureData',
852
			'input_validate' => 'profileValidateSignature',
853
		),
854
		'show_online' => array(
855
			'type' => 'check',
856
			'label' => $txt['show_online'],
857
			'permission' => 'profile_identity',
858
			'enabled' => !empty($modSettings['allow_hideOnline']) || allowedTo('moderate_forum'),
859
		),
860
		'smiley_set' => array(
861
			'type' => 'callback',
862
			'callback_func' => 'smiley_pick',
863
			'enabled' => !empty($modSettings['smiley_sets_enable']),
864
			'permission' => 'profile_extra',
865
			'preload' => function () {
866
				global $modSettings, $context, $txt, $cur_profile;
867
868
				$context['member']['smiley_set']['id'] = empty($cur_profile['smiley_set']) ? '' : $cur_profile['smiley_set'];
869
				$context['smiley_sets'] = explode(',', 'none,,' . $modSettings['smiley_sets_known']);
870
				$set_names = explode("\n", $txt['smileys_none'] . "\n" . $txt['smileys_forum_board_default'] . "\n" . $modSettings['smiley_sets_names']);
871
				foreach ($context['smiley_sets'] as $i => $set)
872
				{
873
					$context['smiley_sets'][$i] = array(
874
						'id' => htmlspecialchars($set, ENT_COMPAT, 'UTF-8'),
875
						'name' => htmlspecialchars($set_names[$i], ENT_COMPAT, 'UTF-8'),
876
						'selected' => $set == $context['member']['smiley_set']['id']
877
					);
878
879
					if ($context['smiley_sets'][$i]['selected'])
880
						$context['member']['smiley_set']['name'] = $set_names[$i];
881
				}
882
				return true;
883
			},
884
			'input_validate' => function (&$value) {
885
				global $modSettings;
886
887
				$smiley_sets = explode(',', $modSettings['smiley_sets_known']);
888
				if (!in_array($value, $smiley_sets) && $value !== 'none')
889
					$value = '';
890
				return true;
891
			},
892
		),
893
		// Pretty much a dummy entry - it populates all the theme settings.
894
		'theme_settings' => array(
895
			'type' => 'callback',
896
			'callback_func' => 'theme_settings',
897
			'permission' => 'profile_extra',
898
			'is_dummy' => true,
899
			'preload' => function () {
900
				global $context, $user_info;
901
902
				loadLanguage('Settings');
903
904
				// Can they disable censoring?
905
				$context['allow_no_censored'] = false;
906
				if ($user_info['is_admin'] || $context['user']['is_owner'])
907
					$context['allow_no_censored'] = allowedTo('disable_censor');
908
909
				return true;
910
			},
911
		),
912
		'time_format' => array(
913
			'type' => 'callback',
914
			'callback_func' => 'timeformat_modify',
915
			'permission' => 'profile_extra',
916
			'preload' => function () {
917
				global $context, $user_info, $txt, $cur_profile, $modSettings;
918
919
				$context['easy_timeformats'] = array(
920
					array('format' => '', 'title' => $txt['timeformat_default']),
921
					array('format' => '%B %d, %Y, %I:%M:%S %p', 'title' => $txt['timeformat_easy1']),
922
					array('format' => '%B %d, %Y, %H:%M:%S', 'title' => $txt['timeformat_easy2']),
923
					array('format' => '%Y-%m-%d, %H:%M:%S', 'title' => $txt['timeformat_easy3']),
924
					array('format' => '%d %B %Y, %H:%M:%S', 'title' => $txt['timeformat_easy4']),
925
					array('format' => '%d-%m-%Y, %H:%M:%S', 'title' => $txt['timeformat_easy5'])
926
				);
927
928
				$context['member']['time_format'] = $cur_profile['time_format'];
929
				$context['current_forum_time'] = standardTime(time() - $user_info['time_offset'] * 3600, false);
930
				$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);
931
				$context['current_forum_time_hour'] = (int) strftime('%H', forum_time(false));
932
				return true;
933
			},
934
		),
935
		'time_offset' => array(
936
			'type' => 'callback',
937
			'callback_func' => 'timeoffset_modify',
938
			'permission' => 'profile_extra',
939
			'preload' => function () {
940
				global $context, $cur_profile;
941
942
				$context['member']['time_offset'] = $cur_profile['time_offset'];
943
				return true;
944
			},
945
			'input_validate' => function (&$value) {
946
				// Validate the time_offset...
947
				$value = (float) strtr($value, ',', '.');
948
949
				if ($value < -23.5 || $value > 23.5)
950
					return 'bad_offset';
951
952
				return true;
953
			},
954
		),
955
		'usertitle' => array(
956
			'type' => 'text',
957
			'label' => $txt['custom_title'],
958
			'log_change' => true,
959
			'input_attr' => array('maxlength="50"'),
960
			'size' => 50,
961
			'permission' => 'profile_title',
962
			'enabled' => !empty($modSettings['titlesEnable']),
963
			'input_validate' => function (&$value) {
964
				if (Util::strlen($value) > 50)
965
					return 'user_title_too_long';
966
967
				return true;
968
			},
969
		),
970
		'website_title' => array(
971
			'type' => 'text',
972
			'label' => $txt['website_title'],
973
			'subtext' => $txt['include_website_url'],
974
			'size' => 50,
975
			'permission' => 'profile_extra',
976
			'link_with' => 'website',
977
		),
978
		'website_url' => array(
979
			'type' => 'url',
980
			'label' => $txt['website_url'],
981
			'subtext' => $txt['complete_url'],
982
			'size' => 50,
983
			'permission' => 'profile_extra',
984
			// Fix the URL...
985
			'input_validate' => function (&$value) {
986
987
				$value = addProtocol($value, array('http://', 'https://', 'ftp://', 'ftps://'));
988
				if (strlen($value) < 8)
989
					$value = '';
990
				return true;
991
			},
992
			'link_with' => 'website',
993
		),
994
	);
995
996
	call_integration_hook('integrate_load_profile_fields', array(&$profile_fields));
997
998
	$disabled_fields = !empty($modSettings['disabled_profile_fields']) ? explode(',', $modSettings['disabled_profile_fields']) : array();
999
1000
	// Hard to imagine this won't be necessary
1001
	require_once(SUBSDIR . '/Members.subs.php');
1002
1003
	// For each of the above let's take out the bits which don't apply - to save memory and security!
1004
	foreach ($profile_fields as $key => $field)
1005
	{
1006
		// Do we have permission to do this?
1007
		if (isset($field['permission']) && !allowedTo(($context['user']['is_owner'] ? array($field['permission'] . '_own', $field['permission'] . '_any') : $field['permission'] . '_any')) && !allowedTo($field['permission']))
1008
			unset($profile_fields[$key]);
1009
1010
		// Is it enabled?
1011
		if (isset($field['enabled']) && !$field['enabled'])
1012
			unset($profile_fields[$key]);
1013
1014
		// Is it specifically disabled?
1015
		if (in_array($key, $disabled_fields) || (isset($field['link_with']) && in_array($field['link_with'], $disabled_fields)))
1016
			unset($profile_fields[$key]);
1017
	}
1018
}
1019
1020
/**
1021
 * Save the profile changes.
1022
 *
1023
 * @param string[] $fields
1024
 * @param string $hook
1025
 * @throws \Elk_Exception
1026
 */
1027
function saveProfileFields($fields, $hook)
1028
{
1029
	global $profile_fields, $profile_vars, $context, $old_profile, $post_errors, $cur_profile;
1030
1031
	if (!empty($hook))
1032
		call_integration_hook('integrate_' . $hook . '_profile_fields', array(&$fields));
1033
1034
	// Load them up.
1035
	loadProfileFields();
1036
1037
	// This makes things easier...
1038
	$old_profile = $cur_profile;
1039
1040
	// This allows variables to call activities when they save
1041
	// - by default just to reload their settings
1042
	$context['profile_execute_on_save'] = array();
1043
	if ($context['user']['is_owner'])
1044
		$context['profile_execute_on_save']['reload_user'] = 'profileReloadUser';
1045
1046
	// Assume we log nothing.
1047
	$context['log_changes'] = array();
1048
1049
	// Cycle through the profile fields working out what to do!
1050
	foreach ($fields as $key)
1051
	{
1052
		if (!isset($profile_fields[$key]))
1053
		{
1054
			continue;
1055
		}
1056
1057
		$field = $profile_fields[$key];
1058
1059
		if (!isset($_POST[$key]) || !empty($field['is_dummy']) || (isset($_POST['preview_signature']) && $key === 'signature'))
1060
			continue;
1061
1062
		// What gets updated?
1063
		$db_key = isset($field['save_key']) ? $field['save_key'] : $key;
1064
1065
		// Right - we have something that is enabled, we can act upon and has a value posted to it. Does it have a validation function?
1066
		if (isset($field['input_validate']))
1067
		{
1068
			$is_valid = $field['input_validate']($_POST[$key]);
1069
1070
			// An error occurred - set it as such!
1071
			if ($is_valid !== true)
1072
			{
1073
				// Is this an actual error?
1074
				if ($is_valid !== false)
1075
				{
1076
					$post_errors[$key] = $is_valid;
1077
					$profile_fields[$key]['is_error'] = $is_valid;
1078
				}
1079
1080
				// Retain the old value.
1081
				$cur_profile[$key] = $_POST[$key];
1082
				continue;
1083
			}
1084
		}
1085
1086
		// Are we doing a cast?
1087
		$field['cast_type'] = empty($field['cast_type']) ? $field['type'] : $field['cast_type'];
1088
1089
		// Finally, clean up certain types.
1090
		if ($field['cast_type'] === 'int')
1091
			$_POST[$key] = (int) $_POST[$key];
1092
		elseif ($field['cast_type'] === 'float')
1093
			$_POST[$key] = (float) $_POST[$key];
1094
		elseif ($field['cast_type'] === 'check')
1095
			$_POST[$key] = !empty($_POST[$key]) ? 1 : 0;
1096
1097
		// If we got here we're doing OK.
1098
		if ($field['type'] !== 'hidden' && (!isset($old_profile[$key]) || $_POST[$key] != $old_profile[$key]))
1099
		{
1100
			// Set the save variable.
1101
			$profile_vars[$db_key] = $_POST[$key];
1102
1103
			// And update the user profile.
1104
			$cur_profile[$key] = $_POST[$key];
1105
1106
			// Are we logging it?
1107
			if (!empty($field['log_change']) && isset($old_profile[$key]))
1108
				$context['log_changes'][$key] = array(
1109
					'previous' => $old_profile[$key],
1110
					'new' => $_POST[$key],
1111
				);
1112
		}
1113
1114
		// Logging group changes are a bit different...
1115
		if ($key === 'id_group' && $field['log_change'])
1116
		{
1117
			profileLoadGroups();
1118
1119
			// Any changes to primary group?
1120
			if ($_POST['id_group'] != $old_profile['id_group'])
1121
			{
1122
				$context['log_changes']['id_group'] = array(
1123
					'previous' => !empty($old_profile[$key]) && isset($context['member_groups'][$old_profile[$key]]) ? $context['member_groups'][$old_profile[$key]]['name'] : '',
1124
					'new' => !empty($_POST[$key]) && isset($context['member_groups'][$_POST[$key]]) ? $context['member_groups'][$_POST[$key]]['name'] : '',
1125
				);
1126
			}
1127
1128
			// Prepare additional groups for comparison.
1129
			$additional_groups = array(
1130
				'previous' => !empty($old_profile['additional_groups']) ? explode(',', $old_profile['additional_groups']) : array(),
1131
				'new' => !empty($_POST['additional_groups']) ? array_diff($_POST['additional_groups'], array(0)) : array(),
1132
			);
1133
1134
			sort($additional_groups['previous']);
1135
			sort($additional_groups['new']);
1136
1137
			// What about additional groups?
1138
			if ($additional_groups['previous'] != $additional_groups['new'])
1139
			{
1140
				foreach ($additional_groups as $type => $groups)
1141
				{
1142
					foreach ($groups as $id => $group)
1143
					{
1144
						if (isset($context['member_groups'][$group]))
1145
							$additional_groups[$type][$id] = $context['member_groups'][$group]['name'];
1146
						else
1147
							unset($additional_groups[$type][$id]);
1148
					}
1149
					$additional_groups[$type] = implode(', ', $additional_groups[$type]);
1150
				}
1151
1152
				$context['log_changes']['additional_groups'] = $additional_groups;
1153
			}
1154
		}
1155
	}
1156
1157
	// @todo Temporary
1158
	if ($context['user']['is_owner'])
1159
		$changeOther = allowedTo(array('profile_extra_any', 'profile_extra_own'));
1160
	else
1161
		$changeOther = allowedTo('profile_extra_any');
1162
1163
	if ($changeOther && empty($post_errors))
1164
	{
1165
		makeThemeChanges($context['id_member'], isset($_POST['id_theme']) ? (int) $_POST['id_theme'] : $old_profile['id_theme']);
1166
		if (!empty($_REQUEST['sa']))
1167
			makeCustomFieldChanges($context['id_member'], $_REQUEST['sa'], false);
1168
	}
1169
1170
	// Free memory!
1171
	unset($profile_fields);
1172
}
1173
1174
/**
1175
 * Validate an email address.
1176
 *
1177
 * @param string $email
1178
 * @param int $memID = 0
1179
 */
1180
function profileValidateEmail($email, $memID = 0)
1181
{
1182
	$db = database();
1183
1184
	// Check the name and email for validity.
1185
	$check = array();
1186
	$check['email'] = strtr($email, array('&#039;' => '\''));
1187
	if (Data_Validator::is_valid($check, array('email' => 'valid_email|required'), array('email' => 'trim')))
1188
		$email = $check['email'];
1189
	else
1190
		return empty($check['email']) ? 'no_email' : 'bad_email';
1191
1192
	// Email addresses should be and stay unique.
1193
	$request = $db->query('', '
1194
		SELECT id_member
1195
		FROM {db_prefix}members
1196
		WHERE ' . ($memID != 0 ? 'id_member != {int:selected_member} AND ' : '') . '
1197
			email_address = {string:email_address}
1198
		LIMIT 1',
1199
		array(
1200
			'selected_member' => $memID,
1201
			'email_address' => $email,
1202
		)
1203
	);
1204
	$num = $db->num_rows($request);
1205
	$db->free_result($request);
1206
1207
	return ($num > 0) ? 'email_taken' : true;
1208
}
1209
1210
/**
1211
 * Save the profile changes
1212
 *
1213
 * @param mixed[] $profile_vars
1214
 * @param int $memID id_member
1215
 * @throws Elk_Exception
1216
 */
1217
function saveProfileChanges(&$profile_vars, $memID)
1218
{
1219
	global $context, $user_profile;
1220
1221
	// These make life easier....
1222
	$old_profile = &$user_profile[$memID];
1223
1224
	// Permissions...
1225
	if ($context['user']['is_owner'])
1226
		$changeOther = allowedTo(array('profile_extra_any', 'profile_extra_own'));
1227
	else
1228
		$changeOther = allowedTo('profile_extra_any');
1229
1230
	// Arrays of all the changes - makes things easier.
1231
	$profile_bools = array(
1232
		'notify_announcements',
1233
		'notify_send_body',
1234
	);
1235
1236
	$profile_ints = array(
1237
		'notify_regularity',
1238
		'notify_types',
1239
	);
1240
1241
	$profile_floats = array(
1242
	);
1243
1244
	$profile_strings = array(
1245
		'buddy_list',
1246
		'ignore_boards',
1247
	);
1248
1249
	call_integration_hook('integrate_save_profile_changes', array(&$profile_bools, &$profile_ints, &$profile_floats, &$profile_strings));
1250
1251
	if (isset($_POST['sa']) && $_POST['sa'] === 'ignoreboards' && empty($_POST['ignore_brd']))
1252
		$_POST['ignore_brd'] = array();
1253
1254
	// Whatever it is set to is a dirty filthy thing.  Kinda like our minds.
1255
	unset($_POST['ignore_boards']);
1256
1257
	if (isset($_POST['ignore_brd']))
1258
	{
1259
		if (!is_array($_POST['ignore_brd']))
1260
			$_POST['ignore_brd'] = array($_POST['ignore_brd']);
1261
1262
		foreach ($_POST['ignore_brd'] as $k => $d)
1263
		{
1264
			$d = (int) $d;
1265
			if ($d != 0)
1266
				$_POST['ignore_brd'][$k] = $d;
1267
			else
1268
				unset($_POST['ignore_brd'][$k]);
1269
		}
1270
		$_POST['ignore_boards'] = implode(',', $_POST['ignore_brd']);
1271
		unset($_POST['ignore_brd']);
1272
	}
1273
1274
	// Here's where we sort out all the 'other' values...
1275
	if ($changeOther)
1276
	{
1277
		makeThemeChanges($memID, isset($_POST['id_theme']) ? (int) $_POST['id_theme'] : $old_profile['id_theme']);
1278
		makeNotificationChanges($memID);
1279
		if (!empty($_REQUEST['sa']))
1280
			makeCustomFieldChanges($memID, $_REQUEST['sa'], false);
1281
1282
		foreach ($profile_bools as $var)
1283
			if (isset($_POST[$var]))
1284
				$profile_vars[$var] = empty($_POST[$var]) ? '0' : '1';
1285
		foreach ($profile_ints as $var)
1286
			if (isset($_POST[$var]))
1287
				$profile_vars[$var] = $_POST[$var] != '' ? (int) $_POST[$var] : '';
1288
		foreach ($profile_floats as $var)
1289
			if (isset($_POST[$var]))
1290
				$profile_vars[$var] = (float) $_POST[$var];
1291
		foreach ($profile_strings as $var)
1292
			if (isset($_POST[$var]))
1293
				$profile_vars[$var] = $_POST[$var];
1294
	}
1295
}
1296
1297
/**
1298
 * Make any theme changes that are sent with the profile.
1299
 *
1300
 * @param int $memID
1301
 * @param int $id_theme
1302
 *
1303
 * @throws Elk_Exception no_access
1304
 */
1305
function makeThemeChanges($memID, $id_theme)
1306
{
1307
	global $modSettings, $context, $user_info;
1308
1309
	$db = database();
1310
1311
	$reservedVars = array(
1312
		'actual_theme_url',
1313
		'actual_images_url',
1314
		'base_theme_dir',
1315
		'base_theme_url',
1316
		'default_images_url',
1317
		'default_theme_dir',
1318
		'default_theme_url',
1319
		'default_template',
1320
		'images_url',
1321
		'number_recent_posts',
1322
		'smiley_sets_default',
1323
		'theme_dir',
1324
		'theme_id',
1325
		'theme_layers',
1326
		'theme_templates',
1327
		'theme_url',
1328
	);
1329
1330
	// Can't change reserved vars.
1331
	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))
1332
		throw new Elk_Exception('no_access', false);
1333
1334
	// Don't allow any overriding of custom fields with default or non-default options.
1335
	$request = $db->query('', '
1336
		SELECT col_name
1337
		FROM {db_prefix}custom_fields
1338
		WHERE active = {int:is_active}',
1339
		array(
1340
			'is_active' => 1,
1341
		)
1342
	);
1343
	$custom_fields = array();
1344
	while ($row = $db->fetch_assoc($request))
1345
		$custom_fields[] = $row['col_name'];
1346
	$db->free_result($request);
1347
1348
	// These are the theme changes...
1349
	$themeSetArray = array();
1350
	if (isset($_POST['options']) && is_array($_POST['options']))
1351
	{
1352
		foreach ($_POST['options'] as $opt => $val)
1353
		{
1354
			if (in_array($opt, $custom_fields))
1355
				continue;
1356
1357
			// These need to be controlled.
1358
			if ($opt === 'topics_per_page' || $opt === 'messages_per_page')
1359
				$val = max(0, min($val, 50));
1360
			// We don't set this per theme anymore.
1361
			elseif ($opt === 'allow_no_censored')
1362
				continue;
1363
1364
			$themeSetArray[] = array($id_theme, $memID, $opt, is_array($val) ? implode(',', $val) : $val);
1365
		}
1366
	}
1367
1368
	$erase_options = array();
1369
	if (isset($_POST['default_options']) && is_array($_POST['default_options']))
1370
	{
1371
		foreach ($_POST['default_options'] as $opt => $val)
1372
		{
1373
			if (in_array($opt, $custom_fields))
1374
				continue;
1375
1376
			// These need to be controlled.
1377
			if ($opt === 'topics_per_page' || $opt === 'messages_per_page')
1378
				$val = max(0, min($val, 50));
1379
			// Only let admins and owners change the censor.
1380
			elseif ($opt === 'allow_no_censored' && !$user_info['is_admin'] && !$context['user']['is_owner'])
1381
				continue;
1382
1383
			$themeSetArray[] = array(1, $memID, $opt, is_array($val) ? implode(',', $val) : $val);
1384
			$erase_options[] = $opt;
1385
		}
1386
	}
1387
1388
	// If themeSetArray isn't still empty, send it to the database.
1389
	if (empty($context['password_auth_failed']))
1390
	{
1391
		require_once(SUBSDIR . '/Themes.subs.php');
1392
		if (!empty($themeSetArray))
1393
			updateThemeOptions($themeSetArray);
1394
1395
		if (!empty($erase_options))
1396
			removeThemeOptions('custom', $memID, $erase_options);
1397
1398
		$themes = explode(',', $modSettings['knownThemes']);
1399
		foreach ($themes as $t)
1400
			Cache::instance()->remove('theme_settings-' . $t . ':' . $memID);
1401
	}
1402
}
1403
1404
/**
1405
 * Make any notification changes that need to be made.
1406
 *
1407
 * @param int $memID id_member
1408
 */
1409
function makeNotificationChanges($memID)
1410
{
1411
	$db = database();
1412
1413
	if (isset($_POST['notify_submit']))
1414
	{
1415
		$to_save = array();
1416
		foreach (getMemberNotificationsProfile($memID) as $mention => $data)
1417
		{
1418
			if (isset($_POST['notify'][$mention]) && !empty($_POST['notify'][$mention]['status']) && isset($data['data'][$_POST['notify'][$mention]['method']]))
1419
			{
1420
				$to_save[$mention] = (int) $_POST['notify'][$mention]['method'];
1421
			}
1422
			else
1423
				$to_save[$mention] = 0;
1424
		}
1425
		saveUserNotificationsPreferences($memID, $to_save);
1426
	}
1427
1428
	// Update the boards they are being notified on.
1429
	if (isset($_POST['edit_notify_boards']))
1430
	{
1431
		if (!isset($_POST['notify_boards']))
1432
			$_POST['notify_boards'] = array();
1433
1434
		// Make sure only integers are added/deleted.
1435
		foreach ($_POST['notify_boards'] as $index => $id)
1436
			$_POST['notify_boards'][$index] = (int) $id;
1437
1438
		// id_board = 0 is reserved for topic notifications only
1439
		$notification_wanted = array_diff($_POST['notify_boards'], array(0));
1440
1441
		// Gather up any any existing board notifications.
1442
		$request = $db->query('', '
1443
			SELECT id_board
1444
			FROM {db_prefix}log_notify
1445
			WHERE id_member = {int:selected_member}
1446
				AND id_board != {int:id_board}',
1447
			array(
1448
				'selected_member' => $memID,
1449
				'id_board' => 0,
1450
			)
1451
		);
1452
		$notification_current = array();
1453
		while ($row = $db->fetch_assoc($request))
1454
			$notification_current[] = $row['id_board'];
1455
		$db->free_result($request);
1456
1457
		// And remove what they no longer want
1458
		$notification_deletes = array_diff($notification_current, $notification_wanted);
1459
		if (!empty($notification_deletes))
1460
			$db->query('', '
1461
				DELETE FROM {db_prefix}log_notify
1462
				WHERE id_board IN ({array_int:board_list})
1463
					AND id_member = {int:selected_member}',
1464
				array(
1465
					'board_list' => $notification_deletes,
1466
					'selected_member' => $memID,
1467
				)
1468
			);
1469
1470
		// Now add in what they do want
1471
		$notification_inserts = array();
1472
		foreach ($notification_wanted as $id)
1473
			$notification_inserts[] = array($memID, $id);
1474
1475
		if (!empty($notification_inserts))
1476
			$db->insert('ignore',
1477
				'{db_prefix}log_notify',
1478
				array('id_member' => 'int', 'id_board' => 'int'),
1479
				$notification_inserts,
1480
				array('id_member', 'id_board')
1481
			);
1482
	}
1483
1484
	// We are editing topic notifications......
1485
	elseif (isset($_POST['edit_notify_topics']) && !empty($_POST['notify_topics']))
1486
	{
1487
		$edit_notify_topics = array();
1488
		foreach ($_POST['notify_topics'] as $index => $id)
1489
			$edit_notify_topics[$index] = (int) $id;
1490
1491
		// Make sure there are no zeros left.
1492
		$edit_notify_topics = array_diff($edit_notify_topics, array(0));
1493
1494
		$db->query('', '
1495
			DELETE FROM {db_prefix}log_notify
1496
			WHERE id_topic IN ({array_int:topic_list})
1497
				AND id_member = {int:selected_member}',
1498
			array(
1499
				'topic_list' => $edit_notify_topics,
1500
				'selected_member' => $memID,
1501
			)
1502
		);
1503
	}
1504
}
1505
1506
/**
1507
 * Save any changes to the custom profile fields
1508
 *
1509
 * @param int $memID
1510
 * @param string $area
1511
 * @param bool $sanitize = true
1512
 */
1513
function makeCustomFieldChanges($memID, $area, $sanitize = true)
1514
{
1515
	global $context, $user_profile, $user_info, $modSettings;
1516
1517
	$db = database();
1518
1519
	if ($sanitize && isset($_POST['customfield']))
1520
		$_POST['customfield'] = htmlspecialchars__recursive($_POST['customfield']);
1521
1522
	$where = $area === 'register' ? 'show_reg != 0' : 'show_profile = {string:area}';
1523
1524
	// Load the fields we are saving too - make sure we save valid data (etc).
1525
	$request = $db->query('', '
1526
		SELECT col_name, field_name, field_desc, field_type, field_length, field_options, default_value, show_reg, mask, private
1527
		FROM {db_prefix}custom_fields
1528
		WHERE ' . $where . '
1529
			AND active = {int:is_active}',
1530
		array(
1531
			'is_active' => 1,
1532
			'area' => $area,
1533
		)
1534
	);
1535
	$changes = array();
1536
	$log_changes = array();
1537
	while ($row = $db->fetch_assoc($request))
1538
	{
1539
		/* This means don't save if:
1540
			- The user is NOT an admin.
1541
			- The data is not freely viewable and editable by users.
1542
			- The data is not invisible to users but editable by the owner (or if it is the user is not the owner)
1543
			- The area isn't registration, and if it is that the field is not supposed to be shown there.
1544
		*/
1545
		if ($row['private'] != 0 && !allowedTo('admin_forum') && ($memID != $user_info['id'] || $row['private'] != 2) && ($area !== 'register' || $row['show_reg'] == 0))
1546
			continue;
1547
1548
		// Validate the user data.
1549
		if ($row['field_type'] === 'check')
1550
			$value = isset($_POST['customfield'][$row['col_name']]) ? 1 : 0;
1551
		elseif (in_array($row['field_type'], array('radio', 'select')))
1552
		{
1553
			$value = $row['default_value'];
1554
			$options = explode(',', $row['field_options']);
1555
1556
			foreach ($options as $k => $v)
1557
			{
1558
				if (isset($_POST['customfield'][$row['col_name']]) && $_POST['customfield'][$row['col_name']] == $k)
1559
				{
1560
					$key = $k;
1561
					$value = $v;
1562
				}
1563
			}
1564
		}
1565
		// Otherwise some form of text!
1566
		else
1567
		{
1568
			// TODO: This is a bit backwards.
1569
			$value = isset($_POST['customfield'][$row['col_name']]) ? $_POST['customfield'][$row['col_name']] : $row['default_value'];
1570
			$is_valid = isCustomFieldValid($row, $value);
1571
1572
			if ($is_valid !== true)
1573
			{
1574
				switch ($is_valid)
1575
				{
1576
					case 'custom_field_too_long':
1577
						$value = Util::substr($value, 0, $row['field_length']);
1578
						break;
1579
					case 'custom_field_invalid_email':
1580
					case 'custom_field_inproper_format':
1581
						$value = $row['default_value'];
1582
						break;
1583
				}
1584
			}
1585
1586
			if ($row['mask'] === 'number')
1587
				$value = (int) $value;
1588
		}
1589
1590
		// Did it change or has it been set?
1591
		if ((!isset($user_profile[$memID]['options'][$row['col_name']]) && !empty($value)) || (isset($user_profile[$memID]['options'][$row['col_name']]) && $user_profile[$memID]['options'][$row['col_name']] !== $value))
1592
		{
1593
			$log_changes[] = array(
1594
				'action' => 'customfield_' . $row['col_name'],
1595
				'log_type' => 'user',
1596
				'extra' => array(
1597
					'previous' => !empty($user_profile[$memID]['options'][$row['col_name']]) ? $user_profile[$memID]['options'][$row['col_name']] : '',
1598
					'new' => $value,
1599
					'applicator' => $user_info['id'],
1600
					'member_affected' => $memID,
1601
				),
1602
			);
1603
1604
			$changes[] = array($row['col_name'], $value, $memID);
1605
			if (in_array($row['field_type'], array('radio', 'select')))
1606
			{
1607
				$user_profile[$memID]['options'][$row['col_name']] = $value;
1608
				$user_profile[$memID]['options'][$row['col_name'] . '_key'] = $row['col_name'] . '_' . $key;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $key does not seem to be defined for all execution paths leading up to this point.
Loading history...
1609
			}
1610
			else
1611
			{
1612
				$user_profile[$memID]['options'][$row['col_name']] = $value;
1613
			}
1614
		}
1615
	}
1616
	$db->free_result($request);
1617
1618
	call_integration_hook('integrate_save_custom_profile_fields', array(&$changes, &$log_changes, $memID, $area, $sanitize));
1619
1620
	// Make those changes!
1621
	if (!empty($changes) && empty($context['password_auth_failed']))
1622
	{
1623
		$db->insert('replace',
1624
			'{db_prefix}custom_fields_data',
1625
			array('variable' => 'string-255', 'value' => 'string-65534', 'id_member' => 'int'),
1626
			$changes,
1627
			array('variable', 'id_member')
1628
		);
1629
1630
		if (!empty($log_changes) && !empty($modSettings['modlog_enabled']))
1631
			logActions($log_changes);
1632
	}
1633
}
1634
1635
/**
1636
 * Validates the value of a custom field
1637
 *
1638
 * @param mixed[] $field - An array describing the field. It consists of the
1639
 *                indexes:
1640
 *                  - type; if different from 'text', only the length is checked
1641
 *                  - mask; if empty or equal to 'none', only the length is
1642
 *                          checked, possible masks are: email, number, regex
1643
 *                  - field_length; maximum length of the field
1644
 * @param string|int $value - The value that we want to validate
1645
 * @return string|bool - A string representing the type of error, or true
1646
 */
1647
function isCustomFieldValid($field, $value)
1648
{
1649
	// Is it too long?
1650
	if ($field['field_length'] && $field['field_length'] < Util::strlen($value))
1651
		return 'custom_field_too_long';
1652
1653
	// Any masks to apply?
1654
	if ($field['field_type'] === 'text' && !empty($field['mask']) && $field['mask'] !== 'none')
1655
	{
1656
		// @todo We never error on this - just ignore it at the moment...
1657
		if ($field['mask'] === 'email' && !isValidEmail($value))
1658
			return 'custom_field_invalid_email';
1659
		elseif ($field['mask'] === 'number' && preg_match('~[^\d]~', $value))
1660
			return 'custom_field_not_number';
1661
		elseif (substr($field['mask'], 0, 5) === 'regex' && trim($value) !== '' && preg_match(substr($field['mask'], 5), $value) === 0)
1662
			return 'custom_field_inproper_format';
1663
	}
1664
1665
	return true;
1666
}
1667
1668
/**
1669
 * Send the user a new activation email if they need to reactivate!
1670
 */
1671
function profileSendActivation()
1672
{
1673
	global $profile_vars, $old_profile, $txt, $context, $scripturl, $cookiename, $cur_profile, $language, $modSettings;
1674
1675
	require_once(SUBSDIR . '/Mail.subs.php');
1676
1677
	// Shouldn't happen but just in case.
1678
	if (empty($profile_vars['email_address']))
1679
		return;
1680
1681
	$replacements = array(
1682
		'ACTIVATIONLINK' => $scripturl . '?action=register;sa=activate;u=' . $context['id_member'] . ';code=' . $old_profile['validation_code'],
1683
		'ACTIVATIONCODE' => $old_profile['validation_code'],
1684
		'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=register;sa=activate;u=' . $context['id_member'],
1685
	);
1686
1687
	// Send off the email.
1688
	$emaildata = loadEmailTemplate('activate_reactivate', $replacements, empty($cur_profile['lngfile']) || empty($modSettings['userLanguage']) ? $language : $cur_profile['lngfile']);
1689
	sendmail($profile_vars['email_address'], $emaildata['subject'], $emaildata['body'], null, null, false, 0);
1690
1691
	// Log the user out.
1692
	require_once(SUBSDIR . '/Logging.subs.php');
1693
	logOnline($context['id_member'], false);
1694
	$_SESSION['log_time'] = 0;
1695
	$_SESSION['login_' . $cookiename] = serialize(array(0, '', 0));
1696
1697
	if (isset($_COOKIE[$cookiename]))
1698
		$_COOKIE[$cookiename] = '';
1699
1700
	loadUserSettings();
1701
1702
	$context['user']['is_logged'] = false;
1703
	$context['user']['is_guest'] = true;
1704
1705
	// Send them to the done-with-registration-login screen.
1706
	loadTemplate('Register');
1707
1708
	$context['page_title'] = $txt['profile'];
1709
	$context['sub_template'] = 'after';
1710
	$context['title'] = $txt['activate_changed_email_title'];
1711
	$context['description'] = $txt['activate_changed_email_desc'];
1712
1713
	// We're gone!
1714
	obExit();
1715
}
1716
1717
/**
1718
 * Load key signature context data.
1719
 * @return boolean
1720
 */
1721
function profileLoadSignatureData()
1722
{
1723
	global $modSettings, $context, $txt, $cur_profile;
1724
1725
	// Signature limits.
1726
	list ($sig_limits, $sig_bbc) = explode(':', $modSettings['signature_settings']);
1727
	$sig_limits = explode(',', $sig_limits);
1728
1729
	$context['signature_enabled'] = isset($sig_limits[0]) ? $sig_limits[0] : 0;
1730
	$context['signature_limits'] = array(
1731
		'max_length' => isset($sig_limits[1]) ? $sig_limits[1] : 0,
1732
		'max_lines' => isset($sig_limits[2]) ? $sig_limits[2] : 0,
1733
		'max_images' => isset($sig_limits[3]) ? $sig_limits[3] : 0,
1734
		'max_smileys' => isset($sig_limits[4]) ? $sig_limits[4] : 0,
1735
		'max_image_width' => isset($sig_limits[5]) ? $sig_limits[5] : 0,
1736
		'max_image_height' => isset($sig_limits[6]) ? $sig_limits[6] : 0,
1737
		'max_font_size' => isset($sig_limits[7]) ? $sig_limits[7] : 0,
1738
		'bbc' => !empty($sig_bbc) ? explode(',', $sig_bbc) : array(),
1739
	);
1740
	// Kept this line in for backwards compatibility!
1741
	$context['max_signature_length'] = $context['signature_limits']['max_length'];
1742
1743
	// Warning message for signature image limits?
1744
	$context['signature_warning'] = '';
1745
	if ($context['signature_limits']['max_image_width'] && $context['signature_limits']['max_image_height'])
1746
		$context['signature_warning'] = sprintf($txt['profile_error_signature_max_image_size'], $context['signature_limits']['max_image_width'], $context['signature_limits']['max_image_height']);
1747
	elseif ($context['signature_limits']['max_image_width'] || $context['signature_limits']['max_image_height'])
1748
		$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']);
1749
1750
	$context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && function_exists('pspell_new');
1751
	if ($context['show_spellchecking'])
1752
		loadJavascriptFile('spellcheck.js', array('defer' => true));
1753
1754
	if (empty($context['do_preview']))
1755
		$context['member']['signature'] = empty($cur_profile['signature']) ? '' : str_replace(array('<br />', '<', '>', '"', '\''), array("\n", '&lt;', '&gt;', '&quot;', '&#039;'), $cur_profile['signature']);
1756
	else
1757
	{
1758
		$signature = !empty($_POST['signature']) ? $_POST['signature'] : '';
1759
		$validation = profileValidateSignature($signature);
1760
		if (empty($context['post_errors']))
1761
		{
1762
			loadLanguage('Errors');
1763
			$context['post_errors'] = array();
1764
		}
1765
1766
		$context['post_errors'][] = 'signature_not_yet_saved';
1767
		if ($validation !== true && $validation !== false)
1768
			$context['post_errors'][] = $validation;
1769
1770
		$context['member']['signature'] = censor($context['member']['signature']);
1771
		$context['member']['current_signature'] = $context['member']['signature'];
1772
		$signature = censor($signature);
1773
		$bbc_parser = \BBC\ParserWrapper::instance();
1774
		$context['member']['signature_preview'] = $bbc_parser->parseSignature($signature, true);
1775
		$context['member']['signature'] = $_POST['signature'];
1776
	}
1777
1778
	return true;
1779
}
1780
1781
/**
1782
 * Load avatar context data.
1783
 *
1784
 * @return boolean
1785
 */
1786
function profileLoadAvatarData()
1787
{
1788
	global $context, $cur_profile, $modSettings, $scripturl;
1789
1790
	$context['avatar_url'] = $modSettings['avatar_url'];
1791
1792
	$valid_protocol = preg_match('~^https' . (detectServer()->supportsSSL() ? '' : '?') . '://~i', $cur_profile['avatar']) === 1;
1793
	$schema = 'http' . (detectServer()->supportsSSL() ? 's' : '') . '://';
1794
1795
	// @todo Temporary
1796
	if ($context['user']['is_owner'])
1797
		$allowedChange = allowedTo('profile_set_avatar') && allowedTo(array('profile_extra_any', 'profile_extra_own'));
1798
	else
1799
		$allowedChange = allowedTo('profile_set_avatar') && allowedTo('profile_extra_any');
1800
1801
	// Default context.
1802
	$context['member']['avatar'] += array(
1803
		'custom' => $valid_protocol ? $cur_profile['avatar'] : $schema,
1804
		'selection' => $valid_protocol ? $cur_profile['avatar'] : '',
1805
		'id_attach' => $cur_profile['id_attach'],
1806
		'filename' => $cur_profile['filename'],
1807
		'allow_server_stored' => !empty($modSettings['avatar_stored_enabled']) && $allowedChange,
1808
		'allow_upload' =>  !empty($modSettings['avatar_upload_enabled']) && $allowedChange,
1809
		'allow_external' =>  !empty($modSettings['avatar_external_enabled']) && $allowedChange,
1810
		'allow_gravatar' =>  !empty($modSettings['avatar_gravatar_enabled']) && $allowedChange,
1811
	);
1812
1813
	if ($cur_profile['avatar'] === '' && $cur_profile['id_attach'] > 0 && $context['member']['avatar']['allow_upload'])
1814
	{
1815
		$context['member']['avatar'] += array(
1816
			'choice' => 'upload',
1817
			'server_pic' => 'blank.png',
1818
			'external' => $schema
1819
		);
1820
		$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'];
1821
	}
1822
	elseif ($valid_protocol && $context['member']['avatar']['allow_external'])
1823
		$context['member']['avatar'] += array(
1824
			'choice' => 'external',
1825
			'server_pic' => 'blank.png',
1826
			'external' => $cur_profile['avatar']
1827
		);
1828
	elseif ($cur_profile['avatar'] === 'gravatar' && $context['member']['avatar']['allow_gravatar'])
1829
		$context['member']['avatar'] += array(
1830
			'choice' => 'gravatar',
1831
			'server_pic' => 'blank.png',
1832
			'external' => 'https://'
1833
		);
1834
	elseif ($cur_profile['avatar'] != '' && file_exists($modSettings['avatar_directory'] . '/' . $cur_profile['avatar']) && $context['member']['avatar']['allow_server_stored'])
1835
		$context['member']['avatar'] += array(
1836
			'choice' => 'server_stored',
1837
			'server_pic' => $cur_profile['avatar'] == '' ? 'blank.png' : $cur_profile['avatar'],
1838
			'external' => $schema
1839
		);
1840
	else
1841
		$context['member']['avatar'] += array(
1842
			'choice' => 'none',
1843
			'server_pic' => 'blank.png',
1844
			'external' => $schema
1845
		);
1846
1847
	// Get a list of all the avatars.
1848
	if ($context['member']['avatar']['allow_server_stored'])
1849
	{
1850
		require_once(SUBSDIR . '/Attachments.subs.php');
1851
		$context['avatar_list'] = array();
1852
		$context['avatars'] = is_dir($modSettings['avatar_directory']) ? getServerStoredAvatars('', 0) : array();
1853
	}
1854
	else
1855
	{
1856
		$context['avatar_list'] = array();
1857
		$context['avatars'] = array();
1858
	}
1859
1860
	// Second level selected avatar...
1861
	$context['avatar_selected'] = substr(strrchr($context['member']['avatar']['server_pic'], '/'), 1);
1862
	return true;
1863
}
1864
1865
/**
1866
 * Loads all the member groups that this member can assign
1867
 * Places the result in context for template use
1868
 */
1869
function profileLoadGroups()
1870
{
1871
	global $cur_profile, $context, $user_settings;
1872
1873
	require_once(SUBSDIR . '/Membergroups.subs.php');
1874
1875
	$context['member_groups'] = getGroupsList();
1876
	$context['member_groups'][0]['is_primary'] = $cur_profile['id_group'] == 0;
1877
1878
	$curGroups = explode(',', $cur_profile['additional_groups']);
1879
1880
	foreach ($context['member_groups'] as $id_group => $row)
1881
	{
1882
		// Registered member was already taken care before
1883
		if ($id_group == 0)
1884
			continue;
1885
1886
		$context['member_groups'][$id_group]['is_primary'] = $cur_profile['id_group'] == $id_group;
1887
		$context['member_groups'][$id_group]['is_additional'] = in_array($id_group, $curGroups);
1888
		$context['member_groups'][$id_group]['can_be_additional'] = true;
1889
		$context['member_groups'][$id_group]['can_be_primary'] = $row['hidden'] != 2;
1890
	}
1891
1892
	$context['member']['group_id'] = $user_settings['id_group'];
1893
1894
	return true;
1895
}
1896
1897
/**
1898
 * Load all the languages for the profile.
1899
 */
1900
function profileLoadLanguages()
1901
{
1902
	global $context;
1903
1904
	$context['profile_languages'] = array();
1905
1906
	// Get our languages!
1907
	$languages = getLanguages();
1908
1909
	// Setup our languages.
1910
	foreach ($languages as $lang)
1911
		$context['profile_languages'][$lang['filename']] = $lang['name'];
1912
1913
	ksort($context['profile_languages']);
1914
1915
	// Return whether we should proceed with this.
1916
	return count($context['profile_languages']) > 1 ? true : false;
1917
}
1918
1919
/**
1920
 * Reload a users settings.
1921
 */
1922
function profileReloadUser()
1923
{
1924
	global $modSettings, $context, $cur_profile;
1925
1926
	// Log them back in - using the verify password as they must have matched and this one doesn't get changed by anyone!
1927
	if (isset($_POST['passwrd2']) && $_POST['passwrd2'] != '')
1928
	{
1929
		require_once(SUBSDIR . '/Auth.subs.php');
1930
		setLoginCookie(60 * $modSettings['cookieTime'], $context['id_member'], hash('sha256', Util::strtolower($cur_profile['member_name']) . un_htmlspecialchars($_POST['passwrd2']) . $cur_profile['password_salt']));
1931
	}
1932
1933
	loadUserSettings();
1934
	writeLog();
1935
}
1936
1937
/**
1938
 * Validate the signature
1939
 *
1940
 * @param string $value
1941
 */
1942
function profileValidateSignature(&$value)
1943
{
1944
	global $modSettings, $txt;
1945
1946
	require_once(SUBSDIR . '/Post.subs.php');
1947
1948
	// Admins can do whatever they hell they want!
1949
	if (!allowedTo('admin_forum'))
1950
	{
1951
		// Load all the signature limits.
1952
		list ($sig_limits, $sig_bbc) = explode(':', $modSettings['signature_settings']);
1953
		$sig_limits = explode(',', $sig_limits);
1954
		$disabledTags = !empty($sig_bbc) ? explode(',', $sig_bbc) : array();
1955
1956
		$unparsed_signature = strtr(un_htmlspecialchars($value), array("\r" => '', '&#039' => '\''));
1957
1958
		// Too many lines?
1959
		if (!empty($sig_limits[2]) && substr_count($unparsed_signature, "\n") >= $sig_limits[2])
1960
		{
1961
			$txt['profile_error_signature_max_lines'] = sprintf($txt['profile_error_signature_max_lines'], $sig_limits[2]);
1962
			return 'signature_max_lines';
1963
		}
1964
1965
		// Too many images?!
1966
		if (!empty($sig_limits[3]) && (substr_count(strtolower($unparsed_signature), '[img') + substr_count(strtolower($unparsed_signature), '<img')) > $sig_limits[3])
1967
		{
1968
			$txt['profile_error_signature_max_image_count'] = sprintf($txt['profile_error_signature_max_image_count'], $sig_limits[3]);
1969
			return 'signature_max_image_count';
1970
		}
1971
1972
		// What about too many smileys!
1973
		$smiley_parsed = $unparsed_signature;
1974
		$wrapper = \BBC\ParserWrapper::instance();
1975
		$parser = $wrapper->getSmileyParser();
1976
		$parser->setEnabled($GLOBALS['user_info']['smiley_set'] !== 'none' && trim($smiley_parsed) !== '');
1977
		$smiley_parsed = $parser->parseBlock($smiley_parsed);
1978
1979
		$smiley_count = substr_count(strtolower($smiley_parsed), '<img') - substr_count(strtolower($unparsed_signature), '<img');
1980
		if (!empty($sig_limits[4]) && $sig_limits[4] == -1 && $smiley_count > 0)
1981
			return 'signature_allow_smileys';
1982
		elseif (!empty($sig_limits[4]) && $sig_limits[4] > 0 && $smiley_count > $sig_limits[4])
1983
		{
1984
			$txt['profile_error_signature_max_smileys'] = sprintf($txt['profile_error_signature_max_smileys'], $sig_limits[4]);
1985
			return 'signature_max_smileys';
1986
		}
1987
1988
		// Maybe we are abusing font sizes?
1989
		if (!empty($sig_limits[7]) && preg_match_all('~\[size=([\d\.]+)(\]|px|pt|em|x-large|larger)~i', $unparsed_signature, $matches) !== false)
1990
		{
1991
			// Same as parse_bbc
1992
			$sizes = array(1 => 0.7, 2 => 1.0, 3 => 1.35, 4 => 1.45, 5 => 2.0, 6 => 2.65, 7 => 3.95);
1993
1994
			foreach ($matches[1] as $ind => $size)
1995
			{
1996
				$limit_broke = 0;
1997
1998
				// Just specifying as [size=x]?
1999
				if (empty($matches[2][$ind]))
2000
				{
2001
					$matches[2][$ind] = 'em';
2002
					$size = isset($sizes[(int) $size]) ? $sizes[(int) $size] : 0;
2003
				}
2004
2005
				// Attempt to allow all sizes of abuse, so to speak.
2006
				if ($matches[2][$ind] === 'px' && $size > $sig_limits[7])
2007
					$limit_broke = $sig_limits[7] . 'px';
2008
				elseif ($matches[2][$ind] === 'pt' && $size > ($sig_limits[7] * 0.75))
2009
					$limit_broke = ((int) $sig_limits[7] * 0.75) . 'pt';
2010
				elseif ($matches[2][$ind] === 'em' && $size > ((float) $sig_limits[7] / 14))
2011
					$limit_broke = ((float) $sig_limits[7] / 14) . 'em';
2012
				elseif ($matches[2][$ind] !== 'px' && $matches[2][$ind] !== 'pt' && $matches[2][$ind] !== 'em' && $sig_limits[7] < 18)
2013
					$limit_broke = 'large';
2014
2015
				if ($limit_broke)
2016
				{
2017
					$txt['profile_error_signature_max_font_size'] = sprintf($txt['profile_error_signature_max_font_size'], $limit_broke);
2018
					return 'signature_max_font_size';
2019
				}
2020
			}
2021
		}
2022
2023
		// The difficult one - image sizes! Don't error on this - just fix it.
2024
		if ((!empty($sig_limits[5]) || !empty($sig_limits[6])))
2025
		{
2026
			// Get all BBC tags...
2027
			preg_match_all('~\[img(\s+width=([\d]+))?(\s+height=([\d]+))?(\s+width=([\d]+))?\s*\](?:<br />)*([^<">]+?)(?:<br />)*\[/img\]~i', $unparsed_signature, $matches);
2028
2029
			// ... and all HTML ones.
2030
			preg_match_all('~<img\s+src=(?:")?((?:http://|ftp://|https://|ftps://).+?)(?:")?(?:\s+alt=(?:")?(.*?)(?:")?)?(?:\s?/)?>~i', $unparsed_signature, $matches2, PREG_PATTERN_ORDER);
2031
2032
			// And stick the HTML in the BBC.
2033
			if (!empty($matches2))
2034
			{
2035
				foreach ($matches2[0] as $ind => $dummy)
2036
				{
2037
					$matches[0][] = $matches2[0][$ind];
2038
					$matches[1][] = '';
2039
					$matches[2][] = '';
2040
					$matches[3][] = '';
2041
					$matches[4][] = '';
2042
					$matches[5][] = '';
2043
					$matches[6][] = '';
2044
					$matches[7][] = $matches2[1][$ind];
2045
				}
2046
			}
2047
2048
			$replaces = array();
2049
2050
			// Try to find all the images!
2051
			if (!empty($matches))
2052
			{
2053
				foreach ($matches[0] as $key => $image)
2054
				{
2055
					$width = -1;
2056
					$height = -1;
2057
2058
					// Does it have predefined restraints? Width first.
2059
					if ($matches[6][$key])
2060
						$matches[2][$key] = $matches[6][$key];
2061
2062
					if ($matches[2][$key] && $sig_limits[5] && $matches[2][$key] > $sig_limits[5])
2063
					{
2064
						$width = $sig_limits[5];
2065
						$matches[4][$key] = $matches[4][$key] * ($width / $matches[2][$key]);
2066
					}
2067
					elseif ($matches[2][$key])
2068
						$width = $matches[2][$key];
2069
2070
					// ... and height.
2071
					if ($matches[4][$key] && $sig_limits[6] && $matches[4][$key] > $sig_limits[6])
2072
					{
2073
						$height = $sig_limits[6];
2074
						if ($width != -1)
2075
							$width = $width * ($height / $matches[4][$key]);
2076
					}
2077
					elseif ($matches[4][$key])
2078
						$height = $matches[4][$key];
2079
2080
					// If the dimensions are still not fixed - we need to check the actual image.
2081
					if (($width == -1 && $sig_limits[5]) || ($height == -1 && $sig_limits[6]))
2082
					{
2083
						require_once(SUBSDIR . '/Attachments.subs.php');
2084
						$sizes = url_image_size($matches[7][$key]);
2085
						if (is_array($sizes))
2086
						{
2087
							// Too wide?
2088
							if ($sizes[0] > $sig_limits[5] && $sig_limits[5])
2089
							{
2090
								$width = $sig_limits[5];
2091
								$sizes[1] = $sizes[1] * ($width / $sizes[0]);
2092
							}
2093
2094
							// Too high?
2095
							if ($sizes[1] > $sig_limits[6] && $sig_limits[6])
2096
							{
2097
								$height = $sig_limits[6];
2098
								if ($width == -1)
2099
									$width = $sizes[0];
2100
								$width = $width * ($height / $sizes[1]);
2101
							}
2102
							elseif ($width != -1)
2103
								$height = $sizes[1];
2104
						}
2105
					}
2106
2107
					// Did we come up with some changes? If so remake the string.
2108
					if ($width != -1 || $height != -1)
2109
						$replaces[$image] = '[img' . ($width != -1 ? ' width=' . round($width) : '') . ($height != -1 ? ' height=' . round($height) : '') . ']' . $matches[7][$key] . '[/img]';
2110
				}
2111
2112
				if (!empty($replaces))
2113
					$value = str_replace(array_keys($replaces), array_values($replaces), $value);
2114
			}
2115
		}
2116
2117
		// @todo temporary, footnotes in signatures is not available at this time
2118
		$disabledTags[] = 'footnote';
2119
2120
		// Any disabled BBC?
2121
		$disabledSigBBC = implode('|', $disabledTags);
2122
2123
		if (!empty($disabledSigBBC))
2124
		{
2125
			if (preg_match('~\[(' . $disabledSigBBC . '[ =\]/])~i', $unparsed_signature, $matches) !== false && isset($matches[1]))
2126
			{
2127
				$disabledTags = array_unique($disabledTags);
2128
				$txt['profile_error_signature_disabled_bbc'] = sprintf($txt['profile_error_signature_disabled_bbc'], implode(', ', $disabledTags));
2129
				return 'signature_disabled_bbc';
2130
			}
2131
		}
2132
	}
2133
2134
	preparsecode($value);
2135
2136
	// Too long?
2137
	if (!allowedTo('admin_forum') && !empty($sig_limits[1]) && Util::strlen(str_replace('<br />', "\n", $value)) > $sig_limits[1])
2138
	{
2139
		$_POST['signature'] = trim(htmlspecialchars(str_replace('<br />', "\n", $value), ENT_QUOTES, 'UTF-8'));
2140
		$txt['profile_error_signature_max_length'] = sprintf($txt['profile_error_signature_max_length'], $sig_limits[1]);
2141
		return 'signature_max_length';
2142
	}
2143
2144
	return true;
2145
}
2146
2147
/**
2148
 * The avatar is incredibly complicated, what with the options... and what not.
2149
 *
2150
 * @todo argh, the avatar here. Take this out of here!
2151
 *
2152
 * @param mixed[] $value
2153
 *
2154
 * @return false|string
2155
 * @throws Elk_Exception attachments_no_write, attach_timeout
2156
 */
2157
function profileSaveAvatarData(&$value)
2158
{
2159
	global $modSettings, $profile_vars, $cur_profile, $context;
2160
2161
	$db = database();
2162
2163
	$memID = $context['id_member'];
2164
	if (empty($memID) && !empty($context['password_auth_failed']))
2165
		return false;
2166
2167
	// We need to know where we're going to be putting it..
2168
	require_once(SUBSDIR . '/Attachments.subs.php');
2169
	require_once(SUBSDIR . '/ManageAttachments.subs.php');
2170
	$uploadDir = getAvatarPath();
2171
	$id_folder = getAvatarPathID();
2172
2173
	$downloadedExternalAvatar = false;
2174
	$valid_http = isset($_POST['userpicpersonal']) && substr($_POST['userpicpersonal'], 0, 7) === 'http://' && strlen($_POST['userpicpersonal']) > 7;
2175
	$valid_https = isset($_POST['userpicpersonal']) && substr($_POST['userpicpersonal'], 0, 8) === 'https://' && strlen($_POST['userpicpersonal']) > 8;
2176
	if ($value === 'external' && !empty($modSettings['avatar_external_enabled']) && ($valid_http || $valid_https) && !empty($modSettings['avatar_download_external']))
0 ignored issues
show
introduced by
The condition $value === 'external' is always false.
Loading history...
2177
	{
2178
		loadLanguage('Post');
2179
		if (!is_writable($uploadDir))
2180
			throw new Elk_Exception('attachments_no_write', 'critical');
2181
2182
		require_once(SUBSDIR . '/Package.subs.php');
2183
2184
		$url = parse_url($_POST['userpicpersonal']);
2185
		$contents = fetch_web_data((empty($url['scheme']) ? 'http://' : $url['scheme'] . '://') . $url['host'] . (empty($url['port']) ? '' : ':' . $url['port']) . str_replace(' ', '%20', trim($url['path'])));
2186
2187
		if ($contents !== false)
2188
		{
2189
			// Create a hashed name to save
2190
			$new_avatar_name = $uploadDir . '/' . getAttachmentFilename('avatar_tmp_' . $memID, null, null, true);
2191
			if (file_put_contents($new_avatar_name, $contents) !== false)
2192
			{
2193
				$downloadedExternalAvatar = true;
2194
				$_FILES['attachment']['tmp_name'] = $new_avatar_name;
2195
			}
2196
		}
2197
	}
2198
2199
	if ($value === 'none')
0 ignored issues
show
introduced by
The condition $value === 'none' is always false.
Loading history...
2200
	{
2201
		$profile_vars['avatar'] = '';
2202
2203
		// Reset the attach ID.
2204
		$cur_profile['id_attach'] = 0;
2205
		$cur_profile['attachment_type'] = 0;
2206
		$cur_profile['filename'] = '';
2207
2208
		removeAttachments(array('id_member' => $memID));
2209
	}
2210
	elseif ($value === 'server_stored' && !empty($modSettings['avatar_stored_enabled']))
0 ignored issues
show
introduced by
The condition $value === 'server_stored' is always false.
Loading history...
2211
	{
2212
		$profile_vars['avatar'] = strtr(empty($_POST['file']) ? (empty($_POST['cat']) ? '' : $_POST['cat']) : $_POST['file'], array('&amp;' => '&'));
2213
		$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']) : '';
2214
2215
		// Clear current profile...
2216
		$cur_profile['id_attach'] = 0;
2217
		$cur_profile['attachment_type'] = 0;
2218
		$cur_profile['filename'] = '';
2219
2220
		// Get rid of their old avatar. (if uploaded.)
2221
		removeAttachments(array('id_member' => $memID));
2222
	}
2223
	elseif ($value === 'gravatar' && !empty($modSettings['avatar_gravatar_enabled']))
0 ignored issues
show
introduced by
The condition $value === 'gravatar' is always false.
Loading history...
2224
	{
2225
		$profile_vars['avatar'] = 'gravatar';
2226
2227
		// Reset the attach ID.
2228
		$cur_profile['id_attach'] = 0;
2229
		$cur_profile['attachment_type'] = 0;
2230
		$cur_profile['filename'] = '';
2231
2232
		removeAttachments(array('id_member' => $memID));
2233
	}
2234
	elseif ($value === 'external' && !empty($modSettings['avatar_external_enabled']) && ($valid_http || $valid_https) && empty($modSettings['avatar_download_external']))
0 ignored issues
show
introduced by
The condition $value === 'external' is always false.
Loading history...
2235
	{
2236
		// We need these clean...
2237
		$cur_profile['id_attach'] = 0;
2238
		$cur_profile['attachment_type'] = 0;
2239
		$cur_profile['filename'] = '';
2240
2241
		// Remove any attached avatar...
2242
		removeAttachments(array('id_member' => $memID));
2243
2244
		$profile_vars['avatar'] = str_replace(' ', '%20', preg_replace('~action(?:=|%3d)(?!dlattach)~i', 'action-', $_POST['userpicpersonal']));
2245
2246
		if (preg_match('~^https?:///?$~i', $profile_vars['avatar']) === 1)
2247
			$profile_vars['avatar'] = '';
2248
		// Trying to make us do something we'll regret?
2249
		elseif ((!$valid_http && !$valid_https) || ($valid_http && detectServer()->supportsSSL()))
2250
			return 'bad_avatar';
2251
		// Should we check dimensions?
2252
		elseif (!empty($modSettings['avatar_max_height']) || !empty($modSettings['avatar_max_width']))
2253
		{
2254
			// Now let's validate the avatar.
2255
			$sizes = url_image_size($profile_vars['avatar']);
2256
2257
			if (is_array($sizes) && (($sizes[0] > $modSettings['avatar_max_width'] && !empty($modSettings['avatar_max_width'])) || ($sizes[1] > $modSettings['avatar_max_height'] && !empty($modSettings['avatar_max_height']))))
2258
			{
2259
				// Houston, we have a problem. The avatar is too large!!
2260
				if ($modSettings['avatar_action_too_large'] === 'option_refuse')
2261
					return 'bad_avatar';
2262
				elseif ($modSettings['avatar_action_too_large'] === 'option_download_and_resize')
2263
				{
2264
					// @todo remove this if appropriate
2265
					require_once(SUBSDIR . '/Attachments.subs.php');
2266
					if (saveAvatar($profile_vars['avatar'], $memID, $modSettings['avatar_max_width'], $modSettings['avatar_max_height']))
2267
					{
2268
						$profile_vars['avatar'] = '';
2269
						$cur_profile['id_attach'] = $modSettings['new_avatar_data']['id'];
2270
						$cur_profile['filename'] = $modSettings['new_avatar_data']['filename'];
2271
						$cur_profile['attachment_type'] = $modSettings['new_avatar_data']['type'];
2272
					}
2273
					else
2274
						return 'bad_avatar';
2275
				}
2276
			}
2277
		}
2278
	}
2279
	elseif (($value === 'upload' && !empty($modSettings['avatar_upload_enabled'])) || $downloadedExternalAvatar)
0 ignored issues
show
introduced by
The condition $value === 'upload' is always false.
Loading history...
introduced by
The condition $downloadedExternalAvatar is always false.
Loading history...
2280
	{
2281
		if ((isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') || $downloadedExternalAvatar)
2282
		{
2283
			// Get the dimensions of the image.
2284
			if (!$downloadedExternalAvatar)
2285
			{
2286
				if (!is_writable($uploadDir))
2287
				{
2288
					loadLanguage('Post');
2289
					throw new Elk_Exception('attachments_no_write', 'critical');
2290
				}
2291
2292
				$new_avatar_name = $uploadDir . '/' . getAttachmentFilename('avatar_tmp_' . $memID, null, null, true);
2293
				if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $new_avatar_name))
2294
				{
2295
					loadLanguage('Post');
2296
					throw new Elk_Exception('attach_timeout', 'critical');
2297
				}
2298
2299
				$_FILES['attachment']['tmp_name'] = $new_avatar_name;
2300
			}
2301
2302
			// If there is no size, then it's probably not a valid pic, so lets remove it.
2303
			$sizes = elk_getimagesize($_FILES['attachment']['tmp_name'], false);
2304
			if ($sizes === false)
2305
			{
2306
				@unlink($_FILES['attachment']['tmp_name']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

2306
				/** @scrutinizer ignore-unhandled */ @unlink($_FILES['attachment']['tmp_name']);

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2307
				return 'bad_avatar';
2308
			}
2309
			// Check whether the image is too large.
2310
			elseif ((!empty($modSettings['avatar_max_width']) && $sizes[0] > $modSettings['avatar_max_width']) || (!empty($modSettings['avatar_max_height']) && $sizes[1] > $modSettings['avatar_max_height']))
2311
			{
2312
				if (!empty($modSettings['avatar_action_too_large']) && $modSettings['avatar_action_too_large'] === 'option_download_and_resize')
2313
				{
2314
					// Attempt to chmod it.
2315
					@chmod($_FILES['attachment']['tmp_name'], 0644);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

2315
					/** @scrutinizer ignore-unhandled */ @chmod($_FILES['attachment']['tmp_name'], 0644);

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2316
2317
					// @todo remove this require when appropriate
2318
					require_once(SUBSDIR . '/Attachments.subs.php');
2319
					if (!saveAvatar($_FILES['attachment']['tmp_name'], $memID, $modSettings['avatar_max_width'], $modSettings['avatar_max_height']))
2320
					{
2321
						// Something went wrong, so lets delete this offender
2322
						@unlink($_FILES['attachment']['tmp_name']);
2323
						return 'bad_avatar';
2324
					}
2325
2326
					// Reset attachment avatar data.
2327
					$cur_profile['id_attach'] = $modSettings['new_avatar_data']['id'];
2328
					$cur_profile['filename'] = $modSettings['new_avatar_data']['filename'];
2329
					$cur_profile['attachment_type'] = $modSettings['new_avatar_data']['type'];
2330
				}
2331
				elseif (!empty($modSettings['avatar_action_too_large']) && !empty($modSettings['avatar_reencode']))
2332
				{
2333
					// Attempt to chmod it.
2334
					@chmod($_FILES['attachment']['tmp_name'], 0644);
2335
2336
					require_once(SUBSDIR . '/Graphics.subs.php');
2337
					if (!reencodeImage($_FILES['attachment']['tmp_name'], $sizes[2]))
2338
					{
2339
						@unlink($_FILES['attachment']['tmp_name']);
2340
						return 'bad_avatar';
2341
					}
2342
2343
					// @todo remove this require when appropriate
2344
					require_once(SUBSDIR . '/Attachments.subs.php');
2345
					if (!saveAvatar($_FILES['attachment']['tmp_name'], $memID, $modSettings['avatar_max_width'], $modSettings['avatar_max_height']))
2346
					{
2347
						// Something went wrong, so lets delete this offender
2348
						@unlink($_FILES['attachment']['tmp_name']);
2349
						return 'bad_avatar5';
2350
					}
2351
2352
					// Reset attachment avatar data.
2353
					$cur_profile['id_attach'] = $modSettings['new_avatar_data']['id'];
2354
					$cur_profile['filename'] = $modSettings['new_avatar_data']['filename'];
2355
					$cur_profile['attachment_type'] = $modSettings['new_avatar_data']['type'];
2356
				}
2357
				else
2358
				{
2359
					@unlink($_FILES['attachment']['tmp_name']);
2360
					return 'bad_avatar';
2361
				}
2362
			}
2363
			elseif (is_array($sizes))
2364
			{
2365
				// Now try to find an infection.
2366
				require_once(SUBSDIR . '/Graphics.subs.php');
2367
				if (!checkImageContents($_FILES['attachment']['tmp_name'], !empty($modSettings['avatar_paranoid'])))
2368
				{
2369
					// It's bad. Try to re-encode the contents?
2370
					if (empty($modSettings['avatar_reencode']) || (!reencodeImage($_FILES['attachment']['tmp_name'], $sizes[2])))
2371
					{
2372
						@unlink($_FILES['attachment']['tmp_name']);
2373
						return 'bad_avatar';
2374
					}
2375
2376
					// We were successful. However, at what price?
2377
					$sizes = elk_getimagesize($_FILES['attachment']['tmp_name'], false);
2378
2379
					// Hard to believe this would happen, but can you bet?
2380
					if ($sizes === false)
2381
					{
2382
						@unlink($_FILES['attachment']['tmp_name']);
2383
						return 'bad_avatar';
2384
					}
2385
				}
2386
2387
				$extensions = array(
2388
					'1' => 'gif',
2389
					'2' => 'jpg',
2390
					'3' => 'png',
2391
					'6' => 'bmp'
2392
				);
2393
2394
				$extension = isset($extensions[$sizes[2]]) ? $extensions[$sizes[2]] : 'bmp';
2395
				$mime_type = 'image/' . ($extension === 'jpg' ? 'jpeg' : ($extension === 'bmp' ? 'x-ms-bmp' : $extension));
2396
				$destName = 'avatar_' . $memID . '_' . time() . '.' . $extension;
2397
				list ($width, $height) = elk_getimagesize($_FILES['attachment']['tmp_name']);
2398
				$file_hash = empty($modSettings['custom_avatar_enabled']) ? getAttachmentFilename($destName, null, null, true) : '';
2399
2400
				// Remove previous attachments this member might have had.
2401
				removeAttachments(array('id_member' => $memID));
2402
2403
				$db->insert('',
2404
					'{db_prefix}attachments',
2405
					array(
2406
						'id_member' => 'int', 'attachment_type' => 'int', 'filename' => 'string', 'file_hash' => 'string', 'fileext' => 'string', 'size' => 'int',
2407
						'width' => 'int', 'height' => 'int', 'mime_type' => 'string', 'id_folder' => 'int',
2408
					),
2409
					array(
2410
						$memID, (empty($modSettings['custom_avatar_enabled']) ? 0 : 1), $destName, $file_hash, $extension, filesize($_FILES['attachment']['tmp_name']),
2411
						(int) $width, (int) $height, $mime_type, $id_folder,
2412
					),
2413
					array('id_attach')
2414
				);
2415
2416
				$cur_profile['id_attach'] = $db->insert_id('{db_prefix}attachments', 'id_attach');
2417
				$cur_profile['filename'] = $destName;
2418
				$cur_profile['attachment_type'] = empty($modSettings['custom_avatar_enabled']) ? 0 : 1;
2419
2420
				$destinationPath = $uploadDir . '/' . (empty($file_hash) ? $destName : $cur_profile['id_attach'] . '_' . $file_hash . '.elk');
2421
				if (!rename($_FILES['attachment']['tmp_name'], $destinationPath))
2422
				{
2423
					loadLanguage('Post');
2424
					// I guess a man can try.
2425
					removeAttachments(array('id_member' => $memID));
2426
					throw new Elk_Exception('attach_timeout', 'critical');
2427
				}
2428
2429
				// Attempt to chmod it.
2430
				@chmod($uploadDir . '/' . $destinationPath, 0644);
2431
			}
2432
			$profile_vars['avatar'] = '';
2433
2434
			// Delete any temporary file.
2435
			if (file_exists($_FILES['attachment']['tmp_name']))
2436
				@unlink($_FILES['attachment']['tmp_name']);
2437
		}
2438
		// Selected the upload avatar option and had one already uploaded before or didn't upload one.
2439
		else
2440
			$profile_vars['avatar'] = '';
2441
	}
2442
	else
2443
		$profile_vars['avatar'] = '';
2444
2445
	// Setup the profile variables so it shows things right on display!
2446
	$cur_profile['avatar'] = $profile_vars['avatar'];
2447
2448
	return false;
2449
}
2450
2451
/**
2452
 * Save a members group.
2453
 *
2454
 * @param int $value
2455
 *
2456
 * @return bool
2457
 * @throws Elk_Exception at_least_one_admin
2458
 */
2459
function profileSaveGroups(&$value)
2460
{
2461
	global $profile_vars, $old_profile, $context, $cur_profile;
2462
2463
	$db = database();
2464
2465
	// Do we need to protect some groups?
2466
	if (!allowedTo('admin_forum'))
2467
	{
2468
		$request = $db->query('', '
2469
			SELECT id_group
2470
			FROM {db_prefix}membergroups
2471
			WHERE group_type = {int:is_protected}',
2472
			array(
2473
				'is_protected' => 1,
2474
			)
2475
		);
2476
		$protected_groups = array(1);
2477
		while ($row = $db->fetch_assoc($request))
2478
			$protected_groups[] = $row['id_group'];
2479
		$db->free_result($request);
2480
2481
		$protected_groups = array_unique($protected_groups);
2482
	}
2483
2484
	// The account page allows the change of your id_group - but not to a protected group!
2485
	if (empty($protected_groups) || count(array_intersect(array((int) $value, $old_profile['id_group']), $protected_groups)) == 0)
2486
		$value = (int) $value;
2487
	// ... otherwise it's the old group sir.
2488
	else
2489
		$value = $old_profile['id_group'];
2490
2491
	// Find the additional membergroups (if any)
2492
	if (isset($_POST['additional_groups']) && is_array($_POST['additional_groups']))
2493
	{
2494
		$additional_groups = array();
2495
		foreach ($_POST['additional_groups'] as $group_id)
2496
		{
2497
			$group_id = (int) $group_id;
2498
			if (!empty($group_id) && (empty($protected_groups) || !in_array($group_id, $protected_groups)))
2499
				$additional_groups[] = $group_id;
2500
		}
2501
2502
		// Put the protected groups back in there if you don't have permission to take them away.
2503
		$old_additional_groups = explode(',', $old_profile['additional_groups']);
2504
		foreach ($old_additional_groups as $group_id)
2505
		{
2506
			if (!empty($protected_groups) && in_array($group_id, $protected_groups))
2507
				$additional_groups[] = $group_id;
2508
		}
2509
2510
		if (implode(',', $additional_groups) !== $old_profile['additional_groups'])
2511
		{
2512
			$profile_vars['additional_groups'] = implode(',', $additional_groups);
2513
			$cur_profile['additional_groups'] = implode(',', $additional_groups);
2514
		}
2515
	}
2516
2517
	// Too often, people remove delete their own account, or something.
2518
	if (in_array(1, explode(',', $old_profile['additional_groups'])) || $old_profile['id_group'] == 1)
2519
	{
2520
		$stillAdmin = $value == 1 || (isset($additional_groups) && in_array(1, $additional_groups));
2521
2522
		// If they would no longer be an admin, look for any other...
2523
		if (!$stillAdmin)
2524
		{
2525
			$request = $db->query('', '
2526
				SELECT id_member
2527
				FROM {db_prefix}members
2528
				WHERE (id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0)
2529
					AND id_member != {int:selected_member}
2530
				LIMIT 1',
2531
				array(
2532
					'admin_group' => 1,
2533
					'selected_member' => $context['id_member'],
2534
				)
2535
			);
2536
			list ($another) = $db->fetch_row($request);
2537
			$db->free_result($request);
2538
2539
			if (empty($another))
2540
				throw new Elk_Exception('at_least_one_admin', 'critical');
2541
		}
2542
	}
2543
2544
	// If we are changing group status, update permission cache as necessary.
2545
	if ($value != $old_profile['id_group'] || isset($profile_vars['additional_groups']))
2546
	{
2547
		if ($context['user']['is_owner'])
2548
			$_SESSION['mc']['time'] = 0;
2549
		else
2550
			updateSettings(array('settings_updated' => time()));
2551
	}
2552
2553
	return true;
2554
}
2555
2556
/**
2557
 * Get the data about a users warnings.
2558
 * Returns an array of them
2559
 *
2560
 * @param int $start The item to start with (for pagination purposes)
2561
 * @param int $items_per_page  The number of items to show per page
2562
 * @param string $sort A string indicating how to sort the results
2563
 * @param int $memID the member ID
2564
 */
2565
function list_getUserWarnings($start, $items_per_page, $sort, $memID)
2566
{
2567
	global $scripturl;
2568
2569
	$db = database();
2570
2571
	$request = $db->query('', '
2572
		SELECT COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, lc.member_name) AS member_name,
2573
			lc.log_time, lc.body, lc.counter, lc.id_notice
2574
		FROM {db_prefix}log_comments AS lc
2575
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lc.id_member)
2576
		WHERE lc.id_recipient = {int:selected_member}
2577
			AND lc.comment_type = {string:warning}
2578
		ORDER BY ' . $sort . '
2579
		LIMIT ' . $start . ', ' . $items_per_page,
2580
		array(
2581
			'selected_member' => $memID,
2582
			'warning' => 'warning',
2583
		)
2584
	);
2585
	$previous_warnings = array();
2586
	while ($row = $db->fetch_assoc($request))
2587
	{
2588
		$previous_warnings[] = array(
2589
			'issuer' => array(
2590
				'id' => $row['id_member'],
2591
				'link' => $row['id_member'] ? ('<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['member_name'] . '</a>') : $row['member_name'],
2592
			),
2593
			'time' => standardTime($row['log_time']),
2594
			'html_time' => htmlTime($row['log_time']),
2595
			'timestamp' => forum_time(true, $row['log_time']),
2596
			'reason' => $row['body'],
2597
			'counter' => $row['counter'] > 0 ? '+' . $row['counter'] : $row['counter'],
2598
			'id_notice' => $row['id_notice'],
2599
		);
2600
	}
2601
	$db->free_result($request);
2602
2603
	return $previous_warnings;
2604
}
2605
2606
/**
2607
 * Get the number of warnings a user has.
2608
 * Returns the total number of warnings for the user
2609
 *
2610
 * @param int $memID
2611
 * @return int the number of warnings
2612
 */
2613
function list_getUserWarningCount($memID)
2614
{
2615
	$db = database();
2616
2617
	$request = $db->query('', '
2618
		SELECT COUNT(*)
2619
		FROM {db_prefix}log_comments
2620
		WHERE id_recipient = {int:selected_member}
2621
			AND comment_type = {string:warning}',
2622
		array(
2623
			'selected_member' => $memID,
2624
			'warning' => 'warning',
2625
		)
2626
	);
2627
	list ($total_warnings) = $db->fetch_row($request);
2628
	$db->free_result($request);
2629
2630
	return $total_warnings;
2631
}
2632
2633
/**
2634
 * Get a list of attachments for this user
2635
 * (used by createList() callback and others)
2636
 *
2637
 * @param int $start The item to start with (for pagination purposes)
2638
 * @param int $items_per_page  The number of items to show per page
2639
 * @param string $sort A string indicating how to sort the results
2640
 * @param int[] $boardsAllowed
2641
 * @param integer $memID
2642
 * @param int[]|null|boolean $exclude_boards
2643
 */
2644
function profileLoadAttachments($start, $items_per_page, $sort, $boardsAllowed, $memID, $exclude_boards = null)
2645
{
2646
	global $board, $modSettings, $context, $settings, $scripturl, $txt;
2647
2648
	$db = database();
2649
2650
	if ($exclude_boards === null && !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0)
2651
		$exclude_boards = array($modSettings['recycle_board']);
2652
2653
	// Retrieve some attachments.
2654
	$request = $db->query('', '
2655
		SELECT a.id_attach, a.id_msg, a.filename, a.downloads, a.approved, a.fileext, a.width, a.height, ' .
2656
			(empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : ' COALESCE(thumb.id_attach, 0) AS id_thumb, thumb.width AS thumb_width, thumb.height AS thumb_height, ') . '
2657
			m.id_msg, m.id_topic, m.id_board, m.poster_time, m.subject, b.name
2658
		FROM {db_prefix}attachments AS a' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : '
2659
			LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)') . '
2660
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
2661
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board AND {query_see_board})
2662
		WHERE a.attachment_type = {int:attachment_type}
2663
			AND a.id_msg != {int:no_message}
2664
			AND m.id_member = {int:current_member}' . (!empty($board) ? '
2665
			AND b.id_board = {int:board}' : '') . (!in_array(0, $boardsAllowed) ? '
2666
			AND b.id_board IN ({array_int:boards_list})' : '') . (!empty($exclude_boards) ? '
2667
			AND b.id_board NOT IN ({array_int:exclude_boards})' : '') . (!$modSettings['postmod_active'] || $context['user']['is_owner'] ? '' : '
2668
			AND m.approved = {int:is_approved}') . '
2669
		ORDER BY {raw:sort}
2670
		LIMIT {int:offset}, {int:limit}',
2671
		array(
2672
			'boards_list' => $boardsAllowed,
2673
			'exclude_boards' => $exclude_boards,
2674
			'attachment_type' => 0,
2675
			'no_message' => 0,
2676
			'current_member' => $memID,
2677
			'is_approved' => 1,
2678
			'board' => $board,
2679
			'sort' => $sort,
2680
			'offset' => $start,
2681
			'limit' => $items_per_page,
2682
		)
2683
	);
2684
	$attachments = array();
2685
	while ($row = $db->fetch_assoc($request))
2686
	{
2687
		if (!$row['approved'])
2688
			$row['filename'] = str_replace(array('{attachment_link}', '{txt_awaiting}'), array('<a href="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $row['id_attach'] . '">' . $row['filename'] . '</a>', $txt['awaiting_approval']), $settings['attachments_awaiting_approval']);
2689
		else
2690
			$row['filename'] = '<a href="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $row['id_attach'] . '">' . $row['filename'] . '</a>';
2691
2692
		$attachments[] = array(
2693
			'id' => $row['id_attach'],
2694
			'filename' => $row['filename'],
2695
			'fileext' => $row['fileext'],
2696
			'width' => $row['width'],
2697
			'height' => $row['height'],
2698
			'downloads' => $row['downloads'],
2699
			'is_image' => !empty($row['width']) && !empty($row['height']) && !empty($modSettings['attachmentShowImages']),
2700
			'id_thumb' => !empty($row['id_thumb']) ? $row['id_thumb'] : '',
2701
			'subject' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '" rel="nofollow">' . censor($row['subject']) . '</a>',
2702
			'posted' => $row['poster_time'],
2703
			'msg' => $row['id_msg'],
2704
			'topic' => $row['id_topic'],
2705
			'board' => $row['id_board'],
2706
			'board_name' => $row['name'],
2707
			'approved' => $row['approved'],
2708
		);
2709
	}
2710
2711
	$db->free_result($request);
2712
2713
	return $attachments;
2714
}
2715
2716
/**
2717
 * Gets the total number of attachments for the user
2718
 * (used by createList() callbacks)
2719
 *
2720
 * @param int[] $boardsAllowed
2721
 * @param int $memID
2722
 * @return int number of attachments
2723
 */
2724
function getNumAttachments($boardsAllowed, $memID)
2725
{
2726
	global $board, $modSettings, $context;
2727
2728
	$db = database();
2729
2730
	// Get the total number of attachments they have posted.
2731
	$request = $db->query('', '
2732
		SELECT COUNT(*)
2733
		FROM {db_prefix}attachments AS a
2734
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
2735
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board AND {query_see_board})
2736
		WHERE a.attachment_type = {int:attachment_type}
2737
			AND a.id_msg != {int:no_message}
2738
			AND m.id_member = {int:current_member}' . (!empty($board) ? '
2739
			AND b.id_board = {int:board}' : '') . (!in_array(0, $boardsAllowed) ? '
2740
			AND b.id_board IN ({array_int:boards_list})' : '') . (!$modSettings['postmod_active'] || $context['user']['is_owner'] ? '' : '
2741
			AND m.approved = {int:is_approved}'),
2742
		array(
2743
			'boards_list' => $boardsAllowed,
2744
			'attachment_type' => 0,
2745
			'no_message' => 0,
2746
			'current_member' => $memID,
2747
			'is_approved' => 1,
2748
			'board' => $board,
2749
		)
2750
	);
2751
	list ($attachCount) = $db->fetch_row($request);
2752
	$db->free_result($request);
2753
2754
	return $attachCount;
2755
}
2756
2757
/**
2758
 * Get the relevant topics in the unwatched list
2759
 * (used by createList() callbacks)
2760
 *
2761
 * @param int $start The item to start with (for pagination purposes)
2762
 * @param int $items_per_page  The number of items to show per page
2763
 * @param string $sort A string indicating how to sort the results
2764
 * @param int $memID
2765
 */
2766
function getUnwatchedBy($start, $items_per_page, $sort, $memID)
2767
{
2768
	$db = database();
2769
2770
	// Get the list of topics we can see
2771
	$request = $db->query('', '
2772
		SELECT lt.id_topic
2773
		FROM {db_prefix}log_topics AS lt
2774
			LEFT JOIN {db_prefix}topics AS t ON (lt.id_topic = t.id_topic)
2775
			LEFT JOIN {db_prefix}boards AS b ON (t.id_board = b.id_board)
2776
			LEFT JOIN {db_prefix}messages AS m ON (t.id_first_msg = m.id_msg)' . (in_array($sort, array('mem.real_name', 'mem.real_name DESC', 'mem.poster_time', 'mem.poster_time DESC')) ? '
2777
			LEFT JOIN {db_prefix}members AS mem ON (m.id_member = mem.id_member)' : '') . '
2778
		WHERE lt.id_member = {int:current_member}
2779
			AND lt.unwatched = 1
2780
			AND {query_see_board}
2781
		ORDER BY {raw:sort}
2782
		LIMIT {int:offset}, {int:limit}',
2783
		array(
2784
			'current_member' => $memID,
2785
			'sort' => $sort,
2786
			'offset' => $start,
2787
			'limit' => $items_per_page,
2788
		)
2789
	);
2790
	$topics = array();
2791
	while ($row = $db->fetch_assoc($request))
2792
		$topics[] = $row['id_topic'];
2793
	$db->free_result($request);
2794
2795
	// Any topics found?
2796
	$topicsInfo = array();
2797
	if (!empty($topics))
2798
	{
2799
		$request = $db->query('', '
2800
			SELECT mf.subject, mf.poster_time as started_on, COALESCE(memf.real_name, mf.poster_name) as started_by, ml.poster_time as last_post_on, COALESCE(meml.real_name, ml.poster_name) as last_post_by, t.id_topic
2801
			FROM {db_prefix}topics AS t
2802
				INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
2803
				INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
2804
				LEFT JOIN {db_prefix}members AS meml ON (meml.id_member = ml.id_member)
2805
				LEFT JOIN {db_prefix}members AS memf ON (memf.id_member = mf.id_member)
2806
			WHERE t.id_topic IN ({array_int:topics})',
2807
			array(
2808
				'topics' => $topics,
2809
			)
2810
		);
2811
		while ($row = $db->fetch_assoc($request))
2812
			$topicsInfo[] = $row;
2813
		$db->free_result($request);
2814
	}
2815
2816
	return $topicsInfo;
2817
}
2818
2819
/**
2820
 * Count the number of topics in the unwatched list
2821
 *
2822
 * @param int $memID
2823
 * @return int
2824
 */
2825
function getNumUnwatchedBy($memID)
2826
{
2827
	$db = database();
2828
2829
	// Get the total number of attachments they have posted.
2830
	$request = $db->query('', '
2831
		SELECT COUNT(*)
2832
		FROM {db_prefix}log_topics AS lt
2833
		LEFT JOIN {db_prefix}topics AS t ON (lt.id_topic = t.id_topic)
2834
		LEFT JOIN {db_prefix}boards AS b ON (t.id_board = b.id_board)
2835
		WHERE id_member = {int:current_member}
2836
			AND unwatched = 1
2837
			AND {query_see_board}',
2838
		array(
2839
			'current_member' => $memID,
2840
		)
2841
	);
2842
	list ($unwatchedCount) = $db->fetch_row($request);
2843
	$db->free_result($request);
2844
2845
	return $unwatchedCount;
2846
}
2847
2848
/**
2849
 * Returns the total number of posts a user has made
2850
 *
2851
 * - Counts all posts or just the posts made on a particular board
2852
 *
2853
 * @param int $memID
2854
 * @param int|null $board
2855
 * @return integer
2856
 */
2857
function count_user_posts($memID, $board = null)
2858
{
2859
	global $modSettings, $user_info;
2860
2861
	$db = database();
2862
2863
	$is_owner = $memID == $user_info['id'];
2864
2865
	$request = $db->query('', '
2866
		SELECT COUNT(*)
2867
		FROM {db_prefix}messages AS m' . ($user_info['query_see_board'] === '1=1' ? '' : '
2868
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board AND {query_see_board})') . '
2869
		WHERE m.id_member = {int:current_member}' . (!empty($board) ? '
2870
			AND m.id_board = {int:board}' : '') . (!$modSettings['postmod_active'] || $is_owner ? '' : '
2871
			AND m.approved = {int:is_approved}'),
2872
		array(
2873
			'current_member' => $memID,
2874
			'is_approved' => 1,
2875
			'board' => $board,
2876
		)
2877
	);
2878
2879
	list ($msgCount) = $db->fetch_row($request);
2880
	$db->free_result($request);
2881
2882
	return $msgCount;
2883
}
2884
2885
/**
2886
 * Returns the total number of new topics a user has made
2887
 *
2888
 * - Counts all posts or just the topics made on a particular board
2889
 *
2890
 * @param int $memID
2891
 * @param int|null $board
2892
 * @return integer
2893
 */
2894
function count_user_topics($memID, $board = null)
2895
{
2896
	global $modSettings, $user_info;
2897
2898
	$db = database();
2899
2900
	$is_owner = $memID == $user_info['id'];
2901
2902
	$request = $db->query('', '
2903
		SELECT COUNT(*)
2904
		FROM {db_prefix}topics AS t' . ($user_info['query_see_board'] === '1=1' ? '' : '
2905
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board AND {query_see_board})') . '
2906
		WHERE t.id_member_started = {int:current_member}' . (!empty($board) ? '
2907
			AND t.id_board = {int:board}' : '') . (!$modSettings['postmod_active'] || $is_owner ? '' : '
2908
			AND t.approved = {int:is_approved}'),
2909
		array(
2910
			'current_member' => $memID,
2911
			'is_approved' => 1,
2912
			'board' => $board,
2913
		)
2914
	);
2915
2916
	list ($msgCount) = $db->fetch_row($request);
2917
	$db->free_result($request);
2918
2919
	return $msgCount;
2920
}
2921
2922
/**
2923
 * Gets a members minimum and maximum message id
2924
 *
2925
 * - Can limit the results to a particular board
2926
 * - Used to help limit queries by proving start/stop points
2927
 *
2928
 * @param int $memID
2929
 * @param int|null $board
2930
 */
2931
function findMinMaxUserMessage($memID, $board = null)
2932
{
2933
	global $modSettings, $user_info;
2934
2935
	$db = database();
2936
2937
	$is_owner = $memID == $user_info['id'];
2938
2939
	$request = $db->query('', '
2940
		SELECT MIN(id_msg), MAX(id_msg)
2941
		FROM {db_prefix}messages AS m
2942
		WHERE m.id_member = {int:current_member}' . (!empty($board) ? '
2943
			AND m.id_board = {int:board}' : '') . (!$modSettings['postmod_active'] || $is_owner ? '' : '
2944
			AND m.approved = {int:is_approved}'),
2945
		array(
2946
			'current_member' => $memID,
2947
			'is_approved' => 1,
2948
			'board' => $board,
2949
		)
2950
	);
2951
	$minmax = $db->fetch_row($request);
2952
	$db->free_result($request);
2953
2954
	return empty($minmax) ? array(0, 0) : $minmax;
2955
}
2956
2957
/**
2958
 * Determines a members minimum and maximum topic id
2959
 *
2960
 * - Can limit the results to a particular board
2961
 * - Used to help limit queries by proving start/stop points
2962
 *
2963
 * @param int $memID
2964
 * @param int|null $board
2965
 */
2966
function findMinMaxUserTopic($memID, $board = null)
2967
{
2968
	global $modSettings, $user_info;
2969
2970
	$db = database();
2971
2972
	$is_owner = $memID == $user_info['id'];
2973
2974
	$request = $db->query('', '
2975
		SELECT MIN(id_topic), MAX(id_topic)
2976
		FROM {db_prefix}topics AS t
2977
		WHERE t.id_member_started = {int:current_member}' . (!empty($board) ? '
2978
			AND t.id_board = {int:board}' : '') . (!$modSettings['postmod_active'] || $is_owner ? '' : '
2979
			AND t.approved = {int:is_approved}'),
2980
		array(
2981
			'current_member' => $memID,
2982
			'is_approved' => 1,
2983
			'board' => $board,
2984
		)
2985
	);
2986
	$minmax = $db->fetch_row($request);
2987
	$db->free_result($request);
2988
2989
	return empty($minmax) ? array(0, 0) : $minmax;
2990
}
2991
2992
/**
2993
 * Used to load all the posts of a user
2994
 *
2995
 * - Can limit to just the posts of a particular board
2996
 * - If range_limit is supplied, will check if count results were returned, if not
2997
 * will drop the limit and try again
2998
 *
2999
 * @param int $memID
3000
 * @param int $start
3001
 * @param int $count
3002
 * @param string|null $range_limit
3003
 * @param boolean $reverse
3004
 * @param int|null $board
3005
 */
3006
function load_user_posts($memID, $start, $count, $range_limit = '', $reverse = false, $board = null)
3007
{
3008
	global $modSettings, $user_info;
3009
3010
	$db = database();
3011
3012
	$is_owner = $memID == $user_info['id'];
3013
	$user_posts = array();
3014
3015
	// Find this user's posts. The left join on categories somehow makes this faster, weird as it looks.
3016
	for ($i = 0; $i < 2; $i++)
3017
	{
3018
		$request = $db->query('', '
3019
			SELECT
3020
				b.id_board, b.name AS bname,
3021
				c.id_cat, c.name AS cname,
3022
				m.id_topic, m.id_msg, m.body, m.smileys_enabled, m.subject, m.poster_time, m.approved,
3023
				t.id_member_started, t.id_first_msg, t.id_last_msg
3024
			FROM {db_prefix}messages AS m
3025
				INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
3026
				INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
3027
				LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
3028
			WHERE m.id_member = {int:current_member}' . (!empty($board) ? '
3029
				AND b.id_board = {int:board}' : '') . (empty($range_limit) ? '' : '
3030
				AND ' . $range_limit) . '
3031
				AND {query_see_board}' . (!$modSettings['postmod_active'] || $is_owner ? '' : '
3032
				AND t.approved = {int:is_approved} AND m.approved = {int:is_approved}') . '
3033
			ORDER BY m.id_msg ' . ($reverse ? 'ASC' : 'DESC') . '
3034
			LIMIT ' . $start . ', ' . $count,
3035
			array(
3036
				'current_member' => $memID,
3037
				'is_approved' => 1,
3038
				'board' => $board,
3039
			)
3040
		);
3041
3042
		// Did we get what we wanted, if so stop looking
3043
		if ($db->num_rows($request) === $count || empty($range_limit))
3044
			break;
3045
		else
3046
			$range_limit = '';
3047
	}
3048
3049
	// Place them in the post array
3050
	while ($row = $db->fetch_assoc($request))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $request does not seem to be defined for all execution paths leading up to this point.
Loading history...
3051
		$user_posts[] = $row;
3052
	$db->free_result($request);
3053
3054
	return $user_posts;
3055
}
3056
3057
/**
3058
 * Used to load all the topics of a user
3059
 *
3060
 * - Can limit to just the posts of a particular board
3061
 * - If range_limit 'guess' is supplied, will check if count results were returned, if not
3062
 * it will drop the guessed limit and try again.
3063
 *
3064
 * @param int $memID
3065
 * @param int $start
3066
 * @param int $count
3067
 * @param string $range_limit
3068
 * @param boolean $reverse
3069
 * @param int|null $board
3070
 */
3071
function load_user_topics($memID, $start, $count, $range_limit = '', $reverse = false, $board = null)
3072
{
3073
	global $modSettings, $user_info;
3074
3075
	$db = database();
3076
3077
	$is_owner = $memID == $user_info['id'];
3078
	$user_topics = array();
3079
3080
	// Find this user's topics.  The left join on categories somehow makes this faster, weird as it looks.
3081
	for ($i = 0; $i < 2; $i++)
3082
	{
3083
		$request = $db->query('', '
3084
			SELECT
3085
				b.id_board, b.name AS bname,
3086
				c.id_cat, c.name AS cname,
3087
				t.id_member_started, t.id_first_msg, t.id_last_msg, t.approved,
3088
				m.body, m.smileys_enabled, m.subject, m.poster_time, m.id_topic, m.id_msg
3089
			FROM {db_prefix}topics AS t
3090
				INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
3091
				LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
3092
				INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
3093
			WHERE t.id_member_started = {int:current_member}' . (!empty($board) ? '
3094
				AND t.id_board = {int:board}' : '') . (empty($range_limit) ? '' : '
3095
				AND ' . $range_limit) . '
3096
				AND {query_see_board}' . (!$modSettings['postmod_active'] || $is_owner ? '' : '
3097
				AND t.approved = {int:is_approved} AND m.approved = {int:is_approved}') . '
3098
			ORDER BY t.id_first_msg ' . ($reverse ? 'ASC' : 'DESC') . '
3099
			LIMIT ' . $start . ', ' . $count,
3100
			array(
3101
				'current_member' => $memID,
3102
				'is_approved' => 1,
3103
				'board' => $board,
3104
			)
3105
		);
3106
3107
		// Did we get what we wanted, if so stop looking
3108
		if ($db->num_rows($request) === $count || empty($range_limit))
3109
			break;
3110
		else
3111
			$range_limit = '';
3112
	}
3113
3114
	// Place them in the topic array
3115
	while ($row = $db->fetch_assoc($request))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $request does not seem to be defined for all execution paths leading up to this point.
Loading history...
3116
		$user_topics[] = $row;
3117
	$db->free_result($request);
3118
3119
	return $user_topics;
3120
}
3121
3122
/**
3123
 * Loads the permissions that are given to a member group or set of groups
3124
 *
3125
 * @param int[] $curGroups
3126
 */
3127
function getMemberGeneralPermissions($curGroups)
3128
{
3129
	global $txt;
3130
3131
	$db = database();
3132
	loadLanguage('ManagePermissions');
3133
3134
	// Get all general permissions.
3135
	$request = $db->query('', '
3136
		SELECT p.permission, p.add_deny, mg.group_name, p.id_group
3137
		FROM {db_prefix}permissions AS p
3138
			LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = p.id_group)
3139
		WHERE p.id_group IN ({array_int:group_list})
3140
		ORDER BY p.add_deny DESC, p.permission, mg.min_posts, CASE WHEN mg.id_group < {int:newbie_group} THEN mg.id_group ELSE 4 END, mg.group_name',
3141
		array(
3142
			'group_list' => $curGroups,
3143
			'newbie_group' => 4,
3144
		)
3145
	);
3146
	$general_permission = array();
3147
	while ($row = $db->fetch_assoc($request))
3148
	{
3149
		// We don't know about this permission, it doesn't exist :P.
3150
		if (!isset($txt['permissionname_' . $row['permission']]))
3151
			continue;
3152
3153
		// Permissions that end with _own or _any consist of two parts.
3154
		if (in_array(substr($row['permission'], -4), array('_own', '_any')) && isset($txt['permissionname_' . substr($row['permission'], 0, -4)]))
3155
			$name = $txt['permissionname_' . substr($row['permission'], 0, -4)] . ' - ' . $txt['permissionname_' . $row['permission']];
3156
		else
3157
			$name = $txt['permissionname_' . $row['permission']];
3158
3159
		// Add this permission if it doesn't exist yet.
3160
		if (!isset($general_permission[$row['permission']]))
3161
		{
3162
			$general_permission[$row['permission']] = array(
3163
				'id' => $row['permission'],
3164
				'groups' => array(
3165
					'allowed' => array(),
3166
					'denied' => array()
3167
				),
3168
				'name' => $name,
3169
				'is_denied' => false,
3170
				'is_global' => true,
3171
			);
3172
		}
3173
3174
		// Add the membergroup to either the denied or the allowed groups.
3175
		$general_permission[$row['permission']]['groups'][empty($row['add_deny']) ? 'denied' : 'allowed'][] = $row['id_group'] == 0 ? $txt['membergroups_members'] : $row['group_name'];
3176
3177
		// Once denied is always denied.
3178
		$general_permission[$row['permission']]['is_denied'] |= empty($row['add_deny']);
3179
	}
3180
	$db->free_result($request);
3181
3182
	return $general_permission;
3183
}
3184
3185
/**
3186
 * Get the permissions a member has, or group they are in has
3187
 * If $board is supplied will return just the permissions for that board
3188
 *
3189
 * @param int $memID
3190
 * @param int[] $curGroups
3191
 * @param int|null $board
3192
 */
3193
function getMemberBoardPermissions($memID, $curGroups, $board = null)
3194
{
3195
	global $txt;
3196
3197
	$db = database();
3198
	loadLanguage('ManagePermissions');
3199
3200
	$request = $db->query('', '
3201
		SELECT
3202
			bp.add_deny, bp.permission, bp.id_group, mg.group_name' . (empty($board) ? '' : ',
3203
			b.id_profile, CASE WHEN mods.id_member IS NULL THEN 0 ELSE 1 END AS is_moderator') . '
3204
		FROM {db_prefix}board_permissions AS bp' . (empty($board) ? '' : '
3205
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = {int:current_board})
3206
			LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})') . '
3207
			LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = bp.id_group)
3208
		WHERE bp.id_profile = {raw:current_profile}
3209
			AND bp.id_group IN ({array_int:group_list}' . (empty($board) ? ')' : ', {int:moderator_group})
3210
			AND (mods.id_member IS NOT NULL OR bp.id_group != {int:moderator_group})'),
3211
		array(
3212
			'current_board' => $board,
3213
			'group_list' => $curGroups,
3214
			'current_member' => $memID,
3215
			'current_profile' => empty($board) ? '1' : 'b.id_profile',
3216
			'moderator_group' => 3,
3217
		)
3218
	);
3219
	$board_permission = array();
3220
	while ($row = $db->fetch_assoc($request))
3221
	{
3222
		// We don't know about this permission, it doesn't exist :P.
3223
		if (!isset($txt['permissionname_' . $row['permission']]))
3224
			continue;
3225
3226
		// The name of the permission using the format 'permission name' - 'own/any topic/event/etc.'.
3227
		if (in_array(substr($row['permission'], -4), array('_own', '_any')) && isset($txt['permissionname_' . substr($row['permission'], 0, -4)]))
3228
			$name = $txt['permissionname_' . substr($row['permission'], 0, -4)] . ' - ' . $txt['permissionname_' . $row['permission']];
3229
		else
3230
			$name = $txt['permissionname_' . $row['permission']];
3231
3232
		// Create the structure for this permission.
3233
		if (!isset($board_permission[$row['permission']]))
3234
			$board_permission[$row['permission']] = array(
3235
				'id' => $row['permission'],
3236
				'groups' => array(
3237
					'allowed' => array(),
3238
					'denied' => array()
3239
				),
3240
				'name' => $name,
3241
				'is_denied' => false,
3242
				'is_global' => empty($board),
3243
			);
3244
3245
		$board_permission[$row['permission']]['groups'][empty($row['add_deny']) ? 'denied' : 'allowed'][$row['id_group']] = $row['id_group'] == 0 ? $txt['membergroups_members'] : $row['group_name'];
3246
		$board_permission[$row['permission']]['is_denied'] |= empty($row['add_deny']);
3247
	}
3248
	$db->free_result($request);
3249
3250
	return $board_permission;
3251
}
3252
3253
/**
3254
 * Retrieves (most of) the IPs used by a certain member in his messages and errors
3255
 *
3256
 * @param int $memID the id of the member
3257
 */
3258
function getMembersIPs($memID)
3259
{
3260
	global $modSettings, $user_profile;
3261
3262
	$db = database();
3263
3264
	// @todo cache this
3265
	// If this is a big forum, or a large posting user, let's limit the search.
3266
	if ($modSettings['totalMessages'] > 50000 && $user_profile[$memID]['posts'] > 500)
3267
	{
3268
		$request = $db->query('', '
3269
			SELECT MAX(id_msg)
3270
			FROM {db_prefix}messages AS m
3271
			WHERE m.id_member = {int:current_member}',
3272
			array(
3273
				'current_member' => $memID,
3274
			)
3275
		);
3276
		list ($max_msg_member) = $db->fetch_row($request);
3277
		$db->free_result($request);
3278
3279
		// There's no point worrying ourselves with messages made yonks ago, just get recent ones!
3280
		$min_msg_member = max(0, $max_msg_member - $user_profile[$memID]['posts'] * 3);
3281
	}
3282
3283
	// Default to at least the ones we know about.
3284
	$ips = array(
3285
		$user_profile[$memID]['member_ip'],
3286
		$user_profile[$memID]['member_ip2'],
3287
	);
3288
3289
	// @todo cache this
3290
	// Get all IP addresses this user has used for his messages.
3291
	$request = $db->query('', '
3292
		SELECT poster_ip
3293
		FROM {db_prefix}messages
3294
		WHERE id_member = {int:current_member} ' . (isset($min_msg_member) ? '
3295
			AND id_msg >= {int:min_msg_member} AND id_msg <= {int:max_msg_member}' : '') . '
3296
		GROUP BY poster_ip',
3297
		array(
3298
			'current_member' => $memID,
3299
			'min_msg_member' => !empty($min_msg_member) ? $min_msg_member : 0,
3300
			'max_msg_member' => !empty($max_msg_member) ? $max_msg_member : 0,
3301
		)
3302
	);
3303
3304
	while ($row = $db->fetch_assoc($request))
3305
		$ips[] = $row['poster_ip'];
3306
3307
	$db->free_result($request);
3308
3309
	// Now also get the IP addresses from the error messages.
3310
	$request = $db->query('', '
3311
		SELECT COUNT(*) AS error_count, ip
3312
		FROM {db_prefix}log_errors
3313
		WHERE id_member = {int:current_member}
3314
		GROUP BY ip',
3315
		array(
3316
			'current_member' => $memID,
3317
		)
3318
	);
3319
3320
	$error_ips = array();
3321
3322
	while ($row = $db->fetch_assoc($request))
3323
		$error_ips[] = $row['ip'];
3324
3325
	$db->free_result($request);
3326
3327
	return array('message_ips' => array_unique($ips), 'error_ips' => array_unique($error_ips));
3328
}
3329
3330
/**
3331
 * Return the details of the members using a certain range of IPs
3332
 * except the current one
3333
 *
3334
 * @param string[] $ips a list of IP addresses
3335
 * @param int $memID the id of the "current" member (maybe it could be retrieved with currentMemberID)
3336
 */
3337
function getMembersInRange($ips, $memID)
3338
{
3339
	$db = database();
3340
3341
	$message_members = array();
3342
	$members_in_range = array();
3343
3344
	// Get member ID's which are in messages...
3345
	$request = $db->query('', '
3346
		SELECT mem.id_member
3347
		FROM {db_prefix}messages AS m
3348
			INNER JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
3349
		WHERE m.poster_ip IN ({array_string:ip_list})
3350
		GROUP BY mem.id_member
3351
		HAVING mem.id_member != {int:current_member}',
3352
		array(
3353
			'current_member' => $memID,
3354
			'ip_list' => $ips,
3355
		)
3356
	);
3357
3358
	while ($row = $db->fetch_assoc($request))
3359
		$message_members[] = $row['id_member'];
3360
	$db->free_result($request);
3361
3362
	// And then get the member ID's belong to other users
3363
	$request = $db->query('', '
3364
		SELECT id_member
3365
		FROM {db_prefix}members
3366
		WHERE id_member != {int:current_member}
3367
			AND member_ip IN ({array_string:ip_list})',
3368
		array(
3369
			'current_member' => $memID,
3370
			'ip_list' => $ips,
3371
		)
3372
	);
3373
	while ($row = $db->fetch_assoc($request))
3374
		$message_members[] = $row['id_member'];
3375
	$db->free_result($request);
3376
3377
	// Once the IDs are all combined, let's clean them up
3378
	$message_members = array_unique($message_members);
3379
3380
	// And finally, fetch their names, cause of the GROUP BY doesn't like giving us that normally.
3381
	if (!empty($message_members))
3382
	{
3383
		require_once(SUBSDIR . '/Members.subs.php');
3384
3385
		// Get the latest activated member's display name.
3386
		$members_in_range = getBasicMemberData($message_members);
3387
	}
3388
3389
	return $members_in_range;
3390
}
3391
3392
/**
3393
 * Return a detailed situation of the notification methods for a certain member.
3394
 * Used in the profile page to load the defaults and validate the new
3395
 * settings.
3396
 *
3397
 * @param int $member_id the id of a member
3398
 */
3399
function getMemberNotificationsProfile($member_id)
3400
{
3401
	global $modSettings, $context;
3402
3403
	if (empty($modSettings['enabled_mentions']))
3404
		return array();
3405
3406
	require_once(SUBSDIR . '/Notification.subs.php');
3407
	Elk_Autoloader::instance()->register(SUBSDIR . '/MentionType', '\\ElkArte\\sources\\subs\\MentionType');
3408
3409
	$mention_methods = Notifications::instance()->getNotifiers();
3410
	$enabled_mentions = explode(',', $modSettings['enabled_mentions']);
3411
	$user_preferences = getUsersNotificationsPreferences($enabled_mentions, $member_id);
3412
	$mention_types = array();
3413
	$push_enabled = false;
3414
3415
	foreach ($enabled_mentions as $type)
3416
	{
3417
		$type_on = false;
3418
		$notif = filterNotificationMethods($mention_methods, $type);
3419
3420
		foreach ($notif as $key => $val)
3421
		{
3422
			$notif[$key] = array('id' => $val, 'enabled' => $user_preferences[$member_id][$type] === $key);
3423
			if ($user_preferences[$member_id][$type] > 0)
3424
				$type_on = true;
3425
3426
			if (!$push_enabled && $val === 'notification' && $user_preferences[$member_id][$type] === $key)
3427
				$push_enabled = true;
3428
		}
3429
3430
		if (!empty($notif))
3431
			$mention_types[$type] = array('data' => $notif, 'enabled' => $type_on);
3432
	}
3433
3434
	// If they enabled notifications alert, then lets ask for browser permission to show them
3435
	// just blows smoke if they already gave it.
3436
	$push_enabled &= $modSettings['usernotif_desktop_enable'] && !empty($context['profile_updated']);
3437
	if ($push_enabled)
3438
	{
3439
		addInlineJavascript('
3440
			$(function() {
3441
				Push.Permission.request();
3442
			});', true);
3443
	}
3444
3445
	return $mention_types;
3446
}
3447