Blame Identity/Webenv/phpBB/3.0.4/includes/functions_user.php

ef5584
ef5584
/**
ef5584
*
ef5584
* @package phpBB3
ef5584
* @version $Id: functions_user.php 8949 2008-09-26 21:29:05Z toonarmy $
ef5584
* @copyright (c) 2005 phpBB Group
ef5584
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
ef5584
*
ef5584
*/
ef5584
ef5584
/**
ef5584
* @ignore
ef5584
*/
ef5584
if (!defined('IN_PHPBB'))
ef5584
{
ef5584
	exit;
ef5584
}
ef5584
ef5584
/**
ef5584
* Obtain user_ids from usernames or vice versa. Returns false on
ef5584
* success else the error string
ef5584
*
ef5584
* @param array &$user_id_ary The user ids to check or empty if usernames used
ef5584
* @param array &$username_ary The usernames to check or empty if user ids used
ef5584
* @param mixed $user_type Array of user types to check, false if not restricting by user type
ef5584
*/
ef5584
function user_get_id_name(&$user_id_ary, &$username_ary, $user_type = false)
ef5584
{
ef5584
	global $db;
ef5584
ef5584
	// Are both arrays already filled? Yep, return else
ef5584
	// are neither array filled?
ef5584
	if ($user_id_ary && $username_ary)
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
	else if (!$user_id_ary && !$username_ary)
ef5584
	{
ef5584
		return 'NO_USERS';
ef5584
	}
ef5584
ef5584
	$which_ary = ($user_id_ary) ? 'user_id_ary' : 'username_ary';
ef5584
ef5584
	if ($$which_ary && !is_array($$which_ary))
ef5584
	{
ef5584
		$$which_ary = array($$which_ary);
ef5584
	}
ef5584
ef5584
	$sql_in = ($which_ary == 'user_id_ary') ? array_map('intval', $$which_ary) : array_map('utf8_clean_string', $$which_ary);
ef5584
	unset($$which_ary);
ef5584
ef5584
	$user_id_ary = $username_ary = array();
ef5584
ef5584
	// Grab the user id/username records
ef5584
	$sql_where = ($which_ary == 'user_id_ary') ? 'user_id' : 'username_clean';
ef5584
	$sql = 'SELECT user_id, username
ef5584
		FROM ' . USERS_TABLE . '
ef5584
		WHERE ' . $db->sql_in_set($sql_where, $sql_in);
ef5584
ef5584
	if ($user_type !== false && !empty($user_type))
ef5584
	{
ef5584
		$sql .= ' AND ' . $db->sql_in_set('user_type', $user_type);
ef5584
	}
ef5584
ef5584
	$result = $db->sql_query($sql);
ef5584
ef5584
	if (!($row = $db->sql_fetchrow($result)))
ef5584
	{
ef5584
		$db->sql_freeresult($result);
ef5584
		return 'NO_USERS';
ef5584
	}
ef5584
ef5584
	do
ef5584
	{
ef5584
		$username_ary[$row['user_id']] = $row['username'];
ef5584
		$user_id_ary[] = $row['user_id'];
ef5584
	}
ef5584
	while ($row = $db->sql_fetchrow($result));
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Get latest registered username and update database to reflect it
ef5584
*/
ef5584
function update_last_username()
ef5584
{
ef5584
	global $db;
ef5584
ef5584
	// Get latest username
ef5584
	$sql = 'SELECT user_id, username, user_colour
ef5584
		FROM ' . USERS_TABLE . '
ef5584
		WHERE user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')
ef5584
		ORDER BY user_id DESC';
ef5584
	$result = $db->sql_query_limit($sql, 1);
ef5584
	$row = $db->sql_fetchrow($result);
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	if ($row)
ef5584
	{
ef5584
		set_config('newest_user_id', $row['user_id'], true);
ef5584
		set_config('newest_username', $row['username'], true);
ef5584
		set_config('newest_user_colour', $row['user_colour'], true);
ef5584
	}
ef5584
}
ef5584
ef5584
/**
ef5584
* Updates a username across all relevant tables/fields
ef5584
*
ef5584
* @param string $old_name the old/current username
ef5584
* @param string $new_name the new username
ef5584
*/
ef5584
function user_update_name($old_name, $new_name)
ef5584
{
ef5584
	global $config, $db, $cache;
ef5584
ef5584
	$update_ary = array(
ef5584
		FORUMS_TABLE			=> array('forum_last_poster_name'),
ef5584
		MODERATOR_CACHE_TABLE	=> array('username'),
ef5584
		POSTS_TABLE				=> array('post_username'),
ef5584
		TOPICS_TABLE			=> array('topic_first_poster_name', 'topic_last_poster_name'),
ef5584
	);
ef5584
ef5584
	foreach ($update_ary as $table => $field_ary)
ef5584
	{
ef5584
		foreach ($field_ary as $field)
ef5584
		{
ef5584
			$sql = "UPDATE $table
ef5584
				SET $field = '" . $db->sql_escape($new_name) . "'
ef5584
				WHERE $field = '" . $db->sql_escape($old_name) . "'";
ef5584
			$db->sql_query($sql);
ef5584
		}
ef5584
	}
ef5584
ef5584
	if ($config['newest_username'] == $old_name)
ef5584
	{
ef5584
		set_config('newest_username', $new_name, true);
ef5584
	}
ef5584
ef5584
	// Because some tables/caches use username-specific data we need to purge this here.
ef5584
	$cache->destroy('sql', MODERATOR_CACHE_TABLE);
ef5584
}
ef5584
ef5584
/**
ef5584
* Adds an user
ef5584
*
ef5584
* @param mixed $user_row An array containing the following keys (and the appropriate values): username, group_id (the group to place the user in), user_email and the user_type(usually 0). Additional entries not overridden by defaults will be forwarded.
ef5584
* @param string $cp_data custom profile fields, see custom_profile::build_insert_sql_array
ef5584
* @return the new user's ID.
ef5584
*/
ef5584
function user_add($user_row, $cp_data = false)
ef5584
{
ef5584
	global $db, $user, $auth, $config, $phpbb_root_path, $phpEx;
ef5584
ef5584
	if (empty($user_row['username']) || !isset($user_row['group_id']) || !isset($user_row['user_email']) || !isset($user_row['user_type']))
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	$username_clean = utf8_clean_string($user_row['username']);
ef5584
ef5584
	if (empty($username_clean))
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	$sql_ary = array(
ef5584
		'username'			=> $user_row['username'],
ef5584
		'username_clean'	=> $username_clean,
ef5584
		'user_password'		=> (isset($user_row['user_password'])) ? $user_row['user_password'] : '',
ef5584
		'user_pass_convert'	=> 0,
ef5584
		'user_email'		=> strtolower($user_row['user_email']),
ef5584
		'user_email_hash'	=> crc32(strtolower($user_row['user_email'])) . strlen($user_row['user_email']),
ef5584
		'group_id'			=> $user_row['group_id'],
ef5584
		'user_type'			=> $user_row['user_type'],
ef5584
	);
ef5584
ef5584
	// These are the additional vars able to be specified
ef5584
	$additional_vars = array(
ef5584
		'user_permissions'	=> '',
ef5584
		'user_timezone'		=> $config['board_timezone'],
ef5584
		'user_dateformat'	=> $config['default_dateformat'],
ef5584
		'user_lang'			=> $config['default_lang'],
ef5584
		'user_style'		=> (int) $config['default_style'],
ef5584
		'user_actkey'		=> '',
ef5584
		'user_ip'			=> '',
ef5584
		'user_regdate'		=> time(),
ef5584
		'user_passchg'		=> time(),
ef5584
		'user_options'		=> 895,
ef5584
ef5584
		'user_inactive_reason'	=> 0,
ef5584
		'user_inactive_time'	=> 0,
ef5584
		'user_lastmark'			=> time(),
ef5584
		'user_lastvisit'		=> 0,
ef5584
		'user_lastpost_time'	=> 0,
ef5584
		'user_lastpage'			=> '',
ef5584
		'user_posts'			=> 0,
ef5584
		'user_dst'				=> (int) $config['board_dst'],
ef5584
		'user_colour'			=> '',
ef5584
		'user_occ'				=> '',
ef5584
		'user_interests'		=> '',
ef5584
		'user_avatar'			=> '',
ef5584
		'user_avatar_type'		=> 0,
ef5584
		'user_avatar_width'		=> 0,
ef5584
		'user_avatar_height'	=> 0,
ef5584
		'user_new_privmsg'		=> 0,
ef5584
		'user_unread_privmsg'	=> 0,
ef5584
		'user_last_privmsg'		=> 0,
ef5584
		'user_message_rules'	=> 0,
ef5584
		'user_full_folder'		=> PRIVMSGS_NO_BOX,
ef5584
		'user_emailtime'		=> 0,
ef5584
ef5584
		'user_notify'			=> 0,
ef5584
		'user_notify_pm'		=> 1,
ef5584
		'user_notify_type'		=> NOTIFY_EMAIL,
ef5584
		'user_allow_pm'			=> 1,
ef5584
		'user_allow_viewonline'	=> 1,
ef5584
		'user_allow_viewemail'	=> 1,
ef5584
		'user_allow_massemail'	=> 1,
ef5584
ef5584
		'user_sig'					=> '',
ef5584
		'user_sig_bbcode_uid'		=> '',
ef5584
		'user_sig_bbcode_bitfield'	=> '',
ef5584
ef5584
		'user_form_salt'			=> unique_id(),
ef5584
	);
ef5584
ef5584
	// Now fill the sql array with not required variables
ef5584
	foreach ($additional_vars as $key => $default_value)
ef5584
	{
ef5584
		$sql_ary[$key] = (isset($user_row[$key])) ? $user_row[$key] : $default_value;
ef5584
	}
ef5584
ef5584
	// Any additional variables in $user_row not covered above?
ef5584
	$remaining_vars = array_diff(array_keys($user_row), array_keys($sql_ary));
ef5584
ef5584
	// Now fill our sql array with the remaining vars
ef5584
	if (sizeof($remaining_vars))
ef5584
	{
ef5584
		foreach ($remaining_vars as $key)
ef5584
		{
ef5584
			$sql_ary[$key] = $user_row[$key];
ef5584
		}
ef5584
	}
ef5584
ef5584
	$sql = 'INSERT INTO ' . USERS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
ef5584
	$db->sql_query($sql);
ef5584
ef5584
	$user_id = $db->sql_nextid();
ef5584
ef5584
	// Insert Custom Profile Fields
ef5584
	if ($cp_data !== false && sizeof($cp_data))
ef5584
	{
ef5584
		$cp_data['user_id'] = (int) $user_id;
ef5584
ef5584
		if (!class_exists('custom_profile'))
ef5584
		{
ef5584
			include_once($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);
ef5584
		}
ef5584
ef5584
		$sql = 'INSERT INTO ' . PROFILE_FIELDS_DATA_TABLE . ' ' .
ef5584
			$db->sql_build_array('INSERT', custom_profile::build_insert_sql_array($cp_data));
ef5584
		$db->sql_query($sql);
ef5584
	}
ef5584
ef5584
	// Place into appropriate group...
ef5584
	$sql = 'INSERT INTO ' . USER_GROUP_TABLE . ' ' . $db->sql_build_array('INSERT', array(
ef5584
		'user_id'		=> (int) $user_id,
ef5584
		'group_id'		=> (int) $user_row['group_id'],
ef5584
		'user_pending'	=> 0)
ef5584
	);
ef5584
	$db->sql_query($sql);
ef5584
ef5584
	// Now make it the users default group...
ef5584
	group_set_user_default($user_row['group_id'], array($user_id), false);
ef5584
ef5584
	// set the newest user and adjust the user count if the user is a normal user and no activation mail is sent
ef5584
	if ($user_row['user_type'] == USER_NORMAL)
ef5584
	{
ef5584
		set_config('newest_user_id', $user_id, true);
ef5584
		set_config('newest_username', $user_row['username'], true);
ef5584
		set_config('num_users', $config['num_users'] + 1, true);
ef5584
ef5584
		$sql = 'SELECT group_colour
ef5584
			FROM ' . GROUPS_TABLE . '
ef5584
			WHERE group_id = ' . (int) $user_row['group_id'];
ef5584
		$result = $db->sql_query_limit($sql, 1);
ef5584
		$row = $db->sql_fetchrow($result);
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		set_config('newest_user_colour', $row['group_colour'], true);
ef5584
	}
ef5584
ef5584
	return $user_id;
ef5584
}
ef5584
ef5584
/**
ef5584
* Remove User
ef5584
*/
ef5584
function user_delete($mode, $user_id, $post_username = false)
ef5584
{
ef5584
	global $cache, $config, $db, $user, $auth;
ef5584
	global $phpbb_root_path, $phpEx;
ef5584
ef5584
	$sql = 'SELECT *
ef5584
		FROM ' . USERS_TABLE . '
ef5584
		WHERE user_id = ' . $user_id;
ef5584
	$result = $db->sql_query($sql);
ef5584
	$user_row = $db->sql_fetchrow($result);
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	if (!$user_row)
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	// Before we begin, we will remove the reports the user issued.
ef5584
	$sql = 'SELECT r.post_id, p.topic_id
ef5584
		FROM ' . REPORTS_TABLE . ' r, ' . POSTS_TABLE . ' p
ef5584
		WHERE r.user_id = ' . $user_id . '
ef5584
			AND p.post_id = r.post_id';
ef5584
	$result = $db->sql_query($sql);
ef5584
ef5584
	$report_posts = $report_topics = array();
ef5584
	while ($row = $db->sql_fetchrow($result))
ef5584
	{
ef5584
		$report_posts[] = $row['post_id'];
ef5584
		$report_topics[] = $row['topic_id'];
ef5584
	}
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	if (sizeof($report_posts))
ef5584
	{
ef5584
		$report_posts = array_unique($report_posts);
ef5584
		$report_topics = array_unique($report_topics);
ef5584
ef5584
		// Get a list of topics that still contain reported posts
ef5584
		$sql = 'SELECT DISTINCT topic_id
ef5584
			FROM ' . POSTS_TABLE . '
ef5584
			WHERE ' . $db->sql_in_set('topic_id', $report_topics) . '
ef5584
				AND post_reported = 1
ef5584
				AND ' . $db->sql_in_set('post_id', $report_posts, true);
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		$keep_report_topics = array();
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$keep_report_topics[] = $row['topic_id'];
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		if (sizeof($keep_report_topics))
ef5584
		{
ef5584
			$report_topics = array_diff($report_topics, $keep_report_topics);
ef5584
		}
ef5584
		unset($keep_report_topics);
ef5584
ef5584
		// Now set the flags back
ef5584
		$sql = 'UPDATE ' . POSTS_TABLE . '
ef5584
			SET post_reported = 0
ef5584
			WHERE ' . $db->sql_in_set('post_id', $report_posts);
ef5584
		$db->sql_query($sql);
ef5584
ef5584
		if (sizeof($report_topics))
ef5584
		{
ef5584
			$sql = 'UPDATE ' . TOPICS_TABLE . '
ef5584
				SET topic_reported = 0
ef5584
				WHERE ' . $db->sql_in_set('topic_id', $report_topics);
ef5584
			$db->sql_query($sql);
ef5584
		}
ef5584
	}
ef5584
ef5584
	// Remove reports
ef5584
	$db->sql_query('DELETE FROM ' . REPORTS_TABLE . ' WHERE user_id = ' . $user_id);
ef5584
ef5584
	if ($user_row['user_avatar'] && $user_row['user_avatar_type'] == AVATAR_UPLOAD)
ef5584
	{
ef5584
		avatar_delete('user', $user_row);
ef5584
	}
ef5584
ef5584
	switch ($mode)
ef5584
	{
ef5584
		case 'retain':
ef5584
ef5584
			$db->sql_transaction('begin');
ef5584
ef5584
			if ($post_username === false)
ef5584
			{
ef5584
				$post_username = $user->lang['GUEST'];
ef5584
			}
ef5584
ef5584
			// If the user is inactive and newly registered we assume no posts from this user being there...
ef5584
			if ($user_row['user_type'] == USER_INACTIVE && $user_row['user_inactive_reason'] == INACTIVE_REGISTER && !$user_row['user_posts'])
ef5584
			{
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				$sql = 'UPDATE ' . FORUMS_TABLE . '
ef5584
					SET forum_last_poster_id = ' . ANONYMOUS . ", forum_last_poster_name = '" . $db->sql_escape($post_username) . "', forum_last_poster_colour = ''
ef5584
					WHERE forum_last_poster_id = $user_id";
ef5584
				$db->sql_query($sql);
ef5584
ef5584
				$sql = 'UPDATE ' . POSTS_TABLE . '
ef5584
					SET poster_id = ' . ANONYMOUS . ", post_username = '" . $db->sql_escape($post_username) . "'
ef5584
					WHERE poster_id = $user_id";
ef5584
				$db->sql_query($sql);
ef5584
ef5584
				$sql = 'UPDATE ' . POSTS_TABLE . '
ef5584
					SET post_edit_user = ' . ANONYMOUS . "
ef5584
					WHERE post_edit_user = $user_id";
ef5584
				$db->sql_query($sql);
ef5584
ef5584
				$sql = 'UPDATE ' . TOPICS_TABLE . '
ef5584
					SET topic_poster = ' . ANONYMOUS . ", topic_first_poster_name = '" . $db->sql_escape($post_username) . "', topic_first_poster_colour = ''
ef5584
					WHERE topic_poster = $user_id";
ef5584
				$db->sql_query($sql);
ef5584
ef5584
				$sql = 'UPDATE ' . TOPICS_TABLE . '
ef5584
					SET topic_last_poster_id = ' . ANONYMOUS . ", topic_last_poster_name = '" . $db->sql_escape($post_username) . "', topic_last_poster_colour = ''
ef5584
					WHERE topic_last_poster_id = $user_id";
ef5584
				$db->sql_query($sql);
ef5584
ef5584
				// Since we change every post by this author, we need to count this amount towards the anonymous user
ef5584
ef5584
				// Update the post count for the anonymous user
ef5584
				if ($user_row['user_posts'])
ef5584
				{
ef5584
					$sql = 'UPDATE ' . USERS_TABLE . '
ef5584
						SET user_posts = user_posts + ' . $user_row['user_posts'] . '
ef5584
						WHERE user_id = ' . ANONYMOUS;
ef5584
					$db->sql_query($sql);
ef5584
				}
ef5584
			}
ef5584
ef5584
			$db->sql_transaction('commit');
ef5584
ef5584
		break;
ef5584
ef5584
		case 'remove':
ef5584
ef5584
			if (!function_exists('delete_posts'))
ef5584
			{
ef5584
				include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
ef5584
			}
ef5584
ef5584
			$sql = 'SELECT topic_id, COUNT(post_id) AS total_posts
ef5584
				FROM ' . POSTS_TABLE . "
ef5584
				WHERE poster_id = $user_id
ef5584
				GROUP BY topic_id";
ef5584
			$result = $db->sql_query($sql);
ef5584
ef5584
			$topic_id_ary = array();
ef5584
			while ($row = $db->sql_fetchrow($result))
ef5584
			{
ef5584
				$topic_id_ary[$row['topic_id']] = $row['total_posts'];
ef5584
			}
ef5584
			$db->sql_freeresult($result);
ef5584
ef5584
			if (sizeof($topic_id_ary))
ef5584
			{
ef5584
				$sql = 'SELECT topic_id, topic_replies, topic_replies_real
ef5584
					FROM ' . TOPICS_TABLE . '
ef5584
					WHERE ' . $db->sql_in_set('topic_id', array_keys($topic_id_ary));
ef5584
				$result = $db->sql_query($sql);
ef5584
ef5584
				$del_topic_ary = array();
ef5584
				while ($row = $db->sql_fetchrow($result))
ef5584
				{
ef5584
					if (max($row['topic_replies'], $row['topic_replies_real']) + 1 == $topic_id_ary[$row['topic_id']])
ef5584
					{
ef5584
						$del_topic_ary[] = $row['topic_id'];
ef5584
					}
ef5584
				}
ef5584
				$db->sql_freeresult($result);
ef5584
ef5584
				if (sizeof($del_topic_ary))
ef5584
				{
ef5584
					$sql = 'DELETE FROM ' . TOPICS_TABLE . '
ef5584
						WHERE ' . $db->sql_in_set('topic_id', $del_topic_ary);
ef5584
					$db->sql_query($sql);
ef5584
				}
ef5584
			}
ef5584
ef5584
			// Delete posts, attachments, etc.
ef5584
			delete_posts('poster_id', $user_id);
ef5584
ef5584
		break;
ef5584
	}
ef5584
ef5584
	$db->sql_transaction('begin');
ef5584
ef5584
	$table_ary = array(USERS_TABLE, USER_GROUP_TABLE, TOPICS_WATCH_TABLE, FORUMS_WATCH_TABLE, ACL_USERS_TABLE, TOPICS_TRACK_TABLE, TOPICS_POSTED_TABLE, FORUMS_TRACK_TABLE, PROFILE_FIELDS_DATA_TABLE, MODERATOR_CACHE_TABLE, DRAFTS_TABLE, BOOKMARKS_TABLE);
ef5584
ef5584
	foreach ($table_ary as $table)
ef5584
	{
ef5584
		$sql = "DELETE FROM $table
ef5584
			WHERE user_id = $user_id";
ef5584
		$db->sql_query($sql);
ef5584
	}
ef5584
ef5584
	$cache->destroy('sql', MODERATOR_CACHE_TABLE);
ef5584
ef5584
	// Remove any undelivered mails...
ef5584
	$sql = 'SELECT msg_id, user_id
ef5584
		FROM ' . PRIVMSGS_TO_TABLE . '
ef5584
		WHERE author_id = ' . $user_id . '
ef5584
			AND folder_id = ' . PRIVMSGS_NO_BOX;
ef5584
	$result = $db->sql_query($sql);
ef5584
ef5584
	$undelivered_msg = $undelivered_user = array();
ef5584
	while ($row = $db->sql_fetchrow($result))
ef5584
	{
ef5584
		$undelivered_msg[] = $row['msg_id'];
ef5584
		$undelivered_user[$row['user_id']][] = true;
ef5584
	}
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	if (sizeof($undelivered_msg))
ef5584
	{
ef5584
		$sql = 'DELETE FROM ' . PRIVMSGS_TABLE . '
ef5584
			WHERE ' . $db->sql_in_set('msg_id', $undelivered_msg);
ef5584
		$db->sql_query($sql);
ef5584
	}
ef5584
ef5584
	$sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
ef5584
		WHERE author_id = ' . $user_id . '
ef5584
			AND folder_id = ' . PRIVMSGS_NO_BOX;
ef5584
	$db->sql_query($sql);
ef5584
ef5584
	// Delete all to-information
ef5584
	$sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
ef5584
		WHERE user_id = ' . $user_id;
ef5584
	$db->sql_query($sql);
ef5584
ef5584
	// Set the remaining author id to anonymous - this way users are still able to read messages from users being removed
ef5584
	$sql = 'UPDATE ' . PRIVMSGS_TO_TABLE . '
ef5584
		SET author_id = ' . ANONYMOUS . '
ef5584
		WHERE author_id = ' . $user_id;
ef5584
	$db->sql_query($sql);
ef5584
ef5584
	$sql = 'UPDATE ' . PRIVMSGS_TABLE . '
ef5584
		SET author_id = ' . ANONYMOUS . '
ef5584
		WHERE author_id = ' . $user_id;
ef5584
	$db->sql_query($sql);
ef5584
ef5584
	foreach ($undelivered_user as $_user_id => $ary)
ef5584
	{
ef5584
		if ($_user_id == $user_id)
ef5584
		{
ef5584
			continue;
ef5584
		}
ef5584
ef5584
		$sql = 'UPDATE ' . USERS_TABLE . '
ef5584
			SET user_new_privmsg = user_new_privmsg - ' . sizeof($ary) . ',
ef5584
				user_unread_privmsg = user_unread_privmsg - ' . sizeof($ary) . '
ef5584
			WHERE user_id = ' . $_user_id;
ef5584
		$db->sql_query($sql);
ef5584
	}
ef5584
ef5584
	$db->sql_transaction('commit');
ef5584
ef5584
	// Reset newest user info if appropriate
ef5584
	if ($config['newest_user_id'] == $user_id)
ef5584
	{
ef5584
		update_last_username();
ef5584
	}
ef5584
ef5584
	// Decrement number of users if this user is active
ef5584
	if ($user_row['user_type'] != USER_INACTIVE && $user_row['user_type'] != USER_IGNORE)
ef5584
	{
ef5584
		set_config('num_users', $config['num_users'] - 1, true);
ef5584
	}
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Flips user_type from active to inactive and vice versa, handles group membership updates
ef5584
*
ef5584
* @param string $mode can be flip for flipping from active/inactive, activate or deactivate
ef5584
*/
ef5584
function user_active_flip($mode, $user_id_ary, $reason = INACTIVE_MANUAL)
ef5584
{
ef5584
	global $config, $db, $user, $auth;
ef5584
ef5584
	$deactivated = $activated = 0;
ef5584
	$sql_statements = array();
ef5584
ef5584
	if (!is_array($user_id_ary))
ef5584
	{
ef5584
		$user_id_ary = array($user_id_ary);
ef5584
	}
ef5584
ef5584
	if (!sizeof($user_id_ary))
ef5584
	{
ef5584
		return;
ef5584
	}
ef5584
ef5584
	$sql = 'SELECT user_id, group_id, user_type, user_inactive_reason
ef5584
		FROM ' . USERS_TABLE . '
ef5584
		WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
ef5584
	$result = $db->sql_query($sql);
ef5584
ef5584
	while ($row = $db->sql_fetchrow($result))
ef5584
	{
ef5584
		$sql_ary = array();
ef5584
ef5584
		if ($row['user_type'] == USER_IGNORE || $row['user_type'] == USER_FOUNDER ||
ef5584
			($mode == 'activate' && $row['user_type'] != USER_INACTIVE) ||
ef5584
			($mode == 'deactivate' && $row['user_type'] == USER_INACTIVE))
ef5584
		{
ef5584
			continue;
ef5584
		}
ef5584
ef5584
		if ($row['user_type'] == USER_INACTIVE)
ef5584
		{
ef5584
			$activated++;
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$deactivated++;
ef5584
ef5584
			// Remove the users session key...
ef5584
			$user->reset_login_keys($row['user_id']);
ef5584
		}
ef5584
ef5584
		$sql_ary += array(
ef5584
			'user_type'				=> ($row['user_type'] == USER_NORMAL) ? USER_INACTIVE : USER_NORMAL,
ef5584
			'user_inactive_time'	=> ($row['user_type'] == USER_NORMAL) ? time() : 0,
ef5584
			'user_inactive_reason'	=> ($row['user_type'] == USER_NORMAL) ? $reason : 0,
ef5584
		);
ef5584
ef5584
		$sql_statements[$row['user_id']] = $sql_ary;
ef5584
	}
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	if (sizeof($sql_statements))
ef5584
	{
ef5584
		foreach ($sql_statements as $user_id => $sql_ary)
ef5584
		{
ef5584
			$sql = 'UPDATE ' . USERS_TABLE . '
ef5584
				SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
ef5584
				WHERE user_id = ' . $user_id;
ef5584
			$db->sql_query($sql);
ef5584
		}
ef5584
ef5584
		$auth->acl_clear_prefetch(array_keys($sql_statements));
ef5584
	}
ef5584
ef5584
	if ($deactivated)
ef5584
	{
ef5584
		set_config('num_users', $config['num_users'] - $deactivated, true);
ef5584
	}
ef5584
ef5584
	if ($activated)
ef5584
	{
ef5584
		set_config('num_users', $config['num_users'] + $activated, true);
ef5584
	}
ef5584
ef5584
	// Update latest username
ef5584
	update_last_username();
ef5584
}
ef5584
ef5584
/**
ef5584
* Add a ban or ban exclusion to the banlist. Bans either a user, an IP or an email address
ef5584
*
ef5584
* @param string $mode Type of ban. One of the following: user, ip, email
ef5584
* @param mixed $ban Banned entity. Either string or array with usernames, ips or email addresses
ef5584
* @param int $ban_len Ban length in minutes
ef5584
* @param string $ban_len_other Ban length as a date (YYYY-MM-DD)
ef5584
* @param boolean $ban_exclude Exclude these entities from banning?
ef5584
* @param string $ban_reason String describing the reason for this ban
ef5584
* @return boolean
ef5584
*/
ef5584
function user_ban($mode, $ban, $ban_len, $ban_len_other, $ban_exclude, $ban_reason, $ban_give_reason = '')
ef5584
{
ef5584
	global $db, $user, $auth, $cache;
ef5584
ef5584
	// Delete stale bans
ef5584
	$sql = 'DELETE FROM ' . BANLIST_TABLE . '
ef5584
		WHERE ban_end < ' . time() . '
ef5584
			AND ban_end <> 0';
ef5584
	$db->sql_query($sql);
ef5584
ef5584
	$ban_list = (!is_array($ban)) ? array_unique(explode("\n", $ban)) : $ban;
ef5584
	$ban_list_log = implode(', ', $ban_list);
ef5584
ef5584
	$current_time = time();
ef5584
ef5584
	// Set $ban_end to the unix time when the ban should end. 0 is a permanent ban.
ef5584
	if ($ban_len)
ef5584
	{
ef5584
		if ($ban_len != -1 || !$ban_len_other)
ef5584
		{
ef5584
			$ban_end = max($current_time, $current_time + ($ban_len) * 60);
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$ban_other = explode('-', $ban_len_other);
ef5584
			if (sizeof($ban_other) == 3 && ((int)$ban_other[0] < 9999) &&
ef5584
				(strlen($ban_other[0]) == 4) && (strlen($ban_other[1]) == 2) && (strlen($ban_other[2]) == 2))
ef5584
			{
ef5584
				$ban_end = max($current_time, gmmktime(0, 0, 0, (int)$ban_other[1], (int)$ban_other[2], (int)$ban_other[0]));
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				trigger_error('LENGTH_BAN_INVALID');
ef5584
			}
ef5584
		}
ef5584
	}
ef5584
	else
ef5584
	{
ef5584
		$ban_end = 0;
ef5584
	}
ef5584
ef5584
	$founder = $founder_names = array();
ef5584
ef5584
	if (!$ban_exclude)
ef5584
	{
ef5584
		// Create a list of founder...
ef5584
		$sql = 'SELECT user_id, user_email, username_clean
ef5584
			FROM ' . USERS_TABLE . '
ef5584
			WHERE user_type = ' . USER_FOUNDER;
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$founder[$row['user_id']] = $row['user_email'];
ef5584
			$founder_names[$row['user_id']] = $row['username_clean'];
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
	}
ef5584
ef5584
	$banlist_ary = array();
ef5584
ef5584
	switch ($mode)
ef5584
	{
ef5584
		case 'user':
ef5584
			$type = 'ban_userid';
ef5584
ef5584
			// At the moment we do not support wildcard username banning
ef5584
ef5584
			// Select the relevant user_ids.
ef5584
			$sql_usernames = array();
ef5584
ef5584
			foreach ($ban_list as $username)
ef5584
			{
ef5584
				$username = trim($username);
ef5584
				if ($username != '')
ef5584
				{
ef5584
					$clean_name = utf8_clean_string($username);
ef5584
					if ($clean_name == $user->data['username_clean'])
ef5584
					{
ef5584
						trigger_error('CANNOT_BAN_YOURSELF', E_USER_WARNING);
ef5584
					}
ef5584
					if (in_array($clean_name, $founder_names))
ef5584
					{
ef5584
						trigger_error('CANNOT_BAN_FOUNDER', E_USER_WARNING);
ef5584
					}
ef5584
					$sql_usernames[] = $clean_name;
ef5584
				}
ef5584
			}
ef5584
ef5584
			// Make sure we have been given someone to ban
ef5584
			if (!sizeof($sql_usernames))
ef5584
			{
ef5584
				trigger_error('NO_USER_SPECIFIED');
ef5584
			}
ef5584
ef5584
			$sql = 'SELECT user_id
ef5584
				FROM ' . USERS_TABLE . '
ef5584
				WHERE ' . $db->sql_in_set('username_clean', $sql_usernames);
ef5584
ef5584
			// Do not allow banning yourself
ef5584
			if (sizeof($founder))
ef5584
			{
ef5584
				$sql .= ' AND ' . $db->sql_in_set('user_id', array_merge(array_keys($founder), array($user->data['user_id'])), true);
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				$sql .= ' AND user_id <> ' . $user->data['user_id'];
ef5584
			}
ef5584
ef5584
			$result = $db->sql_query($sql);
ef5584
ef5584
			if ($row = $db->sql_fetchrow($result))
ef5584
			{
ef5584
				do
ef5584
				{
ef5584
					$banlist_ary[] = (int) $row['user_id'];
ef5584
				}
ef5584
				while ($row = $db->sql_fetchrow($result));
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				$db->sql_freeresult($result);
ef5584
				trigger_error('NO_USERS');
ef5584
			}
ef5584
			$db->sql_freeresult($result);
ef5584
		break;
ef5584
ef5584
		case 'ip':
ef5584
			$type = 'ban_ip';
ef5584
ef5584
			foreach ($ban_list as $ban_item)
ef5584
			{
ef5584
				if (preg_match('#^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})[ ]*\-[ ]*([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$#', trim($ban_item), $ip_range_explode))
ef5584
				{
ef5584
					// This is an IP range
ef5584
					// Don't ask about all this, just don't ask ... !
ef5584
					$ip_1_counter = $ip_range_explode[1];
ef5584
					$ip_1_end = $ip_range_explode[5];
ef5584
ef5584
					while ($ip_1_counter <= $ip_1_end)
ef5584
					{
ef5584
						$ip_2_counter = ($ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[2] : 0;
ef5584
						$ip_2_end = ($ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[6];
ef5584
ef5584
						if ($ip_2_counter == 0 && $ip_2_end == 254)
ef5584
						{
ef5584
							$ip_2_counter = 256;
ef5584
							$ip_2_fragment = 256;
ef5584
ef5584
							$banlist_ary[] = "$ip_1_counter.*";
ef5584
						}
ef5584
ef5584
						while ($ip_2_counter <= $ip_2_end)
ef5584
						{
ef5584
							$ip_3_counter = ($ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[3] : 0;
ef5584
							$ip_3_end = ($ip_2_counter < $ip_2_end || $ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[7];
ef5584
ef5584
							if ($ip_3_counter == 0 && $ip_3_end == 254)
ef5584
							{
ef5584
								$ip_3_counter = 256;
ef5584
								$ip_3_fragment = 256;
ef5584
ef5584
								$banlist_ary[] = "$ip_1_counter.$ip_2_counter.*";
ef5584
							}
ef5584
ef5584
							while ($ip_3_counter <= $ip_3_end)
ef5584
							{
ef5584
								$ip_4_counter = ($ip_3_counter == $ip_range_explode[3] && $ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[4] : 0;
ef5584
								$ip_4_end = ($ip_3_counter < $ip_3_end || $ip_2_counter < $ip_2_end) ? 254 : $ip_range_explode[8];
ef5584
ef5584
								if ($ip_4_counter == 0 && $ip_4_end == 254)
ef5584
								{
ef5584
									$ip_4_counter = 256;
ef5584
									$ip_4_fragment = 256;
ef5584
ef5584
									$banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.*";
ef5584
								}
ef5584
ef5584
								while ($ip_4_counter <= $ip_4_end)
ef5584
								{
ef5584
									$banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.$ip_4_counter";
ef5584
									$ip_4_counter++;
ef5584
								}
ef5584
								$ip_3_counter++;
ef5584
							}
ef5584
							$ip_2_counter++;
ef5584
						}
ef5584
						$ip_1_counter++;
ef5584
					}
ef5584
				}
ef5584
				else if (preg_match('#^([0-9]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})$#', trim($ban_item)) || preg_match('#^[a-f0-9:]+\*?$#i', trim($ban_item)))
ef5584
				{
ef5584
					// Normal IP address
ef5584
					$banlist_ary[] = trim($ban_item);
ef5584
				}
ef5584
				else if (preg_match('#^\*$#', trim($ban_item)))
ef5584
				{
ef5584
					// Ban all IPs
ef5584
					$banlist_ary[] = '*';
ef5584
				}
ef5584
				else if (preg_match('#^([\w\-_]\.?){2,}$#is', trim($ban_item)))
ef5584
				{
ef5584
					// hostname
ef5584
					$ip_ary = gethostbynamel(trim($ban_item));
ef5584
ef5584
					if (!empty($ip_ary))
ef5584
					{
ef5584
						foreach ($ip_ary as $ip)
ef5584
						{
ef5584
							if ($ip)
ef5584
							{
ef5584
								if (strlen($ip) > 40)
ef5584
								{
ef5584
									continue;
ef5584
								}
ef5584
ef5584
								$banlist_ary[] = $ip;
ef5584
							}
ef5584
						}
ef5584
					}
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					trigger_error('NO_IPS_DEFINED');
ef5584
				}
ef5584
			}
ef5584
		break;
ef5584
ef5584
		case 'email':
ef5584
			$type = 'ban_email';
ef5584
ef5584
			foreach ($ban_list as $ban_item)
ef5584
			{
ef5584
				$ban_item = trim($ban_item);
ef5584
ef5584
				if (preg_match('#^.*?@*|(([a-z0-9\-]+\.)+([a-z]{2,3}))$#i', $ban_item))
ef5584
				{
ef5584
					if (strlen($ban_item) > 100)
ef5584
					{
ef5584
						continue;
ef5584
					}
ef5584
ef5584
					if (!sizeof($founder) || !in_array($ban_item, $founder))
ef5584
					{
ef5584
						$banlist_ary[] = $ban_item;
ef5584
					}
ef5584
				}
ef5584
			}
ef5584
ef5584
			if (sizeof($ban_list) == 0)
ef5584
			{
ef5584
				trigger_error('NO_EMAILS_DEFINED');
ef5584
			}
ef5584
		break;
ef5584
ef5584
		default:
ef5584
			trigger_error('NO_MODE');
ef5584
		break;
ef5584
	}
ef5584
ef5584
	// Fetch currently set bans of the specified type and exclude state. Prevent duplicate bans.
ef5584
	$sql_where = ($type == 'ban_userid') ? 'ban_userid <> 0' : "$type <> ''";
ef5584
ef5584
	$sql = "SELECT $type
ef5584
		FROM " . BANLIST_TABLE . "
ef5584
		WHERE $sql_where
ef5584
			AND ban_exclude = " . (int) $ban_exclude;
ef5584
	$result = $db->sql_query($sql);
ef5584
ef5584
	// Reset $sql_where, because we use it later...
ef5584
	$sql_where = '';
ef5584
ef5584
	if ($row = $db->sql_fetchrow($result))
ef5584
	{
ef5584
		$banlist_ary_tmp = array();
ef5584
		do
ef5584
		{
ef5584
			switch ($mode)
ef5584
			{
ef5584
				case 'user':
ef5584
					$banlist_ary_tmp[] = $row['ban_userid'];
ef5584
				break;
ef5584
ef5584
				case 'ip':
ef5584
					$banlist_ary_tmp[] = $row['ban_ip'];
ef5584
				break;
ef5584
ef5584
				case 'email':
ef5584
					$banlist_ary_tmp[] = $row['ban_email'];
ef5584
				break;
ef5584
			}
ef5584
		}
ef5584
		while ($row = $db->sql_fetchrow($result));
ef5584
ef5584
		$banlist_ary = array_unique(array_diff($banlist_ary, $banlist_ary_tmp));
ef5584
		unset($banlist_ary_tmp);
ef5584
	}
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	// We have some entities to ban
ef5584
	if (sizeof($banlist_ary))
ef5584
	{
ef5584
		$sql_ary = array();
ef5584
ef5584
		foreach ($banlist_ary as $ban_entry)
ef5584
		{
ef5584
			$sql_ary[] = array(
ef5584
				$type				=> $ban_entry,
ef5584
				'ban_start'			=> (int) $current_time,
ef5584
				'ban_end'			=> (int) $ban_end,
ef5584
				'ban_exclude'		=> (int) $ban_exclude,
ef5584
				'ban_reason'		=> (string) $ban_reason,
ef5584
				'ban_give_reason'	=> (string) $ban_give_reason,
ef5584
			);
ef5584
		}
ef5584
ef5584
		$db->sql_multi_insert(BANLIST_TABLE, $sql_ary);
ef5584
ef5584
		// If we are banning we want to logout anyone matching the ban
ef5584
		if (!$ban_exclude)
ef5584
		{
ef5584
			switch ($mode)
ef5584
			{
ef5584
				case 'user':
ef5584
					$sql_where = 'WHERE ' . $db->sql_in_set('session_user_id', $banlist_ary);
ef5584
				break;
ef5584
ef5584
				case 'ip':
ef5584
					$sql_where = 'WHERE ' . $db->sql_in_set('session_ip', $banlist_ary);
ef5584
				break;
ef5584
ef5584
				case 'email':
ef5584
					$banlist_ary_sql = array();
ef5584
ef5584
					foreach ($banlist_ary as $ban_entry)
ef5584
					{
ef5584
						$banlist_ary_sql[] = (string) str_replace('*', '%', $ban_entry);
ef5584
					}
ef5584
ef5584
					$sql = 'SELECT user_id
ef5584
						FROM ' . USERS_TABLE . '
ef5584
						WHERE ' . $db->sql_in_set('user_email', $banlist_ary_sql);
ef5584
					$result = $db->sql_query($sql);
ef5584
ef5584
					$sql_in = array();
ef5584
ef5584
					if ($row = $db->sql_fetchrow($result))
ef5584
					{
ef5584
						do
ef5584
						{
ef5584
							$sql_in[] = $row['user_id'];
ef5584
						}
ef5584
						while ($row = $db->sql_fetchrow($result));
ef5584
ef5584
						$sql_where = 'WHERE ' . $db->sql_in_set('session_user_id', $sql_in);
ef5584
					}
ef5584
					$db->sql_freeresult($result);
ef5584
				break;
ef5584
			}
ef5584
ef5584
			if (isset($sql_where) && $sql_where)
ef5584
			{
ef5584
				$sql = 'DELETE FROM ' . SESSIONS_TABLE . "
ef5584
					$sql_where";
ef5584
				$db->sql_query($sql);
ef5584
ef5584
				if ($mode == 'user')
ef5584
				{
ef5584
					$sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . ' ' . ((in_array('*', $banlist_ary)) ? '' : 'WHERE ' . $db->sql_in_set('user_id', $banlist_ary));
ef5584
					$db->sql_query($sql);
ef5584
				}
ef5584
			}
ef5584
		}
ef5584
ef5584
		// Update log
ef5584
		$log_entry = ($ban_exclude) ? 'LOG_BAN_EXCLUDE_' : 'LOG_BAN_';
ef5584
ef5584
		// Add to moderator and admin log
ef5584
		add_log('admin', $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
ef5584
		add_log('mod', 0, 0, $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
ef5584
ef5584
		$cache->destroy('sql', BANLIST_TABLE);
ef5584
ef5584
		return true;
ef5584
	}
ef5584
ef5584
	// There was nothing to ban/exclude. But destroying the cache because of the removal of stale bans.
ef5584
	$cache->destroy('sql', BANLIST_TABLE);
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Unban User
ef5584
*/
ef5584
function user_unban($mode, $ban)
ef5584
{
ef5584
	global $db, $user, $auth, $cache;
ef5584
ef5584
	// Delete stale bans
ef5584
	$sql = 'DELETE FROM ' . BANLIST_TABLE . '
ef5584
		WHERE ban_end < ' . time() . '
ef5584
			AND ban_end <> 0';
ef5584
	$db->sql_query($sql);
ef5584
ef5584
	if (!is_array($ban))
ef5584
	{
ef5584
		$ban = array($ban);
ef5584
	}
ef5584
ef5584
	$unban_sql = array_map('intval', $ban);
ef5584
ef5584
	if (sizeof($unban_sql))
ef5584
	{
ef5584
		// Grab details of bans for logging information later
ef5584
		switch ($mode)
ef5584
		{
ef5584
			case 'user':
ef5584
				$sql = 'SELECT u.username AS unban_info
ef5584
					FROM ' . USERS_TABLE . ' u, ' . BANLIST_TABLE . ' b
ef5584
					WHERE ' . $db->sql_in_set('b.ban_id', $unban_sql) . '
ef5584
						AND u.user_id = b.ban_userid';
ef5584
			break;
ef5584
ef5584
			case 'email':
ef5584
				$sql = 'SELECT ban_email AS unban_info
ef5584
					FROM ' . BANLIST_TABLE . '
ef5584
					WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
ef5584
			break;
ef5584
ef5584
			case 'ip':
ef5584
				$sql = 'SELECT ban_ip AS unban_info
ef5584
					FROM ' . BANLIST_TABLE . '
ef5584
					WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
ef5584
			break;
ef5584
		}
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		$l_unban_list = '';
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$l_unban_list .= (($l_unban_list != '') ? ', ' : '') . $row['unban_info'];
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		$sql = 'DELETE FROM ' . BANLIST_TABLE . '
ef5584
			WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
ef5584
		$db->sql_query($sql);
ef5584
ef5584
		// Add to moderator and admin log
ef5584
		add_log('admin', 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
ef5584
		add_log('mod', 0, 0, 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
ef5584
	}
ef5584
ef5584
	$cache->destroy('sql', BANLIST_TABLE);
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Whois facility
ef5584
*/
ef5584
function user_ipwhois($ip)
ef5584
{
ef5584
	$ipwhois = '';
ef5584
ef5584
	// Check IP
ef5584
	// Only supporting IPv4 at the moment...
ef5584
	if (empty($ip) || !preg_match(get_preg_expression('ipv4'), $ip))
ef5584
	{
ef5584
		return '';
ef5584
	}
ef5584
ef5584
	$match = array(
ef5584
		'#RIPE\.NET#is'				=> 'whois.ripe.net',
ef5584
		'#whois\.apnic\.net#is'		=> 'whois.apnic.net',
ef5584
		'#nic\.ad\.jp#is'			=> 'whois.nic.ad.jp',
ef5584
		'#whois\.registro\.br#is'	=> 'whois.registro.br'
ef5584
	);
ef5584
ef5584
	if (($fsk = @fsockopen('whois.arin.net', 43)))
ef5584
	{
ef5584
		fputs($fsk, "$ip\n");
ef5584
		while (!feof($fsk))
ef5584
		{
ef5584
			$ipwhois .= fgets($fsk, 1024);
ef5584
		}
ef5584
		@fclose($fsk);
ef5584
	}
ef5584
ef5584
	foreach (array_keys($match) as $server)
ef5584
	{
ef5584
		if (preg_match($server, $ipwhois))
ef5584
		{
ef5584
			$ipwhois = '';
ef5584
			if (($fsk = @fsockopen($match[$server], 43)))
ef5584
			{
ef5584
				fputs($fsk, "$ip\n");
ef5584
				while (!feof($fsk))
ef5584
				{
ef5584
					$ipwhois .= fgets($fsk, 1024);
ef5584
				}
ef5584
				@fclose($fsk);
ef5584
			}
ef5584
			break;
ef5584
		}
ef5584
	}
ef5584
ef5584
	$ipwhois = htmlspecialchars($ipwhois);
ef5584
ef5584
	// Magic URL ;)
ef5584
	return trim(make_clickable($ipwhois, false, ''));
ef5584
}
ef5584
ef5584
/**
ef5584
* Data validation ... used primarily but not exclusively by ucp modules
ef5584
*
ef5584
* "Master" function for validating a range of data types
ef5584
*/
ef5584
function validate_data($data, $val_ary)
ef5584
{
ef5584
	global $user;
ef5584
ef5584
	$error = array();
ef5584
ef5584
	foreach ($val_ary as $var => $val_seq)
ef5584
	{
ef5584
		if (!is_array($val_seq[0]))
ef5584
		{
ef5584
			$val_seq = array($val_seq);
ef5584
		}
ef5584
ef5584
		foreach ($val_seq as $validate)
ef5584
		{
ef5584
			$function = array_shift($validate);
ef5584
			array_unshift($validate, $data[$var]);
ef5584
ef5584
			if ($result = call_user_func_array('validate_' . $function, $validate))
ef5584
			{
ef5584
				// Since errors are checked later for their language file existence, we need to make sure custom errors are not adjusted.
ef5584
				$error[] = (empty($user->lang[$result . '_' . strtoupper($var)])) ? $result : $result . '_' . strtoupper($var);
ef5584
			}
ef5584
		}
ef5584
	}
ef5584
ef5584
	return $error;
ef5584
}
ef5584
ef5584
/**
ef5584
* Validate String
ef5584
*
ef5584
* @return	boolean|string	Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
ef5584
*/
ef5584
function validate_string($string, $optional = false, $min = 0, $max = 0)
ef5584
{
ef5584
	if (empty($string) && $optional)
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	if ($min && utf8_strlen(htmlspecialchars_decode($string)) < $min)
ef5584
	{
ef5584
		return 'TOO_SHORT';
ef5584
	}
ef5584
	else if ($max && utf8_strlen(htmlspecialchars_decode($string)) > $max)
ef5584
	{
ef5584
		return 'TOO_LONG';
ef5584
	}
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Validate Number
ef5584
*
ef5584
* @return	boolean|string	Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
ef5584
*/
ef5584
function validate_num($num, $optional = false, $min = 0, $max = 1E99)
ef5584
{
ef5584
	if (empty($num) && $optional)
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	if ($num < $min)
ef5584
	{
ef5584
		return 'TOO_SMALL';
ef5584
	}
ef5584
	else if ($num > $max)
ef5584
	{
ef5584
		return 'TOO_LARGE';
ef5584
	}
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Validate Date
ef5584
* @param String $string a date in the dd-mm-yyyy format
ef5584
* @return	boolean
ef5584
*/
ef5584
function validate_date($date_string, $optional = false)
ef5584
{
ef5584
	$date = explode('-', $date_string);
ef5584
	if ((empty($date) || sizeof($date) != 3) && $optional)
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
	else if ($optional)
ef5584
	{
ef5584
		for ($field = 0; $field <= 1; $field++)
ef5584
		{
ef5584
			$date[$field] = (int) $date[$field];
ef5584
			if (empty($date[$field]))
ef5584
			{
ef5584
				$date[$field] = 1;
ef5584
			}
ef5584
		}
ef5584
		$date[2] = (int) $date[2];
ef5584
		// assume an arbitrary leap year
ef5584
		if (empty($date[2]))
ef5584
		{
ef5584
			$date[2] = 1980;
ef5584
		}
ef5584
	}
ef5584
ef5584
	if (sizeof($date) != 3 || !checkdate($date[1], $date[0], $date[2]))
ef5584
	{
ef5584
		return 'INVALID';
ef5584
	}
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
ef5584
/**
ef5584
* Validate Match
ef5584
*
ef5584
* @return	boolean|string	Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
ef5584
*/
ef5584
function validate_match($string, $optional = false, $match = '')
ef5584
{
ef5584
	if (empty($string) && $optional)
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	if (empty($match))
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	if (!preg_match($match, $string))
ef5584
	{
ef5584
		return 'WRONG_DATA';
ef5584
	}
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Check to see if the username has been taken, or if it is disallowed.
ef5584
* Also checks if it includes the " character, which we don't allow in usernames.
ef5584
* Used for registering, changing names, and posting anonymously with a username
ef5584
*
ef5584
* @param string $username The username to check
ef5584
* @param string $allowed_username An allowed username, default being $user->data['username']
ef5584
*
ef5584
* @return	mixed	Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
ef5584
*/
ef5584
function validate_username($username, $allowed_username = false)
ef5584
{
ef5584
	global $config, $db, $user, $cache;
ef5584
ef5584
	$clean_username = utf8_clean_string($username);
ef5584
	$allowed_username = ($allowed_username === false) ? $user->data['username_clean'] : utf8_clean_string($allowed_username);
ef5584
ef5584
	if ($allowed_username == $clean_username)
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	// ... fast checks first.
ef5584
	if (strpos($username, '"') !== false || strpos($username, '"') !== false || empty($clean_username))
ef5584
	{
ef5584
		return 'INVALID_CHARS';
ef5584
	}
ef5584
ef5584
	$mbstring = $pcre = false;
ef5584
ef5584
	// generic UTF-8 character types supported?
ef5584
	if ((version_compare(PHP_VERSION, '5.1.0', '>=') || (version_compare(PHP_VERSION, '5.0.0-dev', '<=') && version_compare(PHP_VERSION, '4.4.0', '>='))) && @preg_match('/\p{L}/u', 'a') !== false)
ef5584
	{
ef5584
		$pcre = true;
ef5584
	}
ef5584
	else if (function_exists('mb_ereg_match'))
ef5584
	{
ef5584
		mb_regex_encoding('UTF-8');
ef5584
		$mbstring = true;
ef5584
	}
ef5584
ef5584
	switch ($config['allow_name_chars'])
ef5584
	{
ef5584
		case 'USERNAME_CHARS_ANY':
ef5584
			$pcre = true;
ef5584
			$regex = '.+';
ef5584
		break;
ef5584
ef5584
		case 'USERNAME_ALPHA_ONLY':
ef5584
			$pcre = true;
ef5584
			$regex = '[A-Za-z0-9]+';
ef5584
		break;
ef5584
ef5584
		case 'USERNAME_ALPHA_SPACERS':
ef5584
			$pcre = true;
ef5584
			$regex = '[A-Za-z0-9-[\]_+ ]+';
ef5584
		break;
ef5584
ef5584
		case 'USERNAME_LETTER_NUM':
ef5584
			if ($pcre)
ef5584
			{
ef5584
				$regex = '[\p{Lu}\p{Ll}\p{N}]+';
ef5584
			}
ef5584
			else if ($mbstring)
ef5584
			{
ef5584
				$regex = '[[:upper:][:lower:][:digit:]]+';
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				$pcre = true;
ef5584
				$regex = '[a-zA-Z0-9]+';
ef5584
			}
ef5584
		break;
ef5584
ef5584
		case 'USERNAME_LETTER_NUM_SPACERS':
ef5584
			if ($pcre)
ef5584
			{
ef5584
				$regex = '[-\]_+ [\p{Lu}\p{Ll}\p{N}]+';
ef5584
			}
ef5584
			else if ($mbstring)
ef5584
			{
ef5584
				$regex = '[-\]_+ [[:upper:][:lower:][:digit:]]+';
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				$pcre = true;
ef5584
				$regex = '[-\]_+ [a-zA-Z0-9]+';
ef5584
			}
ef5584
		break;
ef5584
ef5584
		case 'USERNAME_ASCII':
ef5584
		default:
ef5584
			$pcre = true;
ef5584
			$regex = '[\x01-\x7F]+';
ef5584
		break;
ef5584
	}
ef5584
ef5584
	if ($pcre)
ef5584
	{
ef5584
		if (!preg_match('#^' . $regex . '$#u', $username))
ef5584
		{
ef5584
			return 'INVALID_CHARS';
ef5584
		}
ef5584
	}
ef5584
	else if ($mbstring)
ef5584
	{
ef5584
		$matches = array();
ef5584
		mb_ereg_search_init('^' . $username . '$', $regex, $matches);
ef5584
		if (!mb_ereg_search())
ef5584
		{
ef5584
			return 'INVALID_CHARS';
ef5584
		}
ef5584
	}
ef5584
ef5584
	$sql = 'SELECT username
ef5584
		FROM ' . USERS_TABLE . "
ef5584
		WHERE username_clean = '" . $db->sql_escape($clean_username) . "'";
ef5584
	$result = $db->sql_query($sql);
ef5584
	$row = $db->sql_fetchrow($result);
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	if ($row)
ef5584
	{
ef5584
		return 'USERNAME_TAKEN';
ef5584
	}
ef5584
ef5584
	$sql = 'SELECT group_name
ef5584
		FROM ' . GROUPS_TABLE . "
ef5584
		WHERE LOWER(group_name) = '" . $db->sql_escape(utf8_strtolower($username)) . "'";
ef5584
	$result = $db->sql_query($sql);
ef5584
	$row = $db->sql_fetchrow($result);
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	if ($row)
ef5584
	{
ef5584
		return 'USERNAME_TAKEN';
ef5584
	}
ef5584
ef5584
	$bad_usernames = $cache->obtain_disallowed_usernames();
ef5584
ef5584
	foreach ($bad_usernames as $bad_username)
ef5584
	{
ef5584
		if (preg_match('#^' . $bad_username . '$#', $clean_username))
ef5584
		{
ef5584
			return 'USERNAME_DISALLOWED';
ef5584
		}
ef5584
	}
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Check to see if the password meets the complexity settings
ef5584
*
ef5584
* @return	boolean|string	Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
ef5584
*/
ef5584
function validate_password($password)
ef5584
{
ef5584
	global $config, $db, $user;
ef5584
ef5584
	if (!$password)
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	$pcre = $mbstring = false;
ef5584
ef5584
	// generic UTF-8 character types supported?
ef5584
	if ((version_compare(PHP_VERSION, '5.1.0', '>=') || (version_compare(PHP_VERSION, '5.0.0-dev', '<=') && version_compare(PHP_VERSION, '4.4.0', '>='))) && @preg_match('/\p{L}/u', 'a') !== false)
ef5584
	{
ef5584
		$upp = '\p{Lu}';
ef5584
		$low = '\p{Ll}';
ef5584
		$let = '\p{L}';
ef5584
		$num = '\p{N}';
ef5584
		$sym = '[^\p{Lu}\p{Ll}\p{N}]';
ef5584
		$pcre = true;
ef5584
	}
ef5584
	else if (function_exists('mb_ereg_match'))
ef5584
	{
ef5584
		mb_regex_encoding('UTF-8');
ef5584
		$upp = '[[:upper:]]';
ef5584
		$low = '[[:lower:]]';
ef5584
		$let = '[[:lower:][:upper:]]';
ef5584
		$num = '[[:digit:]]';
ef5584
		$sym = '[^[:upper:][:lower:][:digit:]]';
ef5584
		$mbstring = true;
ef5584
	}
ef5584
	else
ef5584
	{
ef5584
		$upp = '[A-Z]';
ef5584
		$low = '[a-z]';
ef5584
		$let = '[a-zA-Z]';
ef5584
		$num = '[0-9]';
ef5584
		$sym = '[^A-Za-z0-9]';
ef5584
		$pcre = true;
ef5584
	}
ef5584
ef5584
	$chars = array();
ef5584
ef5584
	switch ($config['pass_complex'])
ef5584
	{
ef5584
		case 'PASS_TYPE_CASE':
ef5584
			$chars[] = $low;
ef5584
			$chars[] = $upp;
ef5584
		break;
ef5584
ef5584
		case 'PASS_TYPE_ALPHA':
ef5584
			$chars[] = $let;
ef5584
			$chars[] = $num;
ef5584
		break;
ef5584
ef5584
		case 'PASS_TYPE_SYMBOL':
ef5584
			$chars[] = $low;
ef5584
			$chars[] = $upp;
ef5584
			$chars[] = $num;
ef5584
			$chars[] = $sym;
ef5584
		break;
ef5584
	}
ef5584
ef5584
	if ($pcre)
ef5584
	{
ef5584
		foreach ($chars as $char)
ef5584
		{
ef5584
			if (!preg_match('#' . $char . '#u', $password))
ef5584
			{
ef5584
				return 'INVALID_CHARS';
ef5584
			}
ef5584
		}
ef5584
	}
ef5584
	else if ($mbstring)
ef5584
	{
ef5584
		foreach ($chars as $char)
ef5584
		{
ef5584
			if (mb_ereg($char, $password) === false)
ef5584
			{
ef5584
				return 'INVALID_CHARS';
ef5584
			}
ef5584
		}
ef5584
	}
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Check to see if email address is banned or already present in the DB
ef5584
*
ef5584
* @param string $email The email to check
ef5584
* @param string $allowed_email An allowed email, default being $user->data['user_email']
ef5584
*
ef5584
* @return mixed Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
ef5584
*/
ef5584
function validate_email($email, $allowed_email = false)
ef5584
{
ef5584
	global $config, $db, $user;
ef5584
ef5584
	$email = strtolower($email);
ef5584
	$allowed_email = ($allowed_email === false) ? strtolower($user->data['user_email']) : strtolower($allowed_email);
ef5584
ef5584
	if ($allowed_email == $email)
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	if (!preg_match('/^' . get_preg_expression('email') . '$/i', $email))
ef5584
	{
ef5584
		return 'EMAIL_INVALID';
ef5584
	}
ef5584
ef5584
	// Check MX record.
ef5584
	// The idea for this is from reading the UseBB blog/announcement. :)
ef5584
	if ($config['email_check_mx'])
ef5584
	{
ef5584
		list(, $domain) = explode('@', $email);
ef5584
ef5584
		if (phpbb_checkdnsrr($domain, 'A') === false && phpbb_checkdnsrr($domain, 'MX') === false)
ef5584
		{
ef5584
			return 'DOMAIN_NO_MX_RECORD';
ef5584
		}
ef5584
	}
ef5584
ef5584
	if (($ban_reason = $user->check_ban(false, false, $email, true)) !== false)
ef5584
	{
ef5584
		return ($ban_reason === true) ? 'EMAIL_BANNED' : $ban_reason;
ef5584
	}
ef5584
ef5584
	if (!$config['allow_emailreuse'])
ef5584
	{
ef5584
		$sql = 'SELECT user_email_hash
ef5584
			FROM ' . USERS_TABLE . "
ef5584
			WHERE user_email_hash = " . (crc32($email) . strlen($email));
ef5584
		$result = $db->sql_query($sql);
ef5584
		$row = $db->sql_fetchrow($result);
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		if ($row)
ef5584
		{
ef5584
			return 'EMAIL_TAKEN';
ef5584
		}
ef5584
	}
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Validate jabber address
ef5584
* Taken from the jabber class within flyspray (see author notes)
ef5584
*
ef5584
* @author flyspray.org
ef5584
*/
ef5584
function validate_jabber($jid)
ef5584
{
ef5584
	if (!$jid)
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	$seperator_pos = strpos($jid, '@');
ef5584
ef5584
	if ($seperator_pos === false)
ef5584
	{
ef5584
		return 'WRONG_DATA';
ef5584
	}
ef5584
ef5584
	$username = substr($jid, 0, $seperator_pos);
ef5584
	$realm = substr($jid, $seperator_pos + 1);
ef5584
ef5584
	if (strlen($username) == 0 || strlen($realm) < 3)
ef5584
	{
ef5584
		return 'WRONG_DATA';
ef5584
	}
ef5584
ef5584
	$arr = explode('.', $realm);
ef5584
ef5584
	if (sizeof($arr) == 0)
ef5584
	{
ef5584
		return 'WRONG_DATA';
ef5584
	}
ef5584
ef5584
	foreach ($arr as $part)
ef5584
	{
ef5584
		if (substr($part, 0, 1) == '-' || substr($part, -1, 1) == '-')
ef5584
		{
ef5584
			return 'WRONG_DATA';
ef5584
		}
ef5584
ef5584
		if (!preg_match("@^[a-zA-Z0-9-.]+$@", $part))
ef5584
		{
ef5584
			return 'WRONG_DATA';
ef5584
		}
ef5584
	}
ef5584
ef5584
	$boundary = array(array(0, 127), array(192, 223), array(224, 239), array(240, 247), array(248, 251), array(252, 253));
ef5584
ef5584
	// Prohibited Characters RFC3454 + RFC3920
ef5584
	$prohibited = array(
ef5584
		// Table C.1.1
ef5584
		array(0x0020, 0x0020),		// SPACE
ef5584
		// Table C.1.2
ef5584
		array(0x00A0, 0x00A0),		// NO-BREAK SPACE
ef5584
		array(0x1680, 0x1680),		// OGHAM SPACE MARK
ef5584
		array(0x2000, 0x2001),		// EN QUAD
ef5584
		array(0x2001, 0x2001),		// EM QUAD
ef5584
		array(0x2002, 0x2002),		// EN SPACE
ef5584
		array(0x2003, 0x2003),		// EM SPACE
ef5584
		array(0x2004, 0x2004),		// THREE-PER-EM SPACE
ef5584
		array(0x2005, 0x2005),		// FOUR-PER-EM SPACE
ef5584
		array(0x2006, 0x2006),		// SIX-PER-EM SPACE
ef5584
		array(0x2007, 0x2007),		// FIGURE SPACE
ef5584
		array(0x2008, 0x2008),		// PUNCTUATION SPACE
ef5584
		array(0x2009, 0x2009),		// THIN SPACE
ef5584
		array(0x200A, 0x200A),		// HAIR SPACE
ef5584
		array(0x200B, 0x200B),		// ZERO WIDTH SPACE
ef5584
		array(0x202F, 0x202F),		// NARROW NO-BREAK SPACE
ef5584
		array(0x205F, 0x205F),		// MEDIUM MATHEMATICAL SPACE
ef5584
		array(0x3000, 0x3000),		// IDEOGRAPHIC SPACE
ef5584
		// Table C.2.1
ef5584
		array(0x0000, 0x001F),		// [CONTROL CHARACTERS]
ef5584
		array(0x007F, 0x007F),		// DELETE
ef5584
		// Table C.2.2
ef5584
		array(0x0080, 0x009F),		// [CONTROL CHARACTERS]
ef5584
		array(0x06DD, 0x06DD),		// ARABIC END OF AYAH
ef5584
		array(0x070F, 0x070F),		// SYRIAC ABBREVIATION MARK
ef5584
		array(0x180E, 0x180E),		// MONGOLIAN VOWEL SEPARATOR
ef5584
		array(0x200C, 0x200C), 		// ZERO WIDTH NON-JOINER
ef5584
		array(0x200D, 0x200D),		// ZERO WIDTH JOINER
ef5584
		array(0x2028, 0x2028),		// LINE SEPARATOR
ef5584
		array(0x2029, 0x2029),		// PARAGRAPH SEPARATOR
ef5584
		array(0x2060, 0x2060),		// WORD JOINER
ef5584
		array(0x2061, 0x2061),		// FUNCTION APPLICATION
ef5584
		array(0x2062, 0x2062),		// INVISIBLE TIMES
ef5584
		array(0x2063, 0x2063),		// INVISIBLE SEPARATOR
ef5584
		array(0x206A, 0x206F),		// [CONTROL CHARACTERS]
ef5584
		array(0xFEFF, 0xFEFF),		// ZERO WIDTH NO-BREAK SPACE
ef5584
		array(0xFFF9, 0xFFFC),		// [CONTROL CHARACTERS]
ef5584
		array(0x1D173, 0x1D17A),	// [MUSICAL CONTROL CHARACTERS]
ef5584
		// Table C.3
ef5584
		array(0xE000, 0xF8FF),		// [PRIVATE USE, PLANE 0]
ef5584
		array(0xF0000, 0xFFFFD),	// [PRIVATE USE, PLANE 15]
ef5584
		array(0x100000, 0x10FFFD),	// [PRIVATE USE, PLANE 16]
ef5584
		// Table C.4
ef5584
		array(0xFDD0, 0xFDEF),		// [NONCHARACTER CODE POINTS]
ef5584
		array(0xFFFE, 0xFFFF),		// [NONCHARACTER CODE POINTS]
ef5584
		array(0x1FFFE, 0x1FFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0x2FFFE, 0x2FFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0x3FFFE, 0x3FFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0x4FFFE, 0x4FFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0x5FFFE, 0x5FFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0x6FFFE, 0x6FFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0x7FFFE, 0x7FFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0x8FFFE, 0x8FFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0x9FFFE, 0x9FFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0xAFFFE, 0xAFFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0xBFFFE, 0xBFFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0xCFFFE, 0xCFFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0xDFFFE, 0xDFFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0xEFFFE, 0xEFFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0xFFFFE, 0xFFFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		array(0x10FFFE, 0x10FFFF),	// [NONCHARACTER CODE POINTS]
ef5584
		// Table C.5
ef5584
		array(0xD800, 0xDFFF),		// [SURROGATE CODES]
ef5584
		// Table C.6
ef5584
		array(0xFFF9, 0xFFF9),		// INTERLINEAR ANNOTATION ANCHOR
ef5584
		array(0xFFFA, 0xFFFA),		// INTERLINEAR ANNOTATION SEPARATOR
ef5584
		array(0xFFFB, 0xFFFB),		// INTERLINEAR ANNOTATION TERMINATOR
ef5584
		array(0xFFFC, 0xFFFC),		// OBJECT REPLACEMENT CHARACTER
ef5584
		array(0xFFFD, 0xFFFD),		// REPLACEMENT CHARACTER
ef5584
		// Table C.7
ef5584
		array(0x2FF0, 0x2FFB),		// [IDEOGRAPHIC DESCRIPTION CHARACTERS]
ef5584
		// Table C.8
ef5584
		array(0x0340, 0x0340),		// COMBINING GRAVE TONE MARK
ef5584
		array(0x0341, 0x0341),		// COMBINING ACUTE TONE MARK
ef5584
		array(0x200E, 0x200E),		// LEFT-TO-RIGHT MARK
ef5584
		array(0x200F, 0x200F),		// RIGHT-TO-LEFT MARK
ef5584
		array(0x202A, 0x202A),		// LEFT-TO-RIGHT EMBEDDING
ef5584
		array(0x202B, 0x202B),		// RIGHT-TO-LEFT EMBEDDING
ef5584
		array(0x202C, 0x202C),		// POP DIRECTIONAL FORMATTING
ef5584
		array(0x202D, 0x202D),		// LEFT-TO-RIGHT OVERRIDE
ef5584
		array(0x202E, 0x202E),		// RIGHT-TO-LEFT OVERRIDE
ef5584
		array(0x206A, 0x206A),		// INHIBIT SYMMETRIC SWAPPING
ef5584
		array(0x206B, 0x206B),		// ACTIVATE SYMMETRIC SWAPPING
ef5584
		array(0x206C, 0x206C),		// INHIBIT ARABIC FORM SHAPING
ef5584
		array(0x206D, 0x206D),		// ACTIVATE ARABIC FORM SHAPING
ef5584
		array(0x206E, 0x206E),		// NATIONAL DIGIT SHAPES
ef5584
		array(0x206F, 0x206F),		// NOMINAL DIGIT SHAPES
ef5584
		// Table C.9
ef5584
		array(0xE0001, 0xE0001),	// LANGUAGE TAG
ef5584
		array(0xE0020, 0xE007F),	// [TAGGING CHARACTERS]
ef5584
		// RFC3920
ef5584
		array(0x22, 0x22),			// "
ef5584
		array(0x26, 0x26),			// &
ef5584
		array(0x27, 0x27),			// '
ef5584
		array(0x2F, 0x2F),			// /
ef5584
		array(0x3A, 0x3A),			// :
ef5584
		array(0x3C, 0x3C),			// <
ef5584
		array(0x3E, 0x3E),			// >
ef5584
		array(0x40, 0x40)			// @
ef5584
	);
ef5584
ef5584
	$pos = 0;
ef5584
	$result = true;
ef5584
ef5584
	while ($pos < strlen($username))
ef5584
	{
ef5584
		$len = $uni = 0;
ef5584
		for ($i = 0; $i <= 5; $i++)
ef5584
		{
ef5584
			if (ord($username[$pos]) >= $boundary[$i][0] && ord($username[$pos]) <= $boundary[$i][1])
ef5584
			{
ef5584
				$len = $i + 1;
ef5584
				$uni = (ord($username[$pos]) - $boundary[$i][0]) * pow(2, $i * 6);
ef5584
ef5584
				for ($k = 1; $k < $len; $k++)
ef5584
				{
ef5584
					$uni += (ord($username[$pos + $k]) - 128) * pow(2, ($i - $k) * 6);
ef5584
				}
ef5584
ef5584
				break;
ef5584
			}
ef5584
		}
ef5584
ef5584
		if ($len == 0)
ef5584
		{
ef5584
			return 'WRONG_DATA';
ef5584
		}
ef5584
ef5584
		foreach ($prohibited as $pval)
ef5584
		{
ef5584
			if ($uni >= $pval[0] && $uni <= $pval[1])
ef5584
			{
ef5584
				$result = false;
ef5584
				break 2;
ef5584
			}
ef5584
		}
ef5584
ef5584
		$pos = $pos + $len;
ef5584
	}
ef5584
ef5584
	if (!$result)
ef5584
	{
ef5584
		return 'WRONG_DATA';
ef5584
	}
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Remove avatar
ef5584
*/
ef5584
function avatar_delete($mode, $row, $clean_db = false)
ef5584
{
ef5584
	global $phpbb_root_path, $config, $db, $user;
ef5584
ef5584
	// Check if the users avatar is actually *not* a group avatar
ef5584
	if ($mode == 'user')
ef5584
	{
ef5584
		if (strpos($row['user_avatar'], 'g') === 0 || (((int)$row['user_avatar'] !== 0) && ((int)$row['user_avatar'] !== (int)$row['user_id'])))
ef5584
		{
ef5584
			return false;
ef5584
		}
ef5584
	}
ef5584
ef5584
	if ($clean_db)
ef5584
	{
ef5584
		avatar_remove_db($row[$mode . '_avatar']);
ef5584
	}
ef5584
	$filename = get_avatar_filename($row[$mode . '_avatar']);
ef5584
	if (file_exists($phpbb_root_path . $config['avatar_path'] . '/' . $filename))
ef5584
	{
ef5584
		@unlink($phpbb_root_path . $config['avatar_path'] . '/' . $filename);
ef5584
		return true;
ef5584
	}
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Remote avatar linkage
ef5584
*/
ef5584
function avatar_remote($data, &$error)
ef5584
{
ef5584
	global $config, $db, $user, $phpbb_root_path, $phpEx;
ef5584
ef5584
	if (!preg_match('#^(http|https|ftp)://#i', $data['remotelink']))
ef5584
	{
ef5584
		$data['remotelink'] = 'http://' . $data['remotelink'];
ef5584
	}
ef5584
	if (!preg_match('#^(http|https|ftp)://(?:(.*?\.)*?[a-z0-9\-]+?\.[a-z]{2,4}|(?:\d{1,3}\.){3,5}\d{1,3}):?([0-9]*?).*?\.(gif|jpg|jpeg|png)$#i', $data['remotelink']))
ef5584
	{
ef5584
		$error[] = $user->lang['AVATAR_URL_INVALID'];
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	// Make sure getimagesize works...
ef5584
	if (($image_data = @getimagesize($data['remotelink'])) === false && (empty($data['width']) || empty($data['height'])))
ef5584
	{
ef5584
		$error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	if (!empty($image_data) && ($image_data[0] < 2 || $image_data[1] < 2))
ef5584
	{
ef5584
		$error[] = $user->lang['AVATAR_NO_SIZE'];
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	$width = ($data['width'] && $data['height']) ? $data['width'] : $image_data[0];
ef5584
	$height = ($data['width'] && $data['height']) ? $data['height'] : $image_data[1];
ef5584
ef5584
	if ($width < 2 || $height < 2)
ef5584
	{
ef5584
		$error[] = $user->lang['AVATAR_NO_SIZE'];
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	// Check image type
ef5584
	include_once($phpbb_root_path . 'includes/functions_upload.' . $phpEx);
ef5584
	$types = fileupload::image_types();
ef5584
	$extension = strtolower(filespec::get_extension($data['remotelink']));
ef5584
ef5584
	if (!empty($image_data) && (!isset($types[$image_data[2]]) || !in_array($extension, $types[$image_data[2]])))
ef5584
	{
ef5584
		if (!isset($types[$image_data[2]]))
ef5584
		{
ef5584
			$error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$error[] = sprintf($user->lang['IMAGE_FILETYPE_MISMATCH'], $types[$image_data[2]][0], $extension);
ef5584
		}
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	if ($config['avatar_max_width'] || $config['avatar_max_height'])
ef5584
	{
ef5584
		if ($width > $config['avatar_max_width'] || $height > $config['avatar_max_height'])
ef5584
		{
ef5584
			$error[] = sprintf($user->lang['AVATAR_WRONG_SIZE'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], $width, $height);
ef5584
			return false;
ef5584
		}
ef5584
	}
ef5584
ef5584
	if ($config['avatar_min_width'] || $config['avatar_min_height'])
ef5584
	{
ef5584
		if ($width < $config['avatar_min_width'] || $height < $config['avatar_min_height'])
ef5584
		{
ef5584
			$error[] = sprintf($user->lang['AVATAR_WRONG_SIZE'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], $width, $height);
ef5584
			return false;
ef5584
		}
ef5584
	}
ef5584
ef5584
	return array(AVATAR_REMOTE, $data['remotelink'], $width, $height);
ef5584
}
ef5584
ef5584
/**
ef5584
* Avatar upload using the upload class
ef5584
*/
ef5584
function avatar_upload($data, &$error)
ef5584
{
ef5584
	global $phpbb_root_path, $config, $db, $user, $phpEx;
ef5584
ef5584
	// Init upload class
ef5584
	include_once($phpbb_root_path . 'includes/functions_upload.' . $phpEx);
ef5584
	$upload = new fileupload('AVATAR_', array('jpg', 'jpeg', 'gif', 'png'), $config['avatar_filesize'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], explode('|', $config['mime_triggers']));
ef5584
ef5584
	if (!empty($_FILES['uploadfile']['name']))
ef5584
	{
ef5584
		$file = $upload->form_upload('uploadfile');
ef5584
	}
ef5584
	else
ef5584
	{
ef5584
		$file = $upload->remote_upload($data['uploadurl']);
ef5584
	}
ef5584
ef5584
	$prefix = $config['avatar_salt'] . '_';
ef5584
	$file->clean_filename('avatar', $prefix, $data['user_id']);
ef5584
ef5584
	$destination = $config['avatar_path'];
ef5584
ef5584
	// Adjust destination path (no trailing slash)
ef5584
	if (substr($destination, -1, 1) == '/' || substr($destination, -1, 1) == '\\')
ef5584
	{
ef5584
		$destination = substr($destination, 0, -1);
ef5584
	}
ef5584
ef5584
	$destination = str_replace(array('../', '..\\', './', '.\\'), '', $destination);
ef5584
	if ($destination && ($destination[0] == '/' || $destination[0] == "\\"))
ef5584
	{
ef5584
		$destination = '';
ef5584
	}
ef5584
ef5584
	// Move file and overwrite any existing image
ef5584
	$file->move_file($destination, true);
ef5584
ef5584
	if (sizeof($file->error))
ef5584
	{
ef5584
		$file->remove();
ef5584
		$error = array_merge($error, $file->error);
ef5584
	}
ef5584
ef5584
	return array(AVATAR_UPLOAD, $data['user_id'] . '_' . time() . '.' . $file->get('extension'), $file->get('width'), $file->get('height'));
ef5584
}
ef5584
ef5584
/**
ef5584
* Generates avatar filename from the database entry
ef5584
*/
ef5584
function get_avatar_filename($avatar_entry)
ef5584
{
ef5584
	global $config;
ef5584
ef5584
ef5584
	if ($avatar_entry[0] === 'g')
ef5584
	{
ef5584
		$avatar_group = true;
ef5584
		$avatar_entry = substr($avatar_entry, 1);
ef5584
	}
ef5584
	else
ef5584
	{
ef5584
		$avatar_group = false;
ef5584
	}
ef5584
	$ext 			= substr(strrchr($avatar_entry, '.'), 1);
ef5584
	$avatar_entry	= intval($avatar_entry);
ef5584
	return $config['avatar_salt'] . '_' . (($avatar_group) ? 'g' : '') . $avatar_entry . '.' . $ext;
ef5584
}
ef5584
ef5584
/**
ef5584
* Avatar Gallery
ef5584
*/
ef5584
function avatar_gallery($category, $avatar_select, $items_per_column, $block_var = 'avatar_row')
ef5584
{
ef5584
	global $user, $cache, $template;
ef5584
	global $config, $phpbb_root_path;
ef5584
ef5584
	$avatar_list = array();
ef5584
ef5584
	$path = $phpbb_root_path . $config['avatar_gallery_path'];
ef5584
ef5584
	if (!file_exists($path) || !is_dir($path))
ef5584
	{
ef5584
		$avatar_list = array($user->lang['NO_AVATAR_CATEGORY'] => array());
ef5584
	}
ef5584
	else
ef5584
	{
ef5584
		// Collect images
ef5584
		$dp = @opendir($path);
ef5584
ef5584
		if (!$dp)
ef5584
		{
ef5584
			return array($user->lang['NO_AVATAR_CATEGORY'] => array());
ef5584
		}
ef5584
ef5584
		while (($file = readdir($dp)) !== false)
ef5584
		{
ef5584
			if ($file[0] != '.' && preg_match('#^[^&"\'<>]+$#i', $file) && is_dir("$path/$file"))
ef5584
			{
ef5584
				$avatar_row_count = $avatar_col_count = 0;
ef5584
ef5584
				if ($dp2 = @opendir("$path/$file"))
ef5584
				{
ef5584
					while (($sub_file = readdir($dp2)) !== false)
ef5584
					{
ef5584
						if (preg_match('#^[^&\'"<>]+\.(?:gif|png|jpe?g)$#i', $sub_file))
ef5584
						{
ef5584
							$avatar_list[$file][$avatar_row_count][$avatar_col_count] = array(
ef5584
								'file'		=> "$file/$sub_file",
ef5584
								'filename'	=> $sub_file,
ef5584
								'name'		=> ucfirst(str_replace('_', ' ', preg_replace('#^(.*)\..*$#', '\1', $sub_file))),
ef5584
							);
ef5584
							$avatar_col_count++;
ef5584
							if ($avatar_col_count == $items_per_column)
ef5584
							{
ef5584
								$avatar_row_count++;
ef5584
								$avatar_col_count = 0;
ef5584
							}
ef5584
						}
ef5584
					}
ef5584
					closedir($dp2);
ef5584
				}
ef5584
			}
ef5584
		}
ef5584
		closedir($dp);
ef5584
	}
ef5584
ef5584
	if (!sizeof($avatar_list))
ef5584
	{
ef5584
		$avatar_list = array($user->lang['NO_AVATAR_CATEGORY'] => array());
ef5584
	}
ef5584
ef5584
	@ksort($avatar_list);
ef5584
ef5584
	$category = (!$category) ? key($avatar_list) : $category;
ef5584
	$avatar_categories = array_keys($avatar_list);
ef5584
ef5584
	$s_category_options = '';
ef5584
	foreach ($avatar_categories as $cat)
ef5584
	{
ef5584
		$s_category_options .= '<option value="' . $cat . '"' . (($cat == $category) ? ' selected="selected"' : '') . '>' . $cat . '</option>';
ef5584
	}
ef5584
ef5584
	$template->assign_vars(array(
ef5584
		'S_AVATARS_ENABLED'		=> true,
ef5584
		'S_IN_AVATAR_GALLERY'	=> true,
ef5584
		'S_CAT_OPTIONS'			=> $s_category_options)
ef5584
	);
ef5584
ef5584
	$avatar_list = (isset($avatar_list[$category])) ? $avatar_list[$category] : array();
ef5584
ef5584
	foreach ($avatar_list as $avatar_row_ary)
ef5584
	{
ef5584
		$template->assign_block_vars($block_var, array());
ef5584
ef5584
		foreach ($avatar_row_ary as $avatar_col_ary)
ef5584
		{
ef5584
			$template->assign_block_vars($block_var . '.avatar_column', array(
ef5584
				'AVATAR_IMAGE'	=> $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar_col_ary['file'],
ef5584
				'AVATAR_NAME'	=> $avatar_col_ary['name'],
ef5584
				'AVATAR_FILE'	=> $avatar_col_ary['filename'])
ef5584
			);
ef5584
ef5584
			$template->assign_block_vars($block_var . '.avatar_option_column', array(
ef5584
				'AVATAR_IMAGE'	=> $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar_col_ary['file'],
ef5584
				'S_OPTIONS_AVATAR'	=> $avatar_col_ary['filename'])
ef5584
			);
ef5584
		}
ef5584
	}
ef5584
ef5584
	return $avatar_list;
ef5584
}
ef5584
ef5584
ef5584
/**
ef5584
* Tries to (re-)establish avatar dimensions
ef5584
*/
ef5584
function avatar_get_dimensions($avatar, $avatar_type, &$error, $current_x = 0, $current_y = 0)
ef5584
{
ef5584
	global $config, $phpbb_root_path, $user;
ef5584
ef5584
	switch ($avatar_type)
ef5584
	{
ef5584
		case AVATAR_REMOTE :
ef5584
			break;
ef5584
ef5584
		case AVATAR_UPLOAD :
ef5584
			$avatar = $phpbb_root_path . $config['avatar_path'] . '/' . get_avatar_filename($avatar);
ef5584
			break;
ef5584
ef5584
		case AVATAR_GALLERY :
ef5584
			$avatar = $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar ;
ef5584
			break;
ef5584
	}
ef5584
ef5584
	// Make sure getimagesize works...
ef5584
	if (($image_data = @getimagesize($avatar)) === false)
ef5584
	{
ef5584
		$error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	if ($image_data[0] < 2 || $image_data[1] < 2)
ef5584
	{
ef5584
		$error[] = $user->lang['AVATAR_NO_SIZE'];
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	// try to maintain ratio
ef5584
	if (!(empty($current_x) && empty($current_y)))
ef5584
	{
ef5584
		if ($current_x != 0)
ef5584
		{
ef5584
			$image_data[1] = (int) floor(($current_x / $image_data[0]) * $image_data[1]);
ef5584
			$image_data[1] = min($config['avatar_max_height'], $image_data[1]);
ef5584
			$image_data[1] = max($config['avatar_min_height'], $image_data[1]);
ef5584
		}
ef5584
		if ($current_y != 0)
ef5584
		{
ef5584
			$image_data[0] = (int) floor(($current_y / $image_data[1]) * $image_data[0]);
ef5584
			$image_data[0] = min($config['avatar_max_width'], $image_data[1]);
ef5584
			$image_data[0] = max($config['avatar_min_width'], $image_data[1]);
ef5584
		}
ef5584
	}
ef5584
	return array($image_data[0], $image_data[1]);
ef5584
}
ef5584
ef5584
/**
ef5584
* Uploading/Changing user avatar
ef5584
*/
ef5584
function avatar_process_user(&$error, $custom_userdata = false)
ef5584
{
ef5584
	global $config, $phpbb_root_path, $auth, $user, $db;
ef5584
ef5584
	$data = array(
ef5584
		'uploadurl'		=> request_var('uploadurl', ''),
ef5584
		'remotelink'	=> request_var('remotelink', ''),
ef5584
		'width'			=> request_var('width', 0),
ef5584
		'height'		=> request_var('height', 0),
ef5584
	);
ef5584
ef5584
	$error = validate_data($data, array(
ef5584
		'uploadurl'		=> array('string', true, 5, 255),
ef5584
		'remotelink'	=> array('string', true, 5, 255),
ef5584
		'width'			=> array('string', true, 1, 3),
ef5584
		'height'		=> array('string', true, 1, 3),
ef5584
	));
ef5584
ef5584
	if (sizeof($error))
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	$sql_ary = array();
ef5584
ef5584
	if ($custom_userdata === false)
ef5584
	{
ef5584
		$userdata = &$user->data;
ef5584
	}
ef5584
	else
ef5584
	{
ef5584
		$userdata = &$custom_userdata;
ef5584
	}
ef5584
ef5584
	$data['user_id'] = $userdata['user_id'];
ef5584
	$change_avatar = ($custom_userdata === false) ? $auth->acl_get('u_chgavatar') : true;
ef5584
	$avatar_select = basename(request_var('avatar_select', ''));
ef5584
ef5584
	// Can we upload?
ef5584
	$can_upload = ($config['allow_avatar_upload'] && file_exists($phpbb_root_path . $config['avatar_path']) && @is_writable($phpbb_root_path . $config['avatar_path']) && $change_avatar && (@ini_get('file_uploads') || strtolower(@ini_get('file_uploads')) == 'on')) ? true : false;
ef5584
ef5584
	if ((!empty($_FILES['uploadfile']['name']) || $data['uploadurl']) && $can_upload)
ef5584
	{
ef5584
		list($sql_ary['user_avatar_type'], $sql_ary['user_avatar'], $sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = avatar_upload($data, $error);
ef5584
	}
ef5584
	else if ($data['remotelink'] && $change_avatar && $config['allow_avatar_remote'])
ef5584
	{
ef5584
		list($sql_ary['user_avatar_type'], $sql_ary['user_avatar'], $sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = avatar_remote($data, $error);
ef5584
	}
ef5584
	else if ($avatar_select && $change_avatar && $config['allow_avatar_local'])
ef5584
	{
ef5584
		$category = basename(request_var('category', ''));
ef5584
ef5584
		$sql_ary['user_avatar_type'] = AVATAR_GALLERY;
ef5584
		$sql_ary['user_avatar'] = $avatar_select;
ef5584
ef5584
		// check avatar gallery
ef5584
		if (!is_dir($phpbb_root_path . $config['avatar_gallery_path'] . '/' . $category))
ef5584
		{
ef5584
			$sql_ary['user_avatar'] = '';
ef5584
			$sql_ary['user_avatar_type'] = $sql_ary['user_avatar_width'] = $sql_ary['user_avatar_height'] = 0;
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			list($sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = getimagesize($phpbb_root_path . $config['avatar_gallery_path'] . '/' . $category . '/' . $sql_ary['user_avatar']);
ef5584
			$sql_ary['user_avatar'] = $category . '/' . $sql_ary['user_avatar'];
ef5584
		}
ef5584
	}
ef5584
	else if (isset($_POST['delete']) && $change_avatar)
ef5584
	{
ef5584
		$sql_ary['user_avatar'] = '';
ef5584
		$sql_ary['user_avatar_type'] = $sql_ary['user_avatar_width'] = $sql_ary['user_avatar_height'] = 0;
ef5584
	}
ef5584
	else if (!empty($userdata['user_avatar']))
ef5584
	{
ef5584
		// Only update the dimensions
ef5584
ef5584
		if (empty($data['width']) || empty($data['height']))
ef5584
		{
ef5584
			if ($dims = avatar_get_dimensions($userdata['user_avatar'], $userdata['user_avatar_type'], $error, $data['width'], $data['height']))
ef5584
			{
ef5584
				list($guessed_x, $guessed_y) = $dims;
ef5584
				if (empty($data['width']))
ef5584
				{
ef5584
					$data['width'] = $guessed_x;
ef5584
				}
ef5584
				if (empty($data['height']))
ef5584
				{
ef5584
					$data['height'] = $guessed_y;
ef5584
				}
ef5584
			}
ef5584
		}
ef5584
		if (($config['avatar_max_width'] || $config['avatar_max_height']) &&
ef5584
			(($data['width'] != $userdata['user_avatar_width']) || $data['height'] != $userdata['user_avatar_height']))
ef5584
		{
ef5584
			if ($data['width'] > $config['avatar_max_width'] || $data['height'] > $config['avatar_max_height'])
ef5584
			{
ef5584
				$error[] = sprintf($user->lang['AVATAR_WRONG_SIZE'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], $data['width'], $data['height']);
ef5584
			}
ef5584
		}
ef5584
ef5584
		if (!sizeof($error))
ef5584
		{
ef5584
			if ($config['avatar_min_width'] || $config['avatar_min_height'])
ef5584
			{
ef5584
				if ($data['width'] < $config['avatar_min_width'] || $data['height'] < $config['avatar_min_height'])
ef5584
				{
ef5584
					$error[] = sprintf($user->lang['AVATAR_WRONG_SIZE'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], $data['width'], $data['height']);
ef5584
				}
ef5584
			}
ef5584
		}
ef5584
ef5584
		if (!sizeof($error))
ef5584
		{
ef5584
			$sql_ary['user_avatar_width'] = $data['width'];
ef5584
			$sql_ary['user_avatar_height'] = $data['height'];
ef5584
		}
ef5584
	}
ef5584
ef5584
	if (!sizeof($error))
ef5584
	{
ef5584
		// Do we actually have any data to update?
ef5584
		if (sizeof($sql_ary))
ef5584
		{
ef5584
			$ext_new = $ext_old = '';
ef5584
			if (isset($sql_ary['user_avatar']))
ef5584
			{
ef5584
				$userdata = ($custom_userdata === false) ? $user->data : $custom_userdata;
ef5584
				$ext_new = (empty($sql_ary['user_avatar'])) ? '' : substr(strrchr($sql_ary['user_avatar'], '.'), 1);
ef5584
				$ext_old = (empty($userdata['user_avatar'])) ? '' : substr(strrchr($userdata['user_avatar'], '.'), 1);
ef5584
ef5584
				if ($userdata['user_avatar_type'] == AVATAR_UPLOAD)
ef5584
				{
ef5584
					// Delete old avatar if present
ef5584
					if ((!empty($userdata['user_avatar']) && empty($sql_ary['user_avatar']))
ef5584
					   || ( !empty($userdata['user_avatar']) && !empty($sql_ary['user_avatar']) && $ext_new !== $ext_old))
ef5584
					{
ef5584
						avatar_delete('user', $userdata);
ef5584
					}
ef5584
				}
ef5584
			}
ef5584
ef5584
			$sql = 'UPDATE ' . USERS_TABLE . '
ef5584
				SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
ef5584
				WHERE user_id = ' . (($custom_userdata === false) ? $user->data['user_id'] : $custom_userdata['user_id']);
ef5584
			$db->sql_query($sql);
ef5584
ef5584
		}
ef5584
	}
ef5584
ef5584
	return (sizeof($error)) ? false : true;
ef5584
}
ef5584
ef5584
//
ef5584
// Usergroup functions
ef5584
//
ef5584
ef5584
/**
ef5584
* Add or edit a group. If we're editing a group we only update user
ef5584
* parameters such as rank, etc. if they are changed
ef5584
*/
ef5584
function group_create(&$group_id, $type, $name, $desc, $group_attributes, $allow_desc_bbcode = false, $allow_desc_urls = false, $allow_desc_smilies = false)
ef5584
{
ef5584
	global $phpbb_root_path, $config, $db, $user, $file_upload;
ef5584
ef5584
	$error = array();
ef5584
	$attribute_ary = array(
ef5584
		'group_colour'			=> 'string',
ef5584
		'group_rank'			=> 'int',
ef5584
		'group_avatar'			=> 'string',
ef5584
		'group_avatar_type'		=> 'int',
ef5584
		'group_avatar_width'	=> 'int',
ef5584
		'group_avatar_height'	=> 'int',
ef5584
ef5584
		'group_receive_pm'		=> 'int',
ef5584
		'group_legend'			=> 'int',
ef5584
		'group_message_limit'	=> 'int',
ef5584
		'group_max_recipients'	=> 'int',
ef5584
ef5584
		'group_founder_manage'	=> 'int',
ef5584
	);
ef5584
ef5584
	// Those are group-only attributes
ef5584
	$group_only_ary = array('group_receive_pm', 'group_legend', 'group_message_limit', 'group_max_recipients', 'group_founder_manage');
ef5584
ef5584
	// Check data. Limit group name length.
ef5584
	if (!utf8_strlen($name) || utf8_strlen($name) > 60)
ef5584
	{
ef5584
		$error[] = (!utf8_strlen($name)) ? $user->lang['GROUP_ERR_USERNAME'] : $user->lang['GROUP_ERR_USER_LONG'];
ef5584
	}
ef5584
ef5584
	$err = group_validate_groupname($group_id, $name);
ef5584
	if (!empty($err))
ef5584
	{
ef5584
		$error[] = $user->lang[$err];
ef5584
	}
ef5584
ef5584
	if (!in_array($type, array(GROUP_OPEN, GROUP_CLOSED, GROUP_HIDDEN, GROUP_SPECIAL, GROUP_FREE)))
ef5584
	{
ef5584
		$error[] = $user->lang['GROUP_ERR_TYPE'];
ef5584
	}
ef5584
ef5584
	if (!sizeof($error))
ef5584
	{
ef5584
		$user_ary = array();
ef5584
		$sql_ary = array(
ef5584
			'group_name'			=> (string) $name,
ef5584
			'group_desc'			=> (string) $desc,
ef5584
			'group_desc_uid'		=> '',
ef5584
			'group_desc_bitfield'	=> '',
ef5584
			'group_type'			=> (int) $type,
ef5584
		);
ef5584
ef5584
		// Parse description
ef5584
		if ($desc)
ef5584
		{
ef5584
			generate_text_for_storage($sql_ary['group_desc'], $sql_ary['group_desc_uid'], $sql_ary['group_desc_bitfield'], $sql_ary['group_desc_options'], $allow_desc_bbcode, $allow_desc_urls, $allow_desc_smilies);
ef5584
		}
ef5584
ef5584
		if (sizeof($group_attributes))
ef5584
		{
ef5584
			foreach ($attribute_ary as $attribute => $_type)
ef5584
			{
ef5584
				if (isset($group_attributes[$attribute]))
ef5584
				{
ef5584
					settype($group_attributes[$attribute], $_type);
ef5584
					$sql_ary[$attribute] = $group_attributes[$attribute];
ef5584
				}
ef5584
			}
ef5584
		}
ef5584
ef5584
		// Setting the log message before we set the group id (if group gets added)
ef5584
		$log = ($group_id) ? 'LOG_GROUP_UPDATED' : 'LOG_GROUP_CREATED';
ef5584
ef5584
		$query = '';
ef5584
ef5584
		if ($group_id)
ef5584
		{
ef5584
			$sql = 'SELECT user_id
ef5584
				FROM ' . USERS_TABLE . '
ef5584
				WHERE group_id = ' . $group_id;
ef5584
			$result = $db->sql_query($sql);
ef5584
ef5584
			while ($row = $db->sql_fetchrow($result))
ef5584
			{
ef5584
				$user_ary[] = $row['user_id'];
ef5584
			}
ef5584
			$db->sql_freeresult($result);
ef5584
ef5584
			if (isset($sql_ary['group_avatar']) && !$sql_ary['group_avatar'])
ef5584
			{
ef5584
				remove_default_avatar($group_id, $user_ary);
ef5584
			}
ef5584
			if (isset($sql_ary['group_rank']) && !$sql_ary['group_rank'])
ef5584
			{
ef5584
				remove_default_rank($group_id, $user_ary);
ef5584
			}
ef5584
ef5584
			$sql = 'UPDATE ' . GROUPS_TABLE . '
ef5584
				SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
ef5584
				WHERE group_id = $group_id";
ef5584
			$db->sql_query($sql);
ef5584
ef5584
			// Since we may update the name too, we need to do this on other tables too...
ef5584
			$sql = 'UPDATE ' . MODERATOR_CACHE_TABLE . "
ef5584
				SET group_name = '" . $db->sql_escape($sql_ary['group_name']) . "'
ef5584
				WHERE group_id = $group_id";
ef5584
			$db->sql_query($sql);
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$sql = 'INSERT INTO ' . GROUPS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
ef5584
			$db->sql_query($sql);
ef5584
		}
ef5584
ef5584
		if (!$group_id)
ef5584
		{
ef5584
			$group_id = $db->sql_nextid();
ef5584
			if (isset($sql_ary['group_avatar_type']) && $sql_ary['group_avatar_type'] == AVATAR_UPLOAD)
ef5584
			{
ef5584
				group_correct_avatar($group_id, $sql_ary['group_avatar']);
ef5584
			}
ef5584
		}
ef5584
ef5584
		// Set user attributes
ef5584
		$sql_ary = array();
ef5584
		if (sizeof($group_attributes))
ef5584
		{
ef5584
			foreach ($attribute_ary as $attribute => $_type)
ef5584
			{
ef5584
				if (isset($group_attributes[$attribute]) && !in_array($attribute, $group_only_ary))
ef5584
				{
ef5584
					// If we are about to set an avatar, we will not overwrite user avatars if no group avatar is set...
ef5584
					if (strpos($attribute, 'group_avatar') === 0 && !$group_attributes[$attribute])
ef5584
					{
ef5584
						continue;
ef5584
					}
ef5584
ef5584
					$sql_ary[$attribute] = $group_attributes[$attribute];
ef5584
				}
ef5584
			}
ef5584
		}
ef5584
ef5584
		if (sizeof($sql_ary) && sizeof($user_ary))
ef5584
		{
ef5584
			group_set_user_default($group_id, $user_ary, $sql_ary);
ef5584
		}
ef5584
ef5584
		$name = ($type == GROUP_SPECIAL) ? $user->lang['G_' . $name] : $name;
ef5584
		add_log('admin', $log, $name);
ef5584
ef5584
		group_update_listings($group_id);
ef5584
	}
ef5584
ef5584
	return (sizeof($error)) ? $error : false;
ef5584
}
ef5584
ef5584
ef5584
/**
ef5584
* Changes a group avatar's filename to conform to the naming scheme
ef5584
*/
ef5584
function group_correct_avatar($group_id, $old_entry)
ef5584
{
ef5584
	global $config, $db, $phpbb_root_path;
ef5584
ef5584
	$group_id		= (int)$group_id;
ef5584
	$ext 			= substr(strrchr($old_entry, '.'), 1);
ef5584
	$old_filename 	= get_avatar_filename($old_entry);
ef5584
	$new_filename 	= $config['avatar_salt'] . "_g$group_id.$ext";
ef5584
	$new_entry 		= 'g' . $group_id . '_' . substr(time(), -5) . ".$ext";
ef5584
ef5584
	$avatar_path = $phpbb_root_path . $config['avatar_path'];
ef5584
	if (@rename($avatar_path . '/'. $old_filename, $avatar_path . '/' . $new_filename))
ef5584
	{
ef5584
		$sql = 'UPDATE ' . GROUPS_TABLE . '
ef5584
			SET group_avatar = \'' . $db->sql_escape($new_entry) . "'
ef5584
			WHERE group_id = $group_id";
ef5584
		$db->sql_query($sql);
ef5584
	}
ef5584
}
ef5584
ef5584
ef5584
/**
ef5584
* Remove avatar also for users not having the group as default
ef5584
*/
ef5584
function avatar_remove_db($avatar_name)
ef5584
{
ef5584
	global $config, $db;
ef5584
ef5584
	$sql = 'UPDATE ' . USERS_TABLE . "
ef5584
		SET user_avatar = '',
ef5584
		user_avatar_type = 0
ef5584
		WHERE user_avatar = '" . $db->sql_escape($avatar_name) . '\'';
ef5584
	$db->sql_query($sql);
ef5584
}
ef5584
ef5584
ef5584
/**
ef5584
* Group Delete
ef5584
*/
ef5584
function group_delete($group_id, $group_name = false)
ef5584
{
ef5584
	global $db, $phpbb_root_path, $phpEx;
ef5584
ef5584
	if (!$group_name)
ef5584
	{
ef5584
		$group_name = get_group_name($group_id);
ef5584
	}
ef5584
ef5584
	$start = 0;
ef5584
ef5584
	do
ef5584
	{
ef5584
		$user_id_ary = $username_ary = array();
ef5584
ef5584
		// Batch query for group members, call group_user_del
ef5584
		$sql = 'SELECT u.user_id, u.username
ef5584
			FROM ' . USER_GROUP_TABLE . ' ug, ' . USERS_TABLE . " u
ef5584
			WHERE ug.group_id = $group_id
ef5584
				AND u.user_id = ug.user_id";
ef5584
		$result = $db->sql_query_limit($sql, 200, $start);
ef5584
ef5584
		if ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			do
ef5584
			{
ef5584
				$user_id_ary[] = $row['user_id'];
ef5584
				$username_ary[] = $row['username'];
ef5584
ef5584
				$start++;
ef5584
			}
ef5584
			while ($row = $db->sql_fetchrow($result));
ef5584
ef5584
			group_user_del($group_id, $user_id_ary, $username_ary, $group_name);
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$start = 0;
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
	}
ef5584
	while ($start);
ef5584
ef5584
	// Delete group
ef5584
	$sql = 'DELETE FROM ' . GROUPS_TABLE . "
ef5584
		WHERE group_id = $group_id";
ef5584
	$db->sql_query($sql);
ef5584
ef5584
	// Delete auth entries from the groups table
ef5584
	$sql = 'DELETE FROM ' . ACL_GROUPS_TABLE . "
ef5584
		WHERE group_id = $group_id";
ef5584
	$db->sql_query($sql);
ef5584
ef5584
	// Re-cache moderators
ef5584
	if (!function_exists('cache_moderators'))
ef5584
	{
ef5584
		include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
ef5584
	}
ef5584
ef5584
	cache_moderators();
ef5584
ef5584
	add_log('admin', 'LOG_GROUP_DELETE', $group_name);
ef5584
ef5584
	// Return false - no error
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Add user(s) to group
ef5584
*
ef5584
* @return mixed false if no errors occurred, else the user lang string for the relevant error, for example 'NO_USER'
ef5584
*/
ef5584
function group_user_add($group_id, $user_id_ary = false, $username_ary = false, $group_name = false, $default = false, $leader = 0, $pending = 0, $group_attributes = false)
ef5584
{
ef5584
	global $db, $auth;
ef5584
ef5584
	// We need both username and user_id info
ef5584
	$result = user_get_id_name($user_id_ary, $username_ary);
ef5584
ef5584
	if (!sizeof($user_id_ary) || $result !== false)
ef5584
	{
ef5584
		return 'NO_USER';
ef5584
	}
ef5584
ef5584
	// Remove users who are already members of this group
ef5584
	$sql = 'SELECT user_id, group_leader
ef5584
		FROM ' . USER_GROUP_TABLE . '
ef5584
		WHERE ' . $db->sql_in_set('user_id', $user_id_ary) . "
ef5584
			AND group_id = $group_id";
ef5584
	$result = $db->sql_query($sql);
ef5584
ef5584
	$add_id_ary = $update_id_ary = array();
ef5584
	while ($row = $db->sql_fetchrow($result))
ef5584
	{
ef5584
		$add_id_ary[] = (int) $row['user_id'];
ef5584
ef5584
		if ($leader && !$row['group_leader'])
ef5584
		{
ef5584
			$update_id_ary[] = (int) $row['user_id'];
ef5584
		}
ef5584
	}
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	// Do all the users exist in this group?
ef5584
	$add_id_ary = array_diff($user_id_ary, $add_id_ary);
ef5584
ef5584
	// If we have no users
ef5584
	if (!sizeof($add_id_ary) && !sizeof($update_id_ary))
ef5584
	{
ef5584
		return 'GROUP_USERS_EXIST';
ef5584
	}
ef5584
ef5584
	$db->sql_transaction('begin');
ef5584
ef5584
	// Insert the new users
ef5584
	if (sizeof($add_id_ary))
ef5584
	{
ef5584
		$sql_ary = array();
ef5584
ef5584
		foreach ($add_id_ary as $user_id)
ef5584
		{
ef5584
			$sql_ary[] = array(
ef5584
				'user_id'		=> (int) $user_id,
ef5584
				'group_id'		=> (int) $group_id,
ef5584
				'group_leader'	=> (int) $leader,
ef5584
				'user_pending'	=> (int) $pending,
ef5584
			);
ef5584
		}
ef5584
ef5584
		$db->sql_multi_insert(USER_GROUP_TABLE, $sql_ary);
ef5584
	}
ef5584
ef5584
	if (sizeof($update_id_ary))
ef5584
	{
ef5584
		$sql = 'UPDATE ' . USER_GROUP_TABLE . '
ef5584
			SET group_leader = 1
ef5584
			WHERE ' . $db->sql_in_set('user_id', $update_id_ary) . "
ef5584
				AND group_id = $group_id";
ef5584
		$db->sql_query($sql);
ef5584
	}
ef5584
ef5584
	if ($default)
ef5584
	{
ef5584
		group_set_user_default($group_id, $user_id_ary, $group_attributes);
ef5584
	}
ef5584
ef5584
	$db->sql_transaction('commit');
ef5584
ef5584
	// Clear permissions cache of relevant users
ef5584
	$auth->acl_clear_prefetch($user_id_ary);
ef5584
ef5584
	if (!$group_name)
ef5584
	{
ef5584
		$group_name = get_group_name($group_id);
ef5584
	}
ef5584
ef5584
	$log = ($leader) ? 'LOG_MODS_ADDED' : 'LOG_USERS_ADDED';
ef5584
ef5584
	add_log('admin', $log, $group_name, implode(', ', $username_ary));
ef5584
ef5584
	group_update_listings($group_id);
ef5584
ef5584
	// Return false - no error
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Remove a user/s from a given group. When we remove users we update their
ef5584
* default group_id. We do this by examining which "special" groups they belong
ef5584
* to. The selection is made based on a reasonable priority system
ef5584
*
ef5584
* @return false if no errors occurred, else the user lang string for the relevant error, for example 'NO_USER'
ef5584
*/
ef5584
function group_user_del($group_id, $user_id_ary = false, $username_ary = false, $group_name = false)
ef5584
{
ef5584
	global $db, $auth;
ef5584
ef5584
	$group_order = array('ADMINISTRATORS', 'GLOBAL_MODERATORS', 'REGISTERED_COPPA', 'REGISTERED', 'BOTS', 'GUESTS');
ef5584
ef5584
	// We need both username and user_id info
ef5584
	$result = user_get_id_name($user_id_ary, $username_ary);
ef5584
ef5584
	if (!sizeof($user_id_ary) || $result !== false)
ef5584
	{
ef5584
		return 'NO_USER';
ef5584
	}
ef5584
ef5584
	$sql = 'SELECT *
ef5584
		FROM ' . GROUPS_TABLE . '
ef5584
		WHERE ' . $db->sql_in_set('group_name', $group_order);
ef5584
	$result = $db->sql_query($sql);
ef5584
ef5584
	$group_order_id = $special_group_data = array();
ef5584
	while ($row = $db->sql_fetchrow($result))
ef5584
	{
ef5584
		$group_order_id[$row['group_name']] = $row['group_id'];
ef5584
ef5584
		$special_group_data[$row['group_id']] = array(
ef5584
			'group_colour'			=> $row['group_colour'],
ef5584
			'group_rank'				=> $row['group_rank'],
ef5584
		);
ef5584
ef5584
		// Only set the group avatar if one is defined...
ef5584
		if ($row['group_avatar'])
ef5584
		{
ef5584
			$special_group_data[$row['group_id']] = array_merge($special_group_data[$row['group_id']], array(
ef5584
				'group_avatar'			=> $row['group_avatar'],
ef5584
				'group_avatar_type'		=> $row['group_avatar_type'],
ef5584
				'group_avatar_width'		=> $row['group_avatar_width'],
ef5584
				'group_avatar_height'	=> $row['group_avatar_height'])
ef5584
			);
ef5584
		}
ef5584
	}
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	// Get users default groups - we only need to reset default group membership if the group from which the user gets removed is set as default
ef5584
	$sql = 'SELECT user_id, group_id
ef5584
		FROM ' . USERS_TABLE . '
ef5584
		WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
ef5584
	$result = $db->sql_query($sql);
ef5584
ef5584
	$default_groups = array();
ef5584
	while ($row = $db->sql_fetchrow($result))
ef5584
	{
ef5584
		$default_groups[$row['user_id']] = $row['group_id'];
ef5584
	}
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	// What special group memberships exist for these users?
ef5584
	$sql = 'SELECT g.group_id, g.group_name, ug.user_id
ef5584
		FROM ' . USER_GROUP_TABLE . ' ug, ' . GROUPS_TABLE . ' g
ef5584
		WHERE ' . $db->sql_in_set('ug.user_id', $user_id_ary) . "
ef5584
			AND g.group_id = ug.group_id
ef5584
			AND g.group_id <> $group_id
ef5584
			AND g.group_type = " . GROUP_SPECIAL . '
ef5584
		ORDER BY ug.user_id, g.group_id';
ef5584
	$result = $db->sql_query($sql);
ef5584
ef5584
	$temp_ary = array();
ef5584
	while ($row = $db->sql_fetchrow($result))
ef5584
	{
ef5584
		if ($default_groups[$row['user_id']] == $group_id && (!isset($temp_ary[$row['user_id']]) || array_search($row['group_name'], $group_order) < $temp_ary[$row['user_id']]))
ef5584
		{
ef5584
			$temp_ary[$row['user_id']] = $row['group_id'];
ef5584
		}
ef5584
	}
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	$sql_where_ary = array();
ef5584
	foreach ($temp_ary as $uid => $gid)
ef5584
	{
ef5584
		$sql_where_ary[$gid][] = $uid;
ef5584
	}
ef5584
	unset($temp_ary);
ef5584
ef5584
	foreach ($special_group_data as $gid => $default_data_ary)
ef5584
	{
ef5584
		if (isset($sql_where_ary[$gid]) && sizeof($sql_where_ary[$gid]))
ef5584
		{
ef5584
			remove_default_rank($group_id, $sql_where_ary[$gid]);
ef5584
			remove_default_avatar($group_id, $sql_where_ary[$gid]);
ef5584
			group_set_user_default($gid, $sql_where_ary[$gid], $default_data_ary);
ef5584
		}
ef5584
	}
ef5584
	unset($special_group_data);
ef5584
ef5584
	$sql = 'DELETE FROM ' . USER_GROUP_TABLE . "
ef5584
		WHERE group_id = $group_id
ef5584
			AND " . $db->sql_in_set('user_id', $user_id_ary);
ef5584
	$db->sql_query($sql);
ef5584
ef5584
	// Clear permissions cache of relevant users
ef5584
	$auth->acl_clear_prefetch($user_id_ary);
ef5584
ef5584
	if (!$group_name)
ef5584
	{
ef5584
		$group_name = get_group_name($group_id);
ef5584
	}
ef5584
ef5584
	$log = 'LOG_GROUP_REMOVE';
ef5584
ef5584
	add_log('admin', $log, $group_name, implode(', ', $username_ary));
ef5584
ef5584
	group_update_listings($group_id);
ef5584
ef5584
	// Return false - no error
ef5584
	return false;
ef5584
}
ef5584
ef5584
ef5584
/**
ef5584
* Removes the group avatar of the default group from the users in user_ids who have that group as default.
ef5584
*/
ef5584
function remove_default_avatar($group_id, $user_ids)
ef5584
{
ef5584
	global $db;
ef5584
ef5584
	if (!is_array($user_ids))
ef5584
	{
ef5584
		$user_ids = array($user_ids);
ef5584
	}
ef5584
	if (empty($user_ids))
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	$user_ids = array_map('intval', $user_ids);
ef5584
ef5584
	$sql = 'SELECT *
ef5584
		FROM ' . GROUPS_TABLE . '
ef5584
		WHERE group_id = ' . (int)$group_id;
ef5584
	$result = $db->sql_query($sql);
ef5584
	if (!$row = $db->sql_fetchrow($result))
ef5584
	{
ef5584
		$db->sql_freeresult($result);
ef5584
		return false;
ef5584
	}
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	$sql = 'UPDATE ' . USERS_TABLE . "
ef5584
		SET user_avatar = '',
ef5584
			user_avatar_type = 0,
ef5584
			user_avatar_width = 0,
ef5584
			user_avatar_height = 0
ef5584
		WHERE group_id = " . (int) $group_id . "
ef5584
		AND user_avatar = '" . $db->sql_escape($row['group_avatar']) . "'
ef5584
		AND " . $db->sql_in_set('user_id', $user_ids);
ef5584
ef5584
	$db->sql_query($sql);
ef5584
}
ef5584
ef5584
/**
ef5584
* Removes the group rank of the default group from the users in user_ids who have that group as default.
ef5584
*/
ef5584
function remove_default_rank($group_id, $user_ids)
ef5584
{
ef5584
	global $db;
ef5584
ef5584
	if (!is_array($user_ids))
ef5584
	{
ef5584
		$user_ids = array($user_ids);
ef5584
	}
ef5584
	if (empty($user_ids))
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	$user_ids = array_map('intval', $user_ids);
ef5584
ef5584
	$sql = 'SELECT *
ef5584
		FROM ' . GROUPS_TABLE . '
ef5584
		WHERE group_id = ' . (int)$group_id;
ef5584
	$result = $db->sql_query($sql);
ef5584
	if (!$row = $db->sql_fetchrow($result))
ef5584
	{
ef5584
		$db->sql_freeresult($result);
ef5584
		return false;
ef5584
	}
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	$sql = 'UPDATE ' . USERS_TABLE . '
ef5584
		SET user_rank = 0
ef5584
		WHERE group_id = ' . (int)$group_id . '
ef5584
		AND user_rank <> 0
ef5584
		AND user_rank = ' . (int)$row['group_rank'] . '
ef5584
		AND ' . $db->sql_in_set('user_id', $user_ids);
ef5584
	$db->sql_query($sql);
ef5584
}
ef5584
ef5584
/**
ef5584
* This is used to promote (to leader), demote or set as default a member/s
ef5584
*/
ef5584
function group_user_attributes($action, $group_id, $user_id_ary = false, $username_ary = false, $group_name = false, $group_attributes = false)
ef5584
{
ef5584
	global $db, $auth, $phpbb_root_path, $phpEx, $config;
ef5584
ef5584
	// We need both username and user_id info
ef5584
	$result = user_get_id_name($user_id_ary, $username_ary);
ef5584
ef5584
	if (!sizeof($user_id_ary) || $result !== false)
ef5584
	{
ef5584
		return 'NO_USERS';
ef5584
	}
ef5584
ef5584
	if (!$group_name)
ef5584
	{
ef5584
		$group_name = get_group_name($group_id);
ef5584
	}
ef5584
ef5584
	switch ($action)
ef5584
	{
ef5584
		case 'demote':
ef5584
		case 'promote':
ef5584
ef5584
			$sql = 'SELECT user_id FROM ' . USER_GROUP_TABLE . "
ef5584
				WHERE group_id = $group_id
ef5584
					AND user_pending = 1
ef5584
					AND " . $db->sql_in_set('user_id', $user_id_ary);
ef5584
			$result = $db->sql_query_limit($sql, 1);
ef5584
			$not_empty = ($db->sql_fetchrow($result));
ef5584
			$db->sql_freeresult($result);
ef5584
			if ($not_empty)
ef5584
			{
ef5584
				return 'NO_VALID_USERS';
ef5584
			}
ef5584
ef5584
			$sql = 'UPDATE ' . USER_GROUP_TABLE . '
ef5584
				SET group_leader = ' . (($action == 'promote') ? 1 : 0) . "
ef5584
				WHERE group_id = $group_id
ef5584
					AND user_pending = 0
ef5584
					AND " . $db->sql_in_set('user_id', $user_id_ary);
ef5584
			$db->sql_query($sql);
ef5584
ef5584
			$log = ($action == 'promote') ? 'LOG_GROUP_PROMOTED' : 'LOG_GROUP_DEMOTED';
ef5584
		break;
ef5584
ef5584
		case 'approve':
ef5584
			// Make sure we only approve those which are pending ;)
ef5584
			$sql = 'SELECT u.user_id, u.user_email, u.username, u.username_clean, u.user_notify_type, u.user_jabber, u.user_lang
ef5584
				FROM ' . USERS_TABLE . ' u, ' . USER_GROUP_TABLE . ' ug
ef5584
				WHERE ug.group_id = ' . $group_id . '
ef5584
					AND ug.user_pending = 1
ef5584
					AND ug.user_id = u.user_id
ef5584
					AND ' . $db->sql_in_set('ug.user_id', $user_id_ary);
ef5584
			$result = $db->sql_query($sql);
ef5584
ef5584
			$user_id_ary = $email_users = array();
ef5584
			while ($row = $db->sql_fetchrow($result))
ef5584
			{
ef5584
				$user_id_ary[] = $row['user_id'];
ef5584
				$email_users[] = $row;
ef5584
			}
ef5584
			$db->sql_freeresult($result);
ef5584
ef5584
			if (!sizeof($user_id_ary))
ef5584
			{
ef5584
				return false;
ef5584
			}
ef5584
ef5584
			$sql = 'UPDATE ' . USER_GROUP_TABLE . "
ef5584
				SET user_pending = 0
ef5584
				WHERE group_id = $group_id
ef5584
					AND " . $db->sql_in_set('user_id', $user_id_ary);
ef5584
			$db->sql_query($sql);
ef5584
ef5584
			// Send approved email to users...
ef5584
			include_once($phpbb_root_path . 'includes/functions_messenger.' . $phpEx);
ef5584
			$messenger = new messenger();
ef5584
ef5584
			foreach ($email_users as $row)
ef5584
			{
ef5584
				$messenger->template('group_approved', $row['user_lang']);
ef5584
ef5584
				$messenger->to($row['user_email'], $row['username']);
ef5584
				$messenger->im($row['user_jabber'], $row['username']);
ef5584
ef5584
				$messenger->assign_vars(array(
ef5584
					'USERNAME'		=> htmlspecialchars_decode($row['username']),
ef5584
					'GROUP_NAME'	=> htmlspecialchars_decode($group_name),
ef5584
					'U_GROUP'		=> generate_board_url() . "/ucp.$phpEx?i=groups&mode=membership")
ef5584
				);
ef5584
ef5584
				$messenger->send($row['user_notify_type']);
ef5584
			}
ef5584
ef5584
			$messenger->save_queue();
ef5584
ef5584
			$log = 'LOG_USERS_APPROVED';
ef5584
		break;
ef5584
ef5584
		case 'default':
ef5584
			$sql = 'SELECT user_id, group_id FROM ' . USERS_TABLE . '
ef5584
				WHERE ' . $db->sql_in_set('user_id', $user_id_ary, false, true);
ef5584
			$result = $db->sql_query($sql);
ef5584
ef5584
			$groups = array();
ef5584
			while ($row = $db->sql_fetchrow($result))
ef5584
			{
ef5584
				if (!isset($groups[$row['group_id']]))
ef5584
				{
ef5584
					$groups[$row['group_id']] = array();
ef5584
				}
ef5584
				$groups[$row['group_id']][] = $row['user_id'];
ef5584
			}
ef5584
			$db->sql_freeresult($result);
ef5584
ef5584
			foreach ($groups as $gid => $uids)
ef5584
			{
ef5584
				remove_default_rank($gid, $uids);
ef5584
				remove_default_avatar($gid, $uids);
ef5584
			}
ef5584
			group_set_user_default($group_id, $user_id_ary, $group_attributes);
ef5584
			$log = 'LOG_GROUP_DEFAULTS';
ef5584
		break;
ef5584
	}
ef5584
ef5584
	// Clear permissions cache of relevant users
ef5584
	$auth->acl_clear_prefetch($user_id_ary);
ef5584
ef5584
	add_log('admin', $log, $group_name, implode(', ', $username_ary));
ef5584
ef5584
	group_update_listings($group_id);
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* A small version of validate_username to check for a group name's existence. To be called directly.
ef5584
*/
ef5584
function group_validate_groupname($group_id, $group_name)
ef5584
{
ef5584
	global $config, $db;
ef5584
ef5584
	$group_name =  utf8_clean_string($group_name);
ef5584
ef5584
	if (!empty($group_id))
ef5584
	{
ef5584
		$sql = 'SELECT group_name
ef5584
			FROM ' . GROUPS_TABLE . '
ef5584
			WHERE group_id = ' . (int) $group_id;
ef5584
		$result = $db->sql_query($sql);
ef5584
		$row = $db->sql_fetchrow($result);
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		if (!$row)
ef5584
		{
ef5584
			return false;
ef5584
		}
ef5584
ef5584
		$allowed_groupname = utf8_clean_string($row['group_name']);
ef5584
ef5584
		if ($allowed_groupname == $group_name)
ef5584
		{
ef5584
			return false;
ef5584
		}
ef5584
	}
ef5584
ef5584
	$sql = 'SELECT group_name
ef5584
		FROM ' . GROUPS_TABLE . "
ef5584
		WHERE LOWER(group_name) = '" . $db->sql_escape(utf8_strtolower($group_name)) . "'";
ef5584
	$result = $db->sql_query($sql);
ef5584
	$row = $db->sql_fetchrow($result);
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	if ($row)
ef5584
	{
ef5584
		return 'GROUP_NAME_TAKEN';
ef5584
	}
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
/**
ef5584
* Set users default group
ef5584
*
ef5584
* @access private
ef5584
*/
ef5584
function group_set_user_default($group_id, $user_id_ary, $group_attributes = false, $update_listing = false)
ef5584
{
ef5584
	global $db;
ef5584
ef5584
	if (empty($user_id_ary))
ef5584
	{
ef5584
		return;
ef5584
	}
ef5584
ef5584
	$attribute_ary = array(
ef5584
		'group_colour'			=> 'string',
ef5584
		'group_rank'			=> 'int',
ef5584
		'group_avatar'			=> 'string',
ef5584
		'group_avatar_type'		=> 'int',
ef5584
		'group_avatar_width'	=> 'int',
ef5584
		'group_avatar_height'	=> 'int',
ef5584
	);
ef5584
ef5584
	$sql_ary = array(
ef5584
		'group_id'		=> $group_id
ef5584
	);
ef5584
ef5584
	// Were group attributes passed to the function? If not we need to obtain them
ef5584
	if ($group_attributes === false)
ef5584
	{
ef5584
		$sql = 'SELECT ' . implode(', ', array_keys($attribute_ary)) . '
ef5584
			FROM ' . GROUPS_TABLE . "
ef5584
			WHERE group_id = $group_id";
ef5584
		$result = $db->sql_query($sql);
ef5584
		$group_attributes = $db->sql_fetchrow($result);
ef5584
		$db->sql_freeresult($result);
ef5584
	}
ef5584
ef5584
	foreach ($attribute_ary as $attribute => $type)
ef5584
	{
ef5584
		if (isset($group_attributes[$attribute]))
ef5584
		{
ef5584
			// If we are about to set an avatar or rank, we will not overwrite with empty, unless we are not actually changing the default group
ef5584
			if ((strpos($attribute, 'group_avatar') === 0 || strpos($attribute, 'group_rank') === 0) && !$group_attributes[$attribute])
ef5584
			{
ef5584
				continue;
ef5584
			}
ef5584
ef5584
			settype($group_attributes[$attribute], $type);
ef5584
			$sql_ary[str_replace('group_', 'user_', $attribute)] = $group_attributes[$attribute];
ef5584
		}
ef5584
	}
ef5584
ef5584
	// Before we update the user attributes, we will make a list of those having now the group avatar assigned
ef5584
	if (isset($sql_ary['user_avatar']))
ef5584
	{
ef5584
		// Ok, get the original avatar data from users having an uploaded one (we need to remove these from the filesystem)
ef5584
		$sql = 'SELECT user_id, group_id, user_avatar
ef5584
			FROM ' . USERS_TABLE . '
ef5584
			WHERE ' . $db->sql_in_set('user_id', $user_id_ary) . '
ef5584
				AND user_avatar_type = ' . AVATAR_UPLOAD;
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			avatar_delete('user', $row);
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
	}
ef5584
	else
ef5584
	{
ef5584
		unset($sql_ary['user_avatar_type']);
ef5584
		unset($sql_ary['user_avatar_height']);
ef5584
		unset($sql_ary['user_avatar_width']);
ef5584
	}
ef5584
ef5584
	$sql = 'UPDATE ' . USERS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
ef5584
		WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
ef5584
	$db->sql_query($sql);
ef5584
ef5584
	if (isset($sql_ary['user_colour']))
ef5584
	{
ef5584
		// Update any cached colour information for these users
ef5584
		$sql = 'UPDATE ' . FORUMS_TABLE . " SET forum_last_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
ef5584
			WHERE " . $db->sql_in_set('forum_last_poster_id', $user_id_ary);
ef5584
		$db->sql_query($sql);
ef5584
ef5584
		$sql = 'UPDATE ' . TOPICS_TABLE . " SET topic_first_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
ef5584
			WHERE " . $db->sql_in_set('topic_poster', $user_id_ary);
ef5584
		$db->sql_query($sql);
ef5584
ef5584
		$sql = 'UPDATE ' . TOPICS_TABLE . " SET topic_last_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
ef5584
			WHERE " . $db->sql_in_set('topic_last_poster_id', $user_id_ary);
ef5584
		$db->sql_query($sql);
ef5584
ef5584
		global $config;
ef5584
ef5584
		if (in_array($config['newest_user_id'], $user_id_ary))
ef5584
		{
ef5584
			set_config('newest_user_colour', $sql_ary['user_colour'], true);
ef5584
		}
ef5584
	}
ef5584
ef5584
	if ($update_listing)
ef5584
	{
ef5584
		group_update_listings($group_id);
ef5584
	}
ef5584
}
ef5584
ef5584
/**
ef5584
* Get group name
ef5584
*/
ef5584
function get_group_name($group_id)
ef5584
{
ef5584
	global $db, $user;
ef5584
ef5584
	$sql = 'SELECT group_name, group_type
ef5584
		FROM ' . GROUPS_TABLE . '
ef5584
		WHERE group_id = ' . (int) $group_id;
ef5584
	$result = $db->sql_query($sql);
ef5584
	$row = $db->sql_fetchrow($result);
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	if (!$row)
ef5584
	{
ef5584
		return '';
ef5584
	}
ef5584
ef5584
	return ($row['group_type'] == GROUP_SPECIAL) ? $user->lang['G_' . $row['group_name']] : $row['group_name'];
ef5584
}
ef5584
ef5584
/**
ef5584
* Obtain either the members of a specified group, the groups the specified user is subscribed to
ef5584
* or checking if a specified user is in a specified group. This function does not return pending memberships.
ef5584
*
ef5584
* Note: Never use this more than once... first group your users/groups
ef5584
*/
ef5584
function group_memberships($group_id_ary = false, $user_id_ary = false, $return_bool = false)
ef5584
{
ef5584
	global $db;
ef5584
ef5584
	if (!$group_id_ary && !$user_id_ary)
ef5584
	{
ef5584
		return true;
ef5584
	}
ef5584
ef5584
	if ($user_id_ary)
ef5584
	{
ef5584
		$user_id_ary = (!is_array($user_id_ary)) ? array($user_id_ary) : $user_id_ary;
ef5584
	}
ef5584
ef5584
	if ($group_id_ary)
ef5584
	{
ef5584
		$group_id_ary = (!is_array($group_id_ary)) ? array($group_id_ary) : $group_id_ary;
ef5584
	}
ef5584
ef5584
	$sql = 'SELECT ug.*, u.username, u.username_clean, u.user_email
ef5584
		FROM ' . USER_GROUP_TABLE . ' ug, ' . USERS_TABLE . ' u
ef5584
		WHERE ug.user_id = u.user_id
ef5584
			AND ug.user_pending = 0 AND ';
ef5584
ef5584
	if ($group_id_ary)
ef5584
	{
ef5584
		$sql .= ' ' . $db->sql_in_set('ug.group_id', $group_id_ary);
ef5584
	}
ef5584
ef5584
	if ($user_id_ary)
ef5584
	{
ef5584
		$sql .= ($group_id_ary) ? ' AND ' : ' ';
ef5584
		$sql .= $db->sql_in_set('ug.user_id', $user_id_ary);
ef5584
	}
ef5584
ef5584
	$result = ($return_bool) ? $db->sql_query_limit($sql, 1) : $db->sql_query($sql);
ef5584
ef5584
	$row = $db->sql_fetchrow($result);
ef5584
ef5584
	if ($return_bool)
ef5584
	{
ef5584
		$db->sql_freeresult($result);
ef5584
		return ($row) ? true : false;
ef5584
	}
ef5584
ef5584
	if (!$row)
ef5584
	{
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	$return = array();
ef5584
ef5584
	do
ef5584
	{
ef5584
		$return[] = $row;
ef5584
	}
ef5584
	while ($row = $db->sql_fetchrow($result));
ef5584
ef5584
	$db->sql_freeresult($result);
ef5584
ef5584
	return $return;
ef5584
}
ef5584
ef5584
/**
ef5584
* Re-cache moderators and foes if group has a_ or m_ permissions
ef5584
*/
ef5584
function group_update_listings($group_id)
ef5584
{
ef5584
	global $auth;
ef5584
ef5584
	$hold_ary = $auth->acl_group_raw_data($group_id, array('a_', 'm_'));
ef5584
ef5584
	if (!sizeof($hold_ary))
ef5584
	{
ef5584
		return;
ef5584
	}
ef5584
ef5584
	$mod_permissions = $admin_permissions = false;
ef5584
ef5584
	foreach ($hold_ary as $g_id => $forum_ary)
ef5584
	{
ef5584
		foreach ($forum_ary as $forum_id => $auth_ary)
ef5584
		{
ef5584
			foreach ($auth_ary as $auth_option => $setting)
ef5584
			{
ef5584
				if ($mod_permissions && $admin_permissions)
ef5584
				{
ef5584
					break 3;
ef5584
				}
ef5584
ef5584
				if ($setting != ACL_YES)
ef5584
				{
ef5584
					continue;
ef5584
				}
ef5584
ef5584
				if ($auth_option == 'm_')
ef5584
				{
ef5584
					$mod_permissions = true;
ef5584
				}
ef5584
ef5584
				if ($auth_option == 'a_')
ef5584
				{
ef5584
					$admin_permissions = true;
ef5584
				}
ef5584
			}
ef5584
		}
ef5584
	}
ef5584
ef5584
	if ($mod_permissions)
ef5584
	{
ef5584
		if (!function_exists('cache_moderators'))
ef5584
		{
ef5584
			global $phpbb_root_path, $phpEx;
ef5584
			include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
ef5584
		}
ef5584
		cache_moderators();
ef5584
	}
ef5584
ef5584
	if ($mod_permissions || $admin_permissions)
ef5584
	{
ef5584
		if (!function_exists('update_foes'))
ef5584
		{
ef5584
			global $phpbb_root_path, $phpEx;
ef5584
			include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
ef5584
		}
ef5584
		update_foes(array($group_id));
ef5584
	}
ef5584
}
ef5584
ef5584
?>