(a little test for later merges)
[phpbb.git] / phpBB / includes / functions_user.php
blob21e82030ee6765378ba62e20ef1d52f2f27d5d22
1 <?php
2 /**
4 * @package phpBB3
5 * @version $Id$
6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
9 */
11 /**
12 * @ignore
14 if (!defined('IN_PHPBB'))
16 exit;
19 /**
20 * Obtain user_ids from usernames or vice versa. Returns false on
21 * success else the error string
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
27 function user_get_id_name(&$user_id_ary, &$username_ary, $user_type = false)
29 global $db;
31 // Are both arrays already filled? Yep, return else
32 // are neither array filled?
33 if ($user_id_ary && $username_ary)
35 return false;
37 else if (!$user_id_ary && !$username_ary)
39 return 'NO_USERS';
42 $which_ary = ($user_id_ary) ? 'user_id_ary' : 'username_ary';
44 if ($$which_ary && !is_array($$which_ary))
46 $$which_ary = array($$which_ary);
49 $sql_in = ($which_ary == 'user_id_ary') ? array_map('intval', $$which_ary) : array_map('utf8_clean_string', $$which_ary);
50 unset($$which_ary);
52 $user_id_ary = $username_ary = array();
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);
60 if ($user_type !== false && !empty($user_type))
62 $sql .= ' AND ' . $db->sql_in_set('user_type', $user_type);
65 $result = $db->sql_query($sql);
67 if (!($row = $db->sql_fetchrow($result)))
69 $db->sql_freeresult($result);
70 return 'NO_USERS';
75 $username_ary[$row['user_id']] = $row['username'];
76 $user_id_ary[] = $row['user_id'];
78 while ($row = $db->sql_fetchrow($result));
79 $db->sql_freeresult($result);
81 return false;
84 /**
85 * Get latest registered username and update database to reflect it
87 function update_last_username()
89 global $db;
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);
100 if ($row)
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);
109 * Updates a username across all relevant tables/fields
111 * @param string $old_name the old/current username
112 * @param string $new_name the new username
114 function user_update_name($old_name, $new_name)
116 global $config, $db, $cache;
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'),
125 foreach ($update_ary as $table => $field_ary)
127 foreach ($field_ary as $field)
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);
136 if ($config['newest_username'] == $old_name)
138 set_config('newest_username', $new_name, true);
141 // Because some tables/caches use username-specific data we need to purge this here.
142 $cache->destroy('sql', MODERATOR_CACHE_TABLE);
146 * Adds an user
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.
152 function user_add($user_row, $cp_data = false)
154 global $db, $user, $auth, $config, $phpbb_root_path, $phpEx;
156 if (empty($user_row['username']) || !isset($user_row['group_id']) || !isset($user_row['user_email']) || !isset($user_row['user_type']))
158 return false;
161 $username_clean = utf8_clean_string($user_row['username']);
163 if (empty($username_clean))
165 return false;
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'],
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,
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,
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,
224 'user_sig' => '',
225 'user_sig_bbcode_uid' => '',
226 'user_sig_bbcode_bitfield' => '',
228 'user_form_salt' => unique_id(),
231 // Now fill the sql array with not required variables
232 foreach ($additional_vars as $key => $default_value)
234 $sql_ary[$key] = (isset($user_row[$key])) ? $user_row[$key] : $default_value;
237 // Any additional variables in $user_row not covered above?
238 $remaining_vars = array_diff(array_keys($user_row), array_keys($sql_ary));
240 // Now fill our sql array with the remaining vars
241 if (sizeof($remaining_vars))
243 foreach ($remaining_vars as $key)
245 $sql_ary[$key] = $user_row[$key];
249 $sql = 'INSERT INTO ' . USERS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
250 $db->sql_query($sql);
252 $user_id = $db->sql_nextid();
254 // Insert Custom Profile Fields
255 if ($cp_data !== false && sizeof($cp_data))
257 $cp_data['user_id'] = (int) $user_id;
259 if (!class_exists('custom_profile'))
261 include_once($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);
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);
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)
275 $db->sql_query($sql);
277 // Now make it the users default group...
278 group_set_user_default($user_row['group_id'], array($user_id), false);
280 // Add to newly registered users group if user_new is 1
281 if ($config['new_member_post_limit'] && $sql_ary['user_new'])
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);
291 if ($add_group_id)
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;
296 // Add user to "newly registered users" group and set to default group if admin specified so.
297 if ($config['new_member_group_default'])
299 group_user_add($add_group_id, $user_id, false, false, true);
301 else
303 group_user_add($add_group_id, $user_id);
306 unset($GLOBALS['skip_add_log']);
310 // set the newest user and adjust the user count if the user is a normal user and no activation mail is sent
311 if ($user_row['user_type'] == USER_NORMAL || $user_row['user_type'] == USER_FOUNDER)
313 set_config('newest_user_id', $user_id, true);
314 set_config('newest_username', $user_row['username'], true);
315 set_config_count('num_users', 1, true);
317 $sql = 'SELECT group_colour
318 FROM ' . GROUPS_TABLE . '
319 WHERE group_id = ' . (int) $user_row['group_id'];
320 $result = $db->sql_query_limit($sql, 1);
321 $row = $db->sql_fetchrow($result);
322 $db->sql_freeresult($result);
324 set_config('newest_user_colour', $row['group_colour'], true);
327 return $user_id;
331 * Remove User
333 function user_delete($mode, $user_id, $post_username = false)
335 global $cache, $config, $db, $user, $auth;
336 global $phpbb_root_path, $phpEx;
338 $sql = 'SELECT *
339 FROM ' . USERS_TABLE . '
340 WHERE user_id = ' . $user_id;
341 $result = $db->sql_query($sql);
342 $user_row = $db->sql_fetchrow($result);
343 $db->sql_freeresult($result);
345 if (!$user_row)
347 return false;
350 // Before we begin, we will remove the reports the user issued.
351 $sql = 'SELECT r.post_id, p.topic_id
352 FROM ' . REPORTS_TABLE . ' r, ' . POSTS_TABLE . ' p
353 WHERE r.user_id = ' . $user_id . '
354 AND p.post_id = r.post_id';
355 $result = $db->sql_query($sql);
357 $report_posts = $report_topics = array();
358 while ($row = $db->sql_fetchrow($result))
360 $report_posts[] = $row['post_id'];
361 $report_topics[] = $row['topic_id'];
363 $db->sql_freeresult($result);
365 if (sizeof($report_posts))
367 $report_posts = array_unique($report_posts);
368 $report_topics = array_unique($report_topics);
370 // Get a list of topics that still contain reported posts
371 $sql = 'SELECT DISTINCT topic_id
372 FROM ' . POSTS_TABLE . '
373 WHERE ' . $db->sql_in_set('topic_id', $report_topics) . '
374 AND post_reported = 1
375 AND ' . $db->sql_in_set('post_id', $report_posts, true);
376 $result = $db->sql_query($sql);
378 $keep_report_topics = array();
379 while ($row = $db->sql_fetchrow($result))
381 $keep_report_topics[] = $row['topic_id'];
383 $db->sql_freeresult($result);
385 if (sizeof($keep_report_topics))
387 $report_topics = array_diff($report_topics, $keep_report_topics);
389 unset($keep_report_topics);
391 // Now set the flags back
392 $sql = 'UPDATE ' . POSTS_TABLE . '
393 SET post_reported = 0
394 WHERE ' . $db->sql_in_set('post_id', $report_posts);
395 $db->sql_query($sql);
397 if (sizeof($report_topics))
399 $sql = 'UPDATE ' . TOPICS_TABLE . '
400 SET topic_reported = 0
401 WHERE ' . $db->sql_in_set('topic_id', $report_topics);
402 $db->sql_query($sql);
406 // Remove reports
407 $db->sql_query('DELETE FROM ' . REPORTS_TABLE . ' WHERE user_id = ' . $user_id);
409 if ($user_row['user_avatar'] && $user_row['user_avatar_type'] == AVATAR_UPLOAD)
411 avatar_delete('user', $user_row);
414 switch ($mode)
416 case 'retain':
418 $db->sql_transaction('begin');
420 if ($post_username === false)
422 $post_username = $user->lang['GUEST'];
425 // If the user is inactive and newly registered we assume no posts from this user being there...
426 if ($user_row['user_type'] == USER_INACTIVE && $user_row['user_inactive_reason'] == INACTIVE_REGISTER && !$user_row['user_posts'])
429 else
431 $sql = 'UPDATE ' . FORUMS_TABLE . '
432 SET forum_last_poster_id = ' . ANONYMOUS . ", forum_last_poster_name = '" . $db->sql_escape($post_username) . "', forum_last_poster_colour = ''
433 WHERE forum_last_poster_id = $user_id";
434 $db->sql_query($sql);
436 $sql = 'UPDATE ' . POSTS_TABLE . '
437 SET poster_id = ' . ANONYMOUS . ", post_username = '" . $db->sql_escape($post_username) . "'
438 WHERE poster_id = $user_id";
439 $db->sql_query($sql);
441 $sql = 'UPDATE ' . POSTS_TABLE . '
442 SET post_edit_user = ' . ANONYMOUS . "
443 WHERE post_edit_user = $user_id";
444 $db->sql_query($sql);
446 $sql = 'UPDATE ' . TOPICS_TABLE . '
447 SET topic_poster = ' . ANONYMOUS . ", topic_first_poster_name = '" . $db->sql_escape($post_username) . "', topic_first_poster_colour = ''
448 WHERE topic_poster = $user_id";
449 $db->sql_query($sql);
451 $sql = 'UPDATE ' . TOPICS_TABLE . '
452 SET topic_last_poster_id = ' . ANONYMOUS . ", topic_last_poster_name = '" . $db->sql_escape($post_username) . "', topic_last_poster_colour = ''
453 WHERE topic_last_poster_id = $user_id";
454 $db->sql_query($sql);
456 $sql = 'UPDATE ' . ATTACHMENTS_TABLE . '
457 SET poster_id = ' . ANONYMOUS . "
458 WHERE poster_id = $user_id";
459 $db->sql_query($sql);
461 // Since we change every post by this author, we need to count this amount towards the anonymous user
463 // Update the post count for the anonymous user
464 if ($user_row['user_posts'])
466 $sql = 'UPDATE ' . USERS_TABLE . '
467 SET user_posts = user_posts + ' . $user_row['user_posts'] . '
468 WHERE user_id = ' . ANONYMOUS;
469 $db->sql_query($sql);
473 $db->sql_transaction('commit');
475 break;
477 case 'remove':
479 if (!function_exists('delete_posts'))
481 include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
484 $sql = 'SELECT topic_id, COUNT(post_id) AS total_posts
485 FROM ' . POSTS_TABLE . "
486 WHERE poster_id = $user_id
487 GROUP BY topic_id";
488 $result = $db->sql_query($sql);
490 $topic_id_ary = array();
491 while ($row = $db->sql_fetchrow($result))
493 $topic_id_ary[$row['topic_id']] = $row['total_posts'];
495 $db->sql_freeresult($result);
497 if (sizeof($topic_id_ary))
499 $sql = 'SELECT topic_id, topic_replies, topic_replies_real
500 FROM ' . TOPICS_TABLE . '
501 WHERE ' . $db->sql_in_set('topic_id', array_keys($topic_id_ary));
502 $result = $db->sql_query($sql);
504 $del_topic_ary = array();
505 while ($row = $db->sql_fetchrow($result))
507 if (max($row['topic_replies'], $row['topic_replies_real']) + 1 == $topic_id_ary[$row['topic_id']])
509 $del_topic_ary[] = $row['topic_id'];
512 $db->sql_freeresult($result);
514 if (sizeof($del_topic_ary))
516 $sql = 'DELETE FROM ' . TOPICS_TABLE . '
517 WHERE ' . $db->sql_in_set('topic_id', $del_topic_ary);
518 $db->sql_query($sql);
522 // Delete posts, attachments, etc.
523 delete_posts('poster_id', $user_id);
525 break;
528 $db->sql_transaction('begin');
530 $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);
532 foreach ($table_ary as $table)
534 $sql = "DELETE FROM $table
535 WHERE user_id = $user_id";
536 $db->sql_query($sql);
539 $cache->destroy('sql', MODERATOR_CACHE_TABLE);
541 // Delete user log entries about this user
542 $sql = 'DELETE FROM ' . LOG_TABLE . '
543 WHERE reportee_id = ' . $user_id;
544 $db->sql_query($sql);
546 // Change user_id to anonymous for this users triggered events
547 $sql = 'UPDATE ' . LOG_TABLE . '
548 SET user_id = ' . ANONYMOUS . '
549 WHERE user_id = ' . $user_id;
550 $db->sql_query($sql);
552 // Delete the user_id from the zebra table
553 $sql = 'DELETE FROM ' . ZEBRA_TABLE . '
554 WHERE user_id = ' . $user_id . '
555 OR zebra_id = ' . $user_id;
556 $db->sql_query($sql);
558 // Delete the user_id from the banlist
559 $sql = 'DELETE FROM ' . BANLIST_TABLE . '
560 WHERE ban_userid = ' . $user_id;
561 $db->sql_query($sql);
563 // Delete the user_id from the session table
564 $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
565 WHERE session_user_id = ' . $user_id;
566 $db->sql_query($sql);
568 // Remove any undelivered mails...
569 $sql = 'SELECT msg_id, user_id
570 FROM ' . PRIVMSGS_TO_TABLE . '
571 WHERE author_id = ' . $user_id . '
572 AND folder_id = ' . PRIVMSGS_NO_BOX;
573 $result = $db->sql_query($sql);
575 $undelivered_msg = $undelivered_user = array();
576 while ($row = $db->sql_fetchrow($result))
578 $undelivered_msg[] = $row['msg_id'];
579 $undelivered_user[$row['user_id']][] = true;
581 $db->sql_freeresult($result);
583 if (sizeof($undelivered_msg))
585 $sql = 'DELETE FROM ' . PRIVMSGS_TABLE . '
586 WHERE ' . $db->sql_in_set('msg_id', $undelivered_msg);
587 $db->sql_query($sql);
590 $sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
591 WHERE author_id = ' . $user_id . '
592 AND folder_id = ' . PRIVMSGS_NO_BOX;
593 $db->sql_query($sql);
595 // Delete all to-information
596 $sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
597 WHERE user_id = ' . $user_id;
598 $db->sql_query($sql);
600 // Set the remaining author id to anonymous - this way users are still able to read messages from users being removed
601 $sql = 'UPDATE ' . PRIVMSGS_TO_TABLE . '
602 SET author_id = ' . ANONYMOUS . '
603 WHERE author_id = ' . $user_id;
604 $db->sql_query($sql);
606 $sql = 'UPDATE ' . PRIVMSGS_TABLE . '
607 SET author_id = ' . ANONYMOUS . '
608 WHERE author_id = ' . $user_id;
609 $db->sql_query($sql);
611 foreach ($undelivered_user as $_user_id => $ary)
613 if ($_user_id == $user_id)
615 continue;
618 $sql = 'UPDATE ' . USERS_TABLE . '
619 SET user_new_privmsg = user_new_privmsg - ' . sizeof($ary) . ',
620 user_unread_privmsg = user_unread_privmsg - ' . sizeof($ary) . '
621 WHERE user_id = ' . $_user_id;
622 $db->sql_query($sql);
625 $db->sql_transaction('commit');
627 // Reset newest user info if appropriate
628 if ($config['newest_user_id'] == $user_id)
630 update_last_username();
633 // Decrement number of users if this user is active
634 if ($user_row['user_type'] != USER_INACTIVE && $user_row['user_type'] != USER_IGNORE)
636 set_config_count('num_users', -1, true);
639 return false;
643 * Flips user_type from active to inactive and vice versa, handles group membership updates
645 * @param string $mode can be flip for flipping from active/inactive, activate or deactivate
647 function user_active_flip($mode, $user_id_ary, $reason = INACTIVE_MANUAL)
649 global $config, $db, $user, $auth;
651 $deactivated = $activated = 0;
652 $sql_statements = array();
654 if (!is_array($user_id_ary))
656 $user_id_ary = array($user_id_ary);
659 if (!sizeof($user_id_ary))
661 return;
664 $sql = 'SELECT user_id, group_id, user_type, user_inactive_reason
665 FROM ' . USERS_TABLE . '
666 WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
667 $result = $db->sql_query($sql);
669 while ($row = $db->sql_fetchrow($result))
671 $sql_ary = array();
673 if ($row['user_type'] == USER_IGNORE || $row['user_type'] == USER_FOUNDER ||
674 ($mode == 'activate' && $row['user_type'] != USER_INACTIVE) ||
675 ($mode == 'deactivate' && $row['user_type'] == USER_INACTIVE))
677 continue;
680 if ($row['user_type'] == USER_INACTIVE)
682 $activated++;
684 else
686 $deactivated++;
688 // Remove the users session key...
689 $user->reset_login_keys($row['user_id']);
692 $sql_ary += array(
693 'user_type' => ($row['user_type'] == USER_NORMAL) ? USER_INACTIVE : USER_NORMAL,
694 'user_inactive_time' => ($row['user_type'] == USER_NORMAL) ? time() : 0,
695 'user_inactive_reason' => ($row['user_type'] == USER_NORMAL) ? $reason : 0,
698 $sql_statements[$row['user_id']] = $sql_ary;
700 $db->sql_freeresult($result);
702 if (sizeof($sql_statements))
704 foreach ($sql_statements as $user_id => $sql_ary)
706 $sql = 'UPDATE ' . USERS_TABLE . '
707 SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
708 WHERE user_id = ' . $user_id;
709 $db->sql_query($sql);
712 $auth->acl_clear_prefetch(array_keys($sql_statements));
715 if ($deactivated)
717 set_config_count('num_users', $deactivated * (-1), true);
720 if ($activated)
722 set_config_count('num_users', $activated, true);
725 // Update latest username
726 update_last_username();
730 * Add a ban or ban exclusion to the banlist. Bans either a user, an IP or an email address
732 * @param string $mode Type of ban. One of the following: user, ip, email
733 * @param mixed $ban Banned entity. Either string or array with usernames, ips or email addresses
734 * @param int $ban_len Ban length in minutes
735 * @param string $ban_len_other Ban length as a date (YYYY-MM-DD)
736 * @param boolean $ban_exclude Exclude these entities from banning?
737 * @param string $ban_reason String describing the reason for this ban
738 * @return boolean
740 function user_ban($mode, $ban, $ban_len, $ban_len_other, $ban_exclude, $ban_reason, $ban_give_reason = '')
742 global $db, $user, $auth, $cache;
744 // Delete stale bans
745 $sql = 'DELETE FROM ' . BANLIST_TABLE . '
746 WHERE ban_end < ' . time() . '
747 AND ban_end <> 0';
748 $db->sql_query($sql);
750 $ban_list = (!is_array($ban)) ? array_unique(explode("\n", $ban)) : $ban;
751 $ban_list_log = implode(', ', $ban_list);
753 $current_time = time();
755 // Set $ban_end to the unix time when the ban should end. 0 is a permanent ban.
756 if ($ban_len)
758 if ($ban_len != -1 || !$ban_len_other)
760 $ban_end = max($current_time, $current_time + ($ban_len) * 60);
762 else
764 $ban_other = explode('-', $ban_len_other);
765 if (sizeof($ban_other) == 3 && ((int)$ban_other[0] < 9999) &&
766 (strlen($ban_other[0]) == 4) && (strlen($ban_other[1]) == 2) && (strlen($ban_other[2]) == 2))
768 $ban_end = max($current_time, gmmktime(0, 0, 0, (int)$ban_other[1], (int)$ban_other[2], (int)$ban_other[0]));
770 else
772 trigger_error('LENGTH_BAN_INVALID');
776 else
778 $ban_end = 0;
781 $founder = $founder_names = array();
783 if (!$ban_exclude)
785 // Create a list of founder...
786 $sql = 'SELECT user_id, user_email, username_clean
787 FROM ' . USERS_TABLE . '
788 WHERE user_type = ' . USER_FOUNDER;
789 $result = $db->sql_query($sql);
791 while ($row = $db->sql_fetchrow($result))
793 $founder[$row['user_id']] = $row['user_email'];
794 $founder_names[$row['user_id']] = $row['username_clean'];
796 $db->sql_freeresult($result);
799 $banlist_ary = array();
801 switch ($mode)
803 case 'user':
804 $type = 'ban_userid';
806 // At the moment we do not support wildcard username banning
808 // Select the relevant user_ids.
809 $sql_usernames = array();
811 foreach ($ban_list as $username)
813 $username = trim($username);
814 if ($username != '')
816 $clean_name = utf8_clean_string($username);
817 if ($clean_name == $user->data['username_clean'])
819 trigger_error('CANNOT_BAN_YOURSELF', E_USER_WARNING);
821 if (in_array($clean_name, $founder_names))
823 trigger_error('CANNOT_BAN_FOUNDER', E_USER_WARNING);
825 $sql_usernames[] = $clean_name;
829 // Make sure we have been given someone to ban
830 if (!sizeof($sql_usernames))
832 trigger_error('NO_USER_SPECIFIED');
835 $sql = 'SELECT user_id
836 FROM ' . USERS_TABLE . '
837 WHERE ' . $db->sql_in_set('username_clean', $sql_usernames);
839 // Do not allow banning yourself
840 if (sizeof($founder))
842 $sql .= ' AND ' . $db->sql_in_set('user_id', array_merge(array_keys($founder), array($user->data['user_id'])), true);
844 else
846 $sql .= ' AND user_id <> ' . $user->data['user_id'];
849 $result = $db->sql_query($sql);
851 if ($row = $db->sql_fetchrow($result))
855 $banlist_ary[] = (int) $row['user_id'];
857 while ($row = $db->sql_fetchrow($result));
859 else
861 $db->sql_freeresult($result);
862 trigger_error('NO_USERS');
864 $db->sql_freeresult($result);
865 break;
867 case 'ip':
868 $type = 'ban_ip';
870 foreach ($ban_list as $ban_item)
872 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))
874 // This is an IP range
875 // Don't ask about all this, just don't ask ... !
876 $ip_1_counter = $ip_range_explode[1];
877 $ip_1_end = $ip_range_explode[5];
879 while ($ip_1_counter <= $ip_1_end)
881 $ip_2_counter = ($ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[2] : 0;
882 $ip_2_end = ($ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[6];
884 if ($ip_2_counter == 0 && $ip_2_end == 254)
886 $ip_2_counter = 256;
887 $ip_2_fragment = 256;
889 $banlist_ary[] = "$ip_1_counter.*";
892 while ($ip_2_counter <= $ip_2_end)
894 $ip_3_counter = ($ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[3] : 0;
895 $ip_3_end = ($ip_2_counter < $ip_2_end || $ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[7];
897 if ($ip_3_counter == 0 && $ip_3_end == 254)
899 $ip_3_counter = 256;
900 $ip_3_fragment = 256;
902 $banlist_ary[] = "$ip_1_counter.$ip_2_counter.*";
905 while ($ip_3_counter <= $ip_3_end)
907 $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;
908 $ip_4_end = ($ip_3_counter < $ip_3_end || $ip_2_counter < $ip_2_end) ? 254 : $ip_range_explode[8];
910 if ($ip_4_counter == 0 && $ip_4_end == 254)
912 $ip_4_counter = 256;
913 $ip_4_fragment = 256;
915 $banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.*";
918 while ($ip_4_counter <= $ip_4_end)
920 $banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.$ip_4_counter";
921 $ip_4_counter++;
923 $ip_3_counter++;
925 $ip_2_counter++;
927 $ip_1_counter++;
930 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)))
932 // Normal IP address
933 $banlist_ary[] = trim($ban_item);
935 else if (preg_match('#^\*$#', trim($ban_item)))
937 // Ban all IPs
938 $banlist_ary[] = '*';
940 else if (preg_match('#^([\w\-_]\.?){2,}$#is', trim($ban_item)))
942 // hostname
943 $ip_ary = gethostbynamel(trim($ban_item));
945 if (!empty($ip_ary))
947 foreach ($ip_ary as $ip)
949 if ($ip)
951 if (strlen($ip) > 40)
953 continue;
956 $banlist_ary[] = $ip;
962 if (empty($banlist_ary))
964 trigger_error('NO_IPS_DEFINED');
967 break;
969 case 'email':
970 $type = 'ban_email';
972 foreach ($ban_list as $ban_item)
974 $ban_item = trim($ban_item);
976 if (preg_match('#^.*?@*|(([a-z0-9\-]+\.)+([a-z]{2,3}))$#i', $ban_item))
978 if (strlen($ban_item) > 100)
980 continue;
983 if (!sizeof($founder) || !in_array($ban_item, $founder))
985 $banlist_ary[] = $ban_item;
990 if (sizeof($ban_list) == 0)
992 trigger_error('NO_EMAILS_DEFINED');
994 break;
996 default:
997 trigger_error('NO_MODE');
998 break;
1001 // Fetch currently set bans of the specified type and exclude state. Prevent duplicate bans.
1002 $sql_where = ($type == 'ban_userid') ? 'ban_userid <> 0' : "$type <> ''";
1004 $sql = "SELECT $type
1005 FROM " . BANLIST_TABLE . "
1006 WHERE $sql_where
1007 AND ban_exclude = " . (int) $ban_exclude;
1008 $result = $db->sql_query($sql);
1010 // Reset $sql_where, because we use it later...
1011 $sql_where = '';
1013 if ($row = $db->sql_fetchrow($result))
1015 $banlist_ary_tmp = array();
1018 switch ($mode)
1020 case 'user':
1021 $banlist_ary_tmp[] = $row['ban_userid'];
1022 break;
1024 case 'ip':
1025 $banlist_ary_tmp[] = $row['ban_ip'];
1026 break;
1028 case 'email':
1029 $banlist_ary_tmp[] = $row['ban_email'];
1030 break;
1033 while ($row = $db->sql_fetchrow($result));
1035 $banlist_ary_tmp = array_intersect($banlist_ary, $banlist_ary_tmp);
1037 if (sizeof($banlist_ary_tmp))
1039 // One or more entities are already banned/excluded, delete the existing bans, so they can be re-inserted with the given new length
1040 $sql = 'DELETE FROM ' . BANLIST_TABLE . '
1041 WHERE ' . $db->sql_in_set($type, $banlist_ary_tmp) . '
1042 AND ban_exclude = ' . (int) $ban_exclude;
1043 $db->sql_query($sql);
1046 unset($banlist_ary_tmp);
1048 $db->sql_freeresult($result);
1050 // We have some entities to ban
1051 if (sizeof($banlist_ary))
1053 $sql_ary = array();
1055 foreach ($banlist_ary as $ban_entry)
1057 $sql_ary[] = array(
1058 $type => $ban_entry,
1059 'ban_start' => (int) $current_time,
1060 'ban_end' => (int) $ban_end,
1061 'ban_exclude' => (int) $ban_exclude,
1062 'ban_reason' => (string) $ban_reason,
1063 'ban_give_reason' => (string) $ban_give_reason,
1067 $db->sql_multi_insert(BANLIST_TABLE, $sql_ary);
1069 // If we are banning we want to logout anyone matching the ban
1070 if (!$ban_exclude)
1072 switch ($mode)
1074 case 'user':
1075 $sql_where = 'WHERE ' . $db->sql_in_set('session_user_id', $banlist_ary);
1076 break;
1078 case 'ip':
1079 $sql_where = 'WHERE ' . $db->sql_in_set('session_ip', $banlist_ary);
1080 break;
1082 case 'email':
1083 $banlist_ary_sql = array();
1085 foreach ($banlist_ary as $ban_entry)
1087 $banlist_ary_sql[] = (string) str_replace('*', '%', $ban_entry);
1090 $sql = 'SELECT user_id
1091 FROM ' . USERS_TABLE . '
1092 WHERE ' . $db->sql_in_set('user_email', $banlist_ary_sql);
1093 $result = $db->sql_query($sql);
1095 $sql_in = array();
1097 if ($row = $db->sql_fetchrow($result))
1101 $sql_in[] = $row['user_id'];
1103 while ($row = $db->sql_fetchrow($result));
1105 $sql_where = 'WHERE ' . $db->sql_in_set('session_user_id', $sql_in);
1107 $db->sql_freeresult($result);
1108 break;
1111 if (isset($sql_where) && $sql_where)
1113 $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
1114 $sql_where";
1115 $db->sql_query($sql);
1117 if ($mode == 'user')
1119 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . ' ' . ((in_array('*', $banlist_ary)) ? '' : 'WHERE ' . $db->sql_in_set('user_id', $banlist_ary));
1120 $db->sql_query($sql);
1125 // Update log
1126 $log_entry = ($ban_exclude) ? 'LOG_BAN_EXCLUDE_' : 'LOG_BAN_';
1128 // Add to moderator log, admin log and user notes
1129 add_log('admin', $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
1130 add_log('mod', 0, 0, $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
1131 if ($mode == 'user')
1133 foreach ($banlist_ary as $user_id)
1135 add_log('user', $user_id, $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
1139 $cache->destroy('sql', BANLIST_TABLE);
1141 return true;
1144 // There was nothing to ban/exclude. But destroying the cache because of the removal of stale bans.
1145 $cache->destroy('sql', BANLIST_TABLE);
1147 return false;
1151 * Unban User
1153 function user_unban($mode, $ban)
1155 global $db, $user, $auth, $cache;
1157 // Delete stale bans
1158 $sql = 'DELETE FROM ' . BANLIST_TABLE . '
1159 WHERE ban_end < ' . time() . '
1160 AND ban_end <> 0';
1161 $db->sql_query($sql);
1163 if (!is_array($ban))
1165 $ban = array($ban);
1168 $unban_sql = array_map('intval', $ban);
1170 if (sizeof($unban_sql))
1172 // Grab details of bans for logging information later
1173 switch ($mode)
1175 case 'user':
1176 $sql = 'SELECT u.username AS unban_info, u.user_id
1177 FROM ' . USERS_TABLE . ' u, ' . BANLIST_TABLE . ' b
1178 WHERE ' . $db->sql_in_set('b.ban_id', $unban_sql) . '
1179 AND u.user_id = b.ban_userid';
1180 break;
1182 case 'email':
1183 $sql = 'SELECT ban_email AS unban_info
1184 FROM ' . BANLIST_TABLE . '
1185 WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
1186 break;
1188 case 'ip':
1189 $sql = 'SELECT ban_ip AS unban_info
1190 FROM ' . BANLIST_TABLE . '
1191 WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
1192 break;
1194 $result = $db->sql_query($sql);
1196 $l_unban_list = '';
1197 $user_ids_ary = array();
1198 while ($row = $db->sql_fetchrow($result))
1200 $l_unban_list .= (($l_unban_list != '') ? ', ' : '') . $row['unban_info'];
1201 if ($mode == 'user')
1203 $user_ids_ary[] = $row['user_id'];
1206 $db->sql_freeresult($result);
1208 $sql = 'DELETE FROM ' . BANLIST_TABLE . '
1209 WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
1210 $db->sql_query($sql);
1212 // Add to moderator log, admin log and user notes
1213 add_log('admin', 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
1214 add_log('mod', 0, 0, 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
1215 if ($mode == 'user')
1217 foreach ($user_ids_ary as $user_id)
1219 add_log('user', $user_id, 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
1224 $cache->destroy('sql', BANLIST_TABLE);
1226 return false;
1230 * Whois facility
1232 * @link http://tools.ietf.org/html/rfc3912 RFC3912: WHOIS Protocol Specification
1234 function user_ipwhois($ip)
1236 $ipwhois = '';
1238 // Check IP
1239 // Only supporting IPv4 at the moment...
1240 if (empty($ip) || !preg_match(get_preg_expression('ipv4'), $ip))
1242 return '';
1245 if (($fsk = @fsockopen('whois.arin.net', 43)))
1247 // CRLF as per RFC3912
1248 fputs($fsk, "$ip\r\n");
1249 while (!feof($fsk))
1251 $ipwhois .= fgets($fsk, 1024);
1253 @fclose($fsk);
1256 $match = array();
1258 // Test for referrals from ARIN to other whois databases, roll on rwhois
1259 if (preg_match('#ReferralServer: whois://(.+)#im', $ipwhois, $match))
1261 if (strpos($match[1], ':') !== false)
1263 $pos = strrpos($match[1], ':');
1264 $server = substr($match[1], 0, $pos);
1265 $port = (int) substr($match[1], $pos + 1);
1266 unset($pos);
1268 else
1270 $server = $match[1];
1271 $port = 43;
1274 $buffer = '';
1276 if (($fsk = @fsockopen($server, $port)))
1278 fputs($fsk, "$ip\r\n");
1279 while (!feof($fsk))
1281 $buffer .= fgets($fsk, 1024);
1283 @fclose($fsk);
1286 // Use the result from ARIN if we don't get any result here
1287 $ipwhois = (empty($buffer)) ? $ipwhois : $buffer;
1290 $ipwhois = htmlspecialchars($ipwhois);
1292 // Magic URL ;)
1293 return trim(make_clickable($ipwhois, false, ''));
1297 * Data validation ... used primarily but not exclusively by ucp modules
1299 * "Master" function for validating a range of data types
1301 function validate_data($data, $val_ary)
1303 global $user;
1305 $error = array();
1307 foreach ($val_ary as $var => $val_seq)
1309 if (!is_array($val_seq[0]))
1311 $val_seq = array($val_seq);
1314 foreach ($val_seq as $validate)
1316 $function = array_shift($validate);
1317 array_unshift($validate, $data[$var]);
1319 if ($result = call_user_func_array('validate_' . $function, $validate))
1321 // Since errors are checked later for their language file existence, we need to make sure custom errors are not adjusted.
1322 $error[] = (empty($user->lang[$result . '_' . strtoupper($var)])) ? $result : $result . '_' . strtoupper($var);
1327 return $error;
1331 * Validate String
1333 * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1335 function validate_string($string, $optional = false, $min = 0, $max = 0)
1337 if (empty($string) && $optional)
1339 return false;
1342 if ($min && utf8_strlen(htmlspecialchars_decode($string)) < $min)
1344 return 'TOO_SHORT';
1346 else if ($max && utf8_strlen(htmlspecialchars_decode($string)) > $max)
1348 return 'TOO_LONG';
1351 return false;
1355 * Validate Number
1357 * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1359 function validate_num($num, $optional = false, $min = 0, $max = 1E99)
1361 if (empty($num) && $optional)
1363 return false;
1366 if ($num < $min)
1368 return 'TOO_SMALL';
1370 else if ($num > $max)
1372 return 'TOO_LARGE';
1375 return false;
1379 * Validate Date
1380 * @param String $string a date in the dd-mm-yyyy format
1381 * @return boolean
1383 function validate_date($date_string, $optional = false)
1385 $date = explode('-', $date_string);
1386 if ((empty($date) || sizeof($date) != 3) && $optional)
1388 return false;
1390 else if ($optional)
1392 for ($field = 0; $field <= 1; $field++)
1394 $date[$field] = (int) $date[$field];
1395 if (empty($date[$field]))
1397 $date[$field] = 1;
1400 $date[2] = (int) $date[2];
1401 // assume an arbitrary leap year
1402 if (empty($date[2]))
1404 $date[2] = 1980;
1408 if (sizeof($date) != 3 || !checkdate($date[1], $date[0], $date[2]))
1410 return 'INVALID';
1413 return false;
1418 * Validate Match
1420 * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1422 function validate_match($string, $optional = false, $match = '')
1424 if (empty($string) && $optional)
1426 return false;
1429 if (empty($match))
1431 return false;
1434 if (!preg_match($match, $string))
1436 return 'WRONG_DATA';
1439 return false;
1443 * Check to see if the username has been taken, or if it is disallowed.
1444 * Also checks if it includes the " character, which we don't allow in usernames.
1445 * Used for registering, changing names, and posting anonymously with a username
1447 * @param string $username The username to check
1448 * @param string $allowed_username An allowed username, default being $user->data['username']
1450 * @return mixed Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1452 function validate_username($username, $allowed_username = false)
1454 global $config, $db, $user, $cache;
1456 $clean_username = utf8_clean_string($username);
1457 $allowed_username = ($allowed_username === false) ? $user->data['username_clean'] : utf8_clean_string($allowed_username);
1459 if ($allowed_username == $clean_username)
1461 return false;
1464 // ... fast checks first.
1465 if (strpos($username, '&quot;') !== false || strpos($username, '"') !== false || empty($clean_username))
1467 return 'INVALID_CHARS';
1470 $mbstring = $pcre = false;
1472 // generic UTF-8 character types supported?
1473 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)
1475 $pcre = true;
1477 else if (function_exists('mb_ereg_match'))
1479 mb_regex_encoding('UTF-8');
1480 $mbstring = true;
1483 switch ($config['allow_name_chars'])
1485 case 'USERNAME_CHARS_ANY':
1486 $pcre = true;
1487 $regex = '.+';
1488 break;
1490 case 'USERNAME_ALPHA_ONLY':
1491 $pcre = true;
1492 $regex = '[A-Za-z0-9]+';
1493 break;
1495 case 'USERNAME_ALPHA_SPACERS':
1496 $pcre = true;
1497 $regex = '[A-Za-z0-9-[\]_+ ]+';
1498 break;
1500 case 'USERNAME_LETTER_NUM':
1501 if ($pcre)
1503 $regex = '[\p{Lu}\p{Ll}\p{N}]+';
1505 else if ($mbstring)
1507 $regex = '[[:upper:][:lower:][:digit:]]+';
1509 else
1511 $pcre = true;
1512 $regex = '[a-zA-Z0-9]+';
1514 break;
1516 case 'USERNAME_LETTER_NUM_SPACERS':
1517 if ($pcre)
1519 $regex = '[-\]_+ [\p{Lu}\p{Ll}\p{N}]+';
1521 else if ($mbstring)
1523 $regex = '[-\]_+ \[[:upper:][:lower:][:digit:]]+';
1525 else
1527 $pcre = true;
1528 $regex = '[-\]_+ [a-zA-Z0-9]+';
1530 break;
1532 case 'USERNAME_ASCII':
1533 default:
1534 $pcre = true;
1535 $regex = '[\x01-\x7F]+';
1536 break;
1539 if ($pcre)
1541 if (!preg_match('#^' . $regex . '$#u', $username))
1543 return 'INVALID_CHARS';
1546 else if ($mbstring)
1548 mb_ereg_search_init($username, '^' . $regex . '$');
1549 if (!mb_ereg_search())
1551 return 'INVALID_CHARS';
1555 $sql = 'SELECT username
1556 FROM ' . USERS_TABLE . "
1557 WHERE username_clean = '" . $db->sql_escape($clean_username) . "'";
1558 $result = $db->sql_query($sql);
1559 $row = $db->sql_fetchrow($result);
1560 $db->sql_freeresult($result);
1562 if ($row)
1564 return 'USERNAME_TAKEN';
1567 $sql = 'SELECT group_name
1568 FROM ' . GROUPS_TABLE . "
1569 WHERE LOWER(group_name) = '" . $db->sql_escape(utf8_strtolower($username)) . "'";
1570 $result = $db->sql_query($sql);
1571 $row = $db->sql_fetchrow($result);
1572 $db->sql_freeresult($result);
1574 if ($row)
1576 return 'USERNAME_TAKEN';
1579 $bad_usernames = $cache->obtain_disallowed_usernames();
1581 foreach ($bad_usernames as $bad_username)
1583 if (preg_match('#^' . $bad_username . '$#', $clean_username))
1585 return 'USERNAME_DISALLOWED';
1589 return false;
1593 * Check to see if the password meets the complexity settings
1595 * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1597 function validate_password($password)
1599 global $config, $db, $user;
1601 if (!$password)
1603 return false;
1606 $pcre = $mbstring = false;
1608 // generic UTF-8 character types supported?
1609 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)
1611 $upp = '\p{Lu}';
1612 $low = '\p{Ll}';
1613 $let = '\p{L}';
1614 $num = '\p{N}';
1615 $sym = '[^\p{Lu}\p{Ll}\p{N}]';
1616 $pcre = true;
1618 else if (function_exists('mb_ereg_match'))
1620 mb_regex_encoding('UTF-8');
1621 $upp = '[[:upper:]]';
1622 $low = '[[:lower:]]';
1623 $let = '[[:lower:][:upper:]]';
1624 $num = '[[:digit:]]';
1625 $sym = '[^[:upper:][:lower:][:digit:]]';
1626 $mbstring = true;
1628 else
1630 $upp = '[A-Z]';
1631 $low = '[a-z]';
1632 $let = '[a-zA-Z]';
1633 $num = '[0-9]';
1634 $sym = '[^A-Za-z0-9]';
1635 $pcre = true;
1638 $chars = array();
1640 switch ($config['pass_complex'])
1642 case 'PASS_TYPE_CASE':
1643 $chars[] = $low;
1644 $chars[] = $upp;
1645 break;
1647 case 'PASS_TYPE_ALPHA':
1648 $chars[] = $let;
1649 $chars[] = $num;
1650 break;
1652 case 'PASS_TYPE_SYMBOL':
1653 $chars[] = $low;
1654 $chars[] = $upp;
1655 $chars[] = $num;
1656 $chars[] = $sym;
1657 break;
1660 if ($pcre)
1662 foreach ($chars as $char)
1664 if (!preg_match('#' . $char . '#u', $password))
1666 return 'INVALID_CHARS';
1670 else if ($mbstring)
1672 foreach ($chars as $char)
1674 if (mb_ereg($char, $password) === false)
1676 return 'INVALID_CHARS';
1681 return false;
1685 * Check to see if email address is banned or already present in the DB
1687 * @param string $email The email to check
1688 * @param string $allowed_email An allowed email, default being $user->data['user_email']
1690 * @return mixed Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1692 function validate_email($email, $allowed_email = false)
1694 global $config, $db, $user;
1696 $email = strtolower($email);
1697 $allowed_email = ($allowed_email === false) ? strtolower($user->data['user_email']) : strtolower($allowed_email);
1699 if ($allowed_email == $email)
1701 return false;
1704 if (!preg_match('/^' . get_preg_expression('email') . '$/i', $email))
1706 return 'EMAIL_INVALID';
1709 // Check MX record.
1710 // The idea for this is from reading the UseBB blog/announcement. :)
1711 if ($config['email_check_mx'])
1713 list(, $domain) = explode('@', $email);
1715 if (phpbb_checkdnsrr($domain, 'A') === false && phpbb_checkdnsrr($domain, 'MX') === false)
1717 return 'DOMAIN_NO_MX_RECORD';
1721 if (($ban_reason = $user->check_ban(false, false, $email, true)) !== false)
1723 return ($ban_reason === true) ? 'EMAIL_BANNED' : $ban_reason;
1726 if (!$config['allow_emailreuse'])
1728 $sql = 'SELECT user_email_hash
1729 FROM ' . USERS_TABLE . "
1730 WHERE user_email_hash = " . $db->sql_escape(phpbb_email_hash($email));
1731 $result = $db->sql_query($sql);
1732 $row = $db->sql_fetchrow($result);
1733 $db->sql_freeresult($result);
1735 if ($row)
1737 return 'EMAIL_TAKEN';
1741 return false;
1745 * Validate jabber address
1746 * Taken from the jabber class within flyspray (see author notes)
1748 * @author flyspray.org
1750 function validate_jabber($jid)
1752 if (!$jid)
1754 return false;
1757 $seperator_pos = strpos($jid, '@');
1759 if ($seperator_pos === false)
1761 return 'WRONG_DATA';
1764 $username = substr($jid, 0, $seperator_pos);
1765 $realm = substr($jid, $seperator_pos + 1);
1767 if (strlen($username) == 0 || strlen($realm) < 3)
1769 return 'WRONG_DATA';
1772 $arr = explode('.', $realm);
1774 if (sizeof($arr) == 0)
1776 return 'WRONG_DATA';
1779 foreach ($arr as $part)
1781 if (substr($part, 0, 1) == '-' || substr($part, -1, 1) == '-')
1783 return 'WRONG_DATA';
1786 if (!preg_match("@^[a-zA-Z0-9-.]+$@", $part))
1788 return 'WRONG_DATA';
1792 $boundary = array(array(0, 127), array(192, 223), array(224, 239), array(240, 247), array(248, 251), array(252, 253));
1794 // Prohibited Characters RFC3454 + RFC3920
1795 $prohibited = array(
1796 // Table C.1.1
1797 array(0x0020, 0x0020), // SPACE
1798 // Table C.1.2
1799 array(0x00A0, 0x00A0), // NO-BREAK SPACE
1800 array(0x1680, 0x1680), // OGHAM SPACE MARK
1801 array(0x2000, 0x2001), // EN QUAD
1802 array(0x2001, 0x2001), // EM QUAD
1803 array(0x2002, 0x2002), // EN SPACE
1804 array(0x2003, 0x2003), // EM SPACE
1805 array(0x2004, 0x2004), // THREE-PER-EM SPACE
1806 array(0x2005, 0x2005), // FOUR-PER-EM SPACE
1807 array(0x2006, 0x2006), // SIX-PER-EM SPACE
1808 array(0x2007, 0x2007), // FIGURE SPACE
1809 array(0x2008, 0x2008), // PUNCTUATION SPACE
1810 array(0x2009, 0x2009), // THIN SPACE
1811 array(0x200A, 0x200A), // HAIR SPACE
1812 array(0x200B, 0x200B), // ZERO WIDTH SPACE
1813 array(0x202F, 0x202F), // NARROW NO-BREAK SPACE
1814 array(0x205F, 0x205F), // MEDIUM MATHEMATICAL SPACE
1815 array(0x3000, 0x3000), // IDEOGRAPHIC SPACE
1816 // Table C.2.1
1817 array(0x0000, 0x001F), // [CONTROL CHARACTERS]
1818 array(0x007F, 0x007F), // DELETE
1819 // Table C.2.2
1820 array(0x0080, 0x009F), // [CONTROL CHARACTERS]
1821 array(0x06DD, 0x06DD), // ARABIC END OF AYAH
1822 array(0x070F, 0x070F), // SYRIAC ABBREVIATION MARK
1823 array(0x180E, 0x180E), // MONGOLIAN VOWEL SEPARATOR
1824 array(0x200C, 0x200C), // ZERO WIDTH NON-JOINER
1825 array(0x200D, 0x200D), // ZERO WIDTH JOINER
1826 array(0x2028, 0x2028), // LINE SEPARATOR
1827 array(0x2029, 0x2029), // PARAGRAPH SEPARATOR
1828 array(0x2060, 0x2060), // WORD JOINER
1829 array(0x2061, 0x2061), // FUNCTION APPLICATION
1830 array(0x2062, 0x2062), // INVISIBLE TIMES
1831 array(0x2063, 0x2063), // INVISIBLE SEPARATOR
1832 array(0x206A, 0x206F), // [CONTROL CHARACTERS]
1833 array(0xFEFF, 0xFEFF), // ZERO WIDTH NO-BREAK SPACE
1834 array(0xFFF9, 0xFFFC), // [CONTROL CHARACTERS]
1835 array(0x1D173, 0x1D17A), // [MUSICAL CONTROL CHARACTERS]
1836 // Table C.3
1837 array(0xE000, 0xF8FF), // [PRIVATE USE, PLANE 0]
1838 array(0xF0000, 0xFFFFD), // [PRIVATE USE, PLANE 15]
1839 array(0x100000, 0x10FFFD), // [PRIVATE USE, PLANE 16]
1840 // Table C.4
1841 array(0xFDD0, 0xFDEF), // [NONCHARACTER CODE POINTS]
1842 array(0xFFFE, 0xFFFF), // [NONCHARACTER CODE POINTS]
1843 array(0x1FFFE, 0x1FFFF), // [NONCHARACTER CODE POINTS]
1844 array(0x2FFFE, 0x2FFFF), // [NONCHARACTER CODE POINTS]
1845 array(0x3FFFE, 0x3FFFF), // [NONCHARACTER CODE POINTS]
1846 array(0x4FFFE, 0x4FFFF), // [NONCHARACTER CODE POINTS]
1847 array(0x5FFFE, 0x5FFFF), // [NONCHARACTER CODE POINTS]
1848 array(0x6FFFE, 0x6FFFF), // [NONCHARACTER CODE POINTS]
1849 array(0x7FFFE, 0x7FFFF), // [NONCHARACTER CODE POINTS]
1850 array(0x8FFFE, 0x8FFFF), // [NONCHARACTER CODE POINTS]
1851 array(0x9FFFE, 0x9FFFF), // [NONCHARACTER CODE POINTS]
1852 array(0xAFFFE, 0xAFFFF), // [NONCHARACTER CODE POINTS]
1853 array(0xBFFFE, 0xBFFFF), // [NONCHARACTER CODE POINTS]
1854 array(0xCFFFE, 0xCFFFF), // [NONCHARACTER CODE POINTS]
1855 array(0xDFFFE, 0xDFFFF), // [NONCHARACTER CODE POINTS]
1856 array(0xEFFFE, 0xEFFFF), // [NONCHARACTER CODE POINTS]
1857 array(0xFFFFE, 0xFFFFF), // [NONCHARACTER CODE POINTS]
1858 array(0x10FFFE, 0x10FFFF), // [NONCHARACTER CODE POINTS]
1859 // Table C.5
1860 array(0xD800, 0xDFFF), // [SURROGATE CODES]
1861 // Table C.6
1862 array(0xFFF9, 0xFFF9), // INTERLINEAR ANNOTATION ANCHOR
1863 array(0xFFFA, 0xFFFA), // INTERLINEAR ANNOTATION SEPARATOR
1864 array(0xFFFB, 0xFFFB), // INTERLINEAR ANNOTATION TERMINATOR
1865 array(0xFFFC, 0xFFFC), // OBJECT REPLACEMENT CHARACTER
1866 array(0xFFFD, 0xFFFD), // REPLACEMENT CHARACTER
1867 // Table C.7
1868 array(0x2FF0, 0x2FFB), // [IDEOGRAPHIC DESCRIPTION CHARACTERS]
1869 // Table C.8
1870 array(0x0340, 0x0340), // COMBINING GRAVE TONE MARK
1871 array(0x0341, 0x0341), // COMBINING ACUTE TONE MARK
1872 array(0x200E, 0x200E), // LEFT-TO-RIGHT MARK
1873 array(0x200F, 0x200F), // RIGHT-TO-LEFT MARK
1874 array(0x202A, 0x202A), // LEFT-TO-RIGHT EMBEDDING
1875 array(0x202B, 0x202B), // RIGHT-TO-LEFT EMBEDDING
1876 array(0x202C, 0x202C), // POP DIRECTIONAL FORMATTING
1877 array(0x202D, 0x202D), // LEFT-TO-RIGHT OVERRIDE
1878 array(0x202E, 0x202E), // RIGHT-TO-LEFT OVERRIDE
1879 array(0x206A, 0x206A), // INHIBIT SYMMETRIC SWAPPING
1880 array(0x206B, 0x206B), // ACTIVATE SYMMETRIC SWAPPING
1881 array(0x206C, 0x206C), // INHIBIT ARABIC FORM SHAPING
1882 array(0x206D, 0x206D), // ACTIVATE ARABIC FORM SHAPING
1883 array(0x206E, 0x206E), // NATIONAL DIGIT SHAPES
1884 array(0x206F, 0x206F), // NOMINAL DIGIT SHAPES
1885 // Table C.9
1886 array(0xE0001, 0xE0001), // LANGUAGE TAG
1887 array(0xE0020, 0xE007F), // [TAGGING CHARACTERS]
1888 // RFC3920
1889 array(0x22, 0x22), // "
1890 array(0x26, 0x26), // &
1891 array(0x27, 0x27), // '
1892 array(0x2F, 0x2F), // /
1893 array(0x3A, 0x3A), // :
1894 array(0x3C, 0x3C), // <
1895 array(0x3E, 0x3E), // >
1896 array(0x40, 0x40) // @
1899 $pos = 0;
1900 $result = true;
1902 while ($pos < strlen($username))
1904 $len = $uni = 0;
1905 for ($i = 0; $i <= 5; $i++)
1907 if (ord($username[$pos]) >= $boundary[$i][0] && ord($username[$pos]) <= $boundary[$i][1])
1909 $len = $i + 1;
1910 $uni = (ord($username[$pos]) - $boundary[$i][0]) * pow(2, $i * 6);
1912 for ($k = 1; $k < $len; $k++)
1914 $uni += (ord($username[$pos + $k]) - 128) * pow(2, ($i - $k) * 6);
1917 break;
1921 if ($len == 0)
1923 return 'WRONG_DATA';
1926 foreach ($prohibited as $pval)
1928 if ($uni >= $pval[0] && $uni <= $pval[1])
1930 $result = false;
1931 break 2;
1935 $pos = $pos + $len;
1938 if (!$result)
1940 return 'WRONG_DATA';
1943 return false;
1947 * Remove avatar
1949 function avatar_delete($mode, $row, $clean_db = false)
1951 global $phpbb_root_path, $config, $db, $user;
1953 // Check if the users avatar is actually *not* a group avatar
1954 if ($mode == 'user')
1956 if (strpos($row['user_avatar'], 'g') === 0 || (((int)$row['user_avatar'] !== 0) && ((int)$row['user_avatar'] !== (int)$row['user_id'])))
1958 return false;
1962 if ($clean_db)
1964 avatar_remove_db($row[$mode . '_avatar']);
1966 $filename = get_avatar_filename($row[$mode . '_avatar']);
1967 if (file_exists($phpbb_root_path . $config['avatar_path'] . '/' . $filename))
1969 @unlink($phpbb_root_path . $config['avatar_path'] . '/' . $filename);
1970 return true;
1973 return false;
1977 * Remote avatar linkage
1979 function avatar_remote($data, &$error)
1981 global $config, $db, $user, $phpbb_root_path, $phpEx;
1983 if (!preg_match('#^(http|https|ftp)://#i', $data['remotelink']))
1985 $data['remotelink'] = 'http://' . $data['remotelink'];
1987 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']))
1989 $error[] = $user->lang['AVATAR_URL_INVALID'];
1990 return false;
1993 // Make sure getimagesize works...
1994 if (($image_data = @getimagesize($data['remotelink'])) === false && (empty($data['width']) || empty($data['height'])))
1996 $error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
1997 return false;
2000 if (!empty($image_data) && ($image_data[0] < 2 || $image_data[1] < 2))
2002 $error[] = $user->lang['AVATAR_NO_SIZE'];
2003 return false;
2006 $width = ($data['width'] && $data['height']) ? $data['width'] : $image_data[0];
2007 $height = ($data['width'] && $data['height']) ? $data['height'] : $image_data[1];
2009 if ($width < 2 || $height < 2)
2011 $error[] = $user->lang['AVATAR_NO_SIZE'];
2012 return false;
2015 // Check image type
2016 include_once($phpbb_root_path . 'includes/functions_upload.' . $phpEx);
2017 $types = fileupload::image_types();
2018 $extension = strtolower(filespec::get_extension($data['remotelink']));
2020 if (!empty($image_data) && (!isset($types[$image_data[2]]) || !in_array($extension, $types[$image_data[2]])))
2022 if (!isset($types[$image_data[2]]))
2024 $error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
2026 else
2028 $error[] = sprintf($user->lang['IMAGE_FILETYPE_MISMATCH'], $types[$image_data[2]][0], $extension);
2030 return false;
2033 if ($config['avatar_max_width'] || $config['avatar_max_height'])
2035 if ($width > $config['avatar_max_width'] || $height > $config['avatar_max_height'])
2037 $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);
2038 return false;
2042 if ($config['avatar_min_width'] || $config['avatar_min_height'])
2044 if ($width < $config['avatar_min_width'] || $height < $config['avatar_min_height'])
2046 $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);
2047 return false;
2051 return array(AVATAR_REMOTE, $data['remotelink'], $width, $height);
2055 * Avatar upload using the upload class
2057 function avatar_upload($data, &$error)
2059 global $phpbb_root_path, $config, $db, $user, $phpEx;
2061 // Init upload class
2062 include_once($phpbb_root_path . 'includes/functions_upload.' . $phpEx);
2063 $upload = new fileupload('AVATAR_', array('jpg', 'jpeg', 'gif', 'png'), $config['avatar_filesize'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], explode('|', $config['mime_triggers']));
2065 if (!empty($_FILES['uploadfile']['name']))
2067 $file = $upload->form_upload('uploadfile');
2069 else
2071 $file = $upload->remote_upload($data['uploadurl']);
2074 $prefix = $config['avatar_salt'] . '_';
2075 $file->clean_filename('avatar', $prefix, $data['user_id']);
2077 $destination = $config['avatar_path'];
2079 // Adjust destination path (no trailing slash)
2080 if (substr($destination, -1, 1) == '/' || substr($destination, -1, 1) == '\\')
2082 $destination = substr($destination, 0, -1);
2085 $destination = str_replace(array('../', '..\\', './', '.\\'), '', $destination);
2086 if ($destination && ($destination[0] == '/' || $destination[0] == "\\"))
2088 $destination = '';
2091 // Move file and overwrite any existing image
2092 $file->move_file($destination, true);
2094 if (sizeof($file->error))
2096 $file->remove();
2097 $error = array_merge($error, $file->error);
2100 return array(AVATAR_UPLOAD, $data['user_id'] . '_' . time() . '.' . $file->get('extension'), $file->get('width'), $file->get('height'));
2104 * Generates avatar filename from the database entry
2106 function get_avatar_filename($avatar_entry)
2108 global $config;
2111 if ($avatar_entry[0] === 'g')
2113 $avatar_group = true;
2114 $avatar_entry = substr($avatar_entry, 1);
2116 else
2118 $avatar_group = false;
2120 $ext = substr(strrchr($avatar_entry, '.'), 1);
2121 $avatar_entry = intval($avatar_entry);
2122 return $config['avatar_salt'] . '_' . (($avatar_group) ? 'g' : '') . $avatar_entry . '.' . $ext;
2126 * Avatar Gallery
2128 function avatar_gallery($category, $avatar_select, $items_per_column, $block_var = 'avatar_row')
2130 global $user, $cache, $template;
2131 global $config, $phpbb_root_path;
2133 $avatar_list = array();
2135 $path = $phpbb_root_path . $config['avatar_gallery_path'];
2137 if (!file_exists($path) || !is_dir($path))
2139 $avatar_list = array($user->lang['NO_AVATAR_CATEGORY'] => array());
2141 else
2143 // Collect images
2144 $dp = @opendir($path);
2146 if (!$dp)
2148 return array($user->lang['NO_AVATAR_CATEGORY'] => array());
2151 while (($file = readdir($dp)) !== false)
2153 if ($file[0] != '.' && preg_match('#^[^&"\'<>]+$#i', $file) && is_dir("$path/$file"))
2155 $avatar_row_count = $avatar_col_count = 0;
2157 if ($dp2 = @opendir("$path/$file"))
2159 while (($sub_file = readdir($dp2)) !== false)
2161 if (preg_match('#^[^&\'"<>]+\.(?:gif|png|jpe?g)$#i', $sub_file))
2163 $avatar_list[$file][$avatar_row_count][$avatar_col_count] = array(
2164 'file' => rawurlencode($file) . '/' . rawurlencode($sub_file),
2165 'filename' => rawurlencode($sub_file),
2166 'name' => ucfirst(str_replace('_', ' ', preg_replace('#^(.*)\..*$#', '\1', $sub_file))),
2168 $avatar_col_count++;
2169 if ($avatar_col_count == $items_per_column)
2171 $avatar_row_count++;
2172 $avatar_col_count = 0;
2176 closedir($dp2);
2180 closedir($dp);
2183 if (!sizeof($avatar_list))
2185 $avatar_list = array($user->lang['NO_AVATAR_CATEGORY'] => array());
2188 @ksort($avatar_list);
2190 $category = (!$category) ? key($avatar_list) : $category;
2191 $avatar_categories = array_keys($avatar_list);
2193 $s_category_options = '';
2194 foreach ($avatar_categories as $cat)
2196 $s_category_options .= '<option value="' . $cat . '"' . (($cat == $category) ? ' selected="selected"' : '') . '>' . $cat . '</option>';
2199 $template->assign_vars(array(
2200 'S_AVATARS_ENABLED' => true,
2201 'S_IN_AVATAR_GALLERY' => true,
2202 'S_CAT_OPTIONS' => $s_category_options)
2205 $avatar_list = (isset($avatar_list[$category])) ? $avatar_list[$category] : array();
2207 foreach ($avatar_list as $avatar_row_ary)
2209 $template->assign_block_vars($block_var, array());
2211 foreach ($avatar_row_ary as $avatar_col_ary)
2213 $template->assign_block_vars($block_var . '.avatar_column', array(
2214 'AVATAR_IMAGE' => $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar_col_ary['file'],
2215 'AVATAR_NAME' => $avatar_col_ary['name'],
2216 'AVATAR_FILE' => $avatar_col_ary['filename'])
2219 $template->assign_block_vars($block_var . '.avatar_option_column', array(
2220 'AVATAR_IMAGE' => $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar_col_ary['file'],
2221 'S_OPTIONS_AVATAR' => $avatar_col_ary['filename'])
2226 return $avatar_list;
2231 * Tries to (re-)establish avatar dimensions
2233 function avatar_get_dimensions($avatar, $avatar_type, &$error, $current_x = 0, $current_y = 0)
2235 global $config, $phpbb_root_path, $user;
2237 switch ($avatar_type)
2239 case AVATAR_REMOTE :
2240 break;
2242 case AVATAR_UPLOAD :
2243 $avatar = $phpbb_root_path . $config['avatar_path'] . '/' . get_avatar_filename($avatar);
2244 break;
2246 case AVATAR_GALLERY :
2247 $avatar = $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar ;
2248 break;
2251 // Make sure getimagesize works...
2252 if (($image_data = @getimagesize($avatar)) === false)
2254 $error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
2255 return false;
2258 if ($image_data[0] < 2 || $image_data[1] < 2)
2260 $error[] = $user->lang['AVATAR_NO_SIZE'];
2261 return false;
2264 // try to maintain ratio
2265 if (!(empty($current_x) && empty($current_y)))
2267 if ($current_x != 0)
2269 $image_data[1] = (int) floor(($current_x / $image_data[0]) * $image_data[1]);
2270 $image_data[1] = min($config['avatar_max_height'], $image_data[1]);
2271 $image_data[1] = max($config['avatar_min_height'], $image_data[1]);
2273 if ($current_y != 0)
2275 $image_data[0] = (int) floor(($current_y / $image_data[1]) * $image_data[0]);
2276 $image_data[0] = min($config['avatar_max_width'], $image_data[1]);
2277 $image_data[0] = max($config['avatar_min_width'], $image_data[1]);
2280 return array($image_data[0], $image_data[1]);
2284 * Uploading/Changing user avatar
2286 function avatar_process_user(&$error, $custom_userdata = false)
2288 global $config, $phpbb_root_path, $auth, $user, $db;
2290 $data = array(
2291 'uploadurl' => request_var('uploadurl', ''),
2292 'remotelink' => request_var('remotelink', ''),
2293 'width' => request_var('width', 0),
2294 'height' => request_var('height', 0),
2297 $error = validate_data($data, array(
2298 'uploadurl' => array('string', true, 5, 255),
2299 'remotelink' => array('string', true, 5, 255),
2300 'width' => array('string', true, 1, 3),
2301 'height' => array('string', true, 1, 3),
2304 if (sizeof($error))
2306 return false;
2309 $sql_ary = array();
2311 if ($custom_userdata === false)
2313 $userdata = &$user->data;
2315 else
2317 $userdata = &$custom_userdata;
2320 $data['user_id'] = $userdata['user_id'];
2321 $change_avatar = ($custom_userdata === false) ? $auth->acl_get('u_chgavatar') : true;
2322 $avatar_select = basename(request_var('avatar_select', ''));
2324 // Can we upload?
2325 $can_upload = ($config['allow_avatar_upload'] && file_exists($phpbb_root_path . $config['avatar_path']) && @is_writable($phpbb_root_path . $config['avatar_path']) && $change_avatar && (@ini_get('file_uploads') || strtolower(@ini_get('file_uploads')) == 'on')) ? true : false;
2327 if ((!empty($_FILES['uploadfile']['name']) || $data['uploadurl']) && $can_upload)
2329 list($sql_ary['user_avatar_type'], $sql_ary['user_avatar'], $sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = avatar_upload($data, $error);
2331 else if ($data['remotelink'] && $change_avatar && $config['allow_avatar_remote'])
2333 list($sql_ary['user_avatar_type'], $sql_ary['user_avatar'], $sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = avatar_remote($data, $error);
2335 else if ($avatar_select && $change_avatar && $config['allow_avatar_local'])
2337 $category = basename(request_var('category', ''));
2339 $sql_ary['user_avatar_type'] = AVATAR_GALLERY;
2340 $sql_ary['user_avatar'] = $avatar_select;
2342 // check avatar gallery
2343 if (!is_dir($phpbb_root_path . $config['avatar_gallery_path'] . '/' . $category))
2345 $sql_ary['user_avatar'] = '';
2346 $sql_ary['user_avatar_type'] = $sql_ary['user_avatar_width'] = $sql_ary['user_avatar_height'] = 0;
2348 else
2350 list($sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = getimagesize($phpbb_root_path . $config['avatar_gallery_path'] . '/' . $category . '/' . $sql_ary['user_avatar']);
2351 $sql_ary['user_avatar'] = $category . '/' . $sql_ary['user_avatar'];
2354 else if (isset($_POST['delete']) && $change_avatar)
2356 $sql_ary['user_avatar'] = '';
2357 $sql_ary['user_avatar_type'] = $sql_ary['user_avatar_width'] = $sql_ary['user_avatar_height'] = 0;
2359 else if (!empty($userdata['user_avatar']))
2361 // Only update the dimensions
2363 if (empty($data['width']) || empty($data['height']))
2365 if ($dims = avatar_get_dimensions($userdata['user_avatar'], $userdata['user_avatar_type'], $error, $data['width'], $data['height']))
2367 list($guessed_x, $guessed_y) = $dims;
2368 if (empty($data['width']))
2370 $data['width'] = $guessed_x;
2372 if (empty($data['height']))
2374 $data['height'] = $guessed_y;
2378 if (($config['avatar_max_width'] || $config['avatar_max_height']) &&
2379 (($data['width'] != $userdata['user_avatar_width']) || $data['height'] != $userdata['user_avatar_height']))
2381 if ($data['width'] > $config['avatar_max_width'] || $data['height'] > $config['avatar_max_height'])
2383 $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']);
2387 if (!sizeof($error))
2389 if ($config['avatar_min_width'] || $config['avatar_min_height'])
2391 if ($data['width'] < $config['avatar_min_width'] || $data['height'] < $config['avatar_min_height'])
2393 $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']);
2398 if (!sizeof($error))
2400 $sql_ary['user_avatar_width'] = $data['width'];
2401 $sql_ary['user_avatar_height'] = $data['height'];
2405 if (!sizeof($error))
2407 // Do we actually have any data to update?
2408 if (sizeof($sql_ary))
2410 $ext_new = $ext_old = '';
2411 if (isset($sql_ary['user_avatar']))
2413 $userdata = ($custom_userdata === false) ? $user->data : $custom_userdata;
2414 $ext_new = (empty($sql_ary['user_avatar'])) ? '' : substr(strrchr($sql_ary['user_avatar'], '.'), 1);
2415 $ext_old = (empty($userdata['user_avatar'])) ? '' : substr(strrchr($userdata['user_avatar'], '.'), 1);
2417 if ($userdata['user_avatar_type'] == AVATAR_UPLOAD)
2419 // Delete old avatar if present
2420 if ((!empty($userdata['user_avatar']) && empty($sql_ary['user_avatar']))
2421 || ( !empty($userdata['user_avatar']) && !empty($sql_ary['user_avatar']) && $ext_new !== $ext_old))
2423 avatar_delete('user', $userdata);
2428 $sql = 'UPDATE ' . USERS_TABLE . '
2429 SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
2430 WHERE user_id = ' . (($custom_userdata === false) ? $user->data['user_id'] : $custom_userdata['user_id']);
2431 $db->sql_query($sql);
2436 return (sizeof($error)) ? false : true;
2440 // Usergroup functions
2444 * Add or edit a group. If we're editing a group we only update user
2445 * parameters such as rank, etc. if they are changed
2447 function group_create(&$group_id, $type, $name, $desc, $group_attributes, $allow_desc_bbcode = false, $allow_desc_urls = false, $allow_desc_smilies = false)
2449 global $phpbb_root_path, $config, $db, $user, $file_upload;
2451 $error = array();
2453 // Attributes which also affect the users table
2454 $user_attribute_ary = array('group_colour', 'group_rank', 'group_avatar', 'group_avatar_type', 'group_avatar_width', 'group_avatar_height');
2456 // Check data. Limit group name length.
2457 if (!utf8_strlen($name) || utf8_strlen($name) > 60)
2459 $error[] = (!utf8_strlen($name)) ? $user->lang['GROUP_ERR_USERNAME'] : $user->lang['GROUP_ERR_USER_LONG'];
2462 $err = group_validate_groupname($group_id, $name);
2463 if (!empty($err))
2465 $error[] = $user->lang[$err];
2468 if (!in_array($type, array(GROUP_OPEN, GROUP_CLOSED, GROUP_HIDDEN, GROUP_SPECIAL, GROUP_FREE)))
2470 $error[] = $user->lang['GROUP_ERR_TYPE'];
2473 if (!sizeof($error))
2475 $user_ary = array();
2476 $sql_ary = array(
2477 'group_name' => (string) $name,
2478 'group_desc' => (string) $desc,
2479 'group_desc_uid' => '',
2480 'group_desc_bitfield' => '',
2481 'group_type' => (int) $type,
2484 // Parse description
2485 if ($desc)
2487 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);
2490 if (sizeof($group_attributes))
2492 // Merge them with $sql_ary to properly update the group
2493 $sql_ary = array_merge($sql_ary, $group_attributes);
2496 // Setting the log message before we set the group id (if group gets added)
2497 $log = ($group_id) ? 'LOG_GROUP_UPDATED' : 'LOG_GROUP_CREATED';
2499 $query = '';
2501 if ($group_id)
2503 $sql = 'SELECT user_id
2504 FROM ' . USERS_TABLE . '
2505 WHERE group_id = ' . $group_id;
2506 $result = $db->sql_query($sql);
2508 while ($row = $db->sql_fetchrow($result))
2510 $user_ary[] = $row['user_id'];
2512 $db->sql_freeresult($result);
2514 if (isset($sql_ary['group_avatar']) && !$sql_ary['group_avatar'])
2516 remove_default_avatar($group_id, $user_ary);
2519 if (isset($sql_ary['group_rank']) && !$sql_ary['group_rank'])
2521 remove_default_rank($group_id, $user_ary);
2524 $sql = 'UPDATE ' . GROUPS_TABLE . '
2525 SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
2526 WHERE group_id = $group_id";
2527 $db->sql_query($sql);
2529 // Since we may update the name too, we need to do this on other tables too...
2530 $sql = 'UPDATE ' . MODERATOR_CACHE_TABLE . "
2531 SET group_name = '" . $db->sql_escape($sql_ary['group_name']) . "'
2532 WHERE group_id = $group_id";
2533 $db->sql_query($sql);
2535 // One special case is the group skip auth setting. If this was changed we need to purge permissions for this group
2536 if (isset($group_attributes['group_skip_auth']))
2538 // Get users within this group...
2539 $sql = 'SELECT user_id
2540 FROM ' . USER_GROUP_TABLE . '
2541 WHERE group_id = ' . $group_id . '
2542 AND user_pending = 0';
2543 $result = $db->sql_query($sql);
2545 $user_id_ary = array();
2546 while ($row = $db->sql_fetchrow($result))
2548 $user_id_ary[] = $row['user_id'];
2550 $db->sql_freeresult($result);
2552 if (!empty($user_id_ary))
2554 global $auth;
2556 // Clear permissions cache of relevant users
2557 $auth->acl_clear_prefetch($user_id_ary);
2561 else
2563 $sql = 'INSERT INTO ' . GROUPS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
2564 $db->sql_query($sql);
2567 if (!$group_id)
2569 $group_id = $db->sql_nextid();
2571 if (isset($sql_ary['group_avatar_type']) && $sql_ary['group_avatar_type'] == AVATAR_UPLOAD)
2573 group_correct_avatar($group_id, $sql_ary['group_avatar']);
2577 // Set user attributes
2578 $sql_ary = array();
2579 if (sizeof($group_attributes))
2581 // Go through the user attributes array, check if a group attribute matches it and then set it. ;)
2582 foreach ($user_attribute_ary as $attribute)
2584 if (!isset($group_attributes[$attribute]))
2586 continue;
2589 // If we are about to set an avatar, we will not overwrite user avatars if no group avatar is set...
2590 if (strpos($attribute, 'group_avatar') === 0 && !$group_attributes[$attribute])
2592 continue;
2595 $sql_ary[$attribute] = $group_attributes[$attribute];
2599 if (sizeof($sql_ary) && sizeof($user_ary))
2601 group_set_user_default($group_id, $user_ary, $sql_ary);
2604 $name = ($type == GROUP_SPECIAL) ? $user->lang['G_' . $name] : $name;
2605 add_log('admin', $log, $name);
2607 group_update_listings($group_id);
2610 return (sizeof($error)) ? $error : false;
2615 * Changes a group avatar's filename to conform to the naming scheme
2617 function group_correct_avatar($group_id, $old_entry)
2619 global $config, $db, $phpbb_root_path;
2621 $group_id = (int)$group_id;
2622 $ext = substr(strrchr($old_entry, '.'), 1);
2623 $old_filename = get_avatar_filename($old_entry);
2624 $new_filename = $config['avatar_salt'] . "_g$group_id.$ext";
2625 $new_entry = 'g' . $group_id . '_' . substr(time(), -5) . ".$ext";
2627 $avatar_path = $phpbb_root_path . $config['avatar_path'];
2628 if (@rename($avatar_path . '/'. $old_filename, $avatar_path . '/' . $new_filename))
2630 $sql = 'UPDATE ' . GROUPS_TABLE . '
2631 SET group_avatar = \'' . $db->sql_escape($new_entry) . "'
2632 WHERE group_id = $group_id";
2633 $db->sql_query($sql);
2639 * Remove avatar also for users not having the group as default
2641 function avatar_remove_db($avatar_name)
2643 global $config, $db;
2645 $sql = 'UPDATE ' . USERS_TABLE . "
2646 SET user_avatar = '',
2647 user_avatar_type = 0
2648 WHERE user_avatar = '" . $db->sql_escape($avatar_name) . '\'';
2649 $db->sql_query($sql);
2654 * Group Delete
2656 function group_delete($group_id, $group_name = false)
2658 global $db, $phpbb_root_path, $phpEx;
2660 if (!$group_name)
2662 $group_name = get_group_name($group_id);
2665 $start = 0;
2669 $user_id_ary = $username_ary = array();
2671 // Batch query for group members, call group_user_del
2672 $sql = 'SELECT u.user_id, u.username
2673 FROM ' . USER_GROUP_TABLE . ' ug, ' . USERS_TABLE . " u
2674 WHERE ug.group_id = $group_id
2675 AND u.user_id = ug.user_id";
2676 $result = $db->sql_query_limit($sql, 200, $start);
2678 if ($row = $db->sql_fetchrow($result))
2682 $user_id_ary[] = $row['user_id'];
2683 $username_ary[] = $row['username'];
2685 $start++;
2687 while ($row = $db->sql_fetchrow($result));
2689 group_user_del($group_id, $user_id_ary, $username_ary, $group_name);
2691 else
2693 $start = 0;
2695 $db->sql_freeresult($result);
2697 while ($start);
2699 // Delete group
2700 $sql = 'DELETE FROM ' . GROUPS_TABLE . "
2701 WHERE group_id = $group_id";
2702 $db->sql_query($sql);
2704 // Delete auth entries from the groups table
2705 $sql = 'DELETE FROM ' . ACL_GROUPS_TABLE . "
2706 WHERE group_id = $group_id";
2707 $db->sql_query($sql);
2709 // Re-cache moderators
2710 if (!function_exists('cache_moderators'))
2712 include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
2715 cache_moderators();
2717 add_log('admin', 'LOG_GROUP_DELETE', $group_name);
2719 // Return false - no error
2720 return false;
2724 * Add user(s) to group
2726 * @return mixed false if no errors occurred, else the user lang string for the relevant error, for example 'NO_USER'
2728 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)
2730 global $db, $auth;
2732 // We need both username and user_id info
2733 $result = user_get_id_name($user_id_ary, $username_ary);
2735 if (!sizeof($user_id_ary) || $result !== false)
2737 return 'NO_USER';
2740 // Remove users who are already members of this group
2741 $sql = 'SELECT user_id, group_leader
2742 FROM ' . USER_GROUP_TABLE . '
2743 WHERE ' . $db->sql_in_set('user_id', $user_id_ary) . "
2744 AND group_id = $group_id";
2745 $result = $db->sql_query($sql);
2747 $add_id_ary = $update_id_ary = array();
2748 while ($row = $db->sql_fetchrow($result))
2750 $add_id_ary[] = (int) $row['user_id'];
2752 if ($leader && !$row['group_leader'])
2754 $update_id_ary[] = (int) $row['user_id'];
2757 $db->sql_freeresult($result);
2759 // Do all the users exist in this group?
2760 $add_id_ary = array_diff($user_id_ary, $add_id_ary);
2762 // If we have no users
2763 if (!sizeof($add_id_ary) && !sizeof($update_id_ary))
2765 return 'GROUP_USERS_EXIST';
2768 $db->sql_transaction('begin');
2770 // Insert the new users
2771 if (sizeof($add_id_ary))
2773 $sql_ary = array();
2775 foreach ($add_id_ary as $user_id)
2777 $sql_ary[] = array(
2778 'user_id' => (int) $user_id,
2779 'group_id' => (int) $group_id,
2780 'group_leader' => (int) $leader,
2781 'user_pending' => (int) $pending,
2785 $db->sql_multi_insert(USER_GROUP_TABLE, $sql_ary);
2788 if (sizeof($update_id_ary))
2790 $sql = 'UPDATE ' . USER_GROUP_TABLE . '
2791 SET group_leader = 1
2792 WHERE ' . $db->sql_in_set('user_id', $update_id_ary) . "
2793 AND group_id = $group_id";
2794 $db->sql_query($sql);
2797 if ($default)
2799 group_user_attributes('default', $group_id, $user_id_ary, false, $group_name, $group_attributes);
2802 $db->sql_transaction('commit');
2804 // Clear permissions cache of relevant users
2805 $auth->acl_clear_prefetch($user_id_ary);
2807 if (!$group_name)
2809 $group_name = get_group_name($group_id);
2812 $log = ($leader) ? 'LOG_MODS_ADDED' : (($pending) ? 'LOG_USERS_PENDING' : 'LOG_USERS_ADDED');
2814 add_log('admin', $log, $group_name, implode(', ', $username_ary));
2816 group_update_listings($group_id);
2818 // Return false - no error
2819 return false;
2823 * Remove a user/s from a given group. When we remove users we update their
2824 * default group_id. We do this by examining which "special" groups they belong
2825 * to. The selection is made based on a reasonable priority system
2827 * @return false if no errors occurred, else the user lang string for the relevant error, for example 'NO_USER'
2829 function group_user_del($group_id, $user_id_ary = false, $username_ary = false, $group_name = false)
2831 global $db, $auth, $config;
2833 if ($config['coppa_enable'])
2835 $group_order = array('ADMINISTRATORS', 'GLOBAL_MODERATORS', 'NEWLY_REGISTERED', 'REGISTERED_COPPA', 'REGISTERED', 'BOTS', 'GUESTS');
2837 else
2839 $group_order = array('ADMINISTRATORS', 'GLOBAL_MODERATORS', 'NEWLY_REGISTERED', 'REGISTERED', 'BOTS', 'GUESTS');
2842 // We need both username and user_id info
2843 $result = user_get_id_name($user_id_ary, $username_ary);
2845 if (!sizeof($user_id_ary) || $result !== false)
2847 return 'NO_USER';
2850 $sql = 'SELECT *
2851 FROM ' . GROUPS_TABLE . '
2852 WHERE ' . $db->sql_in_set('group_name', $group_order);
2853 $result = $db->sql_query($sql);
2855 $group_order_id = $special_group_data = array();
2856 while ($row = $db->sql_fetchrow($result))
2858 $group_order_id[$row['group_name']] = $row['group_id'];
2860 $special_group_data[$row['group_id']] = array(
2861 'group_colour' => $row['group_colour'],
2862 'group_rank' => $row['group_rank'],
2865 // Only set the group avatar if one is defined...
2866 if ($row['group_avatar'])
2868 $special_group_data[$row['group_id']] = array_merge($special_group_data[$row['group_id']], array(
2869 'group_avatar' => $row['group_avatar'],
2870 'group_avatar_type' => $row['group_avatar_type'],
2871 'group_avatar_width' => $row['group_avatar_width'],
2872 'group_avatar_height' => $row['group_avatar_height'])
2876 $db->sql_freeresult($result);
2878 // 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
2879 $sql = 'SELECT user_id, group_id
2880 FROM ' . USERS_TABLE . '
2881 WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
2882 $result = $db->sql_query($sql);
2884 $default_groups = array();
2885 while ($row = $db->sql_fetchrow($result))
2887 $default_groups[$row['user_id']] = $row['group_id'];
2889 $db->sql_freeresult($result);
2891 // What special group memberships exist for these users?
2892 $sql = 'SELECT g.group_id, g.group_name, ug.user_id
2893 FROM ' . USER_GROUP_TABLE . ' ug, ' . GROUPS_TABLE . ' g
2894 WHERE ' . $db->sql_in_set('ug.user_id', $user_id_ary) . "
2895 AND g.group_id = ug.group_id
2896 AND g.group_id <> $group_id
2897 AND g.group_type = " . GROUP_SPECIAL . '
2898 ORDER BY ug.user_id, g.group_id';
2899 $result = $db->sql_query($sql);
2901 $temp_ary = array();
2902 while ($row = $db->sql_fetchrow($result))
2904 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']]))
2906 $temp_ary[$row['user_id']] = $row['group_id'];
2909 $db->sql_freeresult($result);
2911 // sql_where_ary holds the new default groups and their users
2912 $sql_where_ary = array();
2913 foreach ($temp_ary as $uid => $gid)
2915 $sql_where_ary[$gid][] = $uid;
2917 unset($temp_ary);
2919 foreach ($special_group_data as $gid => $default_data_ary)
2921 if (isset($sql_where_ary[$gid]) && sizeof($sql_where_ary[$gid]))
2923 remove_default_rank($group_id, $sql_where_ary[$gid]);
2924 remove_default_avatar($group_id, $sql_where_ary[$gid]);
2925 group_set_user_default($gid, $sql_where_ary[$gid], $default_data_ary);
2928 unset($special_group_data);
2930 $sql = 'DELETE FROM ' . USER_GROUP_TABLE . "
2931 WHERE group_id = $group_id
2932 AND " . $db->sql_in_set('user_id', $user_id_ary);
2933 $db->sql_query($sql);
2935 // Clear permissions cache of relevant users
2936 $auth->acl_clear_prefetch($user_id_ary);
2938 if (!$group_name)
2940 $group_name = get_group_name($group_id);
2943 $log = 'LOG_GROUP_REMOVE';
2945 if ($group_name)
2947 add_log('admin', $log, $group_name, implode(', ', $username_ary));
2950 group_update_listings($group_id);
2952 // Return false - no error
2953 return false;
2958 * Removes the group avatar of the default group from the users in user_ids who have that group as default.
2960 function remove_default_avatar($group_id, $user_ids)
2962 global $db;
2964 if (!is_array($user_ids))
2966 $user_ids = array($user_ids);
2968 if (empty($user_ids))
2970 return false;
2973 $user_ids = array_map('intval', $user_ids);
2975 $sql = 'SELECT *
2976 FROM ' . GROUPS_TABLE . '
2977 WHERE group_id = ' . (int)$group_id;
2978 $result = $db->sql_query($sql);
2979 if (!$row = $db->sql_fetchrow($result))
2981 $db->sql_freeresult($result);
2982 return false;
2984 $db->sql_freeresult($result);
2986 $sql = 'UPDATE ' . USERS_TABLE . "
2987 SET user_avatar = '',
2988 user_avatar_type = 0,
2989 user_avatar_width = 0,
2990 user_avatar_height = 0
2991 WHERE group_id = " . (int) $group_id . "
2992 AND user_avatar = '" . $db->sql_escape($row['group_avatar']) . "'
2993 AND " . $db->sql_in_set('user_id', $user_ids);
2995 $db->sql_query($sql);
2999 * Removes the group rank of the default group from the users in user_ids who have that group as default.
3001 function remove_default_rank($group_id, $user_ids)
3003 global $db;
3005 if (!is_array($user_ids))
3007 $user_ids = array($user_ids);
3009 if (empty($user_ids))
3011 return false;
3014 $user_ids = array_map('intval', $user_ids);
3016 $sql = 'SELECT *
3017 FROM ' . GROUPS_TABLE . '
3018 WHERE group_id = ' . (int)$group_id;
3019 $result = $db->sql_query($sql);
3020 if (!$row = $db->sql_fetchrow($result))
3022 $db->sql_freeresult($result);
3023 return false;
3025 $db->sql_freeresult($result);
3027 $sql = 'UPDATE ' . USERS_TABLE . '
3028 SET user_rank = 0
3029 WHERE group_id = ' . (int)$group_id . '
3030 AND user_rank <> 0
3031 AND user_rank = ' . (int)$row['group_rank'] . '
3032 AND ' . $db->sql_in_set('user_id', $user_ids);
3033 $db->sql_query($sql);
3037 * This is used to promote (to leader), demote or set as default a member/s
3039 function group_user_attributes($action, $group_id, $user_id_ary = false, $username_ary = false, $group_name = false, $group_attributes = false)
3041 global $db, $auth, $phpbb_root_path, $phpEx, $config;
3043 // We need both username and user_id info
3044 $result = user_get_id_name($user_id_ary, $username_ary);
3046 if (!sizeof($user_id_ary) || $result !== false)
3048 return 'NO_USERS';
3051 if (!$group_name)
3053 $group_name = get_group_name($group_id);
3056 switch ($action)
3058 case 'demote':
3059 case 'promote':
3061 $sql = 'SELECT user_id FROM ' . USER_GROUP_TABLE . "
3062 WHERE group_id = $group_id
3063 AND user_pending = 1
3064 AND " . $db->sql_in_set('user_id', $user_id_ary);
3065 $result = $db->sql_query_limit($sql, 1);
3066 $not_empty = ($db->sql_fetchrow($result));
3067 $db->sql_freeresult($result);
3068 if ($not_empty)
3070 return 'NO_VALID_USERS';
3073 $sql = 'UPDATE ' . USER_GROUP_TABLE . '
3074 SET group_leader = ' . (($action == 'promote') ? 1 : 0) . "
3075 WHERE group_id = $group_id
3076 AND user_pending = 0
3077 AND " . $db->sql_in_set('user_id', $user_id_ary);
3078 $db->sql_query($sql);
3080 $log = ($action == 'promote') ? 'LOG_GROUP_PROMOTED' : 'LOG_GROUP_DEMOTED';
3081 break;
3083 case 'approve':
3084 // Make sure we only approve those which are pending ;)
3085 $sql = 'SELECT u.user_id, u.user_email, u.username, u.username_clean, u.user_notify_type, u.user_jabber, u.user_lang
3086 FROM ' . USERS_TABLE . ' u, ' . USER_GROUP_TABLE . ' ug
3087 WHERE ug.group_id = ' . $group_id . '
3088 AND ug.user_pending = 1
3089 AND ug.user_id = u.user_id
3090 AND ' . $db->sql_in_set('ug.user_id', $user_id_ary);
3091 $result = $db->sql_query($sql);
3093 $user_id_ary = $email_users = array();
3094 while ($row = $db->sql_fetchrow($result))
3096 $user_id_ary[] = $row['user_id'];
3097 $email_users[] = $row;
3099 $db->sql_freeresult($result);
3101 if (!sizeof($user_id_ary))
3103 return false;
3106 $sql = 'UPDATE ' . USER_GROUP_TABLE . "
3107 SET user_pending = 0
3108 WHERE group_id = $group_id
3109 AND " . $db->sql_in_set('user_id', $user_id_ary);
3110 $db->sql_query($sql);
3112 // Send approved email to users...
3113 include_once($phpbb_root_path . 'includes/functions_messenger.' . $phpEx);
3114 $messenger = new messenger();
3116 foreach ($email_users as $row)
3118 $messenger->template('group_approved', $row['user_lang']);
3120 $messenger->to($row['user_email'], $row['username']);
3121 $messenger->im($row['user_jabber'], $row['username']);
3123 $messenger->assign_vars(array(
3124 'USERNAME' => htmlspecialchars_decode($row['username']),
3125 'GROUP_NAME' => htmlspecialchars_decode($group_name),
3126 'U_GROUP' => generate_board_url() . "/ucp.$phpEx?i=groups&mode=membership")
3129 $messenger->send($row['user_notify_type']);
3132 $messenger->save_queue();
3134 $log = 'LOG_USERS_APPROVED';
3135 break;
3137 case 'default':
3138 // We only set default group for approved members of the group
3139 $sql = 'SELECT user_id
3140 FROM ' . USER_GROUP_TABLE . "
3141 WHERE group_id = $group_id
3142 AND user_pending = 0
3143 AND " . $db->sql_in_set('user_id', $user_id_ary);
3144 $result = $db->sql_query($sql);
3146 $user_id_ary = $username_ary = array();
3147 while ($row = $db->sql_fetchrow($result))
3149 $user_id_ary[] = $row['user_id'];
3151 $db->sql_freeresult($result);
3153 $result = user_get_id_name($user_id_ary, $username_ary);
3154 if (!sizeof($user_id_ary) || $result !== false)
3156 return 'NO_USERS';
3159 $sql = 'SELECT user_id, group_id FROM ' . USERS_TABLE . '
3160 WHERE ' . $db->sql_in_set('user_id', $user_id_ary, false, true);
3161 $result = $db->sql_query($sql);
3163 $groups = array();
3164 while ($row = $db->sql_fetchrow($result))
3166 if (!isset($groups[$row['group_id']]))
3168 $groups[$row['group_id']] = array();
3170 $groups[$row['group_id']][] = $row['user_id'];
3172 $db->sql_freeresult($result);
3174 foreach ($groups as $gid => $uids)
3176 remove_default_rank($gid, $uids);
3177 remove_default_avatar($gid, $uids);
3179 group_set_user_default($group_id, $user_id_ary, $group_attributes);
3180 $log = 'LOG_GROUP_DEFAULTS';
3181 break;
3184 // Clear permissions cache of relevant users
3185 $auth->acl_clear_prefetch($user_id_ary);
3187 add_log('admin', $log, $group_name, implode(', ', $username_ary));
3189 group_update_listings($group_id);
3191 return false;
3195 * A small version of validate_username to check for a group name's existence. To be called directly.
3197 function group_validate_groupname($group_id, $group_name)
3199 global $config, $db;
3201 $group_name = utf8_clean_string($group_name);
3203 if (!empty($group_id))
3205 $sql = 'SELECT group_name
3206 FROM ' . GROUPS_TABLE . '
3207 WHERE group_id = ' . (int) $group_id;
3208 $result = $db->sql_query($sql);
3209 $row = $db->sql_fetchrow($result);
3210 $db->sql_freeresult($result);
3212 if (!$row)
3214 return false;
3217 $allowed_groupname = utf8_clean_string($row['group_name']);
3219 if ($allowed_groupname == $group_name)
3221 return false;
3225 $sql = 'SELECT group_name
3226 FROM ' . GROUPS_TABLE . "
3227 WHERE LOWER(group_name) = '" . $db->sql_escape(utf8_strtolower($group_name)) . "'";
3228 $result = $db->sql_query($sql);
3229 $row = $db->sql_fetchrow($result);
3230 $db->sql_freeresult($result);
3232 if ($row)
3234 return 'GROUP_NAME_TAKEN';
3237 return false;
3241 * Set users default group
3243 * @access private
3245 function group_set_user_default($group_id, $user_id_ary, $group_attributes = false, $update_listing = false)
3247 global $cache, $db;
3249 if (empty($user_id_ary))
3251 return;
3254 $attribute_ary = array(
3255 'group_colour' => 'string',
3256 'group_rank' => 'int',
3257 'group_avatar' => 'string',
3258 'group_avatar_type' => 'int',
3259 'group_avatar_width' => 'int',
3260 'group_avatar_height' => 'int',
3263 $sql_ary = array(
3264 'group_id' => $group_id
3267 // Were group attributes passed to the function? If not we need to obtain them
3268 if ($group_attributes === false)
3270 $sql = 'SELECT ' . implode(', ', array_keys($attribute_ary)) . '
3271 FROM ' . GROUPS_TABLE . "
3272 WHERE group_id = $group_id";
3273 $result = $db->sql_query($sql);
3274 $group_attributes = $db->sql_fetchrow($result);
3275 $db->sql_freeresult($result);
3278 foreach ($attribute_ary as $attribute => $type)
3280 if (isset($group_attributes[$attribute]))
3282 // 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
3283 if ((strpos($attribute, 'group_avatar') === 0 || strpos($attribute, 'group_rank') === 0) && !$group_attributes[$attribute])
3285 continue;
3288 settype($group_attributes[$attribute], $type);
3289 $sql_ary[str_replace('group_', 'user_', $attribute)] = $group_attributes[$attribute];
3293 // Before we update the user attributes, we will make a list of those having now the group avatar assigned
3294 if (isset($sql_ary['user_avatar']))
3296 // Ok, get the original avatar data from users having an uploaded one (we need to remove these from the filesystem)
3297 $sql = 'SELECT user_id, group_id, user_avatar
3298 FROM ' . USERS_TABLE . '
3299 WHERE ' . $db->sql_in_set('user_id', $user_id_ary) . '
3300 AND user_avatar_type = ' . AVATAR_UPLOAD;
3301 $result = $db->sql_query($sql);
3303 while ($row = $db->sql_fetchrow($result))
3305 avatar_delete('user', $row);
3307 $db->sql_freeresult($result);
3309 else
3311 unset($sql_ary['user_avatar_type']);
3312 unset($sql_ary['user_avatar_height']);
3313 unset($sql_ary['user_avatar_width']);
3316 $sql = 'UPDATE ' . USERS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
3317 WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
3318 $db->sql_query($sql);
3320 if (isset($sql_ary['user_colour']))
3322 // Update any cached colour information for these users
3323 $sql = 'UPDATE ' . FORUMS_TABLE . " SET forum_last_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
3324 WHERE " . $db->sql_in_set('forum_last_poster_id', $user_id_ary);
3325 $db->sql_query($sql);
3327 $sql = 'UPDATE ' . TOPICS_TABLE . " SET topic_first_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
3328 WHERE " . $db->sql_in_set('topic_poster', $user_id_ary);
3329 $db->sql_query($sql);
3331 $sql = 'UPDATE ' . TOPICS_TABLE . " SET topic_last_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
3332 WHERE " . $db->sql_in_set('topic_last_poster_id', $user_id_ary);
3333 $db->sql_query($sql);
3335 global $config;
3337 if (in_array($config['newest_user_id'], $user_id_ary))
3339 set_config('newest_user_colour', $sql_ary['user_colour'], true);
3343 if ($update_listing)
3345 group_update_listings($group_id);
3348 // Because some tables/caches use usercolour-specific data we need to purge this here.
3349 $cache->destroy('sql', MODERATOR_CACHE_TABLE);
3353 * Get group name
3355 function get_group_name($group_id)
3357 global $db, $user;
3359 $sql = 'SELECT group_name, group_type
3360 FROM ' . GROUPS_TABLE . '
3361 WHERE group_id = ' . (int) $group_id;
3362 $result = $db->sql_query($sql);
3363 $row = $db->sql_fetchrow($result);
3364 $db->sql_freeresult($result);
3366 if (!$row || ($row['group_type'] == GROUP_SPECIAL && empty($user->lang)))
3368 return '';
3371 return ($row['group_type'] == GROUP_SPECIAL) ? $user->lang['G_' . $row['group_name']] : $row['group_name'];
3375 * Obtain either the members of a specified group, the groups the specified user is subscribed to
3376 * or checking if a specified user is in a specified group. This function does not return pending memberships.
3378 * Note: Never use this more than once... first group your users/groups
3380 function group_memberships($group_id_ary = false, $user_id_ary = false, $return_bool = false)
3382 global $db;
3384 if (!$group_id_ary && !$user_id_ary)
3386 return true;
3389 if ($user_id_ary)
3391 $user_id_ary = (!is_array($user_id_ary)) ? array($user_id_ary) : $user_id_ary;
3394 if ($group_id_ary)
3396 $group_id_ary = (!is_array($group_id_ary)) ? array($group_id_ary) : $group_id_ary;
3399 $sql = 'SELECT ug.*, u.username, u.username_clean, u.user_email
3400 FROM ' . USER_GROUP_TABLE . ' ug, ' . USERS_TABLE . ' u
3401 WHERE ug.user_id = u.user_id
3402 AND ug.user_pending = 0 AND ';
3404 if ($group_id_ary)
3406 $sql .= ' ' . $db->sql_in_set('ug.group_id', $group_id_ary);
3409 if ($user_id_ary)
3411 $sql .= ($group_id_ary) ? ' AND ' : ' ';
3412 $sql .= $db->sql_in_set('ug.user_id', $user_id_ary);
3415 $result = ($return_bool) ? $db->sql_query_limit($sql, 1) : $db->sql_query($sql);
3417 $row = $db->sql_fetchrow($result);
3419 if ($return_bool)
3421 $db->sql_freeresult($result);
3422 return ($row) ? true : false;
3425 if (!$row)
3427 return false;
3430 $return = array();
3434 $return[] = $row;
3436 while ($row = $db->sql_fetchrow($result));
3438 $db->sql_freeresult($result);
3440 return $return;
3444 * Re-cache moderators and foes if group has a_ or m_ permissions
3446 function group_update_listings($group_id)
3448 global $auth;
3450 $hold_ary = $auth->acl_group_raw_data($group_id, array('a_', 'm_'));
3452 if (!sizeof($hold_ary))
3454 return;
3457 $mod_permissions = $admin_permissions = false;
3459 foreach ($hold_ary as $g_id => $forum_ary)
3461 foreach ($forum_ary as $forum_id => $auth_ary)
3463 foreach ($auth_ary as $auth_option => $setting)
3465 if ($mod_permissions && $admin_permissions)
3467 break 3;
3470 if ($setting != ACL_YES)
3472 continue;
3475 if ($auth_option == 'm_')
3477 $mod_permissions = true;
3480 if ($auth_option == 'a_')
3482 $admin_permissions = true;
3488 if ($mod_permissions)
3490 if (!function_exists('cache_moderators'))
3492 global $phpbb_root_path, $phpEx;
3493 include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
3495 cache_moderators();
3498 if ($mod_permissions || $admin_permissions)
3500 if (!function_exists('update_foes'))
3502 global $phpbb_root_path, $phpEx;
3503 include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
3505 update_foes(array($group_id));
3512 * Funtion to make a user leave the NEWLY_REGISTERED system group.
3513 * @access public
3514 * @param $user_id The id of the user to remove from the group
3516 function remove_newly_registered($user_id, $user_data = false)
3518 global $db;
3520 if ($user_data === false)
3522 $sql = 'SELECT *
3523 FROM ' . USERS_TABLE . '
3524 WHERE user_id = ' . $user_id;
3525 $result = $db->sql_query($sql);
3526 $user_row = $db->sql_fetchrow($result);
3527 $db->sql_freeresult($result);
3529 if (!$user_row)
3531 return false;
3533 else
3535 $user_data = $user_row;
3539 if (empty($user_data['user_new']))
3541 return false;
3544 $sql = 'SELECT group_id
3545 FROM ' . GROUPS_TABLE . "
3546 WHERE group_name = 'NEWLY_REGISTERED'
3547 AND group_type = " . GROUP_SPECIAL;
3548 $result = $db->sql_query($sql);
3549 $group_id = (int) $db->sql_fetchfield('group_id');
3550 $db->sql_freeresult($result);
3552 if (!$group_id)
3554 return false;
3557 // We need to call group_user_del here, because this function makes sure everything is correctly changed.
3558 // A downside for a call within the session handler is that the language is not set up yet - so no log entry
3559 group_user_del($group_id, $user_id);
3561 // Set user_new to 0 to let this not be triggered again
3562 $sql = 'UPDATE ' . USERS_TABLE . '
3563 SET user_new = 0
3564 WHERE user_id = ' . $user_id;
3565 $db->sql_query($sql);
3567 // The new users group was the users default group?
3568 if ($user_data['group_id'] == $group_id)
3570 // Which group is now the users default one?
3571 $sql = 'SELECT group_id
3572 FROM ' . USERS_TABLE . '
3573 WHERE user_id = ' . $user_id;
3574 $result = $db->sql_query($sql);
3575 $user_data['group_id'] = $db->sql_fetchfield('group_id');
3576 $db->sql_freeresult($result);
3579 return $user_data['group_id'];