includes/functions_user.php
changeset 0 ceef6d64c21d
child 18 36b05a593b41
equal deleted inserted replaced
-1:000000000000 0:ceef6d64c21d
       
     1 <?php
       
     2 /**
       
     3 *
       
     4 * @package phpBB3
       
     5 * @version $Id$
       
     6 * @copyright (c) 2005 phpBB Group
       
     7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
       
     8 *
       
     9 */
       
    10 
       
    11 /**
       
    12 * @ignore
       
    13 */
       
    14 if (!defined('IN_PHPBB'))
       
    15 {
       
    16 	exit;
       
    17 }
       
    18 
       
    19 /**
       
    20 * Obtain user_ids from usernames or vice versa. Returns false on
       
    21 * success else the error string
       
    22 *
       
    23 * @param array &$user_id_ary The user ids to check or empty if usernames used
       
    24 * @param array &$username_ary The usernames to check or empty if user ids used
       
    25 * @param mixed $user_type Array of user types to check, false if not restricting by user type
       
    26 */
       
    27 function user_get_id_name(&$user_id_ary, &$username_ary, $user_type = false)
       
    28 {
       
    29 	global $db;
       
    30 
       
    31 	// Are both arrays already filled? Yep, return else
       
    32 	// are neither array filled?
       
    33 	if ($user_id_ary && $username_ary)
       
    34 	{
       
    35 		return false;
       
    36 	}
       
    37 	else if (!$user_id_ary && !$username_ary)
       
    38 	{
       
    39 		return 'NO_USERS';
       
    40 	}
       
    41 
       
    42 	$which_ary = ($user_id_ary) ? 'user_id_ary' : 'username_ary';
       
    43 
       
    44 	if ($$which_ary && !is_array($$which_ary))
       
    45 	{
       
    46 		$$which_ary = array($$which_ary);
       
    47 	}
       
    48 
       
    49 	$sql_in = ($which_ary == 'user_id_ary') ? array_map('intval', $$which_ary) : array_map('utf8_clean_string', $$which_ary);
       
    50 	unset($$which_ary);
       
    51 
       
    52 	$user_id_ary = $username_ary = array();
       
    53 
       
    54 	// Grab the user id/username records
       
    55 	$sql_where = ($which_ary == 'user_id_ary') ? 'user_id' : 'username_clean';
       
    56 	$sql = 'SELECT user_id, username
       
    57 		FROM ' . USERS_TABLE . '
       
    58 		WHERE ' . $db->sql_in_set($sql_where, $sql_in);
       
    59 
       
    60 	if ($user_type !== false && !empty($user_type))
       
    61 	{
       
    62 		$sql .= ' AND ' . $db->sql_in_set('user_type', $user_type);
       
    63 	}
       
    64 
       
    65 	$result = $db->sql_query($sql);
       
    66 
       
    67 	if (!($row = $db->sql_fetchrow($result)))
       
    68 	{
       
    69 		$db->sql_freeresult($result);
       
    70 		return 'NO_USERS';
       
    71 	}
       
    72 
       
    73 	do
       
    74 	{
       
    75 		$username_ary[$row['user_id']] = $row['username'];
       
    76 		$user_id_ary[] = $row['user_id'];
       
    77 	}
       
    78 	while ($row = $db->sql_fetchrow($result));
       
    79 	$db->sql_freeresult($result);
       
    80 
       
    81 	return false;
       
    82 }
       
    83 
       
    84 /**
       
    85 * Get latest registered username and update database to reflect it
       
    86 */
       
    87 function update_last_username()
       
    88 {
       
    89 	global $db;
       
    90 
       
    91 	// Get latest username
       
    92 	$sql = 'SELECT user_id, username, user_colour
       
    93 		FROM ' . USERS_TABLE . '
       
    94 		WHERE user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')
       
    95 		ORDER BY user_id DESC';
       
    96 	$result = $db->sql_query_limit($sql, 1);
       
    97 	$row = $db->sql_fetchrow($result);
       
    98 	$db->sql_freeresult($result);
       
    99 
       
   100 	if ($row)
       
   101 	{
       
   102 		set_config('newest_user_id', $row['user_id'], true);
       
   103 		set_config('newest_username', $row['username'], true);
       
   104 		set_config('newest_user_colour', $row['user_colour'], true);
       
   105 	}
       
   106 }
       
   107 
       
   108 /**
       
   109 * Updates a username across all relevant tables/fields
       
   110 *
       
   111 * @param string $old_name the old/current username
       
   112 * @param string $new_name the new username
       
   113 */
       
   114 function user_update_name($old_name, $new_name)
       
   115 {
       
   116 	global $config, $db, $cache;
       
   117 
       
   118 	$update_ary = array(
       
   119 		FORUMS_TABLE			=> array('forum_last_poster_name'),
       
   120 		MODERATOR_CACHE_TABLE	=> array('username'),
       
   121 		POSTS_TABLE				=> array('post_username'),
       
   122 		TOPICS_TABLE			=> array('topic_first_poster_name', 'topic_last_poster_name'),
       
   123 	);
       
   124 
       
   125 	foreach ($update_ary as $table => $field_ary)
       
   126 	{
       
   127 		foreach ($field_ary as $field)
       
   128 		{
       
   129 			$sql = "UPDATE $table
       
   130 				SET $field = '" . $db->sql_escape($new_name) . "'
       
   131 				WHERE $field = '" . $db->sql_escape($old_name) . "'";
       
   132 			$db->sql_query($sql);
       
   133 		}
       
   134 	}
       
   135 
       
   136 	if ($config['newest_username'] == $old_name)
       
   137 	{
       
   138 		set_config('newest_username', $new_name, true);
       
   139 	}
       
   140 
       
   141 	// Because some tables/caches use username-specific data we need to purge this here.
       
   142 	$cache->destroy('sql', MODERATOR_CACHE_TABLE);
       
   143 }
       
   144 
       
   145 /**
       
   146 * Adds an user
       
   147 *
       
   148 * @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.
       
   149 * @param string $cp_data custom profile fields, see custom_profile::build_insert_sql_array
       
   150 * @return the new user's ID.
       
   151 */
       
   152 function user_add($user_row, $cp_data = false)
       
   153 {
       
   154 	global $db, $user, $auth, $config, $phpbb_root_path, $phpEx;
       
   155 
       
   156 	if (empty($user_row['username']) || !isset($user_row['group_id']) || !isset($user_row['user_email']) || !isset($user_row['user_type']))
       
   157 	{
       
   158 		return false;
       
   159 	}
       
   160 
       
   161 	$username_clean = utf8_clean_string($user_row['username']);
       
   162 
       
   163 	if (empty($username_clean))
       
   164 	{
       
   165 		return false;
       
   166 	}
       
   167 
       
   168 	$sql_ary = array(
       
   169 		'username'			=> $user_row['username'],
       
   170 		'username_clean'	=> $username_clean,
       
   171 		'user_password'		=> (isset($user_row['user_password'])) ? $user_row['user_password'] : '',
       
   172 		'user_pass_convert'	=> 0,
       
   173 		'user_email'		=> strtolower($user_row['user_email']),
       
   174 		'user_email_hash'	=> phpbb_email_hash($user_row['user_email']),
       
   175 		'group_id'			=> $user_row['group_id'],
       
   176 		'user_type'			=> $user_row['user_type'],
       
   177 	);
       
   178 
       
   179 	// These are the additional vars able to be specified
       
   180 	$additional_vars = array(
       
   181 		'user_permissions'	=> '',
       
   182 		'user_timezone'		=> $config['board_timezone'],
       
   183 		'user_dateformat'	=> $config['default_dateformat'],
       
   184 		'user_lang'			=> $config['default_lang'],
       
   185 		'user_style'		=> (int) $config['default_style'],
       
   186 		'user_actkey'		=> '',
       
   187 		'user_ip'			=> '',
       
   188 		'user_regdate'		=> time(),
       
   189 		'user_passchg'		=> time(),
       
   190 		'user_options'		=> 230271,
       
   191 		// We do not set the new flag here - registration scripts need to specify it
       
   192 		'user_new'			=> 0,
       
   193 
       
   194 		'user_inactive_reason'	=> 0,
       
   195 		'user_inactive_time'	=> 0,
       
   196 		'user_lastmark'			=> time(),
       
   197 		'user_lastvisit'		=> 0,
       
   198 		'user_lastpost_time'	=> 0,
       
   199 		'user_lastpage'			=> '',
       
   200 		'user_posts'			=> 0,
       
   201 		'user_dst'				=> (int) $config['board_dst'],
       
   202 		'user_colour'			=> '',
       
   203 		'user_occ'				=> '',
       
   204 		'user_interests'		=> '',
       
   205 		'user_avatar'			=> '',
       
   206 		'user_avatar_type'		=> 0,
       
   207 		'user_avatar_width'		=> 0,
       
   208 		'user_avatar_height'	=> 0,
       
   209 		'user_new_privmsg'		=> 0,
       
   210 		'user_unread_privmsg'	=> 0,
       
   211 		'user_last_privmsg'		=> 0,
       
   212 		'user_message_rules'	=> 0,
       
   213 		'user_full_folder'		=> PRIVMSGS_NO_BOX,
       
   214 		'user_emailtime'		=> 0,
       
   215 
       
   216 		'user_notify'			=> 0,
       
   217 		'user_notify_pm'		=> 1,
       
   218 		'user_notify_type'		=> NOTIFY_EMAIL,
       
   219 		'user_allow_pm'			=> 1,
       
   220 		'user_allow_viewonline'	=> 1,
       
   221 		'user_allow_viewemail'	=> 1,
       
   222 		'user_allow_massemail'	=> 1,
       
   223 
       
   224 		'user_sig'					=> '',
       
   225 		'user_sig_bbcode_uid'		=> '',
       
   226 		'user_sig_bbcode_bitfield'	=> '',
       
   227 
       
   228 		'user_form_salt'			=> unique_id(),
       
   229 	);
       
   230 
       
   231 	// Now fill the sql array with not required variables
       
   232 	foreach ($additional_vars as $key => $default_value)
       
   233 	{
       
   234 		$sql_ary[$key] = (isset($user_row[$key])) ? $user_row[$key] : $default_value;
       
   235 	}
       
   236 
       
   237 	// Any additional variables in $user_row not covered above?
       
   238 	$remaining_vars = array_diff(array_keys($user_row), array_keys($sql_ary));
       
   239 
       
   240 	// Now fill our sql array with the remaining vars
       
   241 	if (sizeof($remaining_vars))
       
   242 	{
       
   243 		foreach ($remaining_vars as $key)
       
   244 		{
       
   245 			$sql_ary[$key] = $user_row[$key];
       
   246 		}
       
   247 	}
       
   248 
       
   249 	$sql = 'INSERT INTO ' . USERS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
       
   250 	$db->sql_query($sql);
       
   251 
       
   252 	$user_id = $db->sql_nextid();
       
   253 
       
   254 	// Insert Custom Profile Fields
       
   255 	if ($cp_data !== false && sizeof($cp_data))
       
   256 	{
       
   257 		$cp_data['user_id'] = (int) $user_id;
       
   258 
       
   259 		if (!class_exists('custom_profile'))
       
   260 		{
       
   261 			include_once($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);
       
   262 		}
       
   263 
       
   264 		$sql = 'INSERT INTO ' . PROFILE_FIELDS_DATA_TABLE . ' ' .
       
   265 			$db->sql_build_array('INSERT', custom_profile::build_insert_sql_array($cp_data));
       
   266 		$db->sql_query($sql);
       
   267 	}
       
   268 
       
   269 	// Place into appropriate group...
       
   270 	$sql = 'INSERT INTO ' . USER_GROUP_TABLE . ' ' . $db->sql_build_array('INSERT', array(
       
   271 		'user_id'		=> (int) $user_id,
       
   272 		'group_id'		=> (int) $user_row['group_id'],
       
   273 		'user_pending'	=> 0)
       
   274 	);
       
   275 	$db->sql_query($sql);
       
   276 
       
   277 	// Now make it the users default group...
       
   278 	group_set_user_default($user_row['group_id'], array($user_id), false);
       
   279 
       
   280 	// Add to newly registered users group if user_new is 1
       
   281 	if ($config['new_member_post_limit'] && $sql_ary['user_new'])
       
   282 	{
       
   283 		$sql = 'SELECT group_id
       
   284 			FROM ' . GROUPS_TABLE . "
       
   285 			WHERE group_name = 'NEWLY_REGISTERED'
       
   286 				AND group_type = " . GROUP_SPECIAL;
       
   287 		$result = $db->sql_query($sql);
       
   288 		$add_group_id = (int) $db->sql_fetchfield('group_id');
       
   289 		$db->sql_freeresult($result);
       
   290 
       
   291 		if ($add_group_id)
       
   292 		{
       
   293 			// Because these actions only fill the log unneccessarily we skip the add_log() entry with a little hack. :/
       
   294 			$GLOBALS['skip_add_log'] = true;
       
   295 
       
   296 			// Add user to "newly registered users" group and set to default group if admin specified so.
       
   297 			if ($config['new_member_group_default'])
       
   298 			{
       
   299 				group_user_add($add_group_id, $user_id, false, false, true);
       
   300 				$user_row['group_id'] = $add_group_id;
       
   301 			}
       
   302 			else
       
   303 			{
       
   304 				group_user_add($add_group_id, $user_id);
       
   305 			}
       
   306 
       
   307 			unset($GLOBALS['skip_add_log']);
       
   308 		}
       
   309 	}
       
   310 
       
   311 	// set the newest user and adjust the user count if the user is a normal user and no activation mail is sent
       
   312 	if ($user_row['user_type'] == USER_NORMAL || $user_row['user_type'] == USER_FOUNDER)
       
   313 	{
       
   314 		set_config('newest_user_id', $user_id, true);
       
   315 		set_config('newest_username', $user_row['username'], true);
       
   316 		set_config_count('num_users', 1, true);
       
   317 
       
   318 		$sql = 'SELECT group_colour
       
   319 			FROM ' . GROUPS_TABLE . '
       
   320 			WHERE group_id = ' . (int) $user_row['group_id'];
       
   321 		$result = $db->sql_query_limit($sql, 1);
       
   322 		$row = $db->sql_fetchrow($result);
       
   323 		$db->sql_freeresult($result);
       
   324 
       
   325 		set_config('newest_user_colour', $row['group_colour'], true);
       
   326 	}
       
   327 
       
   328 	return $user_id;
       
   329 }
       
   330 
       
   331 /**
       
   332 * Remove User
       
   333 */
       
   334 function user_delete($mode, $user_id, $post_username = false)
       
   335 {
       
   336 	global $cache, $config, $db, $user, $auth;
       
   337 	global $phpbb_root_path, $phpEx;
       
   338 
       
   339 	$sql = 'SELECT *
       
   340 		FROM ' . USERS_TABLE . '
       
   341 		WHERE user_id = ' . $user_id;
       
   342 	$result = $db->sql_query($sql);
       
   343 	$user_row = $db->sql_fetchrow($result);
       
   344 	$db->sql_freeresult($result);
       
   345 
       
   346 	if (!$user_row)
       
   347 	{
       
   348 		return false;
       
   349 	}
       
   350 
       
   351 	// Before we begin, we will remove the reports the user issued.
       
   352 	$sql = 'SELECT r.post_id, p.topic_id
       
   353 		FROM ' . REPORTS_TABLE . ' r, ' . POSTS_TABLE . ' p
       
   354 		WHERE r.user_id = ' . $user_id . '
       
   355 			AND p.post_id = r.post_id';
       
   356 	$result = $db->sql_query($sql);
       
   357 
       
   358 	$report_posts = $report_topics = array();
       
   359 	while ($row = $db->sql_fetchrow($result))
       
   360 	{
       
   361 		$report_posts[] = $row['post_id'];
       
   362 		$report_topics[] = $row['topic_id'];
       
   363 	}
       
   364 	$db->sql_freeresult($result);
       
   365 
       
   366 	if (sizeof($report_posts))
       
   367 	{
       
   368 		$report_posts = array_unique($report_posts);
       
   369 		$report_topics = array_unique($report_topics);
       
   370 
       
   371 		// Get a list of topics that still contain reported posts
       
   372 		$sql = 'SELECT DISTINCT topic_id
       
   373 			FROM ' . POSTS_TABLE . '
       
   374 			WHERE ' . $db->sql_in_set('topic_id', $report_topics) . '
       
   375 				AND post_reported = 1
       
   376 				AND ' . $db->sql_in_set('post_id', $report_posts, true);
       
   377 		$result = $db->sql_query($sql);
       
   378 
       
   379 		$keep_report_topics = array();
       
   380 		while ($row = $db->sql_fetchrow($result))
       
   381 		{
       
   382 			$keep_report_topics[] = $row['topic_id'];
       
   383 		}
       
   384 		$db->sql_freeresult($result);
       
   385 
       
   386 		if (sizeof($keep_report_topics))
       
   387 		{
       
   388 			$report_topics = array_diff($report_topics, $keep_report_topics);
       
   389 		}
       
   390 		unset($keep_report_topics);
       
   391 
       
   392 		// Now set the flags back
       
   393 		$sql = 'UPDATE ' . POSTS_TABLE . '
       
   394 			SET post_reported = 0
       
   395 			WHERE ' . $db->sql_in_set('post_id', $report_posts);
       
   396 		$db->sql_query($sql);
       
   397 
       
   398 		if (sizeof($report_topics))
       
   399 		{
       
   400 			$sql = 'UPDATE ' . TOPICS_TABLE . '
       
   401 				SET topic_reported = 0
       
   402 				WHERE ' . $db->sql_in_set('topic_id', $report_topics);
       
   403 			$db->sql_query($sql);
       
   404 		}
       
   405 	}
       
   406 
       
   407 	// Remove reports
       
   408 	$db->sql_query('DELETE FROM ' . REPORTS_TABLE . ' WHERE user_id = ' . $user_id);
       
   409 
       
   410 	if ($user_row['user_avatar'] && $user_row['user_avatar_type'] == AVATAR_UPLOAD)
       
   411 	{
       
   412 		avatar_delete('user', $user_row);
       
   413 	}
       
   414 
       
   415 	switch ($mode)
       
   416 	{
       
   417 		case 'retain':
       
   418 
       
   419 			$db->sql_transaction('begin');
       
   420 
       
   421 			if ($post_username === false)
       
   422 			{
       
   423 				$post_username = $user->lang['GUEST'];
       
   424 			}
       
   425 
       
   426 			// If the user is inactive and newly registered we assume no posts from this user being there...
       
   427 			if ($user_row['user_type'] == USER_INACTIVE && $user_row['user_inactive_reason'] == INACTIVE_REGISTER && !$user_row['user_posts'])
       
   428 			{
       
   429 			}
       
   430 			else
       
   431 			{
       
   432 				$sql = 'UPDATE ' . FORUMS_TABLE . '
       
   433 					SET forum_last_poster_id = ' . ANONYMOUS . ", forum_last_poster_name = '" . $db->sql_escape($post_username) . "', forum_last_poster_colour = ''
       
   434 					WHERE forum_last_poster_id = $user_id";
       
   435 				$db->sql_query($sql);
       
   436 
       
   437 				$sql = 'UPDATE ' . POSTS_TABLE . '
       
   438 					SET poster_id = ' . ANONYMOUS . ", post_username = '" . $db->sql_escape($post_username) . "'
       
   439 					WHERE poster_id = $user_id";
       
   440 				$db->sql_query($sql);
       
   441 
       
   442 				$sql = 'UPDATE ' . POSTS_TABLE . '
       
   443 					SET post_edit_user = ' . ANONYMOUS . "
       
   444 					WHERE post_edit_user = $user_id";
       
   445 				$db->sql_query($sql);
       
   446 
       
   447 				$sql = 'UPDATE ' . TOPICS_TABLE . '
       
   448 					SET topic_poster = ' . ANONYMOUS . ", topic_first_poster_name = '" . $db->sql_escape($post_username) . "', topic_first_poster_colour = ''
       
   449 					WHERE topic_poster = $user_id";
       
   450 				$db->sql_query($sql);
       
   451 
       
   452 				$sql = 'UPDATE ' . TOPICS_TABLE . '
       
   453 					SET topic_last_poster_id = ' . ANONYMOUS . ", topic_last_poster_name = '" . $db->sql_escape($post_username) . "', topic_last_poster_colour = ''
       
   454 					WHERE topic_last_poster_id = $user_id";
       
   455 				$db->sql_query($sql);
       
   456 
       
   457 				$sql = 'UPDATE ' . ATTACHMENTS_TABLE . '
       
   458 					SET poster_id = ' . ANONYMOUS . "
       
   459 					WHERE poster_id = $user_id";
       
   460 				$db->sql_query($sql);
       
   461 
       
   462 				// Since we change every post by this author, we need to count this amount towards the anonymous user
       
   463 
       
   464 				// Update the post count for the anonymous user
       
   465 				if ($user_row['user_posts'])
       
   466 				{
       
   467 					$sql = 'UPDATE ' . USERS_TABLE . '
       
   468 						SET user_posts = user_posts + ' . $user_row['user_posts'] . '
       
   469 						WHERE user_id = ' . ANONYMOUS;
       
   470 					$db->sql_query($sql);
       
   471 				}
       
   472 			}
       
   473 
       
   474 			$db->sql_transaction('commit');
       
   475 
       
   476 		break;
       
   477 
       
   478 		case 'remove':
       
   479 
       
   480 			if (!function_exists('delete_posts'))
       
   481 			{
       
   482 				include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
       
   483 			}
       
   484 
       
   485 			// Delete posts, attachments, etc.
       
   486 			delete_posts('poster_id', $user_id);
       
   487 
       
   488 		break;
       
   489 	}
       
   490 
       
   491 	$db->sql_transaction('begin');
       
   492 
       
   493 	$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, SESSIONS_KEYS_TABLE, PRIVMSGS_FOLDER_TABLE, PRIVMSGS_RULES_TABLE);
       
   494 
       
   495 	foreach ($table_ary as $table)
       
   496 	{
       
   497 		$sql = "DELETE FROM $table
       
   498 			WHERE user_id = $user_id";
       
   499 		$db->sql_query($sql);
       
   500 	}
       
   501 
       
   502 	$cache->destroy('sql', MODERATOR_CACHE_TABLE);
       
   503 
       
   504 	// Delete user log entries about this user
       
   505 	$sql = 'DELETE FROM ' . LOG_TABLE . '
       
   506 		WHERE reportee_id = ' . $user_id;
       
   507 	$db->sql_query($sql);
       
   508 
       
   509 	// Change user_id to anonymous for this users triggered events
       
   510 	$sql = 'UPDATE ' . LOG_TABLE . '
       
   511 		SET user_id = ' . ANONYMOUS . '
       
   512 		WHERE user_id = ' . $user_id;
       
   513 	$db->sql_query($sql);
       
   514 
       
   515 	// Delete the user_id from the zebra table
       
   516 	$sql = 'DELETE FROM ' . ZEBRA_TABLE . '
       
   517 		WHERE user_id = ' . $user_id . '
       
   518 			OR zebra_id = ' . $user_id;
       
   519 	$db->sql_query($sql);
       
   520 
       
   521 	// Delete the user_id from the banlist
       
   522 	$sql = 'DELETE FROM ' . BANLIST_TABLE . '
       
   523 		WHERE ban_userid = ' . $user_id;
       
   524 	$db->sql_query($sql);
       
   525 
       
   526 	// Delete the user_id from the session table
       
   527 	$sql = 'DELETE FROM ' . SESSIONS_TABLE . '
       
   528 		WHERE session_user_id = ' . $user_id;
       
   529 	$db->sql_query($sql);
       
   530 
       
   531 	// Remove any undelivered mails...
       
   532 	$sql = 'SELECT msg_id, user_id
       
   533 		FROM ' . PRIVMSGS_TO_TABLE . '
       
   534 		WHERE author_id = ' . $user_id . '
       
   535 			AND folder_id = ' . PRIVMSGS_NO_BOX;
       
   536 	$result = $db->sql_query($sql);
       
   537 
       
   538 	$undelivered_msg = $undelivered_user = array();
       
   539 	while ($row = $db->sql_fetchrow($result))
       
   540 	{
       
   541 		$undelivered_msg[] = $row['msg_id'];
       
   542 		$undelivered_user[$row['user_id']][] = true;
       
   543 	}
       
   544 	$db->sql_freeresult($result);
       
   545 
       
   546 	if (sizeof($undelivered_msg))
       
   547 	{
       
   548 		$sql = 'DELETE FROM ' . PRIVMSGS_TABLE . '
       
   549 			WHERE ' . $db->sql_in_set('msg_id', $undelivered_msg);
       
   550 		$db->sql_query($sql);
       
   551 	}
       
   552 
       
   553 	$sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
       
   554 		WHERE author_id = ' . $user_id . '
       
   555 			AND folder_id = ' . PRIVMSGS_NO_BOX;
       
   556 	$db->sql_query($sql);
       
   557 
       
   558 	// Delete all to-information
       
   559 	$sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
       
   560 		WHERE user_id = ' . $user_id;
       
   561 	$db->sql_query($sql);
       
   562 
       
   563 	// Set the remaining author id to anonymous - this way users are still able to read messages from users being removed
       
   564 	$sql = 'UPDATE ' . PRIVMSGS_TO_TABLE . '
       
   565 		SET author_id = ' . ANONYMOUS . '
       
   566 		WHERE author_id = ' . $user_id;
       
   567 	$db->sql_query($sql);
       
   568 
       
   569 	$sql = 'UPDATE ' . PRIVMSGS_TABLE . '
       
   570 		SET author_id = ' . ANONYMOUS . '
       
   571 		WHERE author_id = ' . $user_id;
       
   572 	$db->sql_query($sql);
       
   573 
       
   574 	foreach ($undelivered_user as $_user_id => $ary)
       
   575 	{
       
   576 		if ($_user_id == $user_id)
       
   577 		{
       
   578 			continue;
       
   579 		}
       
   580 
       
   581 		$sql = 'UPDATE ' . USERS_TABLE . '
       
   582 			SET user_new_privmsg = user_new_privmsg - ' . sizeof($ary) . ',
       
   583 				user_unread_privmsg = user_unread_privmsg - ' . sizeof($ary) . '
       
   584 			WHERE user_id = ' . $_user_id;
       
   585 		$db->sql_query($sql);
       
   586 	}
       
   587 
       
   588 	$db->sql_transaction('commit');
       
   589 
       
   590 	// Reset newest user info if appropriate
       
   591 	if ($config['newest_user_id'] == $user_id)
       
   592 	{
       
   593 		update_last_username();
       
   594 	}
       
   595 
       
   596 	// Decrement number of users if this user is active
       
   597 	if ($user_row['user_type'] != USER_INACTIVE && $user_row['user_type'] != USER_IGNORE)
       
   598 	{
       
   599 		set_config_count('num_users', -1, true);
       
   600 	}
       
   601 
       
   602 	return false;
       
   603 }
       
   604 
       
   605 /**
       
   606 * Flips user_type from active to inactive and vice versa, handles group membership updates
       
   607 *
       
   608 * @param string $mode can be flip for flipping from active/inactive, activate or deactivate
       
   609 */
       
   610 function user_active_flip($mode, $user_id_ary, $reason = INACTIVE_MANUAL)
       
   611 {
       
   612 	global $config, $db, $user, $auth;
       
   613 
       
   614 	$deactivated = $activated = 0;
       
   615 	$sql_statements = array();
       
   616 
       
   617 	if (!is_array($user_id_ary))
       
   618 	{
       
   619 		$user_id_ary = array($user_id_ary);
       
   620 	}
       
   621 
       
   622 	if (!sizeof($user_id_ary))
       
   623 	{
       
   624 		return;
       
   625 	}
       
   626 
       
   627 	$sql = 'SELECT user_id, group_id, user_type, user_inactive_reason
       
   628 		FROM ' . USERS_TABLE . '
       
   629 		WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
       
   630 	$result = $db->sql_query($sql);
       
   631 
       
   632 	while ($row = $db->sql_fetchrow($result))
       
   633 	{
       
   634 		$sql_ary = array();
       
   635 
       
   636 		if ($row['user_type'] == USER_IGNORE || $row['user_type'] == USER_FOUNDER ||
       
   637 			($mode == 'activate' && $row['user_type'] != USER_INACTIVE) ||
       
   638 			($mode == 'deactivate' && $row['user_type'] == USER_INACTIVE))
       
   639 		{
       
   640 			continue;
       
   641 		}
       
   642 
       
   643 		if ($row['user_type'] == USER_INACTIVE)
       
   644 		{
       
   645 			$activated++;
       
   646 		}
       
   647 		else
       
   648 		{
       
   649 			$deactivated++;
       
   650 
       
   651 			// Remove the users session key...
       
   652 			$user->reset_login_keys($row['user_id']);
       
   653 		}
       
   654 
       
   655 		$sql_ary += array(
       
   656 			'user_type'				=> ($row['user_type'] == USER_NORMAL) ? USER_INACTIVE : USER_NORMAL,
       
   657 			'user_inactive_time'	=> ($row['user_type'] == USER_NORMAL) ? time() : 0,
       
   658 			'user_inactive_reason'	=> ($row['user_type'] == USER_NORMAL) ? $reason : 0,
       
   659 		);
       
   660 
       
   661 		$sql_statements[$row['user_id']] = $sql_ary;
       
   662 	}
       
   663 	$db->sql_freeresult($result);
       
   664 
       
   665 	if (sizeof($sql_statements))
       
   666 	{
       
   667 		foreach ($sql_statements as $user_id => $sql_ary)
       
   668 		{
       
   669 			$sql = 'UPDATE ' . USERS_TABLE . '
       
   670 				SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
       
   671 				WHERE user_id = ' . $user_id;
       
   672 			$db->sql_query($sql);
       
   673 		}
       
   674 
       
   675 		$auth->acl_clear_prefetch(array_keys($sql_statements));
       
   676 	}
       
   677 
       
   678 	if ($deactivated)
       
   679 	{
       
   680 		set_config_count('num_users', $deactivated * (-1), true);
       
   681 	}
       
   682 
       
   683 	if ($activated)
       
   684 	{
       
   685 		set_config_count('num_users', $activated, true);
       
   686 	}
       
   687 
       
   688 	// Update latest username
       
   689 	update_last_username();
       
   690 }
       
   691 
       
   692 /**
       
   693 * Add a ban or ban exclusion to the banlist. Bans either a user, an IP or an email address
       
   694 *
       
   695 * @param string $mode Type of ban. One of the following: user, ip, email
       
   696 * @param mixed $ban Banned entity. Either string or array with usernames, ips or email addresses
       
   697 * @param int $ban_len Ban length in minutes
       
   698 * @param string $ban_len_other Ban length as a date (YYYY-MM-DD)
       
   699 * @param boolean $ban_exclude Exclude these entities from banning?
       
   700 * @param string $ban_reason String describing the reason for this ban
       
   701 * @return boolean
       
   702 */
       
   703 function user_ban($mode, $ban, $ban_len, $ban_len_other, $ban_exclude, $ban_reason, $ban_give_reason = '')
       
   704 {
       
   705 	global $db, $user, $auth, $cache;
       
   706 
       
   707 	// Delete stale bans
       
   708 	$sql = 'DELETE FROM ' . BANLIST_TABLE . '
       
   709 		WHERE ban_end < ' . time() . '
       
   710 			AND ban_end <> 0';
       
   711 	$db->sql_query($sql);
       
   712 
       
   713 	$ban_list = (!is_array($ban)) ? array_unique(explode("\n", $ban)) : $ban;
       
   714 	$ban_list_log = implode(', ', $ban_list);
       
   715 
       
   716 	$current_time = time();
       
   717 
       
   718 	// Set $ban_end to the unix time when the ban should end. 0 is a permanent ban.
       
   719 	if ($ban_len)
       
   720 	{
       
   721 		if ($ban_len != -1 || !$ban_len_other)
       
   722 		{
       
   723 			$ban_end = max($current_time, $current_time + ($ban_len) * 60);
       
   724 		}
       
   725 		else
       
   726 		{
       
   727 			$ban_other = explode('-', $ban_len_other);
       
   728 			if (sizeof($ban_other) == 3 && ((int)$ban_other[0] < 9999) &&
       
   729 				(strlen($ban_other[0]) == 4) && (strlen($ban_other[1]) == 2) && (strlen($ban_other[2]) == 2))
       
   730 			{
       
   731 				$time_offset = (isset($user->timezone) && isset($user->dst)) ? (int) $user->timezone + (int) $user->dst : 0;
       
   732 				$ban_end = max($current_time, gmmktime(0, 0, 0, (int)$ban_other[1], (int)$ban_other[2], (int)$ban_other[0]) - $time_offset);
       
   733 			}
       
   734 			else
       
   735 			{
       
   736 				trigger_error('LENGTH_BAN_INVALID', E_USER_WARNING);
       
   737 			}
       
   738 		}
       
   739 	}
       
   740 	else
       
   741 	{
       
   742 		$ban_end = 0;
       
   743 	}
       
   744 
       
   745 	$founder = $founder_names = array();
       
   746 
       
   747 	if (!$ban_exclude)
       
   748 	{
       
   749 		// Create a list of founder...
       
   750 		$sql = 'SELECT user_id, user_email, username_clean
       
   751 			FROM ' . USERS_TABLE . '
       
   752 			WHERE user_type = ' . USER_FOUNDER;
       
   753 		$result = $db->sql_query($sql);
       
   754 
       
   755 		while ($row = $db->sql_fetchrow($result))
       
   756 		{
       
   757 			$founder[$row['user_id']] = $row['user_email'];
       
   758 			$founder_names[$row['user_id']] = $row['username_clean'];
       
   759 		}
       
   760 		$db->sql_freeresult($result);
       
   761 	}
       
   762 
       
   763 	$banlist_ary = array();
       
   764 
       
   765 	switch ($mode)
       
   766 	{
       
   767 		case 'user':
       
   768 			$type = 'ban_userid';
       
   769 
       
   770 			// At the moment we do not support wildcard username banning
       
   771 
       
   772 			// Select the relevant user_ids.
       
   773 			$sql_usernames = array();
       
   774 
       
   775 			foreach ($ban_list as $username)
       
   776 			{
       
   777 				$username = trim($username);
       
   778 				if ($username != '')
       
   779 				{
       
   780 					$clean_name = utf8_clean_string($username);
       
   781 					if ($clean_name == $user->data['username_clean'])
       
   782 					{
       
   783 						trigger_error('CANNOT_BAN_YOURSELF', E_USER_WARNING);
       
   784 					}
       
   785 					if (in_array($clean_name, $founder_names))
       
   786 					{
       
   787 						trigger_error('CANNOT_BAN_FOUNDER', E_USER_WARNING);
       
   788 					}
       
   789 					$sql_usernames[] = $clean_name;
       
   790 				}
       
   791 			}
       
   792 
       
   793 			// Make sure we have been given someone to ban
       
   794 			if (!sizeof($sql_usernames))
       
   795 			{
       
   796 				trigger_error('NO_USER_SPECIFIED', E_USER_WARNING);
       
   797 			}
       
   798 
       
   799 			$sql = 'SELECT user_id
       
   800 				FROM ' . USERS_TABLE . '
       
   801 				WHERE ' . $db->sql_in_set('username_clean', $sql_usernames);
       
   802 
       
   803 			// Do not allow banning yourself, the guest account, or founders.
       
   804 			$non_bannable = array($user->data['user_id'], ANONYMOUS);
       
   805 			if (sizeof($founder))
       
   806 			{
       
   807 				$sql .= ' AND ' . $db->sql_in_set('user_id', array_merge(array_keys($founder), $non_bannable), true);
       
   808 			}
       
   809 			else
       
   810 			{
       
   811 				$sql .= ' AND ' . $db->sql_in_set('user_id', $non_bannable, true);
       
   812 			}
       
   813 
       
   814 			$result = $db->sql_query($sql);
       
   815 
       
   816 			if ($row = $db->sql_fetchrow($result))
       
   817 			{
       
   818 				do
       
   819 				{
       
   820 					$banlist_ary[] = (int) $row['user_id'];
       
   821 				}
       
   822 				while ($row = $db->sql_fetchrow($result));
       
   823 			}
       
   824 			else
       
   825 			{
       
   826 				$db->sql_freeresult($result);
       
   827 				trigger_error('NO_USERS', E_USER_WARNING);
       
   828 			}
       
   829 			$db->sql_freeresult($result);
       
   830 		break;
       
   831 
       
   832 		case 'ip':
       
   833 			$type = 'ban_ip';
       
   834 
       
   835 			foreach ($ban_list as $ban_item)
       
   836 			{
       
   837 				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))
       
   838 				{
       
   839 					// This is an IP range
       
   840 					// Don't ask about all this, just don't ask ... !
       
   841 					$ip_1_counter = $ip_range_explode[1];
       
   842 					$ip_1_end = $ip_range_explode[5];
       
   843 
       
   844 					while ($ip_1_counter <= $ip_1_end)
       
   845 					{
       
   846 						$ip_2_counter = ($ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[2] : 0;
       
   847 						$ip_2_end = ($ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[6];
       
   848 
       
   849 						if ($ip_2_counter == 0 && $ip_2_end == 254)
       
   850 						{
       
   851 							$ip_2_counter = 256;
       
   852 							$ip_2_fragment = 256;
       
   853 
       
   854 							$banlist_ary[] = "$ip_1_counter.*";
       
   855 						}
       
   856 
       
   857 						while ($ip_2_counter <= $ip_2_end)
       
   858 						{
       
   859 							$ip_3_counter = ($ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[3] : 0;
       
   860 							$ip_3_end = ($ip_2_counter < $ip_2_end || $ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[7];
       
   861 
       
   862 							if ($ip_3_counter == 0 && $ip_3_end == 254)
       
   863 							{
       
   864 								$ip_3_counter = 256;
       
   865 								$ip_3_fragment = 256;
       
   866 
       
   867 								$banlist_ary[] = "$ip_1_counter.$ip_2_counter.*";
       
   868 							}
       
   869 
       
   870 							while ($ip_3_counter <= $ip_3_end)
       
   871 							{
       
   872 								$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;
       
   873 								$ip_4_end = ($ip_3_counter < $ip_3_end || $ip_2_counter < $ip_2_end) ? 254 : $ip_range_explode[8];
       
   874 
       
   875 								if ($ip_4_counter == 0 && $ip_4_end == 254)
       
   876 								{
       
   877 									$ip_4_counter = 256;
       
   878 									$ip_4_fragment = 256;
       
   879 
       
   880 									$banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.*";
       
   881 								}
       
   882 
       
   883 								while ($ip_4_counter <= $ip_4_end)
       
   884 								{
       
   885 									$banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.$ip_4_counter";
       
   886 									$ip_4_counter++;
       
   887 								}
       
   888 								$ip_3_counter++;
       
   889 							}
       
   890 							$ip_2_counter++;
       
   891 						}
       
   892 						$ip_1_counter++;
       
   893 					}
       
   894 				}
       
   895 				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)))
       
   896 				{
       
   897 					// Normal IP address
       
   898 					$banlist_ary[] = trim($ban_item);
       
   899 				}
       
   900 				else if (preg_match('#^\*$#', trim($ban_item)))
       
   901 				{
       
   902 					// Ban all IPs
       
   903 					$banlist_ary[] = '*';
       
   904 				}
       
   905 				else if (preg_match('#^([\w\-_]\.?){2,}$#is', trim($ban_item)))
       
   906 				{
       
   907 					// hostname
       
   908 					$ip_ary = gethostbynamel(trim($ban_item));
       
   909 
       
   910 					if (!empty($ip_ary))
       
   911 					{
       
   912 						foreach ($ip_ary as $ip)
       
   913 						{
       
   914 							if ($ip)
       
   915 							{
       
   916 								if (strlen($ip) > 40)
       
   917 								{
       
   918 									continue;
       
   919 								}
       
   920 
       
   921 								$banlist_ary[] = $ip;
       
   922 							}
       
   923 						}
       
   924 					}
       
   925 				}
       
   926 
       
   927 				if (empty($banlist_ary))
       
   928 				{
       
   929 					trigger_error('NO_IPS_DEFINED', E_USER_WARNING);
       
   930 				}
       
   931 			}
       
   932 		break;
       
   933 
       
   934 		case 'email':
       
   935 			$type = 'ban_email';
       
   936 
       
   937 			foreach ($ban_list as $ban_item)
       
   938 			{
       
   939 				$ban_item = trim($ban_item);
       
   940 
       
   941 				if (preg_match('#^.*?@*|(([a-z0-9\-]+\.)+([a-z]{2,3}))$#i', $ban_item))
       
   942 				{
       
   943 					if (strlen($ban_item) > 100)
       
   944 					{
       
   945 						continue;
       
   946 					}
       
   947 
       
   948 					if (!sizeof($founder) || !in_array($ban_item, $founder))
       
   949 					{
       
   950 						$banlist_ary[] = $ban_item;
       
   951 					}
       
   952 				}
       
   953 			}
       
   954 
       
   955 			if (sizeof($ban_list) == 0)
       
   956 			{
       
   957 				trigger_error('NO_EMAILS_DEFINED', E_USER_WARNING);
       
   958 			}
       
   959 		break;
       
   960 
       
   961 		default:
       
   962 			trigger_error('NO_MODE', E_USER_WARNING);
       
   963 		break;
       
   964 	}
       
   965 
       
   966 	// Fetch currently set bans of the specified type and exclude state. Prevent duplicate bans.
       
   967 	$sql_where = ($type == 'ban_userid') ? 'ban_userid <> 0' : "$type <> ''";
       
   968 
       
   969 	$sql = "SELECT $type
       
   970 		FROM " . BANLIST_TABLE . "
       
   971 		WHERE $sql_where
       
   972 			AND ban_exclude = " . (int) $ban_exclude;
       
   973 	$result = $db->sql_query($sql);
       
   974 
       
   975 	// Reset $sql_where, because we use it later...
       
   976 	$sql_where = '';
       
   977 
       
   978 	if ($row = $db->sql_fetchrow($result))
       
   979 	{
       
   980 		$banlist_ary_tmp = array();
       
   981 		do
       
   982 		{
       
   983 			switch ($mode)
       
   984 			{
       
   985 				case 'user':
       
   986 					$banlist_ary_tmp[] = $row['ban_userid'];
       
   987 				break;
       
   988 
       
   989 				case 'ip':
       
   990 					$banlist_ary_tmp[] = $row['ban_ip'];
       
   991 				break;
       
   992 
       
   993 				case 'email':
       
   994 					$banlist_ary_tmp[] = $row['ban_email'];
       
   995 				break;
       
   996 			}
       
   997 		}
       
   998 		while ($row = $db->sql_fetchrow($result));
       
   999 
       
  1000 		$banlist_ary_tmp = array_intersect($banlist_ary, $banlist_ary_tmp);
       
  1001 
       
  1002 		if (sizeof($banlist_ary_tmp))
       
  1003 		{
       
  1004 			// One or more entities are already banned/excluded, delete the existing bans, so they can be re-inserted with the given new length
       
  1005 			$sql = 'DELETE FROM ' . BANLIST_TABLE . '
       
  1006 				WHERE ' . $db->sql_in_set($type, $banlist_ary_tmp) . '
       
  1007 					AND ban_exclude = ' . (int) $ban_exclude;
       
  1008 			$db->sql_query($sql);
       
  1009 		}
       
  1010 
       
  1011 		unset($banlist_ary_tmp);
       
  1012 	}
       
  1013 	$db->sql_freeresult($result);
       
  1014 
       
  1015 	// We have some entities to ban
       
  1016 	if (sizeof($banlist_ary))
       
  1017 	{
       
  1018 		$sql_ary = array();
       
  1019 
       
  1020 		foreach ($banlist_ary as $ban_entry)
       
  1021 		{
       
  1022 			$sql_ary[] = array(
       
  1023 				$type				=> $ban_entry,
       
  1024 				'ban_start'			=> (int) $current_time,
       
  1025 				'ban_end'			=> (int) $ban_end,
       
  1026 				'ban_exclude'		=> (int) $ban_exclude,
       
  1027 				'ban_reason'		=> (string) $ban_reason,
       
  1028 				'ban_give_reason'	=> (string) $ban_give_reason,
       
  1029 			);
       
  1030 		}
       
  1031 
       
  1032 		$db->sql_multi_insert(BANLIST_TABLE, $sql_ary);
       
  1033 
       
  1034 		// If we are banning we want to logout anyone matching the ban
       
  1035 		if (!$ban_exclude)
       
  1036 		{
       
  1037 			switch ($mode)
       
  1038 			{
       
  1039 				case 'user':
       
  1040 					$sql_where = 'WHERE ' . $db->sql_in_set('session_user_id', $banlist_ary);
       
  1041 				break;
       
  1042 
       
  1043 				case 'ip':
       
  1044 					$sql_where = 'WHERE ' . $db->sql_in_set('session_ip', $banlist_ary);
       
  1045 				break;
       
  1046 
       
  1047 				case 'email':
       
  1048 					$banlist_ary_sql = array();
       
  1049 
       
  1050 					foreach ($banlist_ary as $ban_entry)
       
  1051 					{
       
  1052 						$banlist_ary_sql[] = (string) str_replace('*', '%', $ban_entry);
       
  1053 					}
       
  1054 
       
  1055 					$sql = 'SELECT user_id
       
  1056 						FROM ' . USERS_TABLE . '
       
  1057 						WHERE ' . $db->sql_in_set('user_email', $banlist_ary_sql);
       
  1058 					$result = $db->sql_query($sql);
       
  1059 
       
  1060 					$sql_in = array();
       
  1061 
       
  1062 					if ($row = $db->sql_fetchrow($result))
       
  1063 					{
       
  1064 						do
       
  1065 						{
       
  1066 							$sql_in[] = $row['user_id'];
       
  1067 						}
       
  1068 						while ($row = $db->sql_fetchrow($result));
       
  1069 
       
  1070 						$sql_where = 'WHERE ' . $db->sql_in_set('session_user_id', $sql_in);
       
  1071 					}
       
  1072 					$db->sql_freeresult($result);
       
  1073 				break;
       
  1074 			}
       
  1075 
       
  1076 			if (isset($sql_where) && $sql_where)
       
  1077 			{
       
  1078 				$sql = 'DELETE FROM ' . SESSIONS_TABLE . "
       
  1079 					$sql_where";
       
  1080 				$db->sql_query($sql);
       
  1081 
       
  1082 				if ($mode == 'user')
       
  1083 				{
       
  1084 					$sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . ' ' . ((in_array('*', $banlist_ary)) ? '' : 'WHERE ' . $db->sql_in_set('user_id', $banlist_ary));
       
  1085 					$db->sql_query($sql);
       
  1086 				}
       
  1087 			}
       
  1088 		}
       
  1089 
       
  1090 		// Update log
       
  1091 		$log_entry = ($ban_exclude) ? 'LOG_BAN_EXCLUDE_' : 'LOG_BAN_';
       
  1092 
       
  1093 		// Add to moderator log, admin log and user notes
       
  1094 		add_log('admin', $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
       
  1095 		add_log('mod', 0, 0, $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
       
  1096 		if ($mode == 'user')
       
  1097 		{
       
  1098 			foreach ($banlist_ary as $user_id)
       
  1099 			{
       
  1100 				add_log('user', $user_id, $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
       
  1101 			}
       
  1102 		}
       
  1103 
       
  1104 		$cache->destroy('sql', BANLIST_TABLE);
       
  1105 
       
  1106 		return true;
       
  1107 	}
       
  1108 
       
  1109 	// There was nothing to ban/exclude. But destroying the cache because of the removal of stale bans.
       
  1110 	$cache->destroy('sql', BANLIST_TABLE);
       
  1111 
       
  1112 	return false;
       
  1113 }
       
  1114 
       
  1115 /**
       
  1116 * Unban User
       
  1117 */
       
  1118 function user_unban($mode, $ban)
       
  1119 {
       
  1120 	global $db, $user, $auth, $cache;
       
  1121 
       
  1122 	// Delete stale bans
       
  1123 	$sql = 'DELETE FROM ' . BANLIST_TABLE . '
       
  1124 		WHERE ban_end < ' . time() . '
       
  1125 			AND ban_end <> 0';
       
  1126 	$db->sql_query($sql);
       
  1127 
       
  1128 	if (!is_array($ban))
       
  1129 	{
       
  1130 		$ban = array($ban);
       
  1131 	}
       
  1132 
       
  1133 	$unban_sql = array_map('intval', $ban);
       
  1134 
       
  1135 	if (sizeof($unban_sql))
       
  1136 	{
       
  1137 		// Grab details of bans for logging information later
       
  1138 		switch ($mode)
       
  1139 		{
       
  1140 			case 'user':
       
  1141 				$sql = 'SELECT u.username AS unban_info, u.user_id
       
  1142 					FROM ' . USERS_TABLE . ' u, ' . BANLIST_TABLE . ' b
       
  1143 					WHERE ' . $db->sql_in_set('b.ban_id', $unban_sql) . '
       
  1144 						AND u.user_id = b.ban_userid';
       
  1145 			break;
       
  1146 
       
  1147 			case 'email':
       
  1148 				$sql = 'SELECT ban_email AS unban_info
       
  1149 					FROM ' . BANLIST_TABLE . '
       
  1150 					WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
       
  1151 			break;
       
  1152 
       
  1153 			case 'ip':
       
  1154 				$sql = 'SELECT ban_ip AS unban_info
       
  1155 					FROM ' . BANLIST_TABLE . '
       
  1156 					WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
       
  1157 			break;
       
  1158 		}
       
  1159 		$result = $db->sql_query($sql);
       
  1160 
       
  1161 		$l_unban_list = '';
       
  1162 		$user_ids_ary = array();
       
  1163 		while ($row = $db->sql_fetchrow($result))
       
  1164 		{
       
  1165 			$l_unban_list .= (($l_unban_list != '') ? ', ' : '') . $row['unban_info'];
       
  1166 			if ($mode == 'user')
       
  1167 			{
       
  1168 				$user_ids_ary[] = $row['user_id'];
       
  1169 			}
       
  1170 		}
       
  1171 		$db->sql_freeresult($result);
       
  1172 
       
  1173 		$sql = 'DELETE FROM ' . BANLIST_TABLE . '
       
  1174 			WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
       
  1175 		$db->sql_query($sql);
       
  1176 
       
  1177 		// Add to moderator log, admin log and user notes
       
  1178 		add_log('admin', 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
       
  1179 		add_log('mod', 0, 0, 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
       
  1180 		if ($mode == 'user')
       
  1181 		{
       
  1182 			foreach ($user_ids_ary as $user_id)
       
  1183 			{
       
  1184 				add_log('user', $user_id, 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
       
  1185 			}
       
  1186 		}
       
  1187 	}
       
  1188 
       
  1189 	$cache->destroy('sql', BANLIST_TABLE);
       
  1190 
       
  1191 	return false;
       
  1192 }
       
  1193 
       
  1194 /**
       
  1195 * Internet Protocol Address Whois
       
  1196 * RFC3912: WHOIS Protocol Specification
       
  1197 *
       
  1198 * @param string $ip		Ip address, either IPv4 or IPv6.
       
  1199 *
       
  1200 * @return string		Empty string if not a valid ip address.
       
  1201 *						Otherwise make_clickable()'ed whois result.
       
  1202 */
       
  1203 function user_ipwhois($ip)
       
  1204 {
       
  1205 	if (empty($ip))
       
  1206 	{
       
  1207 		return '';
       
  1208 	}
       
  1209 
       
  1210 	if (preg_match(get_preg_expression('ipv4'), $ip))
       
  1211 	{
       
  1212 		// IPv4 address
       
  1213 		$whois_host = 'whois.arin.net.';
       
  1214 	}
       
  1215 	else if (preg_match(get_preg_expression('ipv6'), $ip))
       
  1216 	{
       
  1217 		// IPv6 address
       
  1218 		$whois_host = 'whois.sixxs.net.';
       
  1219 	}
       
  1220 	else
       
  1221 	{
       
  1222 		return '';
       
  1223 	}
       
  1224 
       
  1225 	$ipwhois = '';
       
  1226 
       
  1227 	if (($fsk = @fsockopen($whois_host, 43)))
       
  1228 	{
       
  1229 		// CRLF as per RFC3912
       
  1230 		fputs($fsk, "$ip\r\n");
       
  1231 		while (!feof($fsk))
       
  1232 		{
       
  1233 			$ipwhois .= fgets($fsk, 1024);
       
  1234 		}
       
  1235 		@fclose($fsk);
       
  1236 	}
       
  1237 
       
  1238 	$match = array();
       
  1239 
       
  1240 	// Test for referrals from $whois_host to other whois databases, roll on rwhois
       
  1241 	if (preg_match('#ReferralServer: whois://(.+)#im', $ipwhois, $match))
       
  1242 	{
       
  1243 		if (strpos($match[1], ':') !== false)
       
  1244 		{
       
  1245 			$pos	= strrpos($match[1], ':');
       
  1246 			$server	= substr($match[1], 0, $pos);
       
  1247 			$port	= (int) substr($match[1], $pos + 1);
       
  1248 			unset($pos);
       
  1249 		}
       
  1250 		else
       
  1251 		{
       
  1252 			$server	= $match[1];
       
  1253 			$port	= 43;
       
  1254 		}
       
  1255 
       
  1256 		$buffer = '';
       
  1257 
       
  1258 		if (($fsk = @fsockopen($server, $port)))
       
  1259 		{
       
  1260 			fputs($fsk, "$ip\r\n");
       
  1261 			while (!feof($fsk))
       
  1262 			{
       
  1263 				$buffer .= fgets($fsk, 1024);
       
  1264 			}
       
  1265 			@fclose($fsk);
       
  1266 		}
       
  1267 
       
  1268 		// Use the result from $whois_host if we don't get any result here
       
  1269 		$ipwhois = (empty($buffer)) ? $ipwhois : $buffer;
       
  1270 	}
       
  1271 
       
  1272 	$ipwhois = htmlspecialchars($ipwhois);
       
  1273 
       
  1274 	// Magic URL ;)
       
  1275 	return trim(make_clickable($ipwhois, false, ''));
       
  1276 }
       
  1277 
       
  1278 /**
       
  1279 * Data validation ... used primarily but not exclusively by ucp modules
       
  1280 *
       
  1281 * "Master" function for validating a range of data types
       
  1282 */
       
  1283 function validate_data($data, $val_ary)
       
  1284 {
       
  1285 	global $user;
       
  1286 
       
  1287 	$error = array();
       
  1288 
       
  1289 	foreach ($val_ary as $var => $val_seq)
       
  1290 	{
       
  1291 		if (!is_array($val_seq[0]))
       
  1292 		{
       
  1293 			$val_seq = array($val_seq);
       
  1294 		}
       
  1295 
       
  1296 		foreach ($val_seq as $validate)
       
  1297 		{
       
  1298 			$function = array_shift($validate);
       
  1299 			array_unshift($validate, $data[$var]);
       
  1300 
       
  1301 			if ($result = call_user_func_array('validate_' . $function, $validate))
       
  1302 			{
       
  1303 				// Since errors are checked later for their language file existence, we need to make sure custom errors are not adjusted.
       
  1304 				$error[] = (empty($user->lang[$result . '_' . strtoupper($var)])) ? $result : $result . '_' . strtoupper($var);
       
  1305 			}
       
  1306 		}
       
  1307 	}
       
  1308 
       
  1309 	return $error;
       
  1310 }
       
  1311 
       
  1312 /**
       
  1313 * Validate String
       
  1314 *
       
  1315 * @return	boolean|string	Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
       
  1316 */
       
  1317 function validate_string($string, $optional = false, $min = 0, $max = 0)
       
  1318 {
       
  1319 	if (empty($string) && $optional)
       
  1320 	{
       
  1321 		return false;
       
  1322 	}
       
  1323 
       
  1324 	if ($min && utf8_strlen(htmlspecialchars_decode($string)) < $min)
       
  1325 	{
       
  1326 		return 'TOO_SHORT';
       
  1327 	}
       
  1328 	else if ($max && utf8_strlen(htmlspecialchars_decode($string)) > $max)
       
  1329 	{
       
  1330 		return 'TOO_LONG';
       
  1331 	}
       
  1332 
       
  1333 	return false;
       
  1334 }
       
  1335 
       
  1336 /**
       
  1337 * Validate Number
       
  1338 *
       
  1339 * @return	boolean|string	Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
       
  1340 */
       
  1341 function validate_num($num, $optional = false, $min = 0, $max = 1E99)
       
  1342 {
       
  1343 	if (empty($num) && $optional)
       
  1344 	{
       
  1345 		return false;
       
  1346 	}
       
  1347 
       
  1348 	if ($num < $min)
       
  1349 	{
       
  1350 		return 'TOO_SMALL';
       
  1351 	}
       
  1352 	else if ($num > $max)
       
  1353 	{
       
  1354 		return 'TOO_LARGE';
       
  1355 	}
       
  1356 
       
  1357 	return false;
       
  1358 }
       
  1359 
       
  1360 /**
       
  1361 * Validate Date
       
  1362 * @param String $string a date in the dd-mm-yyyy format
       
  1363 * @return	boolean
       
  1364 */
       
  1365 function validate_date($date_string, $optional = false)
       
  1366 {
       
  1367 	$date = explode('-', $date_string);
       
  1368 	if ((empty($date) || sizeof($date) != 3) && $optional)
       
  1369 	{
       
  1370 		return false;
       
  1371 	}
       
  1372 	else if ($optional)
       
  1373 	{
       
  1374 		for ($field = 0; $field <= 1; $field++)
       
  1375 		{
       
  1376 			$date[$field] = (int) $date[$field];
       
  1377 			if (empty($date[$field]))
       
  1378 			{
       
  1379 				$date[$field] = 1;
       
  1380 			}
       
  1381 		}
       
  1382 		$date[2] = (int) $date[2];
       
  1383 		// assume an arbitrary leap year
       
  1384 		if (empty($date[2]))
       
  1385 		{
       
  1386 			$date[2] = 1980;
       
  1387 		}
       
  1388 	}
       
  1389 
       
  1390 	if (sizeof($date) != 3 || !checkdate($date[1], $date[0], $date[2]))
       
  1391 	{
       
  1392 		return 'INVALID';
       
  1393 	}
       
  1394 
       
  1395 	return false;
       
  1396 }
       
  1397 
       
  1398 
       
  1399 /**
       
  1400 * Validate Match
       
  1401 *
       
  1402 * @return	boolean|string	Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
       
  1403 */
       
  1404 function validate_match($string, $optional = false, $match = '')
       
  1405 {
       
  1406 	if (empty($string) && $optional)
       
  1407 	{
       
  1408 		return false;
       
  1409 	}
       
  1410 
       
  1411 	if (empty($match))
       
  1412 	{
       
  1413 		return false;
       
  1414 	}
       
  1415 
       
  1416 	if (!preg_match($match, $string))
       
  1417 	{
       
  1418 		return 'WRONG_DATA';
       
  1419 	}
       
  1420 
       
  1421 	return false;
       
  1422 }
       
  1423 
       
  1424 /**
       
  1425 * Validate Language Pack ISO Name
       
  1426 *
       
  1427 * Tests whether a language name is valid and installed
       
  1428 *
       
  1429 * @param string $lang_iso	The language string to test
       
  1430 *
       
  1431 * @return bool|string		Either false if validation succeeded or
       
  1432 *							a string which will be used as the error message
       
  1433 *							(with the variable name appended)
       
  1434 */
       
  1435 function validate_language_iso_name($lang_iso)
       
  1436 {
       
  1437 	global $db;
       
  1438 
       
  1439 	$sql = 'SELECT lang_id
       
  1440 		FROM ' . LANG_TABLE . "
       
  1441 		WHERE lang_iso = '" . $db->sql_escape($lang_iso) . "'";
       
  1442 	$result = $db->sql_query($sql);
       
  1443 	$lang_id = (int) $db->sql_fetchfield('lang_id');
       
  1444 	$db->sql_freeresult($result);
       
  1445 
       
  1446 	return ($lang_id) ? false : 'WRONG_DATA';
       
  1447 }
       
  1448 
       
  1449 /**
       
  1450 * Check to see if the username has been taken, or if it is disallowed.
       
  1451 * Also checks if it includes the " character, which we don't allow in usernames.
       
  1452 * Used for registering, changing names, and posting anonymously with a username
       
  1453 *
       
  1454 * @param string $username The username to check
       
  1455 * @param string $allowed_username An allowed username, default being $user->data['username']
       
  1456 *
       
  1457 * @return	mixed	Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
       
  1458 */
       
  1459 function validate_username($username, $allowed_username = false)
       
  1460 {
       
  1461 	global $config, $db, $user, $cache;
       
  1462 
       
  1463 	$clean_username = utf8_clean_string($username);
       
  1464 	$allowed_username = ($allowed_username === false) ? $user->data['username_clean'] : utf8_clean_string($allowed_username);
       
  1465 
       
  1466 	if ($allowed_username == $clean_username)
       
  1467 	{
       
  1468 		return false;
       
  1469 	}
       
  1470 
       
  1471 	// ... fast checks first.
       
  1472 	if (strpos($username, '&quot;') !== false || strpos($username, '"') !== false || empty($clean_username))
       
  1473 	{
       
  1474 		return 'INVALID_CHARS';
       
  1475 	}
       
  1476 
       
  1477 	$mbstring = $pcre = false;
       
  1478 
       
  1479 	// generic UTF-8 character types supported?
       
  1480 	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)
       
  1481 	{
       
  1482 		$pcre = true;
       
  1483 	}
       
  1484 	else if (function_exists('mb_ereg_match'))
       
  1485 	{
       
  1486 		mb_regex_encoding('UTF-8');
       
  1487 		$mbstring = true;
       
  1488 	}
       
  1489 
       
  1490 	switch ($config['allow_name_chars'])
       
  1491 	{
       
  1492 		case 'USERNAME_CHARS_ANY':
       
  1493 			$pcre = true;
       
  1494 			$regex = '.+';
       
  1495 		break;
       
  1496 
       
  1497 		case 'USERNAME_ALPHA_ONLY':
       
  1498 			$pcre = true;
       
  1499 			$regex = '[A-Za-z0-9]+';
       
  1500 		break;
       
  1501 
       
  1502 		case 'USERNAME_ALPHA_SPACERS':
       
  1503 			$pcre = true;
       
  1504 			$regex = '[A-Za-z0-9-[\]_+ ]+';
       
  1505 		break;
       
  1506 
       
  1507 		case 'USERNAME_LETTER_NUM':
       
  1508 			if ($pcre)
       
  1509 			{
       
  1510 				$regex = '[\p{Lu}\p{Ll}\p{N}]+';
       
  1511 			}
       
  1512 			else if ($mbstring)
       
  1513 			{
       
  1514 				$regex = '[[:upper:][:lower:][:digit:]]+';
       
  1515 			}
       
  1516 			else
       
  1517 			{
       
  1518 				$pcre = true;
       
  1519 				$regex = '[a-zA-Z0-9]+';
       
  1520 			}
       
  1521 		break;
       
  1522 
       
  1523 		case 'USERNAME_LETTER_NUM_SPACERS':
       
  1524 			if ($pcre)
       
  1525 			{
       
  1526 				$regex = '[-\]_+ [\p{Lu}\p{Ll}\p{N}]+';
       
  1527 			}
       
  1528 			else if ($mbstring)
       
  1529 			{
       
  1530 				$regex = '[-\]_+ \[[:upper:][:lower:][:digit:]]+';
       
  1531 			}
       
  1532 			else
       
  1533 			{
       
  1534 				$pcre = true;
       
  1535 				$regex = '[-\]_+ [a-zA-Z0-9]+';
       
  1536 			}
       
  1537 		break;
       
  1538 
       
  1539 		case 'USERNAME_ASCII':
       
  1540 		default:
       
  1541 			$pcre = true;
       
  1542 			$regex = '[\x01-\x7F]+';
       
  1543 		break;
       
  1544 	}
       
  1545 
       
  1546 	if ($pcre)
       
  1547 	{
       
  1548 		if (!preg_match('#^' . $regex . '$#u', $username))
       
  1549 		{
       
  1550 			return 'INVALID_CHARS';
       
  1551 		}
       
  1552 	}
       
  1553 	else if ($mbstring)
       
  1554 	{
       
  1555 		mb_ereg_search_init($username, '^' . $regex . '$');
       
  1556 		if (!mb_ereg_search())
       
  1557 		{
       
  1558 			return 'INVALID_CHARS';
       
  1559 		}
       
  1560 	}
       
  1561 
       
  1562 	$sql = 'SELECT username
       
  1563 		FROM ' . USERS_TABLE . "
       
  1564 		WHERE username_clean = '" . $db->sql_escape($clean_username) . "'";
       
  1565 	$result = $db->sql_query($sql);
       
  1566 	$row = $db->sql_fetchrow($result);
       
  1567 	$db->sql_freeresult($result);
       
  1568 
       
  1569 	if ($row)
       
  1570 	{
       
  1571 		return 'USERNAME_TAKEN';
       
  1572 	}
       
  1573 
       
  1574 	$sql = 'SELECT group_name
       
  1575 		FROM ' . GROUPS_TABLE . "
       
  1576 		WHERE LOWER(group_name) = '" . $db->sql_escape(utf8_strtolower($username)) . "'";
       
  1577 	$result = $db->sql_query($sql);
       
  1578 	$row = $db->sql_fetchrow($result);
       
  1579 	$db->sql_freeresult($result);
       
  1580 
       
  1581 	if ($row)
       
  1582 	{
       
  1583 		return 'USERNAME_TAKEN';
       
  1584 	}
       
  1585 
       
  1586 	$bad_usernames = $cache->obtain_disallowed_usernames();
       
  1587 
       
  1588 	foreach ($bad_usernames as $bad_username)
       
  1589 	{
       
  1590 		if (preg_match('#^' . $bad_username . '$#', $clean_username))
       
  1591 		{
       
  1592 			return 'USERNAME_DISALLOWED';
       
  1593 		}
       
  1594 	}
       
  1595 
       
  1596 	return false;
       
  1597 }
       
  1598 
       
  1599 /**
       
  1600 * Check to see if the password meets the complexity settings
       
  1601 *
       
  1602 * @return	boolean|string	Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
       
  1603 */
       
  1604 function validate_password($password)
       
  1605 {
       
  1606 	global $config, $db, $user;
       
  1607 
       
  1608 	if ($password === '' || $config['pass_complex'] === 'PASS_TYPE_ANY')
       
  1609 	{
       
  1610 		// Password empty or no password complexity required.
       
  1611 		return false;
       
  1612 	}
       
  1613 
       
  1614 	$pcre = $mbstring = false;
       
  1615 
       
  1616 	// generic UTF-8 character types supported?
       
  1617 	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)
       
  1618 	{
       
  1619 		$upp = '\p{Lu}';
       
  1620 		$low = '\p{Ll}';
       
  1621 		$num = '\p{N}';
       
  1622 		$sym = '[^\p{Lu}\p{Ll}\p{N}]';
       
  1623 		$pcre = true;
       
  1624 	}
       
  1625 	else if (function_exists('mb_ereg_match'))
       
  1626 	{
       
  1627 		mb_regex_encoding('UTF-8');
       
  1628 		$upp = '[[:upper:]]';
       
  1629 		$low = '[[:lower:]]';
       
  1630 		$num = '[[:digit:]]';
       
  1631 		$sym = '[^[:upper:][:lower:][:digit:]]';
       
  1632 		$mbstring = true;
       
  1633 	}
       
  1634 	else
       
  1635 	{
       
  1636 		$upp = '[A-Z]';
       
  1637 		$low = '[a-z]';
       
  1638 		$num = '[0-9]';
       
  1639 		$sym = '[^A-Za-z0-9]';
       
  1640 		$pcre = true;
       
  1641 	}
       
  1642 
       
  1643 	$chars = array();
       
  1644 
       
  1645 	switch ($config['pass_complex'])
       
  1646 	{
       
  1647 		// No break statements below ...
       
  1648 		// We require strong passwords in case pass_complex is not set or is invalid
       
  1649 		default:
       
  1650 
       
  1651 		// Require mixed case letters, numbers and symbols
       
  1652 		case 'PASS_TYPE_SYMBOL':
       
  1653 			$chars[] = $sym;
       
  1654 
       
  1655 		// Require mixed case letters and numbers
       
  1656 		case 'PASS_TYPE_ALPHA':
       
  1657 			$chars[] = $num;
       
  1658 
       
  1659 		// Require mixed case letters
       
  1660 		case 'PASS_TYPE_CASE':
       
  1661 			$chars[] = $low;
       
  1662 			$chars[] = $upp;
       
  1663 	}
       
  1664 
       
  1665 	if ($pcre)
       
  1666 	{
       
  1667 		foreach ($chars as $char)
       
  1668 		{
       
  1669 			if (!preg_match('#' . $char . '#u', $password))
       
  1670 			{
       
  1671 				return 'INVALID_CHARS';
       
  1672 			}
       
  1673 		}
       
  1674 	}
       
  1675 	else if ($mbstring)
       
  1676 	{
       
  1677 		foreach ($chars as $char)
       
  1678 		{
       
  1679 			if (mb_ereg($char, $password) === false)
       
  1680 			{
       
  1681 				return 'INVALID_CHARS';
       
  1682 			}
       
  1683 		}
       
  1684 	}
       
  1685 
       
  1686 	return false;
       
  1687 }
       
  1688 
       
  1689 /**
       
  1690 * Check to see if email address is banned or already present in the DB
       
  1691 *
       
  1692 * @param string $email The email to check
       
  1693 * @param string $allowed_email An allowed email, default being $user->data['user_email']
       
  1694 *
       
  1695 * @return mixed Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
       
  1696 */
       
  1697 function validate_email($email, $allowed_email = false)
       
  1698 {
       
  1699 	global $config, $db, $user;
       
  1700 
       
  1701 	$email = strtolower($email);
       
  1702 	$allowed_email = ($allowed_email === false) ? strtolower($user->data['user_email']) : strtolower($allowed_email);
       
  1703 
       
  1704 	if ($allowed_email == $email)
       
  1705 	{
       
  1706 		return false;
       
  1707 	}
       
  1708 
       
  1709 	if (!preg_match('/^' . get_preg_expression('email') . '$/i', $email))
       
  1710 	{
       
  1711 		return 'EMAIL_INVALID';
       
  1712 	}
       
  1713 
       
  1714 	// Check MX record.
       
  1715 	// The idea for this is from reading the UseBB blog/announcement. :)
       
  1716 	if ($config['email_check_mx'])
       
  1717 	{
       
  1718 		list(, $domain) = explode('@', $email);
       
  1719 
       
  1720 		if (phpbb_checkdnsrr($domain, 'A') === false && phpbb_checkdnsrr($domain, 'MX') === false)
       
  1721 		{
       
  1722 			return 'DOMAIN_NO_MX_RECORD';
       
  1723 		}
       
  1724 	}
       
  1725 
       
  1726 	if (($ban_reason = $user->check_ban(false, false, $email, true)) !== false)
       
  1727 	{
       
  1728 		return ($ban_reason === true) ? 'EMAIL_BANNED' : $ban_reason;
       
  1729 	}
       
  1730 
       
  1731 	if (!$config['allow_emailreuse'])
       
  1732 	{
       
  1733 		$sql = 'SELECT user_email_hash
       
  1734 			FROM ' . USERS_TABLE . "
       
  1735 			WHERE user_email_hash = " . $db->sql_escape(phpbb_email_hash($email));
       
  1736 		$result = $db->sql_query($sql);
       
  1737 		$row = $db->sql_fetchrow($result);
       
  1738 		$db->sql_freeresult($result);
       
  1739 
       
  1740 		if ($row)
       
  1741 		{
       
  1742 			return 'EMAIL_TAKEN';
       
  1743 		}
       
  1744 	}
       
  1745 
       
  1746 	return false;
       
  1747 }
       
  1748 
       
  1749 /**
       
  1750 * Validate jabber address
       
  1751 * Taken from the jabber class within flyspray (see author notes)
       
  1752 *
       
  1753 * @author flyspray.org
       
  1754 */
       
  1755 function validate_jabber($jid)
       
  1756 {
       
  1757 	if (!$jid)
       
  1758 	{
       
  1759 		return false;
       
  1760 	}
       
  1761 
       
  1762 	$seperator_pos = strpos($jid, '@');
       
  1763 
       
  1764 	if ($seperator_pos === false)
       
  1765 	{
       
  1766 		return 'WRONG_DATA';
       
  1767 	}
       
  1768 
       
  1769 	$username = substr($jid, 0, $seperator_pos);
       
  1770 	$realm = substr($jid, $seperator_pos + 1);
       
  1771 
       
  1772 	if (strlen($username) == 0 || strlen($realm) < 3)
       
  1773 	{
       
  1774 		return 'WRONG_DATA';
       
  1775 	}
       
  1776 
       
  1777 	$arr = explode('.', $realm);
       
  1778 
       
  1779 	if (sizeof($arr) == 0)
       
  1780 	{
       
  1781 		return 'WRONG_DATA';
       
  1782 	}
       
  1783 
       
  1784 	foreach ($arr as $part)
       
  1785 	{
       
  1786 		if (substr($part, 0, 1) == '-' || substr($part, -1, 1) == '-')
       
  1787 		{
       
  1788 			return 'WRONG_DATA';
       
  1789 		}
       
  1790 
       
  1791 		if (!preg_match("@^[a-zA-Z0-9-.]+$@", $part))
       
  1792 		{
       
  1793 			return 'WRONG_DATA';
       
  1794 		}
       
  1795 	}
       
  1796 
       
  1797 	$boundary = array(array(0, 127), array(192, 223), array(224, 239), array(240, 247), array(248, 251), array(252, 253));
       
  1798 
       
  1799 	// Prohibited Characters RFC3454 + RFC3920
       
  1800 	$prohibited = array(
       
  1801 		// Table C.1.1
       
  1802 		array(0x0020, 0x0020),		// SPACE
       
  1803 		// Table C.1.2
       
  1804 		array(0x00A0, 0x00A0),		// NO-BREAK SPACE
       
  1805 		array(0x1680, 0x1680),		// OGHAM SPACE MARK
       
  1806 		array(0x2000, 0x2001),		// EN QUAD
       
  1807 		array(0x2001, 0x2001),		// EM QUAD
       
  1808 		array(0x2002, 0x2002),		// EN SPACE
       
  1809 		array(0x2003, 0x2003),		// EM SPACE
       
  1810 		array(0x2004, 0x2004),		// THREE-PER-EM SPACE
       
  1811 		array(0x2005, 0x2005),		// FOUR-PER-EM SPACE
       
  1812 		array(0x2006, 0x2006),		// SIX-PER-EM SPACE
       
  1813 		array(0x2007, 0x2007),		// FIGURE SPACE
       
  1814 		array(0x2008, 0x2008),		// PUNCTUATION SPACE
       
  1815 		array(0x2009, 0x2009),		// THIN SPACE
       
  1816 		array(0x200A, 0x200A),		// HAIR SPACE
       
  1817 		array(0x200B, 0x200B),		// ZERO WIDTH SPACE
       
  1818 		array(0x202F, 0x202F),		// NARROW NO-BREAK SPACE
       
  1819 		array(0x205F, 0x205F),		// MEDIUM MATHEMATICAL SPACE
       
  1820 		array(0x3000, 0x3000),		// IDEOGRAPHIC SPACE
       
  1821 		// Table C.2.1
       
  1822 		array(0x0000, 0x001F),		// [CONTROL CHARACTERS]
       
  1823 		array(0x007F, 0x007F),		// DELETE
       
  1824 		// Table C.2.2
       
  1825 		array(0x0080, 0x009F),		// [CONTROL CHARACTERS]
       
  1826 		array(0x06DD, 0x06DD),		// ARABIC END OF AYAH
       
  1827 		array(0x070F, 0x070F),		// SYRIAC ABBREVIATION MARK
       
  1828 		array(0x180E, 0x180E),		// MONGOLIAN VOWEL SEPARATOR
       
  1829 		array(0x200C, 0x200C), 		// ZERO WIDTH NON-JOINER
       
  1830 		array(0x200D, 0x200D),		// ZERO WIDTH JOINER
       
  1831 		array(0x2028, 0x2028),		// LINE SEPARATOR
       
  1832 		array(0x2029, 0x2029),		// PARAGRAPH SEPARATOR
       
  1833 		array(0x2060, 0x2060),		// WORD JOINER
       
  1834 		array(0x2061, 0x2061),		// FUNCTION APPLICATION
       
  1835 		array(0x2062, 0x2062),		// INVISIBLE TIMES
       
  1836 		array(0x2063, 0x2063),		// INVISIBLE SEPARATOR
       
  1837 		array(0x206A, 0x206F),		// [CONTROL CHARACTERS]
       
  1838 		array(0xFEFF, 0xFEFF),		// ZERO WIDTH NO-BREAK SPACE
       
  1839 		array(0xFFF9, 0xFFFC),		// [CONTROL CHARACTERS]
       
  1840 		array(0x1D173, 0x1D17A),	// [MUSICAL CONTROL CHARACTERS]
       
  1841 		// Table C.3
       
  1842 		array(0xE000, 0xF8FF),		// [PRIVATE USE, PLANE 0]
       
  1843 		array(0xF0000, 0xFFFFD),	// [PRIVATE USE, PLANE 15]
       
  1844 		array(0x100000, 0x10FFFD),	// [PRIVATE USE, PLANE 16]
       
  1845 		// Table C.4
       
  1846 		array(0xFDD0, 0xFDEF),		// [NONCHARACTER CODE POINTS]
       
  1847 		array(0xFFFE, 0xFFFF),		// [NONCHARACTER CODE POINTS]
       
  1848 		array(0x1FFFE, 0x1FFFF),	// [NONCHARACTER CODE POINTS]
       
  1849 		array(0x2FFFE, 0x2FFFF),	// [NONCHARACTER CODE POINTS]
       
  1850 		array(0x3FFFE, 0x3FFFF),	// [NONCHARACTER CODE POINTS]
       
  1851 		array(0x4FFFE, 0x4FFFF),	// [NONCHARACTER CODE POINTS]
       
  1852 		array(0x5FFFE, 0x5FFFF),	// [NONCHARACTER CODE POINTS]
       
  1853 		array(0x6FFFE, 0x6FFFF),	// [NONCHARACTER CODE POINTS]
       
  1854 		array(0x7FFFE, 0x7FFFF),	// [NONCHARACTER CODE POINTS]
       
  1855 		array(0x8FFFE, 0x8FFFF),	// [NONCHARACTER CODE POINTS]
       
  1856 		array(0x9FFFE, 0x9FFFF),	// [NONCHARACTER CODE POINTS]
       
  1857 		array(0xAFFFE, 0xAFFFF),	// [NONCHARACTER CODE POINTS]
       
  1858 		array(0xBFFFE, 0xBFFFF),	// [NONCHARACTER CODE POINTS]
       
  1859 		array(0xCFFFE, 0xCFFFF),	// [NONCHARACTER CODE POINTS]
       
  1860 		array(0xDFFFE, 0xDFFFF),	// [NONCHARACTER CODE POINTS]
       
  1861 		array(0xEFFFE, 0xEFFFF),	// [NONCHARACTER CODE POINTS]
       
  1862 		array(0xFFFFE, 0xFFFFF),	// [NONCHARACTER CODE POINTS]
       
  1863 		array(0x10FFFE, 0x10FFFF),	// [NONCHARACTER CODE POINTS]
       
  1864 		// Table C.5
       
  1865 		array(0xD800, 0xDFFF),		// [SURROGATE CODES]
       
  1866 		// Table C.6
       
  1867 		array(0xFFF9, 0xFFF9),		// INTERLINEAR ANNOTATION ANCHOR
       
  1868 		array(0xFFFA, 0xFFFA),		// INTERLINEAR ANNOTATION SEPARATOR
       
  1869 		array(0xFFFB, 0xFFFB),		// INTERLINEAR ANNOTATION TERMINATOR
       
  1870 		array(0xFFFC, 0xFFFC),		// OBJECT REPLACEMENT CHARACTER
       
  1871 		array(0xFFFD, 0xFFFD),		// REPLACEMENT CHARACTER
       
  1872 		// Table C.7
       
  1873 		array(0x2FF0, 0x2FFB),		// [IDEOGRAPHIC DESCRIPTION CHARACTERS]
       
  1874 		// Table C.8
       
  1875 		array(0x0340, 0x0340),		// COMBINING GRAVE TONE MARK
       
  1876 		array(0x0341, 0x0341),		// COMBINING ACUTE TONE MARK
       
  1877 		array(0x200E, 0x200E),		// LEFT-TO-RIGHT MARK
       
  1878 		array(0x200F, 0x200F),		// RIGHT-TO-LEFT MARK
       
  1879 		array(0x202A, 0x202A),		// LEFT-TO-RIGHT EMBEDDING
       
  1880 		array(0x202B, 0x202B),		// RIGHT-TO-LEFT EMBEDDING
       
  1881 		array(0x202C, 0x202C),		// POP DIRECTIONAL FORMATTING
       
  1882 		array(0x202D, 0x202D),		// LEFT-TO-RIGHT OVERRIDE
       
  1883 		array(0x202E, 0x202E),		// RIGHT-TO-LEFT OVERRIDE
       
  1884 		array(0x206A, 0x206A),		// INHIBIT SYMMETRIC SWAPPING
       
  1885 		array(0x206B, 0x206B),		// ACTIVATE SYMMETRIC SWAPPING
       
  1886 		array(0x206C, 0x206C),		// INHIBIT ARABIC FORM SHAPING
       
  1887 		array(0x206D, 0x206D),		// ACTIVATE ARABIC FORM SHAPING
       
  1888 		array(0x206E, 0x206E),		// NATIONAL DIGIT SHAPES
       
  1889 		array(0x206F, 0x206F),		// NOMINAL DIGIT SHAPES
       
  1890 		// Table C.9
       
  1891 		array(0xE0001, 0xE0001),	// LANGUAGE TAG
       
  1892 		array(0xE0020, 0xE007F),	// [TAGGING CHARACTERS]
       
  1893 		// RFC3920
       
  1894 		array(0x22, 0x22),			// "
       
  1895 		array(0x26, 0x26),			// &
       
  1896 		array(0x27, 0x27),			// '
       
  1897 		array(0x2F, 0x2F),			// /
       
  1898 		array(0x3A, 0x3A),			// :
       
  1899 		array(0x3C, 0x3C),			// <
       
  1900 		array(0x3E, 0x3E),			// >
       
  1901 		array(0x40, 0x40)			// @
       
  1902 	);
       
  1903 
       
  1904 	$pos = 0;
       
  1905 	$result = true;
       
  1906 
       
  1907 	while ($pos < strlen($username))
       
  1908 	{
       
  1909 		$len = $uni = 0;
       
  1910 		for ($i = 0; $i <= 5; $i++)
       
  1911 		{
       
  1912 			if (ord($username[$pos]) >= $boundary[$i][0] && ord($username[$pos]) <= $boundary[$i][1])
       
  1913 			{
       
  1914 				$len = $i + 1;
       
  1915 				$uni = (ord($username[$pos]) - $boundary[$i][0]) * pow(2, $i * 6);
       
  1916 
       
  1917 				for ($k = 1; $k < $len; $k++)
       
  1918 				{
       
  1919 					$uni += (ord($username[$pos + $k]) - 128) * pow(2, ($i - $k) * 6);
       
  1920 				}
       
  1921 
       
  1922 				break;
       
  1923 			}
       
  1924 		}
       
  1925 
       
  1926 		if ($len == 0)
       
  1927 		{
       
  1928 			return 'WRONG_DATA';
       
  1929 		}
       
  1930 
       
  1931 		foreach ($prohibited as $pval)
       
  1932 		{
       
  1933 			if ($uni >= $pval[0] && $uni <= $pval[1])
       
  1934 			{
       
  1935 				$result = false;
       
  1936 				break 2;
       
  1937 			}
       
  1938 		}
       
  1939 
       
  1940 		$pos = $pos + $len;
       
  1941 	}
       
  1942 
       
  1943 	if (!$result)
       
  1944 	{
       
  1945 		return 'WRONG_DATA';
       
  1946 	}
       
  1947 
       
  1948 	return false;
       
  1949 }
       
  1950 
       
  1951 /**
       
  1952 * Remove avatar
       
  1953 */
       
  1954 function avatar_delete($mode, $row, $clean_db = false)
       
  1955 {
       
  1956 	global $phpbb_root_path, $config, $db, $user;
       
  1957 
       
  1958 	// Check if the users avatar is actually *not* a group avatar
       
  1959 	if ($mode == 'user')
       
  1960 	{
       
  1961 		if (strpos($row['user_avatar'], 'g') === 0 || (((int)$row['user_avatar'] !== 0) && ((int)$row['user_avatar'] !== (int)$row['user_id'])))
       
  1962 		{
       
  1963 			return false;
       
  1964 		}
       
  1965 	}
       
  1966 
       
  1967 	if ($clean_db)
       
  1968 	{
       
  1969 		avatar_remove_db($row[$mode . '_avatar']);
       
  1970 	}
       
  1971 	$filename = get_avatar_filename($row[$mode . '_avatar']);
       
  1972 	if (file_exists($phpbb_root_path . $config['avatar_path'] . '/' . $filename))
       
  1973 	{
       
  1974 		@unlink($phpbb_root_path . $config['avatar_path'] . '/' . $filename);
       
  1975 		return true;
       
  1976 	}
       
  1977 
       
  1978 	return false;
       
  1979 }
       
  1980 
       
  1981 /**
       
  1982 * Remote avatar linkage
       
  1983 */
       
  1984 function avatar_remote($data, &$error)
       
  1985 {
       
  1986 	global $config, $db, $user, $phpbb_root_path, $phpEx;
       
  1987 
       
  1988 	if (!preg_match('#^(http|https|ftp)://#i', $data['remotelink']))
       
  1989 	{
       
  1990 		$data['remotelink'] = 'http://' . $data['remotelink'];
       
  1991 	}
       
  1992 	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']))
       
  1993 	{
       
  1994 		$error[] = $user->lang['AVATAR_URL_INVALID'];
       
  1995 		return false;
       
  1996 	}
       
  1997 
       
  1998 	// Make sure getimagesize works...
       
  1999 	if (($image_data = @getimagesize($data['remotelink'])) === false && (empty($data['width']) || empty($data['height'])))
       
  2000 	{
       
  2001 		$error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
       
  2002 		return false;
       
  2003 	}
       
  2004 
       
  2005 	if (!empty($image_data) && ($image_data[0] < 2 || $image_data[1] < 2))
       
  2006 	{
       
  2007 		$error[] = $user->lang['AVATAR_NO_SIZE'];
       
  2008 		return false;
       
  2009 	}
       
  2010 
       
  2011 	$width = ($data['width'] && $data['height']) ? $data['width'] : $image_data[0];
       
  2012 	$height = ($data['width'] && $data['height']) ? $data['height'] : $image_data[1];
       
  2013 
       
  2014 	if ($width < 2 || $height < 2)
       
  2015 	{
       
  2016 		$error[] = $user->lang['AVATAR_NO_SIZE'];
       
  2017 		return false;
       
  2018 	}
       
  2019 
       
  2020 	// Check image type
       
  2021 	include_once($phpbb_root_path . 'includes/functions_upload.' . $phpEx);
       
  2022 	$types = fileupload::image_types();
       
  2023 	$extension = strtolower(filespec::get_extension($data['remotelink']));
       
  2024 
       
  2025 	if (!empty($image_data) && (!isset($types[$image_data[2]]) || !in_array($extension, $types[$image_data[2]])))
       
  2026 	{
       
  2027 		if (!isset($types[$image_data[2]]))
       
  2028 		{
       
  2029 			$error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
       
  2030 		}
       
  2031 		else
       
  2032 		{
       
  2033 			$error[] = sprintf($user->lang['IMAGE_FILETYPE_MISMATCH'], $types[$image_data[2]][0], $extension);
       
  2034 		}
       
  2035 		return false;
       
  2036 	}
       
  2037 
       
  2038 	if ($config['avatar_max_width'] || $config['avatar_max_height'])
       
  2039 	{
       
  2040 		if ($width > $config['avatar_max_width'] || $height > $config['avatar_max_height'])
       
  2041 		{
       
  2042 			$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);
       
  2043 			return false;
       
  2044 		}
       
  2045 	}
       
  2046 
       
  2047 	if ($config['avatar_min_width'] || $config['avatar_min_height'])
       
  2048 	{
       
  2049 		if ($width < $config['avatar_min_width'] || $height < $config['avatar_min_height'])
       
  2050 		{
       
  2051 			$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);
       
  2052 			return false;
       
  2053 		}
       
  2054 	}
       
  2055 
       
  2056 	return array(AVATAR_REMOTE, $data['remotelink'], $width, $height);
       
  2057 }
       
  2058 
       
  2059 /**
       
  2060 * Avatar upload using the upload class
       
  2061 */
       
  2062 function avatar_upload($data, &$error)
       
  2063 {
       
  2064 	global $phpbb_root_path, $config, $db, $user, $phpEx;
       
  2065 
       
  2066 	// Init upload class
       
  2067 	include_once($phpbb_root_path . 'includes/functions_upload.' . $phpEx);
       
  2068 	$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'], (isset($config['mime_triggers']) ? explode('|', $config['mime_triggers']) : false));
       
  2069 
       
  2070 	if (!empty($_FILES['uploadfile']['name']))
       
  2071 	{
       
  2072 		$file = $upload->form_upload('uploadfile');
       
  2073 	}
       
  2074 	else
       
  2075 	{
       
  2076 		$file = $upload->remote_upload($data['uploadurl']);
       
  2077 	}
       
  2078 
       
  2079 	$prefix = $config['avatar_salt'] . '_';
       
  2080 	$file->clean_filename('avatar', $prefix, $data['user_id']);
       
  2081 
       
  2082 	$destination = $config['avatar_path'];
       
  2083 
       
  2084 	// Adjust destination path (no trailing slash)
       
  2085 	if (substr($destination, -1, 1) == '/' || substr($destination, -1, 1) == '\\')
       
  2086 	{
       
  2087 		$destination = substr($destination, 0, -1);
       
  2088 	}
       
  2089 
       
  2090 	$destination = str_replace(array('../', '..\\', './', '.\\'), '', $destination);
       
  2091 	if ($destination && ($destination[0] == '/' || $destination[0] == "\\"))
       
  2092 	{
       
  2093 		$destination = '';
       
  2094 	}
       
  2095 
       
  2096 	// Move file and overwrite any existing image
       
  2097 	$file->move_file($destination, true);
       
  2098 
       
  2099 	if (sizeof($file->error))
       
  2100 	{
       
  2101 		$file->remove();
       
  2102 		$error = array_merge($error, $file->error);
       
  2103 	}
       
  2104 
       
  2105 	return array(AVATAR_UPLOAD, $data['user_id'] . '_' . time() . '.' . $file->get('extension'), $file->get('width'), $file->get('height'));
       
  2106 }
       
  2107 
       
  2108 /**
       
  2109 * Generates avatar filename from the database entry
       
  2110 */
       
  2111 function get_avatar_filename($avatar_entry)
       
  2112 {
       
  2113 	global $config;
       
  2114 
       
  2115 
       
  2116 	if ($avatar_entry[0] === 'g')
       
  2117 	{
       
  2118 		$avatar_group = true;
       
  2119 		$avatar_entry = substr($avatar_entry, 1);
       
  2120 	}
       
  2121 	else
       
  2122 	{
       
  2123 		$avatar_group = false;
       
  2124 	}
       
  2125 	$ext 			= substr(strrchr($avatar_entry, '.'), 1);
       
  2126 	$avatar_entry	= intval($avatar_entry);
       
  2127 	return $config['avatar_salt'] . '_' . (($avatar_group) ? 'g' : '') . $avatar_entry . '.' . $ext;
       
  2128 }
       
  2129 
       
  2130 /**
       
  2131 * Avatar Gallery
       
  2132 */
       
  2133 function avatar_gallery($category, $avatar_select, $items_per_column, $block_var = 'avatar_row')
       
  2134 {
       
  2135 	global $user, $cache, $template;
       
  2136 	global $config, $phpbb_root_path;
       
  2137 
       
  2138 	$avatar_list = array();
       
  2139 
       
  2140 	$path = $phpbb_root_path . $config['avatar_gallery_path'];
       
  2141 
       
  2142 	if (!file_exists($path) || !is_dir($path))
       
  2143 	{
       
  2144 		$avatar_list = array($user->lang['NO_AVATAR_CATEGORY'] => array());
       
  2145 	}
       
  2146 	else
       
  2147 	{
       
  2148 		// Collect images
       
  2149 		$dp = @opendir($path);
       
  2150 
       
  2151 		if (!$dp)
       
  2152 		{
       
  2153 			return array($user->lang['NO_AVATAR_CATEGORY'] => array());
       
  2154 		}
       
  2155 
       
  2156 		while (($file = readdir($dp)) !== false)
       
  2157 		{
       
  2158 			if ($file[0] != '.' && preg_match('#^[^&"\'<>]+$#i', $file) && is_dir("$path/$file"))
       
  2159 			{
       
  2160 				$avatar_row_count = $avatar_col_count = 0;
       
  2161 
       
  2162 				if ($dp2 = @opendir("$path/$file"))
       
  2163 				{
       
  2164 					while (($sub_file = readdir($dp2)) !== false)
       
  2165 					{
       
  2166 						if (preg_match('#^[^&\'"<>]+\.(?:gif|png|jpe?g)$#i', $sub_file))
       
  2167 						{
       
  2168 							$avatar_list[$file][$avatar_row_count][$avatar_col_count] = array(
       
  2169 								'file'		=> rawurlencode($file) . '/' . rawurlencode($sub_file),
       
  2170 								'filename'	=> rawurlencode($sub_file),
       
  2171 								'name'		=> ucfirst(str_replace('_', ' ', preg_replace('#^(.*)\..*$#', '\1', $sub_file))),
       
  2172 							);
       
  2173 							$avatar_col_count++;
       
  2174 							if ($avatar_col_count == $items_per_column)
       
  2175 							{
       
  2176 								$avatar_row_count++;
       
  2177 								$avatar_col_count = 0;
       
  2178 							}
       
  2179 						}
       
  2180 					}
       
  2181 					closedir($dp2);
       
  2182 				}
       
  2183 			}
       
  2184 		}
       
  2185 		closedir($dp);
       
  2186 	}
       
  2187 
       
  2188 	if (!sizeof($avatar_list))
       
  2189 	{
       
  2190 		$avatar_list = array($user->lang['NO_AVATAR_CATEGORY'] => array());
       
  2191 	}
       
  2192 
       
  2193 	@ksort($avatar_list);
       
  2194 
       
  2195 	$category = (!$category) ? key($avatar_list) : $category;
       
  2196 	$avatar_categories = array_keys($avatar_list);
       
  2197 
       
  2198 	$s_category_options = '';
       
  2199 	foreach ($avatar_categories as $cat)
       
  2200 	{
       
  2201 		$s_category_options .= '<option value="' . $cat . '"' . (($cat == $category) ? ' selected="selected"' : '') . '>' . $cat . '</option>';
       
  2202 	}
       
  2203 
       
  2204 	$template->assign_vars(array(
       
  2205 		'S_AVATARS_ENABLED'		=> true,
       
  2206 		'S_IN_AVATAR_GALLERY'	=> true,
       
  2207 		'S_CAT_OPTIONS'			=> $s_category_options)
       
  2208 	);
       
  2209 
       
  2210 	$avatar_list = (isset($avatar_list[$category])) ? $avatar_list[$category] : array();
       
  2211 
       
  2212 	foreach ($avatar_list as $avatar_row_ary)
       
  2213 	{
       
  2214 		$template->assign_block_vars($block_var, array());
       
  2215 
       
  2216 		foreach ($avatar_row_ary as $avatar_col_ary)
       
  2217 		{
       
  2218 			$template->assign_block_vars($block_var . '.avatar_column', array(
       
  2219 				'AVATAR_IMAGE'	=> $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar_col_ary['file'],
       
  2220 				'AVATAR_NAME'	=> $avatar_col_ary['name'],
       
  2221 				'AVATAR_FILE'	=> $avatar_col_ary['filename'])
       
  2222 			);
       
  2223 
       
  2224 			$template->assign_block_vars($block_var . '.avatar_option_column', array(
       
  2225 				'AVATAR_IMAGE'	=> $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar_col_ary['file'],
       
  2226 				'S_OPTIONS_AVATAR'	=> $avatar_col_ary['filename'])
       
  2227 			);
       
  2228 		}
       
  2229 	}
       
  2230 
       
  2231 	return $avatar_list;
       
  2232 }
       
  2233 
       
  2234 
       
  2235 /**
       
  2236 * Tries to (re-)establish avatar dimensions
       
  2237 */
       
  2238 function avatar_get_dimensions($avatar, $avatar_type, &$error, $current_x = 0, $current_y = 0)
       
  2239 {
       
  2240 	global $config, $phpbb_root_path, $user;
       
  2241 
       
  2242 	switch ($avatar_type)
       
  2243 	{
       
  2244 		case AVATAR_REMOTE :
       
  2245 			break;
       
  2246 
       
  2247 		case AVATAR_UPLOAD :
       
  2248 			$avatar = $phpbb_root_path . $config['avatar_path'] . '/' . get_avatar_filename($avatar);
       
  2249 			break;
       
  2250 
       
  2251 		case AVATAR_GALLERY :
       
  2252 			$avatar = $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar ;
       
  2253 			break;
       
  2254 	}
       
  2255 
       
  2256 	// Make sure getimagesize works...
       
  2257 	if (($image_data = @getimagesize($avatar)) === false)
       
  2258 	{
       
  2259 		$error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
       
  2260 		return false;
       
  2261 	}
       
  2262 
       
  2263 	if ($image_data[0] < 2 || $image_data[1] < 2)
       
  2264 	{
       
  2265 		$error[] = $user->lang['AVATAR_NO_SIZE'];
       
  2266 		return false;
       
  2267 	}
       
  2268 
       
  2269 	// try to maintain ratio
       
  2270 	if (!(empty($current_x) && empty($current_y)))
       
  2271 	{
       
  2272 		if ($current_x != 0)
       
  2273 		{
       
  2274 			$image_data[1] = (int) floor(($current_x / $image_data[0]) * $image_data[1]);
       
  2275 			$image_data[1] = min($config['avatar_max_height'], $image_data[1]);
       
  2276 			$image_data[1] = max($config['avatar_min_height'], $image_data[1]);
       
  2277 		}
       
  2278 		if ($current_y != 0)
       
  2279 		{
       
  2280 			$image_data[0] = (int) floor(($current_y / $image_data[1]) * $image_data[0]);
       
  2281 			$image_data[0] = min($config['avatar_max_width'], $image_data[1]);
       
  2282 			$image_data[0] = max($config['avatar_min_width'], $image_data[1]);
       
  2283 		}
       
  2284 	}
       
  2285 	return array($image_data[0], $image_data[1]);
       
  2286 }
       
  2287 
       
  2288 /**
       
  2289 * Uploading/Changing user avatar
       
  2290 */
       
  2291 function avatar_process_user(&$error, $custom_userdata = false, $can_upload = null)
       
  2292 {
       
  2293 	global $config, $phpbb_root_path, $auth, $user, $db;
       
  2294 
       
  2295 	$data = array(
       
  2296 		'uploadurl'		=> request_var('uploadurl', ''),
       
  2297 		'remotelink'	=> request_var('remotelink', ''),
       
  2298 		'width'			=> request_var('width', 0),
       
  2299 		'height'		=> request_var('height', 0),
       
  2300 	);
       
  2301 
       
  2302 	$error = validate_data($data, array(
       
  2303 		'uploadurl'		=> array('string', true, 5, 255),
       
  2304 		'remotelink'	=> array('string', true, 5, 255),
       
  2305 		'width'			=> array('string', true, 1, 3),
       
  2306 		'height'		=> array('string', true, 1, 3),
       
  2307 	));
       
  2308 
       
  2309 	if (sizeof($error))
       
  2310 	{
       
  2311 		return false;
       
  2312 	}
       
  2313 
       
  2314 	$sql_ary = array();
       
  2315 
       
  2316 	if ($custom_userdata === false)
       
  2317 	{
       
  2318 		$userdata = &$user->data;
       
  2319 	}
       
  2320 	else
       
  2321 	{
       
  2322 		$userdata = &$custom_userdata;
       
  2323 	}
       
  2324 
       
  2325 	$data['user_id'] = $userdata['user_id'];
       
  2326 	$change_avatar = ($custom_userdata === false) ? $auth->acl_get('u_chgavatar') : true;
       
  2327 	$avatar_select = basename(request_var('avatar_select', ''));
       
  2328 
       
  2329 	// Can we upload?
       
  2330 	if (is_null($can_upload))
       
  2331 	{
       
  2332 		$can_upload = ($config['allow_avatar_upload'] && file_exists($phpbb_root_path . $config['avatar_path']) && phpbb_is_writable($phpbb_root_path . $config['avatar_path']) && $change_avatar && (@ini_get('file_uploads') || strtolower(@ini_get('file_uploads')) == 'on')) ? true : false;
       
  2333 	}
       
  2334 
       
  2335 	if ((!empty($_FILES['uploadfile']['name']) || $data['uploadurl']) && $can_upload)
       
  2336 	{
       
  2337 		list($sql_ary['user_avatar_type'], $sql_ary['user_avatar'], $sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = avatar_upload($data, $error);
       
  2338 	}
       
  2339 	else if ($data['remotelink'] && $change_avatar && $config['allow_avatar_remote'])
       
  2340 	{
       
  2341 		list($sql_ary['user_avatar_type'], $sql_ary['user_avatar'], $sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = avatar_remote($data, $error);
       
  2342 	}
       
  2343 	else if ($avatar_select && $change_avatar && $config['allow_avatar_local'])
       
  2344 	{
       
  2345 		$category = basename(request_var('category', ''));
       
  2346 
       
  2347 		$sql_ary['user_avatar_type'] = AVATAR_GALLERY;
       
  2348 		$sql_ary['user_avatar'] = $avatar_select;
       
  2349 
       
  2350 		// check avatar gallery
       
  2351 		if (!is_dir($phpbb_root_path . $config['avatar_gallery_path'] . '/' . $category))
       
  2352 		{
       
  2353 			$sql_ary['user_avatar'] = '';
       
  2354 			$sql_ary['user_avatar_type'] = $sql_ary['user_avatar_width'] = $sql_ary['user_avatar_height'] = 0;
       
  2355 		}
       
  2356 		else
       
  2357 		{
       
  2358 			list($sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = getimagesize($phpbb_root_path . $config['avatar_gallery_path'] . '/' . $category . '/' . urldecode($sql_ary['user_avatar']));
       
  2359 			$sql_ary['user_avatar'] = $category . '/' . $sql_ary['user_avatar'];
       
  2360 		}
       
  2361 	}
       
  2362 	else if (isset($_POST['delete']) && $change_avatar)
       
  2363 	{
       
  2364 		$sql_ary['user_avatar'] = '';
       
  2365 		$sql_ary['user_avatar_type'] = $sql_ary['user_avatar_width'] = $sql_ary['user_avatar_height'] = 0;
       
  2366 	}
       
  2367 	else if (!empty($userdata['user_avatar']))
       
  2368 	{
       
  2369 		// Only update the dimensions
       
  2370 
       
  2371 		if (empty($data['width']) || empty($data['height']))
       
  2372 		{
       
  2373 			if ($dims = avatar_get_dimensions($userdata['user_avatar'], $userdata['user_avatar_type'], $error, $data['width'], $data['height']))
       
  2374 			{
       
  2375 				list($guessed_x, $guessed_y) = $dims;
       
  2376 				if (empty($data['width']))
       
  2377 				{
       
  2378 					$data['width'] = $guessed_x;
       
  2379 				}
       
  2380 				if (empty($data['height']))
       
  2381 				{
       
  2382 					$data['height'] = $guessed_y;
       
  2383 				}
       
  2384 			}
       
  2385 		}
       
  2386 		if (($config['avatar_max_width'] || $config['avatar_max_height']) &&
       
  2387 			(($data['width'] != $userdata['user_avatar_width']) || $data['height'] != $userdata['user_avatar_height']))
       
  2388 		{
       
  2389 			if ($data['width'] > $config['avatar_max_width'] || $data['height'] > $config['avatar_max_height'])
       
  2390 			{
       
  2391 				$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']);
       
  2392 			}
       
  2393 		}
       
  2394 
       
  2395 		if (!sizeof($error))
       
  2396 		{
       
  2397 			if ($config['avatar_min_width'] || $config['avatar_min_height'])
       
  2398 			{
       
  2399 				if ($data['width'] < $config['avatar_min_width'] || $data['height'] < $config['avatar_min_height'])
       
  2400 				{
       
  2401 					$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']);
       
  2402 				}
       
  2403 			}
       
  2404 		}
       
  2405 
       
  2406 		if (!sizeof($error))
       
  2407 		{
       
  2408 			$sql_ary['user_avatar_width'] = $data['width'];
       
  2409 			$sql_ary['user_avatar_height'] = $data['height'];
       
  2410 		}
       
  2411 	}
       
  2412 
       
  2413 	if (!sizeof($error))
       
  2414 	{
       
  2415 		// Do we actually have any data to update?
       
  2416 		if (sizeof($sql_ary))
       
  2417 		{
       
  2418 			$ext_new = $ext_old = '';
       
  2419 			if (isset($sql_ary['user_avatar']))
       
  2420 			{
       
  2421 				$userdata = ($custom_userdata === false) ? $user->data : $custom_userdata;
       
  2422 				$ext_new = (empty($sql_ary['user_avatar'])) ? '' : substr(strrchr($sql_ary['user_avatar'], '.'), 1);
       
  2423 				$ext_old = (empty($userdata['user_avatar'])) ? '' : substr(strrchr($userdata['user_avatar'], '.'), 1);
       
  2424 
       
  2425 				if ($userdata['user_avatar_type'] == AVATAR_UPLOAD)
       
  2426 				{
       
  2427 					// Delete old avatar if present
       
  2428 					if ((!empty($userdata['user_avatar']) && empty($sql_ary['user_avatar']))
       
  2429 					   || ( !empty($userdata['user_avatar']) && !empty($sql_ary['user_avatar']) && $ext_new !== $ext_old))
       
  2430 					{
       
  2431 						avatar_delete('user', $userdata);
       
  2432 					}
       
  2433 				}
       
  2434 			}
       
  2435 
       
  2436 			$sql = 'UPDATE ' . USERS_TABLE . '
       
  2437 				SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
       
  2438 				WHERE user_id = ' . (($custom_userdata === false) ? $user->data['user_id'] : $custom_userdata['user_id']);
       
  2439 			$db->sql_query($sql);
       
  2440 
       
  2441 		}
       
  2442 	}
       
  2443 
       
  2444 	return (sizeof($error)) ? false : true;
       
  2445 }
       
  2446 
       
  2447 //
       
  2448 // Usergroup functions
       
  2449 //
       
  2450 
       
  2451 /**
       
  2452 * Add or edit a group. If we're editing a group we only update user
       
  2453 * parameters such as rank, etc. if they are changed
       
  2454 */
       
  2455 function group_create(&$group_id, $type, $name, $desc, $group_attributes, $allow_desc_bbcode = false, $allow_desc_urls = false, $allow_desc_smilies = false)
       
  2456 {
       
  2457 	global $phpbb_root_path, $config, $db, $user, $file_upload;
       
  2458 
       
  2459 	$error = array();
       
  2460 
       
  2461 	// Attributes which also affect the users table
       
  2462 	$user_attribute_ary = array('group_colour', 'group_rank', 'group_avatar', 'group_avatar_type', 'group_avatar_width', 'group_avatar_height');
       
  2463 
       
  2464 	// Check data. Limit group name length.
       
  2465 	if (!utf8_strlen($name) || utf8_strlen($name) > 60)
       
  2466 	{
       
  2467 		$error[] = (!utf8_strlen($name)) ? $user->lang['GROUP_ERR_USERNAME'] : $user->lang['GROUP_ERR_USER_LONG'];
       
  2468 	}
       
  2469 
       
  2470 	$err = group_validate_groupname($group_id, $name);
       
  2471 	if (!empty($err))
       
  2472 	{
       
  2473 		$error[] = $user->lang[$err];
       
  2474 	}
       
  2475 
       
  2476 	if (!in_array($type, array(GROUP_OPEN, GROUP_CLOSED, GROUP_HIDDEN, GROUP_SPECIAL, GROUP_FREE)))
       
  2477 	{
       
  2478 		$error[] = $user->lang['GROUP_ERR_TYPE'];
       
  2479 	}
       
  2480 
       
  2481 	if (!sizeof($error))
       
  2482 	{
       
  2483 		$user_ary = array();
       
  2484 		$sql_ary = array(
       
  2485 			'group_name'			=> (string) $name,
       
  2486 			'group_desc'			=> (string) $desc,
       
  2487 			'group_desc_uid'		=> '',
       
  2488 			'group_desc_bitfield'	=> '',
       
  2489 			'group_type'			=> (int) $type,
       
  2490 		);
       
  2491 
       
  2492 		// Parse description
       
  2493 		if ($desc)
       
  2494 		{
       
  2495 			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);
       
  2496 		}
       
  2497 
       
  2498 		if (sizeof($group_attributes))
       
  2499 		{
       
  2500 			// Merge them with $sql_ary to properly update the group
       
  2501 			$sql_ary = array_merge($sql_ary, $group_attributes);
       
  2502 		}
       
  2503 
       
  2504 		// Setting the log message before we set the group id (if group gets added)
       
  2505 		$log = ($group_id) ? 'LOG_GROUP_UPDATED' : 'LOG_GROUP_CREATED';
       
  2506 
       
  2507 		$query = '';
       
  2508 
       
  2509 		if ($group_id)
       
  2510 		{
       
  2511 			$sql = 'SELECT user_id
       
  2512 				FROM ' . USERS_TABLE . '
       
  2513 				WHERE group_id = ' . $group_id;
       
  2514 			$result = $db->sql_query($sql);
       
  2515 
       
  2516 			while ($row = $db->sql_fetchrow($result))
       
  2517 			{
       
  2518 				$user_ary[] = $row['user_id'];
       
  2519 			}
       
  2520 			$db->sql_freeresult($result);
       
  2521 
       
  2522 			if (isset($sql_ary['group_avatar']) && !$sql_ary['group_avatar'])
       
  2523 			{
       
  2524 				remove_default_avatar($group_id, $user_ary);
       
  2525 			}
       
  2526 
       
  2527 			if (isset($sql_ary['group_rank']) && !$sql_ary['group_rank'])
       
  2528 			{
       
  2529 				remove_default_rank($group_id, $user_ary);
       
  2530 			}
       
  2531 
       
  2532 			$sql = 'UPDATE ' . GROUPS_TABLE . '
       
  2533 				SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
       
  2534 				WHERE group_id = $group_id";
       
  2535 			$db->sql_query($sql);
       
  2536 
       
  2537 			// Since we may update the name too, we need to do this on other tables too...
       
  2538 			$sql = 'UPDATE ' . MODERATOR_CACHE_TABLE . "
       
  2539 				SET group_name = '" . $db->sql_escape($sql_ary['group_name']) . "'
       
  2540 				WHERE group_id = $group_id";
       
  2541 			$db->sql_query($sql);
       
  2542 
       
  2543 			// One special case is the group skip auth setting. If this was changed we need to purge permissions for this group
       
  2544 			if (isset($group_attributes['group_skip_auth']))
       
  2545 			{
       
  2546 				// Get users within this group...
       
  2547 				$sql = 'SELECT user_id
       
  2548 					FROM ' . USER_GROUP_TABLE . '
       
  2549 					WHERE group_id = ' . $group_id . '
       
  2550 						AND user_pending = 0';
       
  2551 				$result = $db->sql_query($sql);
       
  2552 
       
  2553 				$user_id_ary = array();
       
  2554 				while ($row = $db->sql_fetchrow($result))
       
  2555 				{
       
  2556 					$user_id_ary[] = $row['user_id'];
       
  2557 				}
       
  2558 				$db->sql_freeresult($result);
       
  2559 
       
  2560 				if (!empty($user_id_ary))
       
  2561 				{
       
  2562 					global $auth;
       
  2563 
       
  2564 					// Clear permissions cache of relevant users
       
  2565 					$auth->acl_clear_prefetch($user_id_ary);
       
  2566 				}
       
  2567 			}
       
  2568 		}
       
  2569 		else
       
  2570 		{
       
  2571 			$sql = 'INSERT INTO ' . GROUPS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
       
  2572 			$db->sql_query($sql);
       
  2573 		}
       
  2574 
       
  2575 		if (!$group_id)
       
  2576 		{
       
  2577 			$group_id = $db->sql_nextid();
       
  2578 
       
  2579 			if (isset($sql_ary['group_avatar_type']) && $sql_ary['group_avatar_type'] == AVATAR_UPLOAD)
       
  2580 			{
       
  2581 				group_correct_avatar($group_id, $sql_ary['group_avatar']);
       
  2582 			}
       
  2583 		}
       
  2584 
       
  2585 		// Set user attributes
       
  2586 		$sql_ary = array();
       
  2587 		if (sizeof($group_attributes))
       
  2588 		{
       
  2589 			// Go through the user attributes array, check if a group attribute matches it and then set it. ;)
       
  2590 			foreach ($user_attribute_ary as $attribute)
       
  2591 			{
       
  2592 				if (!isset($group_attributes[$attribute]))
       
  2593 				{
       
  2594 					continue;
       
  2595 				}
       
  2596 
       
  2597 				// If we are about to set an avatar, we will not overwrite user avatars if no group avatar is set...
       
  2598 				if (strpos($attribute, 'group_avatar') === 0 && !$group_attributes[$attribute])
       
  2599 				{
       
  2600 					continue;
       
  2601 				}
       
  2602 
       
  2603 				$sql_ary[$attribute] = $group_attributes[$attribute];
       
  2604 			}
       
  2605 		}
       
  2606 
       
  2607 		if (sizeof($sql_ary) && sizeof($user_ary))
       
  2608 		{
       
  2609 			group_set_user_default($group_id, $user_ary, $sql_ary);
       
  2610 		}
       
  2611 
       
  2612 		$name = ($type == GROUP_SPECIAL) ? $user->lang['G_' . $name] : $name;
       
  2613 		add_log('admin', $log, $name);
       
  2614 
       
  2615 		group_update_listings($group_id);
       
  2616 	}
       
  2617 
       
  2618 	return (sizeof($error)) ? $error : false;
       
  2619 }
       
  2620 
       
  2621 
       
  2622 /**
       
  2623 * Changes a group avatar's filename to conform to the naming scheme
       
  2624 */
       
  2625 function group_correct_avatar($group_id, $old_entry)
       
  2626 {
       
  2627 	global $config, $db, $phpbb_root_path;
       
  2628 
       
  2629 	$group_id		= (int)$group_id;
       
  2630 	$ext 			= substr(strrchr($old_entry, '.'), 1);
       
  2631 	$old_filename 	= get_avatar_filename($old_entry);
       
  2632 	$new_filename 	= $config['avatar_salt'] . "_g$group_id.$ext";
       
  2633 	$new_entry 		= 'g' . $group_id . '_' . substr(time(), -5) . ".$ext";
       
  2634 
       
  2635 	$avatar_path = $phpbb_root_path . $config['avatar_path'];
       
  2636 	if (@rename($avatar_path . '/'. $old_filename, $avatar_path . '/' . $new_filename))
       
  2637 	{
       
  2638 		$sql = 'UPDATE ' . GROUPS_TABLE . '
       
  2639 			SET group_avatar = \'' . $db->sql_escape($new_entry) . "'
       
  2640 			WHERE group_id = $group_id";
       
  2641 		$db->sql_query($sql);
       
  2642 	}
       
  2643 }
       
  2644 
       
  2645 
       
  2646 /**
       
  2647 * Remove avatar also for users not having the group as default
       
  2648 */
       
  2649 function avatar_remove_db($avatar_name)
       
  2650 {
       
  2651 	global $config, $db;
       
  2652 
       
  2653 	$sql = 'UPDATE ' . USERS_TABLE . "
       
  2654 		SET user_avatar = '',
       
  2655 		user_avatar_type = 0
       
  2656 		WHERE user_avatar = '" . $db->sql_escape($avatar_name) . '\'';
       
  2657 	$db->sql_query($sql);
       
  2658 }
       
  2659 
       
  2660 
       
  2661 /**
       
  2662 * Group Delete
       
  2663 */
       
  2664 function group_delete($group_id, $group_name = false)
       
  2665 {
       
  2666 	global $db, $phpbb_root_path, $phpEx;
       
  2667 
       
  2668 	if (!$group_name)
       
  2669 	{
       
  2670 		$group_name = get_group_name($group_id);
       
  2671 	}
       
  2672 
       
  2673 	$start = 0;
       
  2674 
       
  2675 	do
       
  2676 	{
       
  2677 		$user_id_ary = $username_ary = array();
       
  2678 
       
  2679 		// Batch query for group members, call group_user_del
       
  2680 		$sql = 'SELECT u.user_id, u.username
       
  2681 			FROM ' . USER_GROUP_TABLE . ' ug, ' . USERS_TABLE . " u
       
  2682 			WHERE ug.group_id = $group_id
       
  2683 				AND u.user_id = ug.user_id";
       
  2684 		$result = $db->sql_query_limit($sql, 200, $start);
       
  2685 
       
  2686 		if ($row = $db->sql_fetchrow($result))
       
  2687 		{
       
  2688 			do
       
  2689 			{
       
  2690 				$user_id_ary[] = $row['user_id'];
       
  2691 				$username_ary[] = $row['username'];
       
  2692 
       
  2693 				$start++;
       
  2694 			}
       
  2695 			while ($row = $db->sql_fetchrow($result));
       
  2696 
       
  2697 			group_user_del($group_id, $user_id_ary, $username_ary, $group_name);
       
  2698 		}
       
  2699 		else
       
  2700 		{
       
  2701 			$start = 0;
       
  2702 		}
       
  2703 		$db->sql_freeresult($result);
       
  2704 	}
       
  2705 	while ($start);
       
  2706 
       
  2707 	// Delete group
       
  2708 	$sql = 'DELETE FROM ' . GROUPS_TABLE . "
       
  2709 		WHERE group_id = $group_id";
       
  2710 	$db->sql_query($sql);
       
  2711 
       
  2712 	// Delete auth entries from the groups table
       
  2713 	$sql = 'DELETE FROM ' . ACL_GROUPS_TABLE . "
       
  2714 		WHERE group_id = $group_id";
       
  2715 	$db->sql_query($sql);
       
  2716 
       
  2717 	// Re-cache moderators
       
  2718 	if (!function_exists('cache_moderators'))
       
  2719 	{
       
  2720 		include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
       
  2721 	}
       
  2722 
       
  2723 	cache_moderators();
       
  2724 
       
  2725 	add_log('admin', 'LOG_GROUP_DELETE', $group_name);
       
  2726 
       
  2727 	// Return false - no error
       
  2728 	return false;
       
  2729 }
       
  2730 
       
  2731 /**
       
  2732 * Add user(s) to group
       
  2733 *
       
  2734 * @return mixed false if no errors occurred, else the user lang string for the relevant error, for example 'NO_USER'
       
  2735 */
       
  2736 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)
       
  2737 {
       
  2738 	global $db, $auth;
       
  2739 
       
  2740 	// We need both username and user_id info
       
  2741 	$result = user_get_id_name($user_id_ary, $username_ary);
       
  2742 
       
  2743 	if (!sizeof($user_id_ary) || $result !== false)
       
  2744 	{
       
  2745 		return 'NO_USER';
       
  2746 	}
       
  2747 
       
  2748 	// Remove users who are already members of this group
       
  2749 	$sql = 'SELECT user_id, group_leader
       
  2750 		FROM ' . USER_GROUP_TABLE . '
       
  2751 		WHERE ' . $db->sql_in_set('user_id', $user_id_ary) . "
       
  2752 			AND group_id = $group_id";
       
  2753 	$result = $db->sql_query($sql);
       
  2754 
       
  2755 	$add_id_ary = $update_id_ary = array();
       
  2756 	while ($row = $db->sql_fetchrow($result))
       
  2757 	{
       
  2758 		$add_id_ary[] = (int) $row['user_id'];
       
  2759 
       
  2760 		if ($leader && !$row['group_leader'])
       
  2761 		{
       
  2762 			$update_id_ary[] = (int) $row['user_id'];
       
  2763 		}
       
  2764 	}
       
  2765 	$db->sql_freeresult($result);
       
  2766 
       
  2767 	// Do all the users exist in this group?
       
  2768 	$add_id_ary = array_diff($user_id_ary, $add_id_ary);
       
  2769 
       
  2770 	// If we have no users
       
  2771 	if (!sizeof($add_id_ary) && !sizeof($update_id_ary))
       
  2772 	{
       
  2773 		return 'GROUP_USERS_EXIST';
       
  2774 	}
       
  2775 
       
  2776 	$db->sql_transaction('begin');
       
  2777 
       
  2778 	// Insert the new users
       
  2779 	if (sizeof($add_id_ary))
       
  2780 	{
       
  2781 		$sql_ary = array();
       
  2782 
       
  2783 		foreach ($add_id_ary as $user_id)
       
  2784 		{
       
  2785 			$sql_ary[] = array(
       
  2786 				'user_id'		=> (int) $user_id,
       
  2787 				'group_id'		=> (int) $group_id,
       
  2788 				'group_leader'	=> (int) $leader,
       
  2789 				'user_pending'	=> (int) $pending,
       
  2790 			);
       
  2791 		}
       
  2792 
       
  2793 		$db->sql_multi_insert(USER_GROUP_TABLE, $sql_ary);
       
  2794 	}
       
  2795 
       
  2796 	if (sizeof($update_id_ary))
       
  2797 	{
       
  2798 		$sql = 'UPDATE ' . USER_GROUP_TABLE . '
       
  2799 			SET group_leader = 1
       
  2800 			WHERE ' . $db->sql_in_set('user_id', $update_id_ary) . "
       
  2801 				AND group_id = $group_id";
       
  2802 		$db->sql_query($sql);
       
  2803 	}
       
  2804 
       
  2805 	if ($default)
       
  2806 	{
       
  2807 		group_user_attributes('default', $group_id, $user_id_ary, false, $group_name, $group_attributes);
       
  2808 	}
       
  2809 
       
  2810 	$db->sql_transaction('commit');
       
  2811 
       
  2812 	// Clear permissions cache of relevant users
       
  2813 	$auth->acl_clear_prefetch($user_id_ary);
       
  2814 
       
  2815 	if (!$group_name)
       
  2816 	{
       
  2817 		$group_name = get_group_name($group_id);
       
  2818 	}
       
  2819 
       
  2820 	$log = ($leader) ? 'LOG_MODS_ADDED' : (($pending) ? 'LOG_USERS_PENDING' : 'LOG_USERS_ADDED');
       
  2821 
       
  2822 	add_log('admin', $log, $group_name, implode(', ', $username_ary));
       
  2823 
       
  2824 	group_update_listings($group_id);
       
  2825 
       
  2826 	// Return false - no error
       
  2827 	return false;
       
  2828 }
       
  2829 
       
  2830 /**
       
  2831 * Remove a user/s from a given group. When we remove users we update their
       
  2832 * default group_id. We do this by examining which "special" groups they belong
       
  2833 * to. The selection is made based on a reasonable priority system
       
  2834 *
       
  2835 * @return false if no errors occurred, else the user lang string for the relevant error, for example 'NO_USER'
       
  2836 */
       
  2837 function group_user_del($group_id, $user_id_ary = false, $username_ary = false, $group_name = false)
       
  2838 {
       
  2839 	global $db, $auth, $config;
       
  2840 
       
  2841 	if ($config['coppa_enable'])
       
  2842 	{
       
  2843 		$group_order = array('ADMINISTRATORS', 'GLOBAL_MODERATORS', 'NEWLY_REGISTERED', 'REGISTERED_COPPA', 'REGISTERED', 'BOTS', 'GUESTS');
       
  2844 	}
       
  2845 	else
       
  2846 	{
       
  2847 		$group_order = array('ADMINISTRATORS', 'GLOBAL_MODERATORS', 'NEWLY_REGISTERED', 'REGISTERED', 'BOTS', 'GUESTS');
       
  2848 	}
       
  2849 
       
  2850 	// We need both username and user_id info
       
  2851 	$result = user_get_id_name($user_id_ary, $username_ary);
       
  2852 
       
  2853 	if (!sizeof($user_id_ary) || $result !== false)
       
  2854 	{
       
  2855 		return 'NO_USER';
       
  2856 	}
       
  2857 
       
  2858 	$sql = 'SELECT *
       
  2859 		FROM ' . GROUPS_TABLE . '
       
  2860 		WHERE ' . $db->sql_in_set('group_name', $group_order);
       
  2861 	$result = $db->sql_query($sql);
       
  2862 
       
  2863 	$group_order_id = $special_group_data = array();
       
  2864 	while ($row = $db->sql_fetchrow($result))
       
  2865 	{
       
  2866 		$group_order_id[$row['group_name']] = $row['group_id'];
       
  2867 
       
  2868 		$special_group_data[$row['group_id']] = array(
       
  2869 			'group_colour'			=> $row['group_colour'],
       
  2870 			'group_rank'				=> $row['group_rank'],
       
  2871 		);
       
  2872 
       
  2873 		// Only set the group avatar if one is defined...
       
  2874 		if ($row['group_avatar'])
       
  2875 		{
       
  2876 			$special_group_data[$row['group_id']] = array_merge($special_group_data[$row['group_id']], array(
       
  2877 				'group_avatar'			=> $row['group_avatar'],
       
  2878 				'group_avatar_type'		=> $row['group_avatar_type'],
       
  2879 				'group_avatar_width'		=> $row['group_avatar_width'],
       
  2880 				'group_avatar_height'	=> $row['group_avatar_height'])
       
  2881 			);
       
  2882 		}
       
  2883 	}
       
  2884 	$db->sql_freeresult($result);
       
  2885 
       
  2886 	// 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
       
  2887 	$sql = 'SELECT user_id, group_id
       
  2888 		FROM ' . USERS_TABLE . '
       
  2889 		WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
       
  2890 	$result = $db->sql_query($sql);
       
  2891 
       
  2892 	$default_groups = array();
       
  2893 	while ($row = $db->sql_fetchrow($result))
       
  2894 	{
       
  2895 		$default_groups[$row['user_id']] = $row['group_id'];
       
  2896 	}
       
  2897 	$db->sql_freeresult($result);
       
  2898 
       
  2899 	// What special group memberships exist for these users?
       
  2900 	$sql = 'SELECT g.group_id, g.group_name, ug.user_id
       
  2901 		FROM ' . USER_GROUP_TABLE . ' ug, ' . GROUPS_TABLE . ' g
       
  2902 		WHERE ' . $db->sql_in_set('ug.user_id', $user_id_ary) . "
       
  2903 			AND g.group_id = ug.group_id
       
  2904 			AND g.group_id <> $group_id
       
  2905 			AND g.group_type = " . GROUP_SPECIAL . '
       
  2906 		ORDER BY ug.user_id, g.group_id';
       
  2907 	$result = $db->sql_query($sql);
       
  2908 
       
  2909 	$temp_ary = array();
       
  2910 	while ($row = $db->sql_fetchrow($result))
       
  2911 	{
       
  2912 		if ($default_groups[$row['user_id']] == $group_id && (!isset($temp_ary[$row['user_id']]) || $group_order_id[$row['group_name']] < $temp_ary[$row['user_id']]))
       
  2913 		{
       
  2914 			$temp_ary[$row['user_id']] = $row['group_id'];
       
  2915 		}
       
  2916 	}
       
  2917 	$db->sql_freeresult($result);
       
  2918 
       
  2919 	// sql_where_ary holds the new default groups and their users
       
  2920 	$sql_where_ary = array();
       
  2921 	foreach ($temp_ary as $uid => $gid)
       
  2922 	{
       
  2923 		$sql_where_ary[$gid][] = $uid;
       
  2924 	}
       
  2925 	unset($temp_ary);
       
  2926 
       
  2927 	foreach ($special_group_data as $gid => $default_data_ary)
       
  2928 	{
       
  2929 		if (isset($sql_where_ary[$gid]) && sizeof($sql_where_ary[$gid]))
       
  2930 		{
       
  2931 			remove_default_rank($group_id, $sql_where_ary[$gid]);
       
  2932 			remove_default_avatar($group_id, $sql_where_ary[$gid]);
       
  2933 			group_set_user_default($gid, $sql_where_ary[$gid], $default_data_ary);
       
  2934 		}
       
  2935 	}
       
  2936 	unset($special_group_data);
       
  2937 
       
  2938 	$sql = 'DELETE FROM ' . USER_GROUP_TABLE . "
       
  2939 		WHERE group_id = $group_id
       
  2940 			AND " . $db->sql_in_set('user_id', $user_id_ary);
       
  2941 	$db->sql_query($sql);
       
  2942 
       
  2943 	// Clear permissions cache of relevant users
       
  2944 	$auth->acl_clear_prefetch($user_id_ary);
       
  2945 
       
  2946 	if (!$group_name)
       
  2947 	{
       
  2948 		$group_name = get_group_name($group_id);
       
  2949 	}
       
  2950 
       
  2951 	$log = 'LOG_GROUP_REMOVE';
       
  2952 
       
  2953 	if ($group_name)
       
  2954 	{
       
  2955 		add_log('admin', $log, $group_name, implode(', ', $username_ary));
       
  2956 	}
       
  2957 
       
  2958 	group_update_listings($group_id);
       
  2959 
       
  2960 	// Return false - no error
       
  2961 	return false;
       
  2962 }
       
  2963 
       
  2964 
       
  2965 /**
       
  2966 * Removes the group avatar of the default group from the users in user_ids who have that group as default.
       
  2967 */
       
  2968 function remove_default_avatar($group_id, $user_ids)
       
  2969 {
       
  2970 	global $db;
       
  2971 
       
  2972 	if (!is_array($user_ids))
       
  2973 	{
       
  2974 		$user_ids = array($user_ids);
       
  2975 	}
       
  2976 	if (empty($user_ids))
       
  2977 	{
       
  2978 		return false;
       
  2979 	}
       
  2980 
       
  2981 	$user_ids = array_map('intval', $user_ids);
       
  2982 
       
  2983 	$sql = 'SELECT *
       
  2984 		FROM ' . GROUPS_TABLE . '
       
  2985 		WHERE group_id = ' . (int)$group_id;
       
  2986 	$result = $db->sql_query($sql);
       
  2987 	if (!$row = $db->sql_fetchrow($result))
       
  2988 	{
       
  2989 		$db->sql_freeresult($result);
       
  2990 		return false;
       
  2991 	}
       
  2992 	$db->sql_freeresult($result);
       
  2993 
       
  2994 	$sql = 'UPDATE ' . USERS_TABLE . "
       
  2995 		SET user_avatar = '',
       
  2996 			user_avatar_type = 0,
       
  2997 			user_avatar_width = 0,
       
  2998 			user_avatar_height = 0
       
  2999 		WHERE group_id = " . (int) $group_id . "
       
  3000 		AND user_avatar = '" . $db->sql_escape($row['group_avatar']) . "'
       
  3001 		AND " . $db->sql_in_set('user_id', $user_ids);
       
  3002 
       
  3003 	$db->sql_query($sql);
       
  3004 }
       
  3005 
       
  3006 /**
       
  3007 * Removes the group rank of the default group from the users in user_ids who have that group as default.
       
  3008 */
       
  3009 function remove_default_rank($group_id, $user_ids)
       
  3010 {
       
  3011 	global $db;
       
  3012 
       
  3013 	if (!is_array($user_ids))
       
  3014 	{
       
  3015 		$user_ids = array($user_ids);
       
  3016 	}
       
  3017 	if (empty($user_ids))
       
  3018 	{
       
  3019 		return false;
       
  3020 	}
       
  3021 
       
  3022 	$user_ids = array_map('intval', $user_ids);
       
  3023 
       
  3024 	$sql = 'SELECT *
       
  3025 		FROM ' . GROUPS_TABLE . '
       
  3026 		WHERE group_id = ' . (int)$group_id;
       
  3027 	$result = $db->sql_query($sql);
       
  3028 	if (!$row = $db->sql_fetchrow($result))
       
  3029 	{
       
  3030 		$db->sql_freeresult($result);
       
  3031 		return false;
       
  3032 	}
       
  3033 	$db->sql_freeresult($result);
       
  3034 
       
  3035 	$sql = 'UPDATE ' . USERS_TABLE . '
       
  3036 		SET user_rank = 0
       
  3037 		WHERE group_id = ' . (int)$group_id . '
       
  3038 		AND user_rank <> 0
       
  3039 		AND user_rank = ' . (int)$row['group_rank'] . '
       
  3040 		AND ' . $db->sql_in_set('user_id', $user_ids);
       
  3041 	$db->sql_query($sql);
       
  3042 }
       
  3043 
       
  3044 /**
       
  3045 * This is used to promote (to leader), demote or set as default a member/s
       
  3046 */
       
  3047 function group_user_attributes($action, $group_id, $user_id_ary = false, $username_ary = false, $group_name = false, $group_attributes = false)
       
  3048 {
       
  3049 	global $db, $auth, $phpbb_root_path, $phpEx, $config;
       
  3050 
       
  3051 	// We need both username and user_id info
       
  3052 	$result = user_get_id_name($user_id_ary, $username_ary);
       
  3053 
       
  3054 	if (!sizeof($user_id_ary) || $result !== false)
       
  3055 	{
       
  3056 		return 'NO_USERS';
       
  3057 	}
       
  3058 
       
  3059 	if (!$group_name)
       
  3060 	{
       
  3061 		$group_name = get_group_name($group_id);
       
  3062 	}
       
  3063 
       
  3064 	switch ($action)
       
  3065 	{
       
  3066 		case 'demote':
       
  3067 		case 'promote':
       
  3068 
       
  3069 			$sql = 'SELECT user_id FROM ' . USER_GROUP_TABLE . "
       
  3070 				WHERE group_id = $group_id
       
  3071 					AND user_pending = 1
       
  3072 					AND " . $db->sql_in_set('user_id', $user_id_ary);
       
  3073 			$result = $db->sql_query_limit($sql, 1);
       
  3074 			$not_empty = ($db->sql_fetchrow($result));
       
  3075 			$db->sql_freeresult($result);
       
  3076 			if ($not_empty)
       
  3077 			{
       
  3078 				return 'NO_VALID_USERS';
       
  3079 			}
       
  3080 
       
  3081 			$sql = 'UPDATE ' . USER_GROUP_TABLE . '
       
  3082 				SET group_leader = ' . (($action == 'promote') ? 1 : 0) . "
       
  3083 				WHERE group_id = $group_id
       
  3084 					AND user_pending = 0
       
  3085 					AND " . $db->sql_in_set('user_id', $user_id_ary);
       
  3086 			$db->sql_query($sql);
       
  3087 
       
  3088 			$log = ($action == 'promote') ? 'LOG_GROUP_PROMOTED' : 'LOG_GROUP_DEMOTED';
       
  3089 		break;
       
  3090 
       
  3091 		case 'approve':
       
  3092 			// Make sure we only approve those which are pending ;)
       
  3093 			$sql = 'SELECT u.user_id, u.user_email, u.username, u.username_clean, u.user_notify_type, u.user_jabber, u.user_lang
       
  3094 				FROM ' . USERS_TABLE . ' u, ' . USER_GROUP_TABLE . ' ug
       
  3095 				WHERE ug.group_id = ' . $group_id . '
       
  3096 					AND ug.user_pending = 1
       
  3097 					AND ug.user_id = u.user_id
       
  3098 					AND ' . $db->sql_in_set('ug.user_id', $user_id_ary);
       
  3099 			$result = $db->sql_query($sql);
       
  3100 
       
  3101 			$user_id_ary = $email_users = array();
       
  3102 			while ($row = $db->sql_fetchrow($result))
       
  3103 			{
       
  3104 				$user_id_ary[] = $row['user_id'];
       
  3105 				$email_users[] = $row;
       
  3106 			}
       
  3107 			$db->sql_freeresult($result);
       
  3108 
       
  3109 			if (!sizeof($user_id_ary))
       
  3110 			{
       
  3111 				return false;
       
  3112 			}
       
  3113 
       
  3114 			$sql = 'UPDATE ' . USER_GROUP_TABLE . "
       
  3115 				SET user_pending = 0
       
  3116 				WHERE group_id = $group_id
       
  3117 					AND " . $db->sql_in_set('user_id', $user_id_ary);
       
  3118 			$db->sql_query($sql);
       
  3119 
       
  3120 			// Send approved email to users...
       
  3121 			include_once($phpbb_root_path . 'includes/functions_messenger.' . $phpEx);
       
  3122 			$messenger = new messenger();
       
  3123 
       
  3124 			foreach ($email_users as $row)
       
  3125 			{
       
  3126 				$messenger->template('group_approved', $row['user_lang']);
       
  3127 
       
  3128 				$messenger->to($row['user_email'], $row['username']);
       
  3129 				$messenger->im($row['user_jabber'], $row['username']);
       
  3130 
       
  3131 				$messenger->assign_vars(array(
       
  3132 					'USERNAME'		=> htmlspecialchars_decode($row['username']),
       
  3133 					'GROUP_NAME'	=> htmlspecialchars_decode($group_name),
       
  3134 					'U_GROUP'		=> generate_board_url() . "/ucp.$phpEx?i=groups&mode=membership")
       
  3135 				);
       
  3136 
       
  3137 				$messenger->send($row['user_notify_type']);
       
  3138 			}
       
  3139 
       
  3140 			$messenger->save_queue();
       
  3141 
       
  3142 			$log = 'LOG_USERS_APPROVED';
       
  3143 		break;
       
  3144 
       
  3145 		case 'default':
       
  3146 			// We only set default group for approved members of the group
       
  3147 			$sql = 'SELECT user_id
       
  3148 				FROM ' . USER_GROUP_TABLE . "
       
  3149 				WHERE group_id = $group_id
       
  3150 					AND user_pending = 0
       
  3151 					AND " . $db->sql_in_set('user_id', $user_id_ary);
       
  3152 			$result = $db->sql_query($sql);
       
  3153 
       
  3154 			$user_id_ary = $username_ary = array();
       
  3155 			while ($row = $db->sql_fetchrow($result))
       
  3156 			{
       
  3157 				$user_id_ary[] = $row['user_id'];
       
  3158 			}
       
  3159 			$db->sql_freeresult($result);
       
  3160 
       
  3161 			$result = user_get_id_name($user_id_ary, $username_ary);
       
  3162 			if (!sizeof($user_id_ary) || $result !== false)
       
  3163 			{
       
  3164 				return 'NO_USERS';
       
  3165 			}
       
  3166 
       
  3167 			$sql = 'SELECT user_id, group_id FROM ' . USERS_TABLE . '
       
  3168 				WHERE ' . $db->sql_in_set('user_id', $user_id_ary, false, true);
       
  3169 			$result = $db->sql_query($sql);
       
  3170 
       
  3171 			$groups = array();
       
  3172 			while ($row = $db->sql_fetchrow($result))
       
  3173 			{
       
  3174 				if (!isset($groups[$row['group_id']]))
       
  3175 				{
       
  3176 					$groups[$row['group_id']] = array();
       
  3177 				}
       
  3178 				$groups[$row['group_id']][] = $row['user_id'];
       
  3179 			}
       
  3180 			$db->sql_freeresult($result);
       
  3181 
       
  3182 			foreach ($groups as $gid => $uids)
       
  3183 			{
       
  3184 				remove_default_rank($gid, $uids);
       
  3185 				remove_default_avatar($gid, $uids);
       
  3186 			}
       
  3187 			group_set_user_default($group_id, $user_id_ary, $group_attributes);
       
  3188 			$log = 'LOG_GROUP_DEFAULTS';
       
  3189 		break;
       
  3190 	}
       
  3191 
       
  3192 	// Clear permissions cache of relevant users
       
  3193 	$auth->acl_clear_prefetch($user_id_ary);
       
  3194 
       
  3195 	add_log('admin', $log, $group_name, implode(', ', $username_ary));
       
  3196 
       
  3197 	group_update_listings($group_id);
       
  3198 
       
  3199 	return false;
       
  3200 }
       
  3201 
       
  3202 /**
       
  3203 * A small version of validate_username to check for a group name's existence. To be called directly.
       
  3204 */
       
  3205 function group_validate_groupname($group_id, $group_name)
       
  3206 {
       
  3207 	global $config, $db;
       
  3208 
       
  3209 	$group_name =  utf8_clean_string($group_name);
       
  3210 
       
  3211 	if (!empty($group_id))
       
  3212 	{
       
  3213 		$sql = 'SELECT group_name
       
  3214 			FROM ' . GROUPS_TABLE . '
       
  3215 			WHERE group_id = ' . (int) $group_id;
       
  3216 		$result = $db->sql_query($sql);
       
  3217 		$row = $db->sql_fetchrow($result);
       
  3218 		$db->sql_freeresult($result);
       
  3219 
       
  3220 		if (!$row)
       
  3221 		{
       
  3222 			return false;
       
  3223 		}
       
  3224 
       
  3225 		$allowed_groupname = utf8_clean_string($row['group_name']);
       
  3226 
       
  3227 		if ($allowed_groupname == $group_name)
       
  3228 		{
       
  3229 			return false;
       
  3230 		}
       
  3231 	}
       
  3232 
       
  3233 	$sql = 'SELECT group_name
       
  3234 		FROM ' . GROUPS_TABLE . "
       
  3235 		WHERE LOWER(group_name) = '" . $db->sql_escape(utf8_strtolower($group_name)) . "'";
       
  3236 	$result = $db->sql_query($sql);
       
  3237 	$row = $db->sql_fetchrow($result);
       
  3238 	$db->sql_freeresult($result);
       
  3239 
       
  3240 	if ($row)
       
  3241 	{
       
  3242 		return 'GROUP_NAME_TAKEN';
       
  3243 	}
       
  3244 
       
  3245 	return false;
       
  3246 }
       
  3247 
       
  3248 /**
       
  3249 * Set users default group
       
  3250 *
       
  3251 * @access private
       
  3252 */
       
  3253 function group_set_user_default($group_id, $user_id_ary, $group_attributes = false, $update_listing = false)
       
  3254 {
       
  3255 	global $cache, $db;
       
  3256 
       
  3257 	if (empty($user_id_ary))
       
  3258 	{
       
  3259 		return;
       
  3260 	}
       
  3261 
       
  3262 	$attribute_ary = array(
       
  3263 		'group_colour'			=> 'string',
       
  3264 		'group_rank'			=> 'int',
       
  3265 		'group_avatar'			=> 'string',
       
  3266 		'group_avatar_type'		=> 'int',
       
  3267 		'group_avatar_width'	=> 'int',
       
  3268 		'group_avatar_height'	=> 'int',
       
  3269 	);
       
  3270 
       
  3271 	$sql_ary = array(
       
  3272 		'group_id'		=> $group_id
       
  3273 	);
       
  3274 
       
  3275 	// Were group attributes passed to the function? If not we need to obtain them
       
  3276 	if ($group_attributes === false)
       
  3277 	{
       
  3278 		$sql = 'SELECT ' . implode(', ', array_keys($attribute_ary)) . '
       
  3279 			FROM ' . GROUPS_TABLE . "
       
  3280 			WHERE group_id = $group_id";
       
  3281 		$result = $db->sql_query($sql);
       
  3282 		$group_attributes = $db->sql_fetchrow($result);
       
  3283 		$db->sql_freeresult($result);
       
  3284 	}
       
  3285 
       
  3286 	foreach ($attribute_ary as $attribute => $type)
       
  3287 	{
       
  3288 		if (isset($group_attributes[$attribute]))
       
  3289 		{
       
  3290 			// 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
       
  3291 			if ((strpos($attribute, 'group_avatar') === 0 || strpos($attribute, 'group_rank') === 0) && !$group_attributes[$attribute])
       
  3292 			{
       
  3293 				continue;
       
  3294 			}
       
  3295 
       
  3296 			settype($group_attributes[$attribute], $type);
       
  3297 			$sql_ary[str_replace('group_', 'user_', $attribute)] = $group_attributes[$attribute];
       
  3298 		}
       
  3299 	}
       
  3300 
       
  3301 	// Before we update the user attributes, we will make a list of those having now the group avatar assigned
       
  3302 	if (isset($sql_ary['user_avatar']))
       
  3303 	{
       
  3304 		// Ok, get the original avatar data from users having an uploaded one (we need to remove these from the filesystem)
       
  3305 		$sql = 'SELECT user_id, group_id, user_avatar
       
  3306 			FROM ' . USERS_TABLE . '
       
  3307 			WHERE ' . $db->sql_in_set('user_id', $user_id_ary) . '
       
  3308 				AND user_avatar_type = ' . AVATAR_UPLOAD;
       
  3309 		$result = $db->sql_query($sql);
       
  3310 
       
  3311 		while ($row = $db->sql_fetchrow($result))
       
  3312 		{
       
  3313 			avatar_delete('user', $row);
       
  3314 		}
       
  3315 		$db->sql_freeresult($result);
       
  3316 	}
       
  3317 	else
       
  3318 	{
       
  3319 		unset($sql_ary['user_avatar_type']);
       
  3320 		unset($sql_ary['user_avatar_height']);
       
  3321 		unset($sql_ary['user_avatar_width']);
       
  3322 	}
       
  3323 
       
  3324 	$sql = 'UPDATE ' . USERS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
       
  3325 		WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
       
  3326 	$db->sql_query($sql);
       
  3327 
       
  3328 	if (isset($sql_ary['user_colour']))
       
  3329 	{
       
  3330 		// Update any cached colour information for these users
       
  3331 		$sql = 'UPDATE ' . FORUMS_TABLE . " SET forum_last_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
       
  3332 			WHERE " . $db->sql_in_set('forum_last_poster_id', $user_id_ary);
       
  3333 		$db->sql_query($sql);
       
  3334 
       
  3335 		$sql = 'UPDATE ' . TOPICS_TABLE . " SET topic_first_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
       
  3336 			WHERE " . $db->sql_in_set('topic_poster', $user_id_ary);
       
  3337 		$db->sql_query($sql);
       
  3338 
       
  3339 		$sql = 'UPDATE ' . TOPICS_TABLE . " SET topic_last_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
       
  3340 			WHERE " . $db->sql_in_set('topic_last_poster_id', $user_id_ary);
       
  3341 		$db->sql_query($sql);
       
  3342 
       
  3343 		global $config;
       
  3344 
       
  3345 		if (in_array($config['newest_user_id'], $user_id_ary))
       
  3346 		{
       
  3347 			set_config('newest_user_colour', $sql_ary['user_colour'], true);
       
  3348 		}
       
  3349 	}
       
  3350 
       
  3351 	if ($update_listing)
       
  3352 	{
       
  3353 		group_update_listings($group_id);
       
  3354 	}
       
  3355 
       
  3356 	// Because some tables/caches use usercolour-specific data we need to purge this here.
       
  3357 	$cache->destroy('sql', MODERATOR_CACHE_TABLE);
       
  3358 }
       
  3359 
       
  3360 /**
       
  3361 * Get group name
       
  3362 */
       
  3363 function get_group_name($group_id)
       
  3364 {
       
  3365 	global $db, $user;
       
  3366 
       
  3367 	$sql = 'SELECT group_name, group_type
       
  3368 		FROM ' . GROUPS_TABLE . '
       
  3369 		WHERE group_id = ' . (int) $group_id;
       
  3370 	$result = $db->sql_query($sql);
       
  3371 	$row = $db->sql_fetchrow($result);
       
  3372 	$db->sql_freeresult($result);
       
  3373 
       
  3374 	if (!$row || ($row['group_type'] == GROUP_SPECIAL && empty($user->lang)))
       
  3375 	{
       
  3376 		return '';
       
  3377 	}
       
  3378 
       
  3379 	return ($row['group_type'] == GROUP_SPECIAL) ? $user->lang['G_' . $row['group_name']] : $row['group_name'];
       
  3380 }
       
  3381 
       
  3382 /**
       
  3383 * Obtain either the members of a specified group, the groups the specified user is subscribed to
       
  3384 * or checking if a specified user is in a specified group. This function does not return pending memberships.
       
  3385 *
       
  3386 * Note: Never use this more than once... first group your users/groups
       
  3387 */
       
  3388 function group_memberships($group_id_ary = false, $user_id_ary = false, $return_bool = false)
       
  3389 {
       
  3390 	global $db;
       
  3391 
       
  3392 	if (!$group_id_ary && !$user_id_ary)
       
  3393 	{
       
  3394 		return true;
       
  3395 	}
       
  3396 
       
  3397 	if ($user_id_ary)
       
  3398 	{
       
  3399 		$user_id_ary = (!is_array($user_id_ary)) ? array($user_id_ary) : $user_id_ary;
       
  3400 	}
       
  3401 
       
  3402 	if ($group_id_ary)
       
  3403 	{
       
  3404 		$group_id_ary = (!is_array($group_id_ary)) ? array($group_id_ary) : $group_id_ary;
       
  3405 	}
       
  3406 
       
  3407 	$sql = 'SELECT ug.*, u.username, u.username_clean, u.user_email
       
  3408 		FROM ' . USER_GROUP_TABLE . ' ug, ' . USERS_TABLE . ' u
       
  3409 		WHERE ug.user_id = u.user_id
       
  3410 			AND ug.user_pending = 0 AND ';
       
  3411 
       
  3412 	if ($group_id_ary)
       
  3413 	{
       
  3414 		$sql .= ' ' . $db->sql_in_set('ug.group_id', $group_id_ary);
       
  3415 	}
       
  3416 
       
  3417 	if ($user_id_ary)
       
  3418 	{
       
  3419 		$sql .= ($group_id_ary) ? ' AND ' : ' ';
       
  3420 		$sql .= $db->sql_in_set('ug.user_id', $user_id_ary);
       
  3421 	}
       
  3422 
       
  3423 	$result = ($return_bool) ? $db->sql_query_limit($sql, 1) : $db->sql_query($sql);
       
  3424 
       
  3425 	$row = $db->sql_fetchrow($result);
       
  3426 
       
  3427 	if ($return_bool)
       
  3428 	{
       
  3429 		$db->sql_freeresult($result);
       
  3430 		return ($row) ? true : false;
       
  3431 	}
       
  3432 
       
  3433 	if (!$row)
       
  3434 	{
       
  3435 		return false;
       
  3436 	}
       
  3437 
       
  3438 	$return = array();
       
  3439 
       
  3440 	do
       
  3441 	{
       
  3442 		$return[] = $row;
       
  3443 	}
       
  3444 	while ($row = $db->sql_fetchrow($result));
       
  3445 
       
  3446 	$db->sql_freeresult($result);
       
  3447 
       
  3448 	return $return;
       
  3449 }
       
  3450 
       
  3451 /**
       
  3452 * Re-cache moderators and foes if group has a_ or m_ permissions
       
  3453 */
       
  3454 function group_update_listings($group_id)
       
  3455 {
       
  3456 	global $auth;
       
  3457 
       
  3458 	$hold_ary = $auth->acl_group_raw_data($group_id, array('a_', 'm_'));
       
  3459 
       
  3460 	if (!sizeof($hold_ary))
       
  3461 	{
       
  3462 		return;
       
  3463 	}
       
  3464 
       
  3465 	$mod_permissions = $admin_permissions = false;
       
  3466 
       
  3467 	foreach ($hold_ary as $g_id => $forum_ary)
       
  3468 	{
       
  3469 		foreach ($forum_ary as $forum_id => $auth_ary)
       
  3470 		{
       
  3471 			foreach ($auth_ary as $auth_option => $setting)
       
  3472 			{
       
  3473 				if ($mod_permissions && $admin_permissions)
       
  3474 				{
       
  3475 					break 3;
       
  3476 				}
       
  3477 
       
  3478 				if ($setting != ACL_YES)
       
  3479 				{
       
  3480 					continue;
       
  3481 				}
       
  3482 
       
  3483 				if ($auth_option == 'm_')
       
  3484 				{
       
  3485 					$mod_permissions = true;
       
  3486 				}
       
  3487 
       
  3488 				if ($auth_option == 'a_')
       
  3489 				{
       
  3490 					$admin_permissions = true;
       
  3491 				}
       
  3492 			}
       
  3493 		}
       
  3494 	}
       
  3495 
       
  3496 	if ($mod_permissions)
       
  3497 	{
       
  3498 		if (!function_exists('cache_moderators'))
       
  3499 		{
       
  3500 			global $phpbb_root_path, $phpEx;
       
  3501 			include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
       
  3502 		}
       
  3503 		cache_moderators();
       
  3504 	}
       
  3505 
       
  3506 	if ($mod_permissions || $admin_permissions)
       
  3507 	{
       
  3508 		if (!function_exists('update_foes'))
       
  3509 		{
       
  3510 			global $phpbb_root_path, $phpEx;
       
  3511 			include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
       
  3512 		}
       
  3513 		update_foes(array($group_id));
       
  3514 	}
       
  3515 }
       
  3516 
       
  3517 
       
  3518 
       
  3519 /**
       
  3520 * Funtion to make a user leave the NEWLY_REGISTERED system group.
       
  3521 * @access public
       
  3522 * @param $user_id The id of the user to remove from the group
       
  3523 */
       
  3524 function remove_newly_registered($user_id, $user_data = false)
       
  3525 {
       
  3526 	global $db;
       
  3527 
       
  3528 	if ($user_data === false)
       
  3529 	{
       
  3530 		$sql = 'SELECT *
       
  3531 			FROM ' . USERS_TABLE . '
       
  3532 			WHERE user_id = ' . $user_id;
       
  3533 		$result = $db->sql_query($sql);
       
  3534 		$user_row = $db->sql_fetchrow($result);
       
  3535 		$db->sql_freeresult($result);
       
  3536 
       
  3537 		if (!$user_row)
       
  3538 		{
       
  3539 			return false;
       
  3540 		}
       
  3541 		else
       
  3542 		{
       
  3543 			$user_data  = $user_row;
       
  3544 		}
       
  3545 	}
       
  3546 
       
  3547 	if (empty($user_data['user_new']))
       
  3548 	{
       
  3549 		return false;
       
  3550 	}
       
  3551 
       
  3552 	$sql = 'SELECT group_id
       
  3553 		FROM ' . GROUPS_TABLE . "
       
  3554 		WHERE group_name = 'NEWLY_REGISTERED'
       
  3555 			AND group_type = " . GROUP_SPECIAL;
       
  3556 	$result = $db->sql_query($sql);
       
  3557 	$group_id = (int) $db->sql_fetchfield('group_id');
       
  3558 	$db->sql_freeresult($result);
       
  3559 
       
  3560 	if (!$group_id)
       
  3561 	{
       
  3562 		return false;
       
  3563 	}
       
  3564 
       
  3565 	// We need to call group_user_del here, because this function makes sure everything is correctly changed.
       
  3566 	// A downside for a call within the session handler is that the language is not set up yet - so no log entry
       
  3567 	group_user_del($group_id, $user_id);
       
  3568 
       
  3569 	// Set user_new to 0 to let this not be triggered again
       
  3570 	$sql = 'UPDATE ' . USERS_TABLE . '
       
  3571 		SET user_new = 0
       
  3572 		WHERE user_id = ' . $user_id;
       
  3573 	$db->sql_query($sql);
       
  3574 
       
  3575 	// The new users group was the users default group?
       
  3576 	if ($user_data['group_id'] == $group_id)
       
  3577 	{
       
  3578 		// Which group is now the users default one?
       
  3579 		$sql = 'SELECT group_id
       
  3580 			FROM ' . USERS_TABLE . '
       
  3581 			WHERE user_id = ' . $user_id;
       
  3582 		$result = $db->sql_query($sql);
       
  3583 		$user_data['group_id'] = $db->sql_fetchfield('group_id');
       
  3584 		$db->sql_freeresult($result);
       
  3585 	}
       
  3586 
       
  3587 	return $user_data['group_id'];
       
  3588 }
       
  3589 
       
  3590 ?>