Issues (1014)

Sources/Subs-Members.php (1 issue)

Labels
Severity
1
<?php
2
3
/**
4
 * This file contains some useful functions for members and membergroups.
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines https://www.simplemachines.org
10
 * @copyright 2022 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1.2
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
/**
20
 * Delete one or more members.
21
 * Requires profile_remove_own or profile_remove_any permission for
22
 * respectively removing your own account or any account.
23
 * Non-admins cannot delete admins.
24
 * The function:
25
 *   - changes author of messages, topics and polls to guest authors.
26
 *   - removes all log entries concerning the deleted members, except the
27
 * error logs, ban logs and moderation logs.
28
 *   - removes these members' personal messages (only the inbox), avatars,
29
 * ban entries, theme settings, moderator positions, poll and votes.
30
 *   - updates member statistics afterwards.
31
 *
32
 * @param int|array $users The ID of a user or an array of user IDs
33
 * @param bool $check_not_admin Whether to verify that the users aren't admins
34
 */
35
function deleteMembers($users, $check_not_admin = false)
36
{
37
	global $sourcedir, $modSettings, $user_info, $smcFunc, $cache_enable;
38
39
	// Try give us a while to sort this out...
40
	@set_time_limit(600);
41
42
	// Try to get some more memory.
43
	setMemoryLimit('128M');
44
45
	// If it's not an array, make it so!
46
	if (!is_array($users))
47
		$users = array($users);
48
	else
49
		$users = array_unique($users);
50
51
	// Make sure there's no void user in here.
52
	$users = array_diff($users, array(0));
53
54
	// How many are they deleting?
55
	if (empty($users))
56
		return;
57
	elseif (count($users) == 1)
58
	{
59
		list ($user) = $users;
60
61
		if ($user == $user_info['id'])
62
			isAllowedTo('profile_remove_own');
63
		else
64
			isAllowedTo('profile_remove_any');
65
	}
66
	else
67
	{
68
		foreach ($users as $k => $v)
69
			$users[$k] = (int) $v;
70
71
		// Deleting more than one?  You can't have more than one account...
72
		isAllowedTo('profile_remove_any');
73
	}
74
75
	// Get their names for logging purposes.
76
	$request = $smcFunc['db_query']('', '
77
		SELECT id_member, member_name, CASE WHEN id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0 THEN 1 ELSE 0 END AS is_admin
78
		FROM {db_prefix}members
79
		WHERE id_member IN ({array_int:user_list})
80
		LIMIT {int:limit}',
81
		array(
82
			'user_list' => $users,
83
			'admin_group' => 1,
84
			'limit' => count($users),
85
		)
86
	);
87
	$admins = array();
88
	$user_log_details = array();
89
	while ($row = $smcFunc['db_fetch_assoc']($request))
90
	{
91
		if ($row['is_admin'])
92
			$admins[] = $row['id_member'];
93
		$user_log_details[$row['id_member']] = array($row['id_member'], $row['member_name']);
94
	}
95
	$smcFunc['db_free_result']($request);
96
97
	if (empty($user_log_details))
98
		return;
99
100
	// Make sure they aren't trying to delete administrators if they aren't one.  But don't bother checking if it's just themself.
101
	if (!empty($admins) && ($check_not_admin || (!allowedTo('admin_forum') && (count($users) != 1 || $users[0] != $user_info['id']))))
102
	{
103
		$users = array_diff($users, $admins);
104
		foreach ($admins as $id)
105
			unset($user_log_details[$id]);
106
	}
107
108
	// No one left?
109
	if (empty($users))
110
		return;
111
112
	// Log the action - regardless of who is deleting it.
113
	$log_changes = array();
114
	foreach ($user_log_details as $user)
115
	{
116
		$log_changes[] = array(
117
			'action' => 'delete_member',
118
			'log_type' => 'admin',
119
			'extra' => array(
120
				'member' => $user[0],
121
				'name' => $user[1],
122
				'member_acted' => $user_info['name'],
123
			),
124
		);
125
126
		// Remove any cached data if enabled.
127
		if (!empty($cache_enable) && $cache_enable >= 2)
128
			cache_put_data('user_settings-' . $user[0], null, 60);
129
	}
130
131
	// Make these peoples' posts guest posts.
132
	$smcFunc['db_query']('', '
133
		UPDATE {db_prefix}messages
134
		SET id_member = {int:guest_id}' . (!empty($modSettings['deleteMembersRemovesEmail']) ? ',
135
			poster_email = {string:blank_email}' : '') . '
136
		WHERE id_member IN ({array_int:users})',
137
		array(
138
			'guest_id' => 0,
139
			'blank_email' => '',
140
			'users' => $users,
141
		)
142
	);
143
	$smcFunc['db_query']('', '
144
		UPDATE {db_prefix}polls
145
		SET id_member = {int:guest_id}
146
		WHERE id_member IN ({array_int:users})',
147
		array(
148
			'guest_id' => 0,
149
			'users' => $users,
150
		)
151
	);
152
153
	// Make these peoples' posts guest first posts and last posts.
154
	$smcFunc['db_query']('', '
155
		UPDATE {db_prefix}topics
156
		SET id_member_started = {int:guest_id}
157
		WHERE id_member_started IN ({array_int:users})',
158
		array(
159
			'guest_id' => 0,
160
			'users' => $users,
161
		)
162
	);
163
	$smcFunc['db_query']('', '
164
		UPDATE {db_prefix}topics
165
		SET id_member_updated = {int:guest_id}
166
		WHERE id_member_updated IN ({array_int:users})',
167
		array(
168
			'guest_id' => 0,
169
			'users' => $users,
170
		)
171
	);
172
173
	$smcFunc['db_query']('', '
174
		UPDATE {db_prefix}log_actions
175
		SET id_member = {int:guest_id}
176
		WHERE id_member IN ({array_int:users})',
177
		array(
178
			'guest_id' => 0,
179
			'users' => $users,
180
		)
181
	);
182
183
	$smcFunc['db_query']('', '
184
		UPDATE {db_prefix}log_banned
185
		SET id_member = {int:guest_id}
186
		WHERE id_member IN ({array_int:users})',
187
		array(
188
			'guest_id' => 0,
189
			'users' => $users,
190
		)
191
	);
192
193
	$smcFunc['db_query']('', '
194
		UPDATE {db_prefix}log_errors
195
		SET id_member = {int:guest_id}
196
		WHERE id_member IN ({array_int:users})',
197
		array(
198
			'guest_id' => 0,
199
			'users' => $users,
200
		)
201
	);
202
203
	// Delete the member.
204
	$smcFunc['db_query']('', '
205
		DELETE FROM {db_prefix}members
206
		WHERE id_member IN ({array_int:users})',
207
		array(
208
			'users' => $users,
209
		)
210
	);
211
212
	// Delete any drafts...
213
	$smcFunc['db_query']('', '
214
		DELETE FROM {db_prefix}user_drafts
215
		WHERE id_member IN ({array_int:users})',
216
		array(
217
			'users' => $users,
218
		)
219
	);
220
221
	// Delete anything they liked.
222
	$smcFunc['db_query']('', '
223
		DELETE FROM {db_prefix}user_likes
224
		WHERE id_member IN ({array_int:users})',
225
		array(
226
			'users' => $users,
227
		)
228
	);
229
230
	// Delete their mentions
231
	$smcFunc['db_query']('', '
232
		DELETE FROM {db_prefix}mentions
233
		WHERE id_member IN ({array_int:members})',
234
		array(
235
			'members' => $users,
236
		)
237
	);
238
239
	// Delete the logs...
240
	$smcFunc['db_query']('', '
241
		DELETE FROM {db_prefix}log_actions
242
		WHERE id_log = {int:log_type}
243
			AND id_member IN ({array_int:users})',
244
		array(
245
			'log_type' => 2,
246
			'users' => $users,
247
		)
248
	);
249
	$smcFunc['db_query']('', '
250
		DELETE FROM {db_prefix}log_boards
251
		WHERE id_member IN ({array_int:users})',
252
		array(
253
			'users' => $users,
254
		)
255
	);
256
	$smcFunc['db_query']('', '
257
		DELETE FROM {db_prefix}log_comments
258
		WHERE id_recipient IN ({array_int:users})
259
			AND comment_type = {string:warntpl}',
260
		array(
261
			'users' => $users,
262
			'warntpl' => 'warntpl',
263
		)
264
	);
265
	$smcFunc['db_query']('', '
266
		DELETE FROM {db_prefix}log_group_requests
267
		WHERE id_member IN ({array_int:users})',
268
		array(
269
			'users' => $users,
270
		)
271
	);
272
	$smcFunc['db_query']('', '
273
		DELETE FROM {db_prefix}log_mark_read
274
		WHERE id_member IN ({array_int:users})',
275
		array(
276
			'users' => $users,
277
		)
278
	);
279
	$smcFunc['db_query']('', '
280
		DELETE FROM {db_prefix}log_notify
281
		WHERE id_member IN ({array_int:users})',
282
		array(
283
			'users' => $users,
284
		)
285
	);
286
	$smcFunc['db_query']('', '
287
		DELETE FROM {db_prefix}log_online
288
		WHERE id_member IN ({array_int:users})',
289
		array(
290
			'users' => $users,
291
		)
292
	);
293
	$smcFunc['db_query']('', '
294
		DELETE FROM {db_prefix}log_subscribed
295
		WHERE id_member IN ({array_int:users})',
296
		array(
297
			'users' => $users,
298
		)
299
	);
300
	$smcFunc['db_query']('', '
301
		DELETE FROM {db_prefix}log_topics
302
		WHERE id_member IN ({array_int:users})',
303
		array(
304
			'users' => $users,
305
		)
306
	);
307
308
	// Make their votes appear as guest votes - at least it keeps the totals right.
309
	// @todo Consider adding back in cookie protection.
310
	$smcFunc['db_query']('', '
311
		UPDATE {db_prefix}log_polls
312
		SET id_member = {int:guest_id}
313
		WHERE id_member IN ({array_int:users})',
314
		array(
315
			'guest_id' => 0,
316
			'users' => $users,
317
		)
318
	);
319
320
	// Delete personal messages.
321
	require_once($sourcedir . '/PersonalMessage.php');
322
	deleteMessages(null, null, $users);
323
324
	$smcFunc['db_query']('', '
325
		UPDATE {db_prefix}personal_messages
326
		SET id_member_from = {int:guest_id}
327
		WHERE id_member_from IN ({array_int:users})',
328
		array(
329
			'guest_id' => 0,
330
			'users' => $users,
331
		)
332
	);
333
334
	// They no longer exist, so we don't know who it was sent to.
335
	$smcFunc['db_query']('', '
336
		DELETE FROM {db_prefix}pm_recipients
337
		WHERE id_member IN ({array_int:users})',
338
		array(
339
			'users' => $users,
340
		)
341
	);
342
343
	// Delete avatar.
344
	require_once($sourcedir . '/ManageAttachments.php');
345
	removeAttachments(array('id_member' => $users));
346
347
	// It's over, no more moderation for you.
348
	$smcFunc['db_query']('', '
349
		DELETE FROM {db_prefix}moderators
350
		WHERE id_member IN ({array_int:users})',
351
		array(
352
			'users' => $users,
353
		)
354
	);
355
	$smcFunc['db_query']('', '
356
		DELETE FROM {db_prefix}group_moderators
357
		WHERE id_member IN ({array_int:users})',
358
		array(
359
			'users' => $users,
360
		)
361
	);
362
363
	// If you don't exist we can't ban you.
364
	$smcFunc['db_query']('', '
365
		DELETE FROM {db_prefix}ban_items
366
		WHERE id_member IN ({array_int:users})',
367
		array(
368
			'users' => $users,
369
		)
370
	);
371
372
	// Remove individual theme settings.
373
	$smcFunc['db_query']('', '
374
		DELETE FROM {db_prefix}themes
375
		WHERE id_member IN ({array_int:users})',
376
		array(
377
			'users' => $users,
378
		)
379
	);
380
381
	// These users are nobody's buddy nomore.
382
	$request = $smcFunc['db_query']('', '
383
		SELECT id_member, pm_ignore_list, buddy_list
384
		FROM {db_prefix}members
385
		WHERE FIND_IN_SET({raw:pm_ignore_list}, pm_ignore_list) != 0 OR FIND_IN_SET({raw:buddy_list}, buddy_list) != 0',
386
		array(
387
			'pm_ignore_list' => implode(', pm_ignore_list) != 0 OR FIND_IN_SET(', $users),
388
			'buddy_list' => implode(', buddy_list) != 0 OR FIND_IN_SET(', $users),
389
		)
390
	);
391
	while ($row = $smcFunc['db_fetch_assoc']($request))
392
		$smcFunc['db_query']('', '
393
			UPDATE {db_prefix}members
394
			SET
395
				pm_ignore_list = {string:pm_ignore_list},
396
				buddy_list = {string:buddy_list}
397
			WHERE id_member = {int:id_member}',
398
			array(
399
				'id_member' => $row['id_member'],
400
				'pm_ignore_list' => implode(',', array_diff(explode(',', $row['pm_ignore_list']), $users)),
401
				'buddy_list' => implode(',', array_diff(explode(',', $row['buddy_list']), $users)),
402
			)
403
		);
404
	$smcFunc['db_free_result']($request);
405
406
	// Make sure no member's birthday is still sticking in the calendar...
407
	updateSettings(array(
408
		'calendar_updated' => time(),
409
	));
410
411
	// Integration rocks!
412
	call_integration_hook('integrate_delete_members', array($users));
413
414
	updateStats('member');
415
416
	require_once($sourcedir . '/Logging.php');
417
	logActions($log_changes);
418
}
419
420
/**
421
 * Registers a member to the forum.
422
 * Allows two types of interface: 'guest' and 'admin'. The first
423
 * includes hammering protection, the latter can perform the
424
 * registration silently.
425
 * The strings used in the options array are assumed to be escaped.
426
 * Allows to perform several checks on the input, e.g. reserved names.
427
 * The function will adjust member statistics.
428
 * If an error is detected will fatal error on all errors unless return_errors is true.
429
 *
430
 * @param array $regOptions An array of registration options
431
 * @param bool $return_errors Whether to return the errors
432
 * @return int|array The ID of the newly registered user or an array of error info if $return_errors is true
433
 */
434
function registerMember(&$regOptions, $return_errors = false)
435
{
436
	global $scripturl, $txt, $modSettings, $context, $sourcedir;
437
	global $user_info, $smcFunc;
438
439
	loadLanguage('Login');
440
441
	// We'll need some external functions.
442
	require_once($sourcedir . '/Subs-Auth.php');
443
	require_once($sourcedir . '/Subs-Post.php');
444
445
	// Put any errors in here.
446
	$reg_errors = array();
447
448
	// Registration from the admin center, let them sweat a little more.
449
	if ($regOptions['interface'] == 'admin')
450
	{
451
		is_not_guest();
452
		isAllowedTo('moderate_forum');
453
	}
454
	// If you're an admin, you're special ;).
455
	elseif ($regOptions['interface'] == 'guest')
456
	{
457
		// You cannot register twice...
458
		if (empty($user_info['is_guest']))
459
			redirectexit();
460
461
		// Make sure they didn't just register with this session.
462
		if (!empty($_SESSION['just_registered']) && empty($modSettings['disableRegisterCheck']))
463
			fatal_lang_error('register_only_once', false);
464
	}
465
466
	// Spaces and other odd characters are evil...
467
	$regOptions['username'] = trim(normalize_spaces(sanitize_chars($regOptions['username'], 1, ' '), true, true, array('no_breaks' => true, 'replace_tabs' => true, 'collapse_hspace' => true)));
468
469
	// Convert character encoding for non-utf8mb4 database
470
	$regOptions['username'] = $smcFunc['htmlspecialchars']($regOptions['username']);
471
472
	// @todo Separate the sprintf?
473
	if (empty($regOptions['email']) || !filter_var($regOptions['email'], FILTER_VALIDATE_EMAIL) || strlen($regOptions['email']) > 255)
474
		$reg_errors[] = array('lang', 'profile_error_bad_email');
475
476
	$username_validation_errors = validateUsername(0, $regOptions['username'], true, !empty($regOptions['check_reserved_name']));
477
	if (!empty($username_validation_errors))
478
		$reg_errors = array_merge($reg_errors, $username_validation_errors);
479
480
	// Generate a validation code if it's supposed to be emailed.
481
	$validation_code = '';
482
	if ($regOptions['require'] == 'activation')
483
		$validation_code = generateValidationCode();
484
485
	// If you haven't put in a password generate one.
486
	if ($regOptions['interface'] == 'admin' && $regOptions['password'] == '')
487
	{
488
		mt_srand(time() + 1277);
489
		$regOptions['password'] = generateValidationCode();
490
		$regOptions['password_check'] = $regOptions['password'];
491
	}
492
	// Does the first password match the second?
493
	elseif ($regOptions['password'] != $regOptions['password_check'])
494
		$reg_errors[] = array('lang', 'passwords_dont_match');
495
496
	// That's kind of easy to guess...
497
	if ($regOptions['password'] == '')
498
	{
499
		$reg_errors[] = array('lang', 'no_password');
500
	}
501
502
	// Now perform hard password validation as required.
503
	if (!empty($regOptions['check_password_strength']) && $regOptions['password'] != '')
504
	{
505
		$passwordError = validatePassword($regOptions['password'], $regOptions['username'], array($regOptions['email']));
506
507
		// Password isn't legal?
508
		if ($passwordError != null)
0 ignored issues
show
It seems like you are loosely comparing $passwordError of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
509
		{
510
			$errorCode = array('lang', 'profile_error_password_' . $passwordError, false);
511
			if ($passwordError == 'short')
512
				$errorCode[] = array(empty($modSettings['password_strength']) ? 4 : 8);
513
			$reg_errors[] = $errorCode;
514
		}
515
	}
516
517
	// You may not be allowed to register this email.
518
	if (!empty($regOptions['check_email_ban']))
519
		isBannedEmail($regOptions['email'], 'cannot_register', $txt['ban_register_prohibited']);
520
521
	// Check if the email address is in use.
522
	$request = $smcFunc['db_query']('', '
523
		SELECT id_member
524
		FROM {db_prefix}members
525
		WHERE email_address = {string:email_address}
526
			OR email_address = {string:username}
527
		LIMIT 1',
528
		array(
529
			'email_address' => $regOptions['email'],
530
			'username' => $regOptions['username'],
531
		)
532
	);
533
	// @todo Separate the sprintf?
534
	if ($smcFunc['db_num_rows']($request) != 0)
535
		$reg_errors[] = array('lang', 'email_in_use', false, array($smcFunc['htmlspecialchars']($regOptions['email'])));
536
537
	$smcFunc['db_free_result']($request);
538
539
	// Perhaps someone else wants to check this user.
540
	call_integration_hook('integrate_register_check', array(&$regOptions, &$reg_errors));
541
542
	// If we found any errors we need to do something about it right away!
543
	foreach ($reg_errors as $key => $error)
544
	{
545
		/* Note for each error:
546
			0 = 'lang' if it's an index, 'done' if it's clear text.
547
			1 = The text/index.
548
			2 = Whether to log.
549
			3 = sprintf data if necessary. */
550
		if ($error[0] == 'lang')
551
			loadLanguage('Errors');
552
		$message = $error[0] == 'lang' ? (empty($error[3]) ? $txt[$error[1]] : vsprintf($txt[$error[1]], (array) $error[3])) : $error[1];
553
554
		// What to do, what to do, what to do.
555
		if ($return_errors)
556
		{
557
			if (!empty($error[2]))
558
				log_error($message, $error[2]);
559
			$reg_errors[$key] = $message;
560
		}
561
		else
562
			fatal_error($message, empty($error[2]) ? false : $error[2]);
563
	}
564
565
	// If there's any errors left return them at once!
566
	if (!empty($reg_errors))
567
		return $reg_errors;
568
569
	$reservedVars = array(
570
		'actual_theme_url',
571
		'actual_images_url',
572
		'base_theme_dir',
573
		'base_theme_url',
574
		'default_images_url',
575
		'default_theme_dir',
576
		'default_theme_url',
577
		'default_template',
578
		'images_url',
579
		'number_recent_posts',
580
		'smiley_sets_default',
581
		'theme_dir',
582
		'theme_id',
583
		'theme_layers',
584
		'theme_templates',
585
		'theme_url',
586
	);
587
588
	// Can't change reserved vars.
589
	if (isset($regOptions['theme_vars']) && count(array_intersect(array_keys($regOptions['theme_vars']), $reservedVars)) != 0)
590
		fatal_lang_error('no_theme');
591
592
	// Some of these might be overwritten. (the lower ones that are in the arrays below.)
593
	$regOptions['register_vars'] = array(
594
		'member_name' => $regOptions['username'],
595
		'email_address' => $regOptions['email'],
596
		'passwd' => hash_password($regOptions['username'], $regOptions['password']),
597
		'password_salt' => bin2hex($smcFunc['random_bytes'](16)),
598
		'posts' => 0,
599
		'date_registered' => time(),
600
		'member_ip' => $regOptions['interface'] == 'admin' ? '127.0.0.1' : $user_info['ip'],
601
		'member_ip2' => $regOptions['interface'] == 'admin' ? '127.0.0.1' : $_SERVER['BAN_CHECK_IP'],
602
		'validation_code' => $validation_code,
603
		'real_name' => $regOptions['username'],
604
		'personal_text' => $modSettings['default_personal_text'],
605
		'id_theme' => 0,
606
		'id_post_group' => 4,
607
		'lngfile' => '',
608
		'buddy_list' => '',
609
		'pm_ignore_list' => '',
610
		'website_title' => '',
611
		'website_url' => '',
612
		'time_format' => '',
613
		'signature' => '',
614
		'avatar' => '',
615
		'usertitle' => '',
616
		'secret_question' => '',
617
		'secret_answer' => '',
618
		'additional_groups' => '',
619
		'ignore_boards' => '',
620
		'smiley_set' => '',
621
		'timezone' => empty($modSettings['default_timezone']) || !array_key_exists($modSettings['default_timezone'], smf_list_timezones()) ? 'UTC' : $modSettings['default_timezone'],
622
	);
623
624
	// Setup the activation status on this new account so it is correct - firstly is it an under age account?
625
	if ($regOptions['require'] == 'coppa')
626
	{
627
		$regOptions['register_vars']['is_activated'] = 5;
628
		// @todo This should be changed.  To what should be it be changed??
629
		$regOptions['register_vars']['validation_code'] = '';
630
	}
631
	// Maybe it can be activated right away?
632
	elseif ($regOptions['require'] == 'nothing')
633
		$regOptions['register_vars']['is_activated'] = 1;
634
	// Maybe it must be activated by email?
635
	elseif ($regOptions['require'] == 'activation')
636
		$regOptions['register_vars']['is_activated'] = 0;
637
	// Otherwise it must be awaiting approval!
638
	else
639
		$regOptions['register_vars']['is_activated'] = 3;
640
641
	if (isset($regOptions['memberGroup']))
642
	{
643
		// Make sure the id_group will be valid, if this is an administrator.
644
		$regOptions['register_vars']['id_group'] = $regOptions['memberGroup'] == 1 && !allowedTo('admin_forum') ? 0 : $regOptions['memberGroup'];
645
646
		// Check if this group is assignable.
647
		$unassignableGroups = array(-1, 3);
648
		$request = $smcFunc['db_query']('', '
649
			SELECT id_group
650
			FROM {db_prefix}membergroups
651
			WHERE min_posts != {int:min_posts}' . (allowedTo('admin_forum') ? '' : '
652
				OR group_type = {int:is_protected}'),
653
			array(
654
				'min_posts' => -1,
655
				'is_protected' => 1,
656
			)
657
		);
658
		while ($row = $smcFunc['db_fetch_assoc']($request))
659
			$unassignableGroups[] = $row['id_group'];
660
		$smcFunc['db_free_result']($request);
661
662
		if (in_array($regOptions['register_vars']['id_group'], $unassignableGroups))
663
			$regOptions['register_vars']['id_group'] = 0;
664
	}
665
666
	// Verify that timezone is correct, if provided.
667
	if (!empty($regOptions['extra_register_vars']) && !empty($regOptions['extra_register_vars']['timezone']) &&
668
		!array_key_exists($regOptions['extra_register_vars']['timezone'], smf_list_timezones()))
669
		unset($regOptions['extra_register_vars']['timezone']);
670
671
	// Integrate optional member settings to be set.
672
	if (!empty($regOptions['extra_register_vars']))
673
		foreach ($regOptions['extra_register_vars'] as $var => $value)
674
			$regOptions['register_vars'][$var] = $value;
675
676
	// Integrate optional user theme options to be set.
677
	$theme_vars = array();
678
	if (!empty($regOptions['theme_vars']))
679
		foreach ($regOptions['theme_vars'] as $var => $value)
680
			$theme_vars[$var] = $value;
681
682
	// Right, now let's prepare for insertion.
683
	$knownInts = array(
684
		'date_registered', 'posts', 'id_group', 'last_login', 'instant_messages', 'unread_messages',
685
		'new_pm', 'pm_prefs', 'show_online',
686
		'id_theme', 'is_activated', 'id_msg_last_visit', 'id_post_group', 'total_time_logged_in', 'warning',
687
	);
688
	$knownFloats = array(
689
		'time_offset',
690
	);
691
	$knownInets = array(
692
		'member_ip', 'member_ip2',
693
	);
694
695
	// Call an optional function to validate the users' input.
696
	call_integration_hook('integrate_register', array(&$regOptions, &$theme_vars, &$knownInts, &$knownFloats));
697
698
	$column_names = array();
699
	$values = array();
700
	foreach ($regOptions['register_vars'] as $var => $val)
701
	{
702
		$type = 'string';
703
		if (in_array($var, $knownInts))
704
			$type = 'int';
705
		elseif (in_array($var, $knownFloats))
706
			$type = 'float';
707
		elseif (in_array($var, $knownInets))
708
			$type = 'inet';
709
		elseif ($var == 'birthdate')
710
			$type = 'date';
711
712
		$column_names[$var] = $type;
713
		$values[$var] = $val;
714
	}
715
716
	// Register them into the database.
717
	$memberID = $smcFunc['db_insert']('',
718
		'{db_prefix}members',
719
		$column_names,
720
		$values,
721
		array('id_member'),
722
		1
723
	);
724
725
	// Call an optional function as notification of registration.
726
	call_integration_hook('integrate_post_register', array(&$regOptions, &$theme_vars, &$memberID));
727
728
	// Update the number of members and latest member's info - and pass the name, but remove the 's.
729
	if ($regOptions['register_vars']['is_activated'] == 1)
730
		updateStats('member', $memberID, $regOptions['register_vars']['real_name']);
731
	else
732
		updateStats('member');
733
734
	// Theme variables too?
735
	if (!empty($theme_vars))
736
	{
737
		$inserts = array();
738
		foreach ($theme_vars as $var => $val)
739
			$inserts[] = array($memberID, $var, $val);
740
		$smcFunc['db_insert']('insert',
741
			'{db_prefix}themes',
742
			array('id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
743
			$inserts,
744
			array('id_member', 'variable')
745
		);
746
	}
747
748
	// Log their acceptance of the agreement and privacy policy, for future reference.
749
	foreach (array('agreement_accepted', 'policy_accepted') as $key)
750
		if (!empty($theme_vars[$key]))
751
			logAction($key, array('member_affected' => $memberID, 'applicator' => $memberID), 'user');
752
753
	// If it's enabled, increase the registrations for today.
754
	trackStats(array('registers' => '+'));
755
756
	// Administrative registrations are a bit different...
757
	if ($regOptions['interface'] == 'admin')
758
	{
759
		if ($regOptions['require'] == 'activation')
760
			$email_message = 'admin_register_activate';
761
		elseif (!empty($regOptions['send_welcome_email']))
762
			$email_message = 'admin_register_immediate';
763
764
		if (isset($email_message))
765
		{
766
			$replacements = array(
767
				'REALNAME' => $regOptions['register_vars']['real_name'],
768
				'USERNAME' => $regOptions['username'],
769
				'PASSWORD' => $regOptions['password'],
770
				'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder',
771
				'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $memberID . ';code=' . $validation_code,
772
				'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $memberID,
773
				'ACTIVATIONCODE' => $validation_code,
774
			);
775
776
			$emaildata = loadEmailTemplate($email_message, $replacements);
777
778
			sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, $email_message . $memberID, $emaildata['is_html'], 0);
779
		}
780
781
		// All admins are finished here.
782
		return $memberID;
783
	}
784
785
	// Can post straight away - welcome them to your fantastic community...
786
	if ($regOptions['require'] == 'nothing')
787
	{
788
		if (!empty($regOptions['send_welcome_email']))
789
		{
790
			$replacements = array(
791
				'REALNAME' => $regOptions['register_vars']['real_name'],
792
				'USERNAME' => $regOptions['username'],
793
				'PASSWORD' => $regOptions['password'],
794
				'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder',
795
			);
796
			$emaildata = loadEmailTemplate('register_immediate', $replacements);
797
			sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, 'register', $emaildata['is_html'], 0);
798
		}
799
800
		// Send admin their notification.
801
		adminNotify('standard', $memberID, $regOptions['username']);
802
	}
803
	// Need to activate their account - or fall under COPPA.
804
	elseif ($regOptions['require'] == 'activation' || $regOptions['require'] == 'coppa')
805
	{
806
		$replacements = array(
807
			'REALNAME' => $regOptions['register_vars']['real_name'],
808
			'USERNAME' => $regOptions['username'],
809
			'PASSWORD' => $regOptions['password'],
810
			'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder',
811
		);
812
813
		if ($regOptions['require'] == 'activation')
814
			$replacements += array(
815
				'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $memberID . ';code=' . $validation_code,
816
				'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $memberID,
817
				'ACTIVATIONCODE' => $validation_code,
818
			);
819
820
		else
821
			$replacements += array(
822
				'COPPALINK' => $scripturl . '?action=coppa;member=' . $memberID,
823
			);
824
825
		$emaildata = loadEmailTemplate('register_' . ($regOptions['require'] == 'activation' ? 'activate' : 'coppa'), $replacements);
826
827
		sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, 'reg_' . $regOptions['require'] . $memberID, $emaildata['is_html'], 0);
828
	}
829
	// Must be awaiting approval.
830
	else
831
	{
832
		$replacements = array(
833
			'REALNAME' => $regOptions['register_vars']['real_name'],
834
			'USERNAME' => $regOptions['username'],
835
			'PASSWORD' => $regOptions['password'],
836
			'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder',
837
		);
838
839
		$emaildata = loadEmailTemplate('register_pending', $replacements);
840
841
		sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, 'reg_pending', $emaildata['is_html'], 0);
842
843
		// Admin gets informed here...
844
		adminNotify('approval', $memberID, $regOptions['username']);
845
	}
846
847
	// Okay, they're for sure registered... make sure the session is aware of this for security. (Just married :P!)
848
	$_SESSION['just_registered'] = 1;
849
850
	// If they are for sure registered, let other people to know about it
851
	call_integration_hook('integrate_register_after', array($regOptions, $memberID));
852
853
	return $memberID;
854
}
855
856
/**
857
 * Check if a name is in the reserved words list.
858
 * (name, current member id, name/username?.)
859
 * - checks if name is a reserved name or username.
860
 * - if is_name is false, the name is assumed to be a username.
861
 * - the id_member variable is used to ignore duplicate matches with the
862
 * current member.
863
 *
864
 * @param string $name The name to check
865
 * @param int $current_id_member The ID of the current member (to avoid false positives with the current member)
866
 * @param bool $is_name Whether we're checking against reserved names or just usernames
867
 * @param bool $fatal Whether to die with a fatal error if the name is reserved
868
 * @return bool|void False if name is not reserved, otherwise true if $fatal is false or dies with a fatal_lang_error if $fatal is true
869
 */
870
function isReservedName($name, $current_id_member = 0, $is_name = true, $fatal = true)
871
{
872
	global $modSettings, $smcFunc;
873
874
	$name = preg_replace_callback('~(&#(\d{1,7}|x[0-9a-fA-F]{1,6});)~', 'replaceEntities__callback', $name);
875
	$checkName = $smcFunc['strtolower']($name);
876
877
	// Administrators are never restricted ;).
878
	if (!allowedTo('moderate_forum') && ((!empty($modSettings['reserveName']) && $is_name) || !empty($modSettings['reserveUser']) && !$is_name))
879
	{
880
		$reservedNames = explode("\n", $modSettings['reserveNames']);
881
		// Case sensitive check?
882
		$checkMe = empty($modSettings['reserveCase']) ? $checkName : $name;
883
884
		// Check each name in the list...
885
		foreach ($reservedNames as $reserved)
886
		{
887
			if ($reserved == '')
888
				continue;
889
890
			// The admin might've used entities too, level the playing field.
891
			$reservedCheck = preg_replace('~(&#(\d{1,7}|x[0-9a-fA-F]{1,6});)~', 'replaceEntities__callback', $reserved);
892
893
			// Case sensitive name?
894
			if (empty($modSettings['reserveCase']))
895
				$reservedCheck = $smcFunc['strtolower']($reservedCheck);
896
897
			// If it's not just entire word, check for it in there somewhere...
898
			if ($checkMe == $reservedCheck || ($smcFunc['strpos']($checkMe, $reservedCheck) !== false && empty($modSettings['reserveWord'])))
899
				if ($fatal)
900
					fatal_lang_error('username_reserved', 'password', array($reserved));
901
				else
902
					return true;
903
		}
904
905
		$censor_name = $name;
906
		if (censorText($censor_name) != $name)
907
			if ($fatal)
908
				fatal_lang_error('name_censored', 'password', array($name));
909
			else
910
				return true;
911
	}
912
913
	// Characters we just shouldn't allow, regardless.
914
	foreach (array('*') as $char)
915
		if (strpos($checkName, $char) !== false)
916
			if ($fatal)
917
				fatal_lang_error('username_reserved', 'password', array($char));
918
			else
919
				return true;
920
921
	$request = $smcFunc['db_query']('', '
922
		SELECT id_member
923
		FROM {db_prefix}members
924
		WHERE ' . (empty($current_id_member) ? '' : 'id_member != {int:current_member}
925
			AND ') . '({raw:real_name} {raw:operator} LOWER({string:check_name}) OR {raw:member_name} {raw:operator} LOWER({string:check_name}))
926
		LIMIT 1',
927
		array(
928
			'real_name' => $smcFunc['db_case_sensitive'] ? 'LOWER(real_name)' : 'real_name',
929
			'member_name' => $smcFunc['db_case_sensitive'] ? 'LOWER(member_name)' : 'member_name',
930
			'current_member' => $current_id_member,
931
			'check_name' => $checkName,
932
			'operator' => strpos($checkName, '%') || strpos($checkName, '_') ? 'LIKE' : '=',
933
		)
934
	);
935
	if ($smcFunc['db_num_rows']($request) > 0)
936
	{
937
		$smcFunc['db_free_result']($request);
938
		return true;
939
	}
940
941
	// Does name case insensitive match a member group name?
942
	$request = $smcFunc['db_query']('', '
943
		SELECT id_group
944
		FROM {db_prefix}membergroups
945
		WHERE {raw:group_name} LIKE {string:check_name}
946
		LIMIT 1',
947
		array(
948
			'group_name' => $smcFunc['db_case_sensitive'] ? 'LOWER(group_name)' : 'group_name',
949
			'check_name' => $checkName,
950
		)
951
	);
952
	if ($smcFunc['db_num_rows']($request) > 0)
953
	{
954
		$smcFunc['db_free_result']($request);
955
		return true;
956
	}
957
958
	// Okay, they passed.
959
	$is_reserved = false;
960
961
	// Maybe a mod wants to perform further checks?
962
	call_integration_hook('integrate_check_name', array($checkName, &$is_reserved, $current_id_member, $is_name));
963
964
	return $is_reserved;
965
}
966
967
/**
968
 * Retrieves a list of membergroups that have the given permission, either on
969
 * a given board or in general.
970
 *
971
 * If board_id is not null, a board permission is assumed.
972
 * The function takes different permission settings into account.
973
 *
974
 * @param string $permission The permission to check
975
 * @param int $board_id = null If set, checks permissions for the specified board
976
 * @return array An array containing two arrays - 'allowed', which has which groups are allowed to do it and 'denied' which has the groups that are denied
977
 */
978
function groupsAllowedTo($permission, $board_id = null)
979
{
980
	global $board_info, $smcFunc;
981
982
	// Admins are allowed to do anything.
983
	$member_groups = array(
984
		'allowed' => array(1),
985
		'denied' => array(),
986
	);
987
988
	// Assume we're dealing with regular permissions (like profile_view).
989
	if ($board_id === null)
990
	{
991
		$request = $smcFunc['db_query']('', '
992
			SELECT id_group, add_deny
993
			FROM {db_prefix}permissions
994
			WHERE permission = {string:permission}',
995
			array(
996
				'permission' => $permission,
997
			)
998
		);
999
1000
		while ($row = $smcFunc['db_fetch_assoc']($request))
1001
		{
1002
			$member_groups[$row['add_deny'] === '1' ? 'allowed' : 'denied'][] = $row['id_group'];
1003
		}
1004
1005
		$smcFunc['db_free_result']($request);
1006
	}
1007
1008
	// Otherwise it's time to look at the board.
1009
	else
1010
	{
1011
		$board_id = (int) $board_id;
1012
1013
		// First get the profile of the given board.
1014
		if (isset($board_info['id']) && $board_info['id'] == $board_id)
1015
		{
1016
			$profile_id = $board_info['profile'];
1017
		}
1018
		elseif ($board_id !== 0)
1019
		{
1020
			$request = $smcFunc['db_query']('', '
1021
				SELECT id_profile
1022
				FROM {db_prefix}boards
1023
				WHERE id_board = {int:id_board}
1024
				LIMIT 1',
1025
				array(
1026
					'id_board' => $board_id,
1027
				)
1028
			);
1029
1030
			if ($smcFunc['db_num_rows']($request) == 0)
1031
			{
1032
				fatal_lang_error('no_board');
1033
			}
1034
1035
			list ($profile_id) = $smcFunc['db_fetch_row']($request);
1036
1037
			$smcFunc['db_free_result']($request);
1038
		}
1039
		else
1040
			$profile_id = 1;
1041
1042
		$request = $smcFunc['db_query']('', '
1043
			SELECT bp.id_group, bp.add_deny
1044
			FROM {db_prefix}board_permissions AS bp
1045
			WHERE bp.permission = {string:permission}
1046
				AND bp.id_profile = {int:profile_id}',
1047
			array(
1048
				'profile_id' => $profile_id,
1049
				'permission' => $permission,
1050
			)
1051
		);
1052
1053
		while ($row = $smcFunc['db_fetch_assoc']($request))
1054
		{
1055
			$member_groups[$row['add_deny'] === '1' ? 'allowed' : 'denied'][] = $row['id_group'];
1056
		}
1057
1058
		$smcFunc['db_free_result']($request);
1059
1060
		$moderator_groups = array();
1061
1062
		// "Inherit" any moderator permissions as needed
1063
		if (isset($board_info['moderator_groups']))
1064
		{
1065
			$moderator_groups = array_keys($board_info['moderator_groups']);
1066
		}
1067
		elseif ($board_id !== 0)
1068
		{
1069
			// Get the groups that can moderate this board
1070
			$request = $smcFunc['db_query']('', '
1071
				SELECT id_group
1072
				FROM {db_prefix}moderator_groups
1073
				WHERE id_board = {int:board_id}',
1074
				array(
1075
					'board_id' => $board_id,
1076
				)
1077
			);
1078
1079
			while ($row = $smcFunc['db_fetch_assoc']($request))
1080
			{
1081
				$moderator_groups[] = $row['id_group'];
1082
			}
1083
1084
			$smcFunc['db_free_result']($request);
1085
		}
1086
1087
		// "Inherit" any additional permissions from the "Moderators" group
1088
		foreach ($moderator_groups as $mod_group)
1089
		{
1090
			// If they're not specifically allowed, but the moderator group is, then allow it
1091
			if (in_array(3, $member_groups['allowed']) && !in_array($mod_group, $member_groups['allowed']))
1092
			{
1093
				$member_groups['allowed'][] = $mod_group;
1094
			}
1095
1096
			// They're not denied, but the moderator group is, so deny it
1097
			if (in_array(3, $member_groups['denied']) && !in_array($mod_group, $member_groups['denied']))
1098
			{
1099
				$member_groups['denied'][] = $mod_group;
1100
			}
1101
		}
1102
	}
1103
1104
	// Maybe a mod needs to tweak the list of allowed groups on the fly?
1105
	call_integration_hook('integrate_groups_allowed_to', array(&$member_groups, $permission, $board_id));
1106
1107
	// Denied is never allowed.
1108
	$member_groups['allowed'] = array_diff($member_groups['allowed'], $member_groups['denied']);
1109
1110
	return $member_groups;
1111
}
1112
1113
/**
1114
 * Retrieves a list of members that have a given permission
1115
 * (on a given board).
1116
 * If board_id is not null, a board permission is assumed.
1117
 * Takes different permission settings into account.
1118
 * Takes possible moderators (on board 'board_id') into account.
1119
 *
1120
 * @param string $permission The permission to check
1121
 * @param int $board_id If set, checks permission for that specific board
1122
 * @return array An array containing the IDs of the members having that permission
1123
 */
1124
function membersAllowedTo($permission, $board_id = null)
1125
{
1126
	global $smcFunc;
1127
1128
	$member_groups = groupsAllowedTo($permission, $board_id);
1129
1130
	$all_groups = array_merge($member_groups['allowed'], $member_groups['denied']);
1131
1132
	$include_moderators = in_array(3, $member_groups['allowed']) && $board_id !== null;
1133
	$member_groups['allowed'] = array_diff($member_groups['allowed'], array(3));
1134
1135
	$exclude_moderators = in_array(3, $member_groups['denied']) && $board_id !== null;
1136
	$member_groups['denied'] = array_diff($member_groups['denied'], array(3));
1137
1138
	$request = $smcFunc['db_query']('', '
1139
		SELECT mem.id_member
1140
		FROM {db_prefix}members AS mem' . ($include_moderators || $exclude_moderators ? '
1141
			LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_member = mem.id_member AND mods.id_board = {int:board_id})' : '') . '
1142
		WHERE (' . ($include_moderators ? 'mods.id_member IS NOT NULL OR ' : '') . 'mem.id_group IN ({array_int:member_groups_allowed}) OR FIND_IN_SET({raw:member_group_allowed_implode}, mem.additional_groups) != 0 OR mem.id_post_group IN ({array_int:member_groups_allowed}))' . (empty($member_groups['denied']) ? '' : '
1143
			AND NOT (' . ($exclude_moderators ? 'mods.id_member IS NOT NULL OR ' : '') . 'mem.id_group IN ({array_int:member_groups_denied}) OR FIND_IN_SET({raw:member_group_denied_implode}, mem.additional_groups) != 0 OR mem.id_post_group IN ({array_int:member_groups_denied}))'),
1144
		array(
1145
			'member_groups_allowed' => $member_groups['allowed'],
1146
			'member_groups_denied' => $member_groups['denied'],
1147
			'all_member_groups' => $all_groups,
1148
			'board_id' => $board_id,
1149
			'member_group_allowed_implode' => implode(', mem.additional_groups) != 0 OR FIND_IN_SET(', $member_groups['allowed']),
1150
			'member_group_denied_implode' => implode(', mem.additional_groups) != 0 OR FIND_IN_SET(', $member_groups['denied']),
1151
		)
1152
	);
1153
	$members = array();
1154
	while ($row = $smcFunc['db_fetch_assoc']($request))
1155
		$members[] = $row['id_member'];
1156
	$smcFunc['db_free_result']($request);
1157
1158
	return $members;
1159
}
1160
1161
/**
1162
 * This function is used to reassociate members with relevant posts.
1163
 * Reattribute guest posts to a specified member.
1164
 * Does not check for any permissions.
1165
 * If add_to_post_count is set, the member's post count is increased.
1166
 *
1167
 * @param int $memID The ID of the original poster
1168
 * @param bool|string $email If set, should be the email of the poster
1169
 * @param bool|string $membername If set, the membername of the poster
1170
 * @param bool $post_count Whether to adjust post counts
1171
 * @return array An array containing the number of messages, topics and reports updated
1172
 */
1173
function reattributePosts($memID, $email = false, $membername = false, $post_count = false)
1174
{
1175
	global $smcFunc, $modSettings;
1176
1177
	$updated = array(
1178
		'messages' => 0,
1179
		'topics' => 0,
1180
		'reports' => 0,
1181
	);
1182
1183
	// Firstly, if email and username aren't passed find out the members email address and name.
1184
	if ($email === false && $membername === false)
1185
	{
1186
		$request = $smcFunc['db_query']('', '
1187
			SELECT email_address, member_name
1188
			FROM {db_prefix}members
1189
			WHERE id_member = {int:memID}
1190
			LIMIT 1',
1191
			array(
1192
				'memID' => $memID,
1193
			)
1194
		);
1195
		list ($email, $membername) = $smcFunc['db_fetch_row']($request);
1196
		$smcFunc['db_free_result']($request);
1197
	}
1198
1199
	// If they want the post count restored then we need to do some research.
1200
	if ($post_count)
1201
	{
1202
		$recycle_board = !empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']) ? (int) $modSettings['recycle_board'] : 0;
1203
		$request = $smcFunc['db_query']('', '
1204
			SELECT COUNT(*)
1205
			FROM {db_prefix}messages AS m
1206
				INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board AND b.count_posts = {int:count_posts})
1207
			WHERE m.id_member = {int:guest_id}
1208
				AND m.approved = {int:is_approved}' . (!empty($recycle_board) ? '
1209
				AND m.id_board != {int:recycled_board}' : '') . (empty($email) ? '' : '
1210
				AND m.poster_email = {string:email_address}') . (empty($membername) ? '' : '
1211
				AND m.poster_name = {string:member_name}'),
1212
			array(
1213
				'count_posts' => 0,
1214
				'guest_id' => 0,
1215
				'email_address' => $email,
1216
				'member_name' => $membername,
1217
				'is_approved' => 1,
1218
				'recycled_board' => $recycle_board,
1219
			)
1220
		);
1221
		list ($messageCount) = $smcFunc['db_fetch_row']($request);
1222
		$smcFunc['db_free_result']($request);
1223
1224
		updateMemberData($memID, array('posts' => 'posts + ' . $messageCount));
1225
	}
1226
1227
	$query_parts = array();
1228
	if (!empty($email))
1229
		$query_parts[] = 'poster_email = {string:email_address}';
1230
	if (!empty($membername))
1231
		$query_parts[] = 'poster_name = {string:member_name}';
1232
	$query = implode(' AND ', $query_parts);
1233
1234
	// Finally, update the posts themselves!
1235
	$smcFunc['db_query']('', '
1236
		UPDATE {db_prefix}messages
1237
		SET id_member = {int:memID}
1238
		WHERE ' . $query,
1239
		array(
1240
			'memID' => $memID,
1241
			'email_address' => $email,
1242
			'member_name' => $membername,
1243
		)
1244
	);
1245
	$updated['messages'] = $smcFunc['db_affected_rows']();
1246
1247
	// Did we update any messages?
1248
	if ($updated['messages'] > 0)
1249
	{
1250
		// First, check for updated topics.
1251
		$smcFunc['db_query']('', '
1252
			UPDATE {db_prefix}topics AS t
1253
			SET id_member_started = {int:memID}
1254
			WHERE t.id_first_msg = (
1255
				SELECT m.id_msg
1256
				FROM {db_prefix}messages m
1257
				WHERE m.id_member = {int:memID}
1258
					AND m.id_msg = t.id_first_msg
1259
					AND ' . $query . '
1260
				)',
1261
			array(
1262
				'memID' => $memID,
1263
				'email_address' => $email,
1264
				'member_name' => $membername,
1265
			)
1266
		);
1267
		$updated['topics'] = $smcFunc['db_affected_rows']();
1268
1269
		// Second, check for updated reports.
1270
		$smcFunc['db_query']('', '
1271
			UPDATE {db_prefix}log_reported AS lr
1272
			SET id_member = {int:memID}
1273
			WHERE lr.id_msg = (
1274
				SELECT m.id_msg
1275
				FROM {db_prefix}messages m
1276
				WHERE m.id_member = {int:memID}
1277
					AND m.id_msg = lr.id_msg
1278
					AND ' . $query . '
1279
				)',
1280
			array(
1281
				'memID' => $memID,
1282
				'email_address' => $email,
1283
				'member_name' => $membername,
1284
			)
1285
		);
1286
		$updated['reports'] = $smcFunc['db_affected_rows']();
1287
	}
1288
1289
	// Allow mods with their own post tables to reattribute posts as well :)
1290
	call_integration_hook('integrate_reattribute_posts', array($memID, $email, $membername, $post_count, &$updated));
1291
1292
	return $updated;
1293
}
1294
1295
/**
1296
 * This simple function adds/removes the passed user from the current users buddy list.
1297
 * Requires profile_identity_own permission.
1298
 * Called by ?action=buddy;u=x;session_id=y.
1299
 * Redirects to ?action=profile;u=x.
1300
 */
1301
function BuddyListToggle()
1302
{
1303
	global $user_info, $smcFunc;
1304
1305
	checkSession('get');
1306
1307
	isAllowedTo('profile_extra_own');
1308
	is_not_guest();
1309
1310
	$userReceiver = (int) !empty($_REQUEST['u']) ? $_REQUEST['u'] : 0;
1311
1312
	if (empty($userReceiver))
1313
		fatal_lang_error('no_access', false);
1314
1315
	// Remove if it's already there...
1316
	if (in_array($userReceiver, $user_info['buddies']))
1317
		$user_info['buddies'] = array_diff($user_info['buddies'], array($userReceiver));
1318
1319
	// ...or add if it's not and if it's not you.
1320
	elseif ($user_info['id'] != $userReceiver)
1321
	{
1322
		$user_info['buddies'][] = $userReceiver;
1323
1324
		// And add a nice alert. Don't abuse though!
1325
		if ((cache_get_data('Buddy-sent-' . $user_info['id'] . '-' . $userReceiver, 86400)) == null)
1326
		{
1327
			$smcFunc['db_insert']('insert',
1328
				'{db_prefix}background_tasks',
1329
				array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
1330
				array('$sourcedir/tasks/Buddy-Notify.php', 'Buddy_Notify_Background', $smcFunc['json_encode'](array(
1331
					'receiver_id' => $userReceiver,
1332
					'id_member' => $user_info['id'],
1333
					'member_name' => $user_info['username'],
1334
					'time' => time(),
1335
				)), 0),
1336
				array('id_task')
1337
			);
1338
1339
			// Store this in a cache entry to avoid creating multiple alerts. Give it a long life cycle.
1340
			cache_put_data('Buddy-sent-' . $user_info['id'] . '-' . $userReceiver, '1', 86400);
1341
		}
1342
	}
1343
1344
	// Update the settings.
1345
	updateMemberData($user_info['id'], array('buddy_list' => implode(',', $user_info['buddies'])));
1346
1347
	// Redirect back to the profile
1348
	redirectexit('action=profile;u=' . $userReceiver);
1349
}
1350
1351
/**
1352
 * Callback for createList().
1353
 *
1354
 * @param int $start Which item to start with (for pagination purposes)
1355
 * @param int $items_per_page How many items to show per page
1356
 * @param string $sort An SQL query indicating how to sort the results
1357
 * @param string $where An SQL query used to filter the results
1358
 * @param array $where_params An array of parameters for $where
1359
 * @param bool $get_duplicates Whether to get duplicates (used for the admin member list)
1360
 * @return array An array of information for displaying the list of members
1361
 */
1362
function list_getMembers($start, $items_per_page, $sort, $where, $where_params = array(), $get_duplicates = false)
1363
{
1364
	global $smcFunc;
1365
1366
	$request = $smcFunc['db_query']('', '
1367
		SELECT
1368
			mem.id_member, mem.member_name, mem.real_name, mem.email_address, mem.member_ip, mem.member_ip2, mem.last_login,
1369
			mem.posts, mem.is_activated, mem.date_registered, mem.id_group, mem.additional_groups, mg.group_name
1370
		FROM {db_prefix}members AS mem
1371
			LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = mem.id_group)
1372
		WHERE ' . ($where == '1' ? '1=1' : $where) . '
1373
		ORDER BY {raw:sort}
1374
		LIMIT {int:start}, {int:per_page}',
1375
		array_merge($where_params, array(
1376
			'sort' => $sort,
1377
			'start' => $start,
1378
			'per_page' => $items_per_page,
1379
		))
1380
	);
1381
1382
	$members = array();
1383
	while ($row = $smcFunc['db_fetch_assoc']($request))
1384
	{
1385
		$row['member_ip'] = inet_dtop($row['member_ip']);
1386
		$row['member_ip2'] = inet_dtop($row['member_ip2']);
1387
		$members[] = $row;
1388
	}
1389
	$smcFunc['db_free_result']($request);
1390
1391
	// If we want duplicates pass the members array off.
1392
	if ($get_duplicates)
1393
		populateDuplicateMembers($members);
1394
1395
	return $members;
1396
}
1397
1398
/**
1399
 * Callback for createList().
1400
 *
1401
 * @param string $where An SQL query to filter the results
1402
 * @param array $where_params An array of parameters for $where
1403
 * @return int The number of members matching the given situation
1404
 */
1405
function list_getNumMembers($where, $where_params = array())
1406
{
1407
	global $smcFunc, $modSettings;
1408
1409
	// We know how many members there are in total.
1410
	if (empty($where) || $where == '1=1')
1411
		$num_members = $modSettings['totalMembers'];
1412
1413
	// The database knows the amount when there are extra conditions.
1414
	else
1415
	{
1416
		$request = $smcFunc['db_query']('', '
1417
			SELECT COUNT(*)
1418
			FROM {db_prefix}members AS mem
1419
			WHERE ' . $where,
1420
			array_merge($where_params, array(
1421
			))
1422
		);
1423
		list ($num_members) = $smcFunc['db_fetch_row']($request);
1424
		$smcFunc['db_free_result']($request);
1425
	}
1426
1427
	return $num_members;
1428
}
1429
1430
/**
1431
 * Find potential duplicate registration members based on the same IP address
1432
 *
1433
 * @param array $members An array of members
1434
 */
1435
function populateDuplicateMembers(&$members)
1436
{
1437
	global $smcFunc;
1438
1439
	// This will hold all the ip addresses.
1440
	$ips = array();
1441
	foreach ($members as $key => $member)
1442
	{
1443
		// Create the duplicate_members element.
1444
		$members[$key]['duplicate_members'] = array();
1445
1446
		// Store the IPs.
1447
		if (!empty($member['member_ip']))
1448
			$ips[] = $member['member_ip'];
1449
		if (!empty($member['member_ip2']))
1450
			$ips[] = $member['member_ip2'];
1451
	}
1452
1453
	$ips = array_unique($ips);
1454
1455
	if (empty($ips))
1456
		return false;
1457
1458
	// Fetch all members with this IP address, we'll filter out the current ones in a sec.
1459
	$request = $smcFunc['db_query']('', '
1460
		SELECT
1461
			id_member, member_name, email_address, member_ip, member_ip2, is_activated
1462
		FROM {db_prefix}members
1463
		WHERE member_ip IN ({array_inet:ips})
1464
			OR member_ip2 IN ({array_inet:ips})',
1465
		array(
1466
			'ips' => $ips,
1467
		)
1468
	);
1469
	$duplicate_members = array();
1470
	$duplicate_ids = array();
1471
	while ($row = $smcFunc['db_fetch_assoc']($request))
1472
	{
1473
		//$duplicate_ids[] = $row['id_member'];
1474
		$row['member_ip'] = inet_dtop($row['member_ip']);
1475
		$row['member_ip2'] = inet_dtop($row['member_ip2']);
1476
1477
		$member_context = array(
1478
			'id' => $row['id_member'],
1479
			'name' => $row['member_name'],
1480
			'email' => $row['email_address'],
1481
			'is_banned' => $row['is_activated'] > 10,
1482
			'ip' => $row['member_ip'],
1483
			'ip2' => $row['member_ip2'],
1484
		);
1485
1486
		if (in_array($row['member_ip'], $ips))
1487
			$duplicate_members[$row['member_ip']][] = $member_context;
1488
		if ($row['member_ip'] != $row['member_ip2'] && in_array($row['member_ip2'], $ips))
1489
			$duplicate_members[$row['member_ip2']][] = $member_context;
1490
	}
1491
	$smcFunc['db_free_result']($request);
1492
1493
	// Also try to get a list of messages using these ips.
1494
	$request = $smcFunc['db_query']('', '
1495
		SELECT
1496
			m.poster_ip, mem.id_member, mem.member_name, mem.email_address, mem.is_activated
1497
		FROM {db_prefix}messages AS m
1498
			INNER JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
1499
		WHERE m.id_member != 0
1500
			' . (!empty($duplicate_ids) ? 'AND m.id_member NOT IN ({array_int:duplicate_ids})' : '') . '
1501
			AND m.poster_ip IN ({array_inet:ips})',
1502
		array(
1503
			'duplicate_ids' => $duplicate_ids,
1504
			'ips' => $ips,
1505
		)
1506
	);
1507
1508
	$had_ips = array();
1509
	while ($row = $smcFunc['db_fetch_assoc']($request))
1510
	{
1511
		$row['poster_ip'] = inet_dtop($row['poster_ip']);
1512
1513
		// Don't collect lots of the same.
1514
		if (isset($had_ips[$row['poster_ip']]) && in_array($row['id_member'], $had_ips[$row['poster_ip']]))
1515
			continue;
1516
		$had_ips[$row['poster_ip']][] = $row['id_member'];
1517
1518
		$duplicate_members[$row['poster_ip']][] = array(
1519
			'id' => $row['id_member'],
1520
			'name' => $row['member_name'],
1521
			'email' => $row['email_address'],
1522
			'is_banned' => $row['is_activated'] > 10,
1523
			'ip' => $row['poster_ip'],
1524
			'ip2' => $row['poster_ip'],
1525
		);
1526
	}
1527
	$smcFunc['db_free_result']($request);
1528
1529
	// Now we have all the duplicate members, stick them with their respective member in the list.
1530
	if (!empty($duplicate_members))
1531
		foreach ($members as $key => $member)
1532
		{
1533
			if (isset($duplicate_members[$member['member_ip']]))
1534
				$members[$key]['duplicate_members'] = $duplicate_members[$member['member_ip']];
1535
			if ($member['member_ip'] != $member['member_ip2'] && isset($duplicate_members[$member['member_ip2']]))
1536
				$members[$key]['duplicate_members'] = array_merge($member['duplicate_members'], $duplicate_members[$member['member_ip2']]);
1537
1538
			// Check we don't have lots of the same member.
1539
			$member_track = array($member['id_member']);
1540
			foreach ($members[$key]['duplicate_members'] as $duplicate_id_member => $duplicate_member)
1541
			{
1542
				if (in_array($duplicate_member['id'], $member_track))
1543
				{
1544
					unset($members[$key]['duplicate_members'][$duplicate_id_member]);
1545
					continue;
1546
				}
1547
1548
				$member_track[] = $duplicate_member['id'];
1549
			}
1550
		}
1551
}
1552
1553
/**
1554
 * Generate a random validation code.
1555
 *
1556
 * @return string A random validation code
1557
 */
1558
function generateValidationCode()
1559
{
1560
	global $smcFunc;
1561
1562
	return bin2hex($smcFunc['random_bytes'](5));
1563
}
1564
1565
?>