PageRenderTime 166ms CodeModel.GetById 84ms app.highlight 71ms RepoModel.GetById 1ms app.codeStats 0ms

/php/Sources/Subs-Members.php

https://github.com/dekoza/openshift-smf-2.0.7
PHP | 1392 lines | 1027 code | 163 blank | 202 comment | 186 complexity | ef353f25bc0072a839763eeefb838d7c MD5 | raw file
   1<?php
   2
   3/**
   4 * Simple Machines Forum (SMF)
   5 *
   6 * @package SMF
   7 * @author Simple Machines http://www.simplemachines.org
   8 * @copyright 2011 Simple Machines
   9 * @license http://www.simplemachines.org/about/smf/license.php BSD
  10 *
  11 * @version 2.0.7
  12 */
  13
  14if (!defined('SMF'))
  15	die('Hacking attempt...');
  16
  17/* This file contains some useful functions for members and membergroups.
  18
  19	void deleteMembers(array $users, bool check_not_admin = false)
  20		- delete of 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		- changes author of messages, topics and polls to guest authors.
  25		- removes all log entries concerning the deleted members, except the
  26		  error logs, ban logs and moderation logs.
  27		- removes these members' personal messages (only the inbox), avatars,
  28		  ban entries, theme settings, moderator positions, poll votes, and
  29		  karma votes.
  30		- updates member statistics afterwards.
  31
  32	int registerMember(array options, bool return_errors)
  33		- registers a member to the forum.
  34		- returns the ID of the newly created member.
  35		- allows two types of interface: 'guest' and 'admin'. The first
  36		  includes hammering protection, the latter can perform the
  37		  registration silently.
  38		- the strings used in the options array are assumed to be escaped.
  39		- allows to perform several checks on the input, e.g. reserved names.
  40		- adjusts member statistics.
  41		- if an error is detected will fatal error on all errors unless return_errors is true.
  42
  43	bool isReservedName(string name, int id_member = 0, bool is_name = true, bool fatal = true)
  44		- checks if name is a reserved name or username.
  45		- if is_name is false, the name is assumed to be a username.
  46		- the id_member variable is used to ignore duplicate matches with the
  47		  current member.
  48
  49	array groupsAllowedTo(string permission, int board_id = null)
  50		- retrieves a list of membergroups that are allowed to do the given
  51		  permission.
  52		- if board_id is not null, a board permission is assumed.
  53		- takes different permission settings into account.
  54		- returns an array containing an array for the allowed membergroup ID's
  55		  and an array for the denied membergroup ID's.
  56
  57	array membersAllowedTo(string permission, int board_id = null)
  58		- retrieves a list of members that are allowed to do the given
  59		  permission.
  60		- if board_id is not null, a board permission is assumed.
  61		- takes different permission settings into account.
  62		- takes possible moderators (on board 'board_id') into account.
  63		- returns an array containing member ID's.
  64
  65	int reattributePosts(int id_member, string email = false, string membername = false, bool add_to_post_count = false)
  66		- reattribute guest posts to a specified member.
  67		- does not check for any permissions.
  68		- returns the number of successful reattributed posts.
  69		- if add_to_post_count is set, the member's post count is increased.
  70
  71	void BuddyListToggle()
  72		- add a member to your buddy list or remove it.
  73		- requires profile_identity_own permission.
  74		- called by ?action=buddy;u=x;session_id=y.
  75		- redirects to ?action=profile;u=x.
  76
  77	void populateDuplicateMembers(&array members)
  78		// !!!
  79
  80*/
  81
  82// Delete a group of/single member.
  83function deleteMembers($users, $check_not_admin = false)
  84{
  85	global $sourcedir, $modSettings, $user_info, $smcFunc;
  86
  87	// Try give us a while to sort this out...
  88	@set_time_limit(600);
  89	// Try to get some more memory.
  90	if (@ini_get('memory_limit') < 128)
  91		@ini_set('memory_limit', '128M');
  92
  93	// If it's not an array, make it so!
  94	if (!is_array($users))
  95		$users = array($users);
  96	else
  97		$users = array_unique($users);
  98
  99	// Make sure there's no void user in here.
 100	$users = array_diff($users, array(0));
 101
 102	// How many are they deleting?
 103	if (empty($users))
 104		return;
 105	elseif (count($users) == 1)
 106	{
 107		list ($user) = $users;
 108
 109		if ($user == $user_info['id'])
 110			isAllowedTo('profile_remove_own');
 111		else
 112			isAllowedTo('profile_remove_any');
 113	}
 114	else
 115	{
 116		foreach ($users as $k => $v)
 117			$users[$k] = (int) $v;
 118
 119		// Deleting more than one?  You can't have more than one account...
 120		isAllowedTo('profile_remove_any');
 121	}
 122
 123	// Get their names for logging purposes.
 124	$request = $smcFunc['db_query']('', '
 125		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
 126		FROM {db_prefix}members
 127		WHERE id_member IN ({array_int:user_list})
 128		LIMIT ' . count($users),
 129		array(
 130			'user_list' => $users,
 131			'admin_group' => 1,
 132		)
 133	);
 134	$admins = array();
 135	$user_log_details = array();
 136	while ($row = $smcFunc['db_fetch_assoc']($request))
 137	{
 138		if ($row['is_admin'])
 139			$admins[] = $row['id_member'];
 140		$user_log_details[$row['id_member']] = array($row['id_member'], $row['member_name']);
 141	}
 142	$smcFunc['db_free_result']($request);
 143
 144	if (empty($user_log_details))
 145		return;
 146
 147	// Make sure they aren't trying to delete administrators if they aren't one.  But don't bother checking if it's just themself.
 148	if (!empty($admins) && ($check_not_admin || (!allowedTo('admin_forum') && (count($users) != 1 || $users[0] != $user_info['id']))))
 149	{
 150		$users = array_diff($users, $admins);
 151		foreach ($admins as $id)
 152			unset($user_log_details[$id]);
 153	}
 154
 155	// No one left?
 156	if (empty($users))
 157		return;
 158
 159	// Log the action - regardless of who is deleting it.
 160	$log_inserts = array();
 161	foreach ($user_log_details as $user)
 162	{
 163		// Integration rocks!
 164		call_integration_hook('integrate_delete_member', array($user[0]));
 165
 166		// Add it to the administration log for future reference.
 167		$log_inserts[] = array(
 168			time(), 3, $user_info['id'], $user_info['ip'], 'delete_member',
 169			0, 0, 0, serialize(array('member' => $user[0], 'name' => $user[1], 'member_acted' => $user_info['name'])),
 170		);
 171
 172		// Remove any cached data if enabled.
 173		if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
 174			cache_put_data('user_settings-' . $user[0], null, 60);
 175	}
 176
 177	// Do the actual logging...
 178	if (!empty($log_inserts) && !empty($modSettings['modlog_enabled']))
 179		$smcFunc['db_insert']('',
 180			'{db_prefix}log_actions',
 181			array(
 182				'log_time' => 'int', 'id_log' => 'int', 'id_member' => 'int', 'ip' => 'string-16', 'action' => 'string',
 183				'id_board' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'extra' => 'string-65534',
 184			),
 185			$log_inserts,
 186			array('id_action')
 187		);
 188
 189	// Make these peoples' posts guest posts.
 190	$smcFunc['db_query']('', '
 191		UPDATE {db_prefix}messages
 192		SET id_member = {int:guest_id}, poster_email = {string:blank_email}
 193		WHERE id_member IN ({array_int:users})',
 194		array(
 195			'guest_id' => 0,
 196			'blank_email' => '',
 197			'users' => $users,
 198		)
 199	);
 200	$smcFunc['db_query']('', '
 201		UPDATE {db_prefix}polls
 202		SET id_member = {int:guest_id}
 203		WHERE id_member IN ({array_int:users})',
 204		array(
 205			'guest_id' => 0,
 206			'users' => $users,
 207		)
 208	);
 209
 210	// Make these peoples' posts guest first posts and last posts.
 211	$smcFunc['db_query']('', '
 212		UPDATE {db_prefix}topics
 213		SET id_member_started = {int:guest_id}
 214		WHERE id_member_started IN ({array_int:users})',
 215		array(
 216			'guest_id' => 0,
 217			'users' => $users,
 218		)
 219	);
 220	$smcFunc['db_query']('', '
 221		UPDATE {db_prefix}topics
 222		SET id_member_updated = {int:guest_id}
 223		WHERE id_member_updated IN ({array_int:users})',
 224		array(
 225			'guest_id' => 0,
 226			'users' => $users,
 227		)
 228	);
 229
 230	$smcFunc['db_query']('', '
 231		UPDATE {db_prefix}log_actions
 232		SET id_member = {int:guest_id}
 233		WHERE id_member IN ({array_int:users})',
 234		array(
 235			'guest_id' => 0,
 236			'users' => $users,
 237		)
 238	);
 239
 240	$smcFunc['db_query']('', '
 241		UPDATE {db_prefix}log_banned
 242		SET id_member = {int:guest_id}
 243		WHERE id_member IN ({array_int:users})',
 244		array(
 245			'guest_id' => 0,
 246			'users' => $users,
 247		)
 248	);
 249
 250	$smcFunc['db_query']('', '
 251		UPDATE {db_prefix}log_errors
 252		SET id_member = {int:guest_id}
 253		WHERE id_member IN ({array_int:users})',
 254		array(
 255			'guest_id' => 0,
 256			'users' => $users,
 257		)
 258	);
 259
 260	// Delete the member.
 261	$smcFunc['db_query']('', '
 262		DELETE FROM {db_prefix}members
 263		WHERE id_member IN ({array_int:users})',
 264		array(
 265			'users' => $users,
 266		)
 267	);
 268
 269	// Delete the logs...
 270	$smcFunc['db_query']('', '
 271		DELETE FROM {db_prefix}log_actions
 272		WHERE id_log = {int:log_type}
 273			AND id_member IN ({array_int:users})',
 274		array(
 275			'log_type' => 2,
 276			'users' => $users,
 277		)
 278	);
 279	$smcFunc['db_query']('', '
 280		DELETE FROM {db_prefix}log_boards
 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_comments
 288		WHERE id_recipient IN ({array_int:users})
 289			AND comment_type = {string:warntpl}',
 290		array(
 291			'users' => $users,
 292			'warntpl' => 'warntpl',
 293		)
 294	);
 295	$smcFunc['db_query']('', '
 296		DELETE FROM {db_prefix}log_group_requests
 297		WHERE id_member IN ({array_int:users})',
 298		array(
 299			'users' => $users,
 300		)
 301	);
 302	$smcFunc['db_query']('', '
 303		DELETE FROM {db_prefix}log_karma
 304		WHERE id_target IN ({array_int:users})
 305			OR id_executor IN ({array_int:users})',
 306		array(
 307			'users' => $users,
 308		)
 309	);
 310	$smcFunc['db_query']('', '
 311		DELETE FROM {db_prefix}log_mark_read
 312		WHERE id_member IN ({array_int:users})',
 313		array(
 314			'users' => $users,
 315		)
 316	);
 317	$smcFunc['db_query']('', '
 318		DELETE FROM {db_prefix}log_notify
 319		WHERE id_member IN ({array_int:users})',
 320		array(
 321			'users' => $users,
 322		)
 323	);
 324	$smcFunc['db_query']('', '
 325		DELETE FROM {db_prefix}log_online
 326		WHERE id_member IN ({array_int:users})',
 327		array(
 328			'users' => $users,
 329		)
 330	);
 331	$smcFunc['db_query']('', '
 332		DELETE FROM {db_prefix}log_subscribed
 333		WHERE id_member IN ({array_int:users})',
 334		array(
 335			'users' => $users,
 336		)
 337	);
 338	$smcFunc['db_query']('', '
 339		DELETE FROM {db_prefix}log_topics
 340		WHERE id_member IN ({array_int:users})',
 341		array(
 342			'users' => $users,
 343		)
 344	);
 345	$smcFunc['db_query']('', '
 346		DELETE FROM {db_prefix}collapsed_categories
 347		WHERE id_member IN ({array_int:users})',
 348		array(
 349			'users' => $users,
 350		)
 351	);
 352
 353	// Make their votes appear as guest votes - at least it keeps the totals right.
 354	//!!! Consider adding back in cookie protection.
 355	$smcFunc['db_query']('', '
 356		UPDATE {db_prefix}log_polls
 357		SET id_member = {int:guest_id}
 358		WHERE id_member IN ({array_int:users})',
 359		array(
 360			'guest_id' => 0,
 361			'users' => $users,
 362		)
 363	);
 364
 365	// Delete personal messages.
 366	require_once($sourcedir . '/PersonalMessage.php');
 367	deleteMessages(null, null, $users);
 368
 369	$smcFunc['db_query']('', '
 370		UPDATE {db_prefix}personal_messages
 371		SET id_member_from = {int:guest_id}
 372		WHERE id_member_from IN ({array_int:users})',
 373		array(
 374			'guest_id' => 0,
 375			'users' => $users,
 376		)
 377	);
 378
 379	// They no longer exist, so we don't know who it was sent to.
 380	$smcFunc['db_query']('', '
 381		DELETE FROM {db_prefix}pm_recipients
 382		WHERE id_member IN ({array_int:users})',
 383		array(
 384			'users' => $users,
 385		)
 386	);
 387
 388	// Delete avatar.
 389	require_once($sourcedir . '/ManageAttachments.php');
 390	removeAttachments(array('id_member' => $users));
 391
 392	// It's over, no more moderation for you.
 393	$smcFunc['db_query']('', '
 394		DELETE FROM {db_prefix}moderators
 395		WHERE id_member IN ({array_int:users})',
 396		array(
 397			'users' => $users,
 398		)
 399	);
 400	$smcFunc['db_query']('', '
 401		DELETE FROM {db_prefix}group_moderators
 402		WHERE id_member IN ({array_int:users})',
 403		array(
 404			'users' => $users,
 405		)
 406	);
 407
 408	// If you don't exist we can't ban you.
 409	$smcFunc['db_query']('', '
 410		DELETE FROM {db_prefix}ban_items
 411		WHERE id_member IN ({array_int:users})',
 412		array(
 413			'users' => $users,
 414		)
 415	);
 416
 417	// Remove individual theme settings.
 418	$smcFunc['db_query']('', '
 419		DELETE FROM {db_prefix}themes
 420		WHERE id_member IN ({array_int:users})',
 421		array(
 422			'users' => $users,
 423		)
 424	);
 425
 426	// These users are nobody's buddy nomore.
 427	$request = $smcFunc['db_query']('', '
 428		SELECT id_member, pm_ignore_list, buddy_list
 429		FROM {db_prefix}members
 430		WHERE FIND_IN_SET({raw:pm_ignore_list}, pm_ignore_list) != 0 OR FIND_IN_SET({raw:buddy_list}, buddy_list) != 0',
 431		array(
 432			'pm_ignore_list' => implode(', pm_ignore_list) != 0 OR FIND_IN_SET(', $users),
 433			'buddy_list' => implode(', buddy_list) != 0 OR FIND_IN_SET(', $users),
 434		)
 435	);
 436	while ($row = $smcFunc['db_fetch_assoc']($request))
 437		$smcFunc['db_query']('', '
 438			UPDATE {db_prefix}members
 439			SET
 440				pm_ignore_list = {string:pm_ignore_list},
 441				buddy_list = {string:buddy_list}
 442			WHERE id_member = {int:id_member}',
 443			array(
 444				'id_member' => $row['id_member'],
 445				'pm_ignore_list' => implode(',', array_diff(explode(',', $row['pm_ignore_list']), $users)),
 446				'buddy_list' => implode(',', array_diff(explode(',', $row['buddy_list']), $users)),
 447			)
 448		);
 449	$smcFunc['db_free_result']($request);
 450
 451	// Make sure no member's birthday is still sticking in the calendar...
 452	updateSettings(array(
 453		'calendar_updated' => time(),
 454	));
 455
 456	updateStats('member');
 457}
 458
 459function registerMember(&$regOptions, $return_errors = false)
 460{
 461	global $scripturl, $txt, $modSettings, $context, $sourcedir;
 462	global $user_info, $options, $settings, $smcFunc;
 463
 464	loadLanguage('Login');
 465
 466	// We'll need some external functions.
 467	require_once($sourcedir . '/Subs-Auth.php');
 468	require_once($sourcedir . '/Subs-Post.php');
 469
 470	// Put any errors in here.
 471	$reg_errors = array();
 472
 473	// Registration from the admin center, let them sweat a little more.
 474	if ($regOptions['interface'] == 'admin')
 475	{
 476		is_not_guest();
 477		isAllowedTo('moderate_forum');
 478	}
 479	// If you're an admin, you're special ;).
 480	elseif ($regOptions['interface'] == 'guest')
 481	{
 482		// You cannot register twice...
 483		if (empty($user_info['is_guest']))
 484			redirectexit();
 485
 486		// Make sure they didn't just register with this session.
 487		if (!empty($_SESSION['just_registered']) && empty($modSettings['disableRegisterCheck']))
 488			fatal_lang_error('register_only_once', false);
 489	}
 490
 491	// What method of authorization are we going to use?
 492	if (empty($regOptions['auth_method']) || !in_array($regOptions['auth_method'], array('password', 'openid')))
 493	{
 494		if (!empty($regOptions['openid']))
 495			$regOptions['auth_method'] = 'openid';
 496		else
 497			$regOptions['auth_method'] = 'password';
 498	}
 499
 500	// No name?!  How can you register with no name?
 501	if (empty($regOptions['username']))
 502		$reg_errors[] = array('lang', 'need_username');
 503
 504	// Spaces and other odd characters are evil...
 505	$regOptions['username'] = trim(preg_replace('~[\t\n\r \x0B\0' . ($context['utf8'] ? ($context['server']['complex_preg_chars'] ? '\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}' : "\xC2\xA0\xC2\xAD\xE2\x80\x80-\xE2\x80\x8F\xE2\x80\x9F\xE2\x80\xAF\xE2\x80\x9F\xE3\x80\x80\xEF\xBB\xBF") : '\x00-\x08\x0B\x0C\x0E-\x19\xA0') . ']+~' . ($context['utf8'] ? 'u' : ''), ' ', $regOptions['username']));
 506
 507	// Don't use too long a name.
 508	if ($smcFunc['strlen']($regOptions['username']) > 25)
 509		$reg_errors[] = array('lang', 'error_long_name');
 510
 511	// Only these characters are permitted.
 512	if (preg_match('~[<>&"\'=\\\\]~', preg_replace('~&#(?:\\d{1,7}|x[0-9a-fA-F]{1,6});~', '', $regOptions['username'])) != 0 || $regOptions['username'] == '_' || $regOptions['username'] == '|' || strpos($regOptions['username'], '[code') !== false || strpos($regOptions['username'], '[/code') !== false)
 513		$reg_errors[] = array('lang', 'error_invalid_characters_username');
 514
 515	if ($smcFunc['strtolower']($regOptions['username']) === $smcFunc['strtolower']($txt['guest_title']))
 516		$reg_errors[] = array('lang', 'username_reserved', 'general', array($txt['guest_title']));
 517
 518	// !!! Separate the sprintf?
 519	if (empty($regOptions['email']) || preg_match('~^[0-9A-Za-z=_+\-/][0-9A-Za-z=_\'+\-/\.]*@[\w\-]+(\.[\w\-]+)*(\.[\w]{2,6})$~', $regOptions['email']) === 0 || strlen($regOptions['email']) > 255)
 520		$reg_errors[] = array('lang', 'profile_error_bad_email');
 521
 522	if (!empty($regOptions['check_reserved_name']) && isReservedName($regOptions['username'], 0, false))
 523	{
 524		if ($regOptions['password'] == 'chocolate cake')
 525			$reg_errors[] = array('done', 'Sorry, I don\'t take bribes... you\'ll need to come up with a different name.');
 526		$reg_errors[] = array('done', '(' . htmlspecialchars($regOptions['username']) . ') ' . $txt['name_in_use']);
 527	}
 528
 529	// Generate a validation code if it's supposed to be emailed.
 530	$validation_code = '';
 531	if ($regOptions['require'] == 'activation')
 532		$validation_code = generateValidationCode();
 533
 534	// If you haven't put in a password generate one.
 535	if ($regOptions['interface'] == 'admin' && $regOptions['password'] == '' && $regOptions['auth_method'] == 'password')
 536	{
 537		mt_srand(time() + 1277);
 538		$regOptions['password'] = generateValidationCode();
 539		$regOptions['password_check'] = $regOptions['password'];
 540	}
 541	// Does the first password match the second?
 542	elseif ($regOptions['password'] != $regOptions['password_check'] && $regOptions['auth_method'] == 'password')
 543		$reg_errors[] = array('lang', 'passwords_dont_match');
 544
 545	// That's kind of easy to guess...
 546	if ($regOptions['password'] == '')
 547	{
 548		if ($regOptions['auth_method'] == 'password')
 549			$reg_errors[] = array('lang', 'no_password');
 550		else
 551			$regOptions['password'] = sha1(mt_rand());
 552	}
 553
 554	// Now perform hard password validation as required.
 555	if (!empty($regOptions['check_password_strength']) && $regOptions['password'] != '')
 556	{
 557		$passwordError = validatePassword($regOptions['password'], $regOptions['username'], array($regOptions['email']));
 558
 559		// Password isn't legal?
 560		if ($passwordError != null)
 561			$reg_errors[] = array('lang', 'profile_error_password_' . $passwordError);
 562	}
 563
 564	// If they are using an OpenID that hasn't been verified yet error out.
 565	// !!! Change this so they can register without having to attempt a login first
 566	if ($regOptions['auth_method'] == 'openid' && (empty($_SESSION['openid']['verified']) || $_SESSION['openid']['openid_uri'] != $regOptions['openid']))
 567		$reg_errors[] = array('lang', 'openid_not_verified');
 568
 569	// You may not be allowed to register this email.
 570	if (!empty($regOptions['check_email_ban']))
 571		isBannedEmail($regOptions['email'], 'cannot_register', $txt['ban_register_prohibited']);
 572
 573	// Check if the email address is in use.
 574	$request = $smcFunc['db_query']('', '
 575		SELECT id_member
 576		FROM {db_prefix}members
 577		WHERE email_address = {string:email_address}
 578			OR email_address = {string:username}
 579		LIMIT 1',
 580		array(
 581			'email_address' => $regOptions['email'],
 582			'username' => $regOptions['username'],
 583		)
 584	);
 585	// !!! Separate the sprintf?
 586	if ($smcFunc['db_num_rows']($request) != 0)
 587		$reg_errors[] = array('lang', 'email_in_use', false, array(htmlspecialchars($regOptions['email'])));
 588	$smcFunc['db_free_result']($request);
 589
 590	// If we found any errors we need to do something about it right away!
 591	foreach ($reg_errors as $key => $error)
 592	{
 593		/* Note for each error:
 594			0 = 'lang' if it's an index, 'done' if it's clear text.
 595			1 = The text/index.
 596			2 = Whether to log.
 597			3 = sprintf data if necessary. */
 598		if ($error[0] == 'lang')
 599			loadLanguage('Errors');
 600		$message = $error[0] == 'lang' ? (empty($error[3]) ? $txt[$error[1]] : vsprintf($txt[$error[1]], $error[3])) : $error[1];
 601
 602		// What to do, what to do, what to do.
 603		if ($return_errors)
 604		{
 605			if (!empty($error[2]))
 606				log_error($message, $error[2]);
 607			$reg_errors[$key] = $message;
 608		}
 609		else
 610			fatal_error($message, empty($error[2]) ? false : $error[2]);
 611	}
 612
 613	// If there's any errors left return them at once!
 614	if (!empty($reg_errors))
 615		return $reg_errors;
 616
 617	$reservedVars = array(
 618		'actual_theme_url',
 619		'actual_images_url',
 620		'base_theme_dir',
 621		'base_theme_url',
 622		'default_images_url',
 623		'default_theme_dir',
 624		'default_theme_url',
 625		'default_template',
 626		'images_url',
 627		'number_recent_posts',
 628		'smiley_sets_default',
 629		'theme_dir',
 630		'theme_id',
 631		'theme_layers',
 632		'theme_templates',
 633		'theme_url',
 634	);
 635
 636	// Can't change reserved vars.
 637	if (isset($regOptions['theme_vars']) && array_intersect($regOptions['theme_vars'], $reservedVars) != array())
 638		fatal_lang_error('no_theme');
 639
 640	// Some of these might be overwritten. (the lower ones that are in the arrays below.)
 641	$regOptions['register_vars'] = array(
 642		'member_name' => $regOptions['username'],
 643		'email_address' => $regOptions['email'],
 644		'passwd' => sha1(strtolower($regOptions['username']) . $regOptions['password']),
 645		'password_salt' => substr(md5(mt_rand()), 0, 4) ,
 646		'posts' => 0,
 647		'date_registered' => time(),
 648		'member_ip' => $regOptions['interface'] == 'admin' ? '127.0.0.1' : $user_info['ip'],
 649		'member_ip2' => $regOptions['interface'] == 'admin' ? '127.0.0.1' : $_SERVER['BAN_CHECK_IP'],
 650		'validation_code' => $validation_code,
 651		'real_name' => $regOptions['username'],
 652		'personal_text' => $modSettings['default_personal_text'],
 653		'pm_email_notify' => 1,
 654		'id_theme' => 0,
 655		'id_post_group' => 4,
 656		'lngfile' => '',
 657		'buddy_list' => '',
 658		'pm_ignore_list' => '',
 659		'message_labels' => '',
 660		'website_title' => '',
 661		'website_url' => '',
 662		'location' => '',
 663		'icq' => '',
 664		'aim' => '',
 665		'yim' => '',
 666		'msn' => '',
 667		'time_format' => '',
 668		'signature' => '',
 669		'avatar' => '',
 670		'usertitle' => '',
 671		'secret_question' => '',
 672		'secret_answer' => '',
 673		'additional_groups' => '',
 674		'ignore_boards' => '',
 675		'smiley_set' => '',
 676		'openid_uri' => (!empty($regOptions['openid']) ? $regOptions['openid'] : ''),
 677	);
 678
 679	// Setup the activation status on this new account so it is correct - firstly is it an under age account?
 680	if ($regOptions['require'] == 'coppa')
 681	{
 682		$regOptions['register_vars']['is_activated'] = 5;
 683		// !!! This should be changed.  To what should be it be changed??
 684		$regOptions['register_vars']['validation_code'] = '';
 685	}
 686	// Maybe it can be activated right away?
 687	elseif ($regOptions['require'] == 'nothing')
 688		$regOptions['register_vars']['is_activated'] = 1;
 689	// Maybe it must be activated by email?
 690	elseif ($regOptions['require'] == 'activation')
 691		$regOptions['register_vars']['is_activated'] = 0;
 692	// Otherwise it must be awaiting approval!
 693	else
 694		$regOptions['register_vars']['is_activated'] = 3;
 695
 696	if (isset($regOptions['memberGroup']))
 697	{
 698		// Make sure the id_group will be valid, if this is an administator.
 699		$regOptions['register_vars']['id_group'] = $regOptions['memberGroup'] == 1 && !allowedTo('admin_forum') ? 0 : $regOptions['memberGroup'];
 700
 701		// Check if this group is assignable.
 702		$unassignableGroups = array(-1, 3);
 703		$request = $smcFunc['db_query']('', '
 704			SELECT id_group
 705			FROM {db_prefix}membergroups
 706			WHERE min_posts != {int:min_posts}' . (allowedTo('admin_forum') ? '' : '
 707				OR group_type = {int:is_protected}'),
 708			array(
 709				'min_posts' => -1,
 710				'is_protected' => 1,
 711			)
 712		);
 713		while ($row = $smcFunc['db_fetch_assoc']($request))
 714			$unassignableGroups[] = $row['id_group'];
 715		$smcFunc['db_free_result']($request);
 716
 717		if (in_array($regOptions['register_vars']['id_group'], $unassignableGroups))
 718			$regOptions['register_vars']['id_group'] = 0;
 719	}
 720
 721	// ICQ cannot be zero.
 722	if (isset($regOptions['extra_register_vars']['icq']) && empty($regOptions['extra_register_vars']['icq']))
 723		$regOptions['extra_register_vars']['icq'] = '';
 724
 725	// Integrate optional member settings to be set.
 726	if (!empty($regOptions['extra_register_vars']))
 727		foreach ($regOptions['extra_register_vars'] as $var => $value)
 728			$regOptions['register_vars'][$var] = $value;
 729
 730	// Integrate optional user theme options to be set.
 731	$theme_vars = array();
 732	if (!empty($regOptions['theme_vars']))
 733		foreach ($regOptions['theme_vars'] as $var => $value)
 734			$theme_vars[$var] = $value;
 735
 736	// Call an optional function to validate the users' input.
 737	call_integration_hook('integrate_register', array(&$regOptions, &$theme_vars));
 738
 739	// Right, now let's prepare for insertion.
 740	$knownInts = array(
 741		'date_registered', 'posts', 'id_group', 'last_login', 'instant_messages', 'unread_messages',
 742		'new_pm', 'pm_prefs', 'gender', 'hide_email', 'show_online', 'pm_email_notify', 'karma_good', 'karma_bad',
 743		'notify_announcements', 'notify_send_body', 'notify_regularity', 'notify_types',
 744		'id_theme', 'is_activated', 'id_msg_last_visit', 'id_post_group', 'total_time_logged_in', 'warning',
 745	);
 746	$knownFloats = array(
 747		'time_offset',
 748	);
 749
 750	$column_names = array();
 751	$values = array();
 752	foreach ($regOptions['register_vars'] as $var => $val)
 753	{
 754		$type = 'string';
 755		if (in_array($var, $knownInts))
 756			$type = 'int';
 757		elseif (in_array($var, $knownFloats))
 758			$type = 'float';
 759		elseif ($var == 'birthdate')
 760			$type = 'date';
 761
 762		$column_names[$var] = $type;
 763		$values[$var] = $val;
 764	}
 765
 766	// Register them into the database.
 767	$smcFunc['db_insert']('',
 768		'{db_prefix}members',
 769		$column_names,
 770		$values,
 771		array('id_member')
 772	);
 773	$memberID = $smcFunc['db_insert_id']('{db_prefix}members', 'id_member');
 774
 775	// Update the number of members and latest member's info - and pass the name, but remove the 's.
 776	if ($regOptions['register_vars']['is_activated'] == 1)
 777		updateStats('member', $memberID, $regOptions['register_vars']['real_name']);
 778	else
 779		updateStats('member');
 780
 781	// Theme variables too?
 782	if (!empty($theme_vars))
 783	{
 784		$inserts = array();
 785		foreach ($theme_vars as $var => $val)
 786			$inserts[] = array($memberID, $var, $val);
 787		$smcFunc['db_insert']('insert',
 788			'{db_prefix}themes',
 789			array('id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
 790			$inserts,
 791			array('id_member', 'variable')
 792		);
 793	}
 794
 795	// If it's enabled, increase the registrations for today.
 796	trackStats(array('registers' => '+'));
 797
 798	// Administrative registrations are a bit different...
 799	if ($regOptions['interface'] == 'admin')
 800	{
 801		if ($regOptions['require'] == 'activation')
 802			$email_message = 'admin_register_activate';
 803		elseif (!empty($regOptions['send_welcome_email']))
 804			$email_message = 'admin_register_immediate';
 805
 806		if (isset($email_message))
 807		{
 808			$replacements = array(
 809				'REALNAME' => $regOptions['register_vars']['real_name'],
 810				'USERNAME' => $regOptions['username'],
 811				'PASSWORD' => $regOptions['password'],
 812				'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder',
 813				'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $memberID . ';code=' . $validation_code,
 814				'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $memberID,
 815				'ACTIVATIONCODE' => $validation_code,
 816			);
 817
 818			$emaildata = loadEmailTemplate($email_message, $replacements);
 819
 820			sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0);
 821		}
 822
 823		// All admins are finished here.
 824		return $memberID;
 825	}
 826
 827	// Can post straight away - welcome them to your fantastic community...
 828	if ($regOptions['require'] == 'nothing')
 829	{
 830		if (!empty($regOptions['send_welcome_email']))
 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				'OPENID' => !empty($regOptions['openid']) ? $regOptions['openid'] : '',
 838			);
 839			$emaildata = loadEmailTemplate('register_' . ($regOptions['auth_method'] == 'openid' ? 'openid_' : '') . 'immediate', $replacements);
 840			sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0);
 841		}
 842
 843		// Send admin their notification.
 844		adminNotify('standard', $memberID, $regOptions['username']);
 845	}
 846	// Need to activate their account - or fall under COPPA.
 847	elseif ($regOptions['require'] == 'activation' || $regOptions['require'] == 'coppa')
 848	{
 849		$replacements = array(
 850			'REALNAME' => $regOptions['register_vars']['real_name'],
 851			'USERNAME' => $regOptions['username'],
 852			'PASSWORD' => $regOptions['password'],
 853			'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder',
 854			'OPENID' => !empty($regOptions['openid']) ? $regOptions['openid'] : '',
 855		);
 856
 857		if ($regOptions['require'] == 'activation')
 858			$replacements += array(
 859				'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $memberID . ';code=' . $validation_code,
 860				'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $memberID,
 861				'ACTIVATIONCODE' => $validation_code,
 862			);
 863		else
 864			$replacements += array(
 865				'COPPALINK' => $scripturl . '?action=coppa;u=' . $memberID,
 866			);
 867
 868		$emaildata = loadEmailTemplate('register_' . ($regOptions['auth_method'] == 'openid' ? 'openid_' : '') . ($regOptions['require'] == 'activation' ? 'activate' : 'coppa'), $replacements);
 869
 870		sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0);
 871	}
 872	// Must be awaiting approval.
 873	else
 874	{
 875		$replacements = array(
 876			'REALNAME' => $regOptions['register_vars']['real_name'],
 877			'USERNAME' => $regOptions['username'],
 878			'PASSWORD' => $regOptions['password'],
 879			'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder',
 880			'OPENID' => !empty($regOptions['openid']) ? $regOptions['openid'] : '',
 881		);
 882
 883		$emaildata = loadEmailTemplate('register_' . ($regOptions['auth_method'] == 'openid' ? 'openid_' : '') . 'pending', $replacements);
 884
 885		sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0);
 886
 887		// Admin gets informed here...
 888		adminNotify('approval', $memberID, $regOptions['username']);
 889	}
 890
 891	// Okay, they're for sure registered... make sure the session is aware of this for security. (Just married :P!)
 892	$_SESSION['just_registered'] = 1;
 893
 894	return $memberID;
 895}
 896
 897// Check if a name is in the reserved words list. (name, current member id, name/username?.)
 898function isReservedName($name, $current_ID_MEMBER = 0, $is_name = true, $fatal = true)
 899{
 900	global $user_info, $modSettings, $smcFunc, $context;
 901
 902	// No cheating with entities please.
 903	$replaceEntities = create_function('$string', '
 904		$num = substr($string, 0, 1) === \'x\' ? hexdec(substr($string, 1)) : (int) $string;
 905		if ($num === 0x202E || $num === 0x202D) return \'\'; if (in_array($num, array(0x22, 0x26, 0x27, 0x3C, 0x3E))) return \'&#\' . $num . \';\';' .
 906		(empty($context['utf8']) ? 'return $num < 0x20 ? \'\' : ($num < 0x80 ? chr($num) : \'&#\' . $string . \';\');' : '
 907		return $num < 0x20 || $num > 0x10FFFF || ($num >= 0xD800 && $num <= 0xDFFF) ? \'\' : ($num < 0x80 ? chr($num) : ($num < 0x800 ? chr(192 | $num >> 6) . chr(128 | $num & 63) : ($num < 0x10000 ? chr(224 | $num >> 12) . chr(128 | $num >> 6 & 63) . chr(128 | $num & 63) : chr(240 | $num >> 18) . chr(128 | $num >> 12 & 63) . chr(128 | $num >> 6 & 63) . chr(128 | $num & 63))));')
 908	);
 909
 910	$name = preg_replace_callback('~(&#(\d{1,7}|x[0-9a-fA-F]{1,6});)~', 'replaceEntities__callback', $name);
 911	$checkName = $smcFunc['strtolower']($name);
 912
 913	// Administrators are never restricted ;).
 914	if (!allowedTo('moderate_forum') && ((!empty($modSettings['reserveName']) && $is_name) || !empty($modSettings['reserveUser']) && !$is_name))
 915	{
 916		$reservedNames = explode("\n", $modSettings['reserveNames']);
 917		// Case sensitive check?
 918		$checkMe = empty($modSettings['reserveCase']) ? $checkName : $name;
 919
 920		// Check each name in the list...
 921		foreach ($reservedNames as $reserved)
 922		{
 923			if ($reserved == '')
 924				continue;
 925
 926			// The admin might've used entities too, level the playing field.
 927			$reservedCheck = preg_replace('~(&#(\d{1,7}|x[0-9a-fA-F]{1,6});)~', 'replaceEntities__callback', $reserved);
 928
 929			// Case sensitive name?
 930			if (empty($modSettings['reserveCase']))
 931				$reservedCheck = $smcFunc['strtolower']($reservedCheck);
 932
 933			// If it's not just entire word, check for it in there somewhere...
 934			if ($checkMe == $reservedCheck || ($smcFunc['strpos']($checkMe, $reservedCheck) !== false && empty($modSettings['reserveWord'])))
 935				if ($fatal)
 936					fatal_lang_error('username_reserved', 'password', array($reserved));
 937				else
 938					return true;
 939		}
 940
 941		$censor_name = $name;
 942		if (censorText($censor_name) != $name)
 943			if ($fatal)
 944				fatal_lang_error('name_censored', 'password', array($name));
 945			else
 946				return true;
 947	}
 948
 949	// Characters we just shouldn't allow, regardless.
 950	foreach (array('*') as $char)
 951		if (strpos($checkName, $char) !== false)
 952			if ($fatal)
 953				fatal_lang_error('username_reserved', 'password', array($char));
 954			else
 955				return true;
 956
 957	// Get rid of any SQL parts of the reserved name...
 958	$checkName = strtr($name, array('_' => '\\_', '%' => '\\%'));
 959
 960	// Make sure they don't want someone else's name.
 961	$request = $smcFunc['db_query']('', '
 962		SELECT id_member
 963		FROM {db_prefix}members
 964		WHERE ' . (empty($current_ID_MEMBER) ? '' : 'id_member != {int:current_member}
 965			AND ') . '(real_name LIKE {string:check_name} OR member_name LIKE {string:check_name})
 966		LIMIT 1',
 967		array(
 968			'current_member' => $current_ID_MEMBER,
 969			'check_name' => $checkName,
 970		)
 971	);
 972	if ($smcFunc['db_num_rows']($request) > 0)
 973	{
 974		$smcFunc['db_free_result']($request);
 975		return true;
 976	}
 977
 978	// Does name case insensitive match a member group name?
 979	$request = $smcFunc['db_query']('', '
 980		SELECT id_group
 981		FROM {db_prefix}membergroups
 982		WHERE group_name LIKE {string:check_name}
 983		LIMIT 1',
 984		array(
 985			'check_name' => $checkName,
 986		)
 987	);
 988	if ($smcFunc['db_num_rows']($request) > 0)
 989	{
 990		$smcFunc['db_free_result']($request);
 991		return true;
 992	}
 993
 994	// Okay, they passed.
 995	return false;
 996}
 997
 998// Get a list of groups that have a given permission (on a given board).
 999function groupsAllowedTo($permission, $board_id = null)
1000{
1001	global $modSettings, $board_info, $smcFunc;
1002
1003	// Admins are allowed to do anything.
1004	$member_groups = array(
1005		'allowed' => array(1),
1006		'denied' => array(),
1007	);
1008
1009	// Assume we're dealing with regular permissions (like profile_view_own).
1010	if ($board_id === null)
1011	{
1012		$request = $smcFunc['db_query']('', '
1013			SELECT id_group, add_deny
1014			FROM {db_prefix}permissions
1015			WHERE permission = {string:permission}',
1016			array(
1017				'permission' => $permission,
1018			)
1019		);
1020		while ($row = $smcFunc['db_fetch_assoc']($request))
1021			$member_groups[$row['add_deny'] === '1' ? 'allowed' : 'denied'][] = $row['id_group'];
1022		$smcFunc['db_free_result']($request);
1023	}
1024
1025	// Otherwise it's time to look at the board.
1026	else
1027	{
1028		// First get the profile of the given board.
1029		if (isset($board_info['id']) && $board_info['id'] == $board_id)
1030			$profile_id = $board_info['profile'];
1031		elseif ($board_id !== 0)
1032		{
1033			$request = $smcFunc['db_query']('', '
1034				SELECT id_profile
1035				FROM {db_prefix}boards
1036				WHERE id_board = {int:id_board}
1037				LIMIT 1',
1038				array(
1039					'id_board' => $board_id,
1040				)
1041			);
1042			if ($smcFunc['db_num_rows']($request) == 0)
1043				fatal_lang_error('no_board');
1044			list ($profile_id) = $smcFunc['db_fetch_row']($request);
1045			$smcFunc['db_free_result']($request);
1046		}
1047		else
1048			$profile_id = 1;
1049
1050		$request = $smcFunc['db_query']('', '
1051			SELECT bp.id_group, bp.add_deny
1052			FROM {db_prefix}board_permissions AS bp
1053			WHERE bp.permission = {string:permission}
1054				AND bp.id_profile = {int:profile_id}',
1055			array(
1056				'profile_id' => $profile_id,
1057				'permission' => $permission,
1058			)
1059		);
1060		while ($row = $smcFunc['db_fetch_assoc']($request))
1061			$member_groups[$row['add_deny'] === '1' ? 'allowed' : 'denied'][] = $row['id_group'];
1062		$smcFunc['db_free_result']($request);
1063	}
1064
1065	// Denied is never allowed.
1066	$member_groups['allowed'] = array_diff($member_groups['allowed'], $member_groups['denied']);
1067
1068	return $member_groups;
1069}
1070
1071// Get a list of members that have a given permission (on a given board).
1072function membersAllowedTo($permission, $board_id = null)
1073{
1074	global $smcFunc;
1075
1076	$member_groups = groupsAllowedTo($permission, $board_id);
1077
1078	$include_moderators = in_array(3, $member_groups['allowed']) && $board_id !== null;
1079	$member_groups['allowed'] = array_diff($member_groups['allowed'], array(3));
1080
1081	$exclude_moderators = in_array(3, $member_groups['denied']) && $board_id !== null;
1082	$member_groups['denied'] = array_diff($member_groups['denied'], array(3));
1083
1084	$request = $smcFunc['db_query']('', '
1085		SELECT mem.id_member
1086		FROM {db_prefix}members AS mem' . ($include_moderators || $exclude_moderators ? '
1087			LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_member = mem.id_member AND mods.id_board = {int:board_id})' : '') . '
1088		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)' . (empty($member_groups['denied']) ? '' : '
1089			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)'),
1090		array(
1091			'member_groups_allowed' => $member_groups['allowed'],
1092			'member_groups_denied' => $member_groups['denied'],
1093			'board_id' => $board_id,
1094			'member_group_allowed_implode' => implode(', mem.additional_groups) != 0 OR FIND_IN_SET(', $member_groups['allowed']),
1095			'member_group_denied_implode' => implode(', mem.additional_groups) != 0 OR FIND_IN_SET(', $member_groups['denied']),
1096		)
1097	);
1098	$members = array();
1099	while ($row = $smcFunc['db_fetch_assoc']($request))
1100		$members[] = $row['id_member'];
1101	$smcFunc['db_free_result']($request);
1102
1103	return $members;
1104}
1105
1106// This function is used to reassociate members with relevant posts.
1107function reattributePosts($memID, $email = false, $membername = false, $post_count = false)
1108{
1109	global $smcFunc;
1110
1111	// Firstly, if email and username aren't passed find out the members email address and name.
1112	if ($email === false && $membername === false)
1113	{
1114		$request = $smcFunc['db_query']('', '
1115			SELECT email_address, member_name
1116			FROM {db_prefix}members
1117			WHERE id_member = {int:memID}
1118			LIMIT 1',
1119			array(
1120				'memID' => $memID,
1121			)
1122		);
1123		list ($email, $membername) = $smcFunc['db_fetch_row']($request);
1124		$smcFunc['db_free_result']($request);
1125	}
1126
1127	// If they want the post count restored then we need to do some research.
1128	if ($post_count)
1129	{
1130		$request = $smcFunc['db_query']('', '
1131			SELECT COUNT(*)
1132			FROM {db_prefix}messages AS m
1133				INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board AND b.count_posts = {int:count_posts})
1134			WHERE m.id_member = {int:guest_id}
1135				AND m.approved = {int:is_approved}
1136				AND m.icon != {string:recycled_icon}' . (empty($email) ? '' : '
1137				AND m.poster_email = {string:email_address}') . (empty($membername) ? '' : '
1138				AND m.poster_name = {string:member_name}'),
1139			array(
1140				'count_posts' => 0,
1141				'guest_id' => 0,
1142				'email_address' => $email,
1143				'member_name' => $membername,
1144				'is_approved' => 1,
1145				'recycled_icon' => 'recycled',
1146			)
1147		);
1148		list ($messageCount) = $smcFunc['db_fetch_row']($request);
1149		$smcFunc['db_free_result']($request);
1150
1151		updateMemberData($memID, array('posts' => 'posts + ' . $messageCount));
1152	}
1153
1154	$query_parts = array();
1155	if (!empty($email))
1156		$query_parts[] = 'poster_email = {string:email_address}';
1157	if (!empty($membername))
1158		$query_parts[] = 'poster_name = {string:member_name}';
1159	$query = implode(' AND ', $query_parts);
1160
1161	// Finally, update the posts themselves!
1162	$smcFunc['db_query']('', '
1163		UPDATE {db_prefix}messages
1164		SET id_member = {int:memID}
1165		WHERE ' . $query,
1166		array(
1167			'memID' => $memID,
1168			'email_address' => $email,
1169			'member_name' => $membername,
1170		)
1171	);
1172
1173	return $smcFunc['db_affected_rows']();
1174}
1175
1176// This simple function adds/removes the passed user from the current users buddy list.
1177function BuddyListToggle()
1178{
1179	global $user_info;
1180
1181	checkSession('get');
1182
1183	isAllowedTo('profile_identity_own');
1184	is_not_guest();
1185
1186	if (empty($_REQUEST['u']))
1187		fatal_lang_error('no_access', false);
1188	$_REQUEST['u'] = (int) $_REQUEST['u'];
1189
1190	// Remove if it's already there...
1191	if (in_array($_REQUEST['u'], $user_info['buddies']))
1192		$user_info['buddies'] = array_diff($user_info['buddies'], array($_REQUEST['u']));
1193	// ...or add if it's not and if it's not you.
1194	elseif ($user_info['id'] != $_REQUEST['u'])
1195		$user_info['buddies'][] = (int) $_REQUEST['u'];
1196
1197	// Update the settings.
1198	updateMemberData($user_info['id'], array('buddy_list' => implode(',', $user_info['buddies'])));
1199
1200	// Redirect back to the profile
1201	redirectexit('action=profile;u=' . $_REQUEST['u']);
1202}
1203
1204function list_getMembers($start, $items_per_page, $sort, $where, $where_params = array(), $get_duplicates = false)
1205{
1206	global $smcFunc;
1207
1208	$request = $smcFunc['db_query']('', '
1209		SELECT
1210			mem.id_member, mem.member_name, mem.real_name, mem.email_address, mem.icq, mem.aim, mem.yim, mem.msn, mem.member_ip, mem.member_ip2, mem.last_login,
1211			mem.posts, mem.is_activated, mem.date_registered, mem.id_group, mem.additional_groups, mg.group_name
1212		FROM {db_prefix}members AS mem
1213			LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = mem.id_group)
1214		WHERE ' . $where . '
1215		ORDER BY {raw:sort}
1216		LIMIT {int:start}, {int:per_page}',
1217		array_merge($where_params, array(
1218			'sort' => $sort,
1219			'start' => $start,
1220			'per_page' => $items_per_page,
1221		))
1222	);
1223
1224	$members = array();
1225	while ($row = $smcFunc['db_fetch_assoc']($request))
1226		$members[] = $row;
1227	$smcFunc['db_free_result']($request);
1228
1229	// If we want duplicates pass the members array off.
1230	if ($get_duplicates)
1231		populateDuplicateMembers($members);
1232
1233	return $members;
1234}
1235
1236function list_getNumMembers($where, $where_params = array())
1237{
1238	global $smcFunc, $modSettings;
1239
1240	// We know how many members there are in total.
1241	if (empty($where) || $where == '1')
1242		$num_members = $modSettings['totalMembers'];
1243
1244	// The database knows the amount when there are extra conditions.
1245	else
1246	{
1247		$request = $smcFunc['db_query']('', '
1248			SELECT COUNT(*)
1249			FROM {db_prefix}members AS mem
1250			WHERE ' . $where,
1251			array_merge($where_params, array(
1252			))
1253		);
1254		list ($num_members) = $smcFunc['db_fetch_row']($request);
1255		$smcFunc['db_free_result']($request);
1256	}
1257
1258	return $num_members;
1259}
1260
1261function populateDuplicateMembers(&$members)
1262{
1263	global $smcFunc;
1264
1265	// This will hold all the ip addresses.
1266	$ips = array();
1267	foreach ($members as $key => $member)
1268	{
1269		// Create the duplicate_members element.
1270		$members[$key]['duplicate_members'] = array();
1271
1272		// Store the IPs.
1273		if (!empty($member['member_ip']))
1274			$ips[] = $member['member_ip'];
1275		if (!empty($member['member_ip2']))
1276			$ips[] = $member['member_ip2'];
1277	}
1278
1279	$ips = array_unique($ips);
1280
1281	if (empty($ips))
1282		return false;
1283
1284	// Fetch all members with this IP address, we'll filter out the current ones in a sec.
1285	$request = $smcFunc['db_query']('', '
1286		SELECT
1287			id_member, member_name, email_address, member_ip, member_ip2, is_activated
1288		FROM {db_prefix}members
1289		WHERE member_ip IN ({array_string:ips})
1290			OR member_ip2 IN ({array_string:ips})',
1291		array(
1292			'ips' => $ips,
1293		)
1294	);
1295	$duplicate_members = array();
1296	$duplicate_ids = array();
1297	while ($row = $smcFunc['db_fetch_assoc']($request))
1298	{
1299		//$duplicate_ids[] = $row['id_member'];
1300
1301		$member_context = array(
1302			'id' => $row['id_member'],
1303			'name' => $row['member_name'],
1304			'email' => $row['email_address'],
1305			'is_banned' => $row['is_activated'] > 10,
1306			'ip' => $row['member_ip'],
1307			'ip2' => $row['member_ip2'],
1308		);
1309
1310		if (in_array($row['member_ip'], $ips))
1311			$duplicate_members[$row['member_ip']][] = $member_context;
1312		if ($row['member_ip'] != $row['member_ip2'] && in_array($row['member_ip2'], $ips))
1313			$duplicate_members[$row['member_ip2']][] = $member_context;
1314	}
1315	$smcFunc['db_free_result']($request);
1316
1317	// Also try to get a list of messages using these ips.
1318	$request = $smcFunc['db_query']('', '
1319		SELECT
1320			m.poster_ip, mem.id_member, mem.member_name, mem.email_address, mem.is_activated
1321		FROM {db_prefix}messages AS m
1322			INNER JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
1323		WHERE m.id_member != 0
1324			' . (!empty($duplicate_ids) ? 'AND m.id_member NOT IN ({array_int:duplicate_ids})' : '') . '
1325			AND m.poster_ip IN ({array_string:ips})',
1326		array(
1327			'duplicate_ids' => $duplicate_ids,
1328			'ips' => $ips,
1329		)
1330	);
1331
1332	$had_ips = array();
1333	while ($row = $smcFunc['db_fetch_assoc']($request))
1334	{
1335		// Don't collect lots of the same.
1336		if (isset($had_ips[$row['poster_ip']]) && in_array($row['id_member'], $had_ips[$row['poster_ip']]))
1337			continue;
1338		$had_ips[$row['poster_ip']][] = $row['id_member'];
1339
1340		$duplicate_members[$row['poster_ip']][] = array(
1341			'id' => $row['id_member'],
1342			'name' => $row['member_name'],
1343			'email' => $row['email_address'],
1344			'is_banned' => $row['is_activated'] > 10,
1345			'ip' => $row['poster_ip'],
1346			'ip2' => $row['poster_ip'],
1347		);
1348	}
1349	$smcFunc['db_free_result']($request);
1350
1351	// Now we have all the duplicate members, stick them with their respective member in the list.
1352	if (!empty($duplicate_members))
1353		foreach ($members as $key => $member)
1354		{
1355			if (isset($duplicate_members[$member['member_ip']]))
1356				$members[$key]['duplicate_members'] = $duplicate_members[$member['member_ip']];
1357			if ($member['member_ip'] != $member['member_ip2'] && isset($duplicate_members[$member['member_ip2']]))
1358				$members[$key]['duplicate_members'] = array_merge($member['duplicate_members'], $duplicate_members[$member['member_ip2']]);
1359
1360			// Check we don't have lots of the same member.
1361			$member_track = array($member['id_member']);
1362			foreach ($members[$key]['duplicate_members'] as $duplicate_id_member => $duplicate_member)
1363			{
1364				if (in_array($duplicate_member['id'], $member_track))
1365				{
1366					unset($members[$key]['duplicate_members'][$duplicate_id_member]);
1367					continue;
1368				}
1369
1370				$member_track[] = $duplicate_member['id'];
1371			}
1372		}
1373}
1374
1375// Generate a random validation code.
1376function generateValidationCode()
1377{
1378	global $smcFunc, $modSettings;
1379
1380	$request = $smcFunc['db_query']('get_random_number', '
1381		SELECT RAND()',
1382		array(
1383		)
1384	);
1385
1386	list ($dbRand) = $smcFunc['db_fetch_row']($request);
1387	$smcFunc['db_free_result']($request);
1388
1389	return substr(preg_replace('/\W/', '', sha1(microtime() . mt_rand() . $dbRand . $modSettings['rand_seed'])), 0, 10);
1390}
1391
1392?>