Merge changes made in revisions #r9405 to #r9467
[phpbb.git] / phpBB / includes / functions_user.php
blob5c22cfb4ef86f1576e511cec6b17b89a32c2dedb
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 // Are both arrays already filled? Yep, return else
30 // are neither array filled?
31 if ($user_id_ary && $username_ary)
33 return false;
35 else if (!$user_id_ary && !$username_ary)
37 return 'NO_USERS';
40 $which_ary = ($user_id_ary) ? 'user_id_ary' : 'username_ary';
42 if ($$which_ary && !is_array($$which_ary))
44 $$which_ary = array($$which_ary);
47 $sql_in = ($which_ary == 'user_id_ary') ? array_map('intval', $$which_ary) : array_map('utf8_clean_string', $$which_ary);
48 unset($$which_ary);
50 $user_id_ary = $username_ary = array();
52 // Grab the user id/username records
53 $sql_where = ($which_ary == 'user_id_ary') ? 'user_id' : 'username_clean';
54 $sql = 'SELECT user_id, username
55 FROM ' . USERS_TABLE . '
56 WHERE ' . phpbb::$db->sql_in_set($sql_where, $sql_in);
58 if ($user_type !== false && !empty($user_type))
60 $sql .= ' AND ' . phpbb::$db->sql_in_set('user_type', $user_type);
63 $result = phpbb::$db->sql_query($sql);
65 if (!($row = phpbb::$db->sql_fetchrow($result)))
67 phpbb::$db->sql_freeresult($result);
68 return 'NO_USERS';
73 $username_ary[$row['user_id']] = $row['username'];
74 $user_id_ary[] = $row['user_id'];
76 while ($row = phpbb::$db->sql_fetchrow($result));
77 phpbb::$db->sql_freeresult($result);
79 return false;
82 /**
83 * Get latest registered username and update database to reflect it
85 function update_last_username()
87 // Get latest username
88 $sql = 'SELECT user_id, username, user_colour
89 FROM ' . USERS_TABLE . '
90 WHERE user_type IN (' . phpbb::USER_NORMAL . ', ' . phpbb::USER_FOUNDER . ')
91 ORDER BY user_id DESC';
92 $result = phpbb::$db->sql_query_limit($sql, 1);
93 $row = phpbb::$db->sql_fetchrow($result);
94 phpbb::$db->sql_freeresult($result);
96 if ($row)
98 set_config('newest_user_id', $row['user_id'], true);
99 set_config('newest_username', $row['username'], true);
100 set_config('newest_user_colour', $row['user_colour'], true);
105 * Updates a username across all relevant tables/fields
107 * @param string $old_name the old/current username
108 * @param string $new_name the new username
110 function user_update_name($old_name, $new_name)
112 $update_ary = array(
113 FORUMS_TABLE => array('forum_last_poster_name'),
114 MODERATOR_CACHE_TABLE => array('username'),
115 POSTS_TABLE => array('post_username'),
116 TOPICS_TABLE => array('topic_first_poster_name', 'topic_last_poster_name'),
119 foreach ($update_ary as $table => $field_ary)
121 foreach ($field_ary as $field)
123 $sql = "UPDATE $table
124 SET $field = '" . phpbb::$db->sql_escape($new_name) . "'
125 WHERE $field = '" . phpbb::$db->sql_escape($old_name) . "'";
126 phpbb::$db->sql_query($sql);
130 if (phpbb::$config['newest_username'] == $old_name)
132 set_config('newest_username', $new_name, true);
135 // Because some tables/caches use username-specific data we need to purge this here.
136 phpbb::$acm->destroy_sql(MODERATOR_CACHE_TABLE);
140 * Adds a user
142 * @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.
143 * @param string $cp_data custom profile fields, see custom_profile::build_insert_sql_array
144 * @return the new user's ID.
146 function user_add($user_row, $cp_data = false)
148 if (empty($user_row['username']) || !isset($user_row['group_id']) || !isset($user_row['user_email']) || !isset($user_row['user_type']))
150 return false;
153 $username_clean = utf8_clean_string($user_row['username']);
155 if (empty($username_clean))
157 return false;
160 $sql_ary = array(
161 'username' => $user_row['username'],
162 'username_clean' => $username_clean,
163 'user_password' => (isset($user_row['user_password'])) ? $user_row['user_password'] : '',
164 'user_pass_convert' => 0,
165 'user_email' => strtolower($user_row['user_email']),
166 'user_email_hash' => hexdec(crc32(strtolower($user_row['user_email'])) . strlen($user_row['user_email'])),
167 'group_id' => $user_row['group_id'],
168 'user_type' => $user_row['user_type'],
171 // These are the additional vars able to be specified
172 $additional_vars = array(
173 'user_permissions' => '',
174 'user_timezone' => phpbb::$config['board_timezone'],
175 'user_dateformat' => phpbb::$config['default_dateformat'],
176 'user_lang' => phpbb::$config['default_lang'],
177 'user_style' => phpbb::$config['default_style'],
178 'user_actkey' => '',
179 'user_ip' => '',
180 'user_regdate' => time(),
181 'user_passchg' => time(),
182 'user_options' => 895,
184 'user_inactive_reason' => 0,
185 'user_inactive_time' => 0,
186 'user_lastmark' => time(),
187 'user_lastvisit' => 0,
188 'user_lastpost_time' => 0,
189 'user_lastpage' => '',
190 'user_posts' => 0,
191 'user_dst' => (int) phpbb::$config['board_dst'],
192 'user_colour' => '',
193 'user_occ' => '',
194 'user_interests' => '',
195 'user_avatar' => '',
196 'user_avatar_type' => 0,
197 'user_avatar_width' => 0,
198 'user_avatar_height' => 0,
199 'user_new_privmsg' => 0,
200 'user_unread_privmsg' => 0,
201 'user_last_privmsg' => 0,
202 'user_message_rules' => 0,
203 'user_full_folder' => PRIVMSGS_NO_BOX,
204 'user_emailtime' => 0,
206 'user_notify' => 0,
207 'user_notify_pm' => 1,
208 'user_notify_type' => NOTIFY_EMAIL,
209 'user_allow_pm' => 1,
210 'user_allow_viewonline' => 1,
211 'user_allow_viewemail' => 1,
212 'user_allow_massemail' => 1,
214 'user_sig' => '',
215 'user_sig_bbcode_uid' => '',
216 'user_sig_bbcode_bitfield' => '',
218 'user_form_salt' => phpbb::$security->unique_id(),
221 // Now fill the sql array with not required variables
222 foreach ($additional_vars as $key => $default_value)
224 $sql_ary[$key] = (isset($user_row[$key])) ? $user_row[$key] : $default_value;
227 // Any additional variables in $user_row not covered above?
228 $remaining_vars = array_diff(array_keys($user_row), array_keys($sql_ary));
230 // Now fill our sql array with the remaining vars
231 if (sizeof($remaining_vars))
233 foreach ($remaining_vars as $key)
235 $sql_ary[$key] = $user_row[$key];
239 $sql = 'INSERT INTO ' . USERS_TABLE . ' ' . phpbb::$db->sql_build_array('INSERT', $sql_ary);
240 phpbb::$db->sql_query($sql);
242 $user_id = phpbb::$db->sql_nextid();
244 // Insert Custom Profile Fields
245 if ($cp_data !== false && sizeof($cp_data))
247 $cp_data['user_id'] = (int) $user_id;
249 if (!class_exists('custom_profile'))
251 include_once PHPBB_ROOT_PATH . 'includes/functions_profile_fields.' . PHP_EXT;
254 $sql = 'INSERT INTO ' . PROFILE_FIELDS_DATA_TABLE . ' ' .
255 phpbb::$db->sql_build_array('INSERT', custom_profile::build_insert_sql_array($cp_data));
256 phpbb::$db->sql_query($sql);
259 // Place into appropriate group...
260 $sql = 'INSERT INTO ' . USER_GROUP_TABLE . ' ' . phpbb::$db->sql_build_array('INSERT', array(
261 'user_id' => (int) $user_id,
262 'group_id' => (int) $user_row['group_id'],
263 'user_pending' => 0)
265 phpbb::$db->sql_query($sql);
267 // Now make it the users default group...
268 group_set_user_default($user_row['group_id'], array($user_id), false);
270 // set the newest user and adjust the user count if the user is a normal user and no activation mail is sent
271 if ($user_row['user_type'] == phpbb::USER_NORMAL)
273 set_config('newest_user_id', $user_id, true);
274 set_config('newest_username', $user_row['username'], true);
275 set_config_count('num_users', 1, true);
277 $sql = 'SELECT group_colour
278 FROM ' . GROUPS_TABLE . '
279 WHERE group_id = ' . (int) $user_row['group_id'];
280 $result = phpbb::$db->sql_query_limit($sql, 1);
281 $row = phpbb::$db->sql_fetchrow($result);
282 phpbb::$db->sql_freeresult($result);
284 set_config('newest_user_colour', $row['group_colour'], true);
287 return $user_id;
291 * Remove User
293 function user_delete($mode, $user_id, $post_username = false)
295 $sql = 'SELECT *
296 FROM ' . USERS_TABLE . '
297 WHERE user_id = ' . $user_id;
298 $result = phpbb::$db->sql_query($sql);
299 $user_row = phpbb::$db->sql_fetchrow($result);
300 phpbb::$db->sql_freeresult($result);
302 if (!$user_row)
304 return false;
307 // Before we begin, we will remove the reports the user issued.
308 $sql = 'SELECT r.post_id, p.topic_id
309 FROM ' . REPORTS_TABLE . ' r, ' . POSTS_TABLE . ' p
310 WHERE r.user_id = ' . $user_id . '
311 AND p.post_id = r.post_id';
312 $result = phpbb::$db->sql_query($sql);
314 $report_posts = $report_topics = array();
315 while ($row = phpbb::$db->sql_fetchrow($result))
317 $report_posts[] = $row['post_id'];
318 $report_topics[] = $row['topic_id'];
320 phpbb::$db->sql_freeresult($result);
322 if (sizeof($report_posts))
324 $report_posts = array_unique($report_posts);
325 $report_topics = array_unique($report_topics);
327 // Get a list of topics that still contain reported posts
328 $sql = 'SELECT DISTINCT topic_id
329 FROM ' . POSTS_TABLE . '
330 WHERE ' . phpbb::$db->sql_in_set('topic_id', $report_topics) . '
331 AND post_reported = 1
332 AND ' . phpbb::$db->sql_in_set('post_id', $report_posts, true);
333 $result = phpbb::$db->sql_query($sql);
335 $keep_report_topics = array();
336 while ($row = phpbb::$db->sql_fetchrow($result))
338 $keep_report_topics[] = $row['topic_id'];
340 phpbb::$db->sql_freeresult($result);
342 if (sizeof($keep_report_topics))
344 $report_topics = array_diff($report_topics, $keep_report_topics);
346 unset($keep_report_topics);
348 // Now set the flags back
349 $sql = 'UPDATE ' . POSTS_TABLE . '
350 SET post_reported = 0
351 WHERE ' . phpbb::$db->sql_in_set('post_id', $report_posts);
352 phpbb::$db->sql_query($sql);
354 if (sizeof($report_topics))
356 $sql = 'UPDATE ' . TOPICS_TABLE . '
357 SET topic_reported = 0
358 WHERE ' . phpbb::$db->sql_in_set('topic_id', $report_topics);
359 phpbb::$db->sql_query($sql);
363 // Remove reports
364 phpbb::$db->sql_query('DELETE FROM ' . REPORTS_TABLE . ' WHERE user_id = ' . $user_id);
366 if ($user_row['user_avatar'] && $user_row['user_avatar_type'] == AVATAR_UPLOAD)
368 avatar_delete('user', $user_row);
371 switch ($mode)
373 case 'retain':
375 phpbb::$db->sql_transaction('begin');
377 if ($post_username === false)
379 $post_username = phpbb::$user->lang['GUEST'];
382 // If the user is inactive and newly registered we assume no posts from this user being there...
383 if ($user_row['user_type'] == phpbb::USER_INACTIVE && $user_row['user_inactive_reason'] == INACTIVE_REGISTER && !$user_row['user_posts'])
386 else
388 $sql = 'UPDATE ' . FORUMS_TABLE . '
389 SET forum_last_poster_id = ' . ANONYMOUS . ", forum_last_poster_name = '" . phpbb::$db->sql_escape($post_username) . "', forum_last_poster_colour = ''
390 WHERE forum_last_poster_id = $user_id";
391 phpbb::$db->sql_query($sql);
393 $sql = 'UPDATE ' . POSTS_TABLE . '
394 SET poster_id = ' . ANONYMOUS . ", post_username = '" . phpbb::$db->sql_escape($post_username) . "'
395 WHERE poster_id = $user_id";
396 phpbb::$db->sql_query($sql);
398 $sql = 'UPDATE ' . POSTS_TABLE . '
399 SET post_edit_user = ' . ANONYMOUS . "
400 WHERE post_edit_user = $user_id";
401 phpbb::$db->sql_query($sql);
403 $sql = 'UPDATE ' . TOPICS_TABLE . '
404 SET topic_poster = ' . ANONYMOUS . ", topic_first_poster_name = '" . phpbb::$db->sql_escape($post_username) . "', topic_first_poster_colour = ''
405 WHERE topic_poster = $user_id";
406 phpbb::$db->sql_query($sql);
408 $sql = 'UPDATE ' . TOPICS_TABLE . '
409 SET topic_last_poster_id = ' . ANONYMOUS . ", topic_last_poster_name = '" . phpbb::$db->sql_escape($post_username) . "', topic_last_poster_colour = ''
410 WHERE topic_last_poster_id = $user_id";
411 phpbb::$db->sql_query($sql);
413 // Since we change every post by this author, we need to count this amount towards the anonymous user
415 // Update the post count for the anonymous user
416 if ($user_row['user_posts'])
418 $sql = 'UPDATE ' . USERS_TABLE . '
419 SET user_posts = user_posts + ' . $user_row['user_posts'] . '
420 WHERE user_id = ' . ANONYMOUS;
421 phpbb::$db->sql_query($sql);
425 phpbb::$db->sql_transaction('commit');
427 break;
429 case 'remove':
431 if (!function_exists('delete_posts'))
433 include(PHPBB_ROOT_PATH . 'includes/functions_admin.' . PHP_EXT);
436 $sql = 'SELECT topic_id, COUNT(post_id) AS total_posts
437 FROM ' . POSTS_TABLE . "
438 WHERE poster_id = $user_id
439 GROUP BY topic_id";
440 $result = phpbb::$db->sql_query($sql);
442 $topic_id_ary = array();
443 while ($row = phpbb::$db->sql_fetchrow($result))
445 $topic_id_ary[$row['topic_id']] = $row['total_posts'];
447 phpbb::$db->sql_freeresult($result);
449 if (sizeof($topic_id_ary))
451 $sql = 'SELECT topic_id, topic_replies, topic_replies_real
452 FROM ' . TOPICS_TABLE . '
453 WHERE ' . phpbb::$db->sql_in_set('topic_id', array_keys($topic_id_ary));
454 $result = phpbb::$db->sql_query($sql);
456 $del_topic_ary = array();
457 while ($row = phpbb::$db->sql_fetchrow($result))
459 if (max($row['topic_replies'], $row['topic_replies_real']) + 1 == $topic_id_ary[$row['topic_id']])
461 $del_topic_ary[] = $row['topic_id'];
464 phpbb::$db->sql_freeresult($result);
466 if (sizeof($del_topic_ary))
468 $sql = 'DELETE FROM ' . TOPICS_TABLE . '
469 WHERE ' . phpbb::$db->sql_in_set('topic_id', $del_topic_ary);
470 phpbb::$db->sql_query($sql);
474 // Delete posts, attachments, etc.
475 delete_posts('poster_id', $user_id);
477 break;
480 phpbb::$db->sql_transaction('begin');
482 $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);
484 foreach ($table_ary as $table)
486 $sql = "DELETE FROM $table
487 WHERE user_id = $user_id";
488 phpbb::$db->sql_query($sql);
491 phpbb::$acm->destroy_sql(MODERATOR_CACHE_TABLE);
493 // Delete the user_id from the banlist
494 $sql = 'DELETE FROM ' . BANLIST_TABLE . '
495 WHERE ban_userid = ' . $user_id;
496 phpbb::$db->sql_query($sql);
498 // Delete the user_id from the session table
499 $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
500 WHERE session_user_id = ' . $user_id;
501 phpbb::$db->sql_query($sql);
503 // Remove any undelivered mails...
504 $sql = 'SELECT msg_id, user_id
505 FROM ' . PRIVMSGS_TO_TABLE . '
506 WHERE author_id = ' . $user_id . '
507 AND folder_id = ' . PRIVMSGS_NO_BOX;
508 $result = phpbb::$db->sql_query($sql);
510 $undelivered_msg = $undelivered_user = array();
511 while ($row = phpbb::$db->sql_fetchrow($result))
513 $undelivered_msg[] = $row['msg_id'];
514 $undelivered_user[$row['user_id']][] = true;
516 phpbb::$db->sql_freeresult($result);
518 if (sizeof($undelivered_msg))
520 $sql = 'DELETE FROM ' . PRIVMSGS_TABLE . '
521 WHERE ' . phpbb::$db->sql_in_set('msg_id', $undelivered_msg);
522 phpbb::$db->sql_query($sql);
525 $sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
526 WHERE author_id = ' . $user_id . '
527 AND folder_id = ' . PRIVMSGS_NO_BOX;
528 phpbb::$db->sql_query($sql);
530 // Delete all to-information
531 $sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
532 WHERE user_id = ' . $user_id;
533 phpbb::$db->sql_query($sql);
535 // Set the remaining author id to anonymous - this way users are still able to read messages from users being removed
536 $sql = 'UPDATE ' . PRIVMSGS_TO_TABLE . '
537 SET author_id = ' . ANONYMOUS . '
538 WHERE author_id = ' . $user_id;
539 phpbb::$db->sql_query($sql);
541 $sql = 'UPDATE ' . PRIVMSGS_TABLE . '
542 SET author_id = ' . ANONYMOUS . '
543 WHERE author_id = ' . $user_id;
544 phpbb::$db->sql_query($sql);
546 foreach ($undelivered_user as $_user_id => $ary)
548 if ($_user_id == $user_id)
550 continue;
553 $sql = 'UPDATE ' . USERS_TABLE . '
554 SET user_new_privmsg = user_new_privmsg - ' . sizeof($ary) . ',
555 user_unread_privmsg = user_unread_privmsg - ' . sizeof($ary) . '
556 WHERE user_id = ' . $_user_id;
557 phpbb::$db->sql_query($sql);
560 phpbb::$db->sql_transaction('commit');
562 // Reset newest user info if appropriate
563 if (phpbb::$config['newest_user_id'] == $user_id)
565 update_last_username();
568 // Decrement number of users if this user is active
569 if ($user_row['user_type'] != phpbb::USER_INACTIVE && $user_row['user_type'] != phpbb::USER_IGNORE)
571 set_config_count('num_users', -1, true);
574 return false;
578 * Flips user_type from active to inactive and vice versa, handles group membership updates
580 * @param string $mode can be flip for flipping from active/inactive, activate or deactivate
582 function user_active_flip($mode, $user_id_ary, $reason = INACTIVE_MANUAL)
584 $deactivated = $activated = 0;
585 $sql_statements = array();
587 if (!is_array($user_id_ary))
589 $user_id_ary = array($user_id_ary);
592 if (!sizeof($user_id_ary))
594 return;
597 $sql = 'SELECT user_id, group_id, user_type, user_inactive_reason
598 FROM ' . USERS_TABLE . '
599 WHERE ' . phpbb::$db->sql_in_set('user_id', $user_id_ary);
600 $result = phpbb::$db->sql_query($sql);
602 while ($row = phpbb::$db->sql_fetchrow($result))
604 $sql_ary = array();
606 if ($row['user_type'] == phpbb::USER_IGNORE || $row['user_type'] == phpbb::USER_FOUNDER ||
607 ($mode == 'activate' && $row['user_type'] != phpbb::USER_INACTIVE) ||
608 ($mode == 'deactivate' && $row['user_type'] == phpbb::USER_INACTIVE))
610 continue;
613 if ($row['user_type'] == phpbb::USER_INACTIVE)
615 $activated++;
617 else
619 $deactivated++;
621 // Remove the users session key...
622 phpbb::$user->reset_login_keys($row['user_id']);
625 $sql_ary += array(
626 'user_type' => ($row['user_type'] == phpbb::USER_NORMAL) ? phpbb::USER_INACTIVE : phpbb::USER_NORMAL,
627 'user_inactive_time' => ($row['user_type'] == phpbb::USER_NORMAL) ? time() : 0,
628 'user_inactive_reason' => ($row['user_type'] == phpbb::USER_NORMAL) ? $reason : 0,
631 $sql_statements[$row['user_id']] = $sql_ary;
633 phpbb::$db->sql_freeresult($result);
635 if (sizeof($sql_statements))
637 foreach ($sql_statements as $user_id => $sql_ary)
639 $sql = 'UPDATE ' . USERS_TABLE . '
640 SET ' . phpbb::$db->sql_build_array('UPDATE', $sql_ary) . '
641 WHERE user_id = ' . $user_id;
642 phpbb::$db->sql_query($sql);
645 phpbb::$acl->acl_clear_prefetch(array_keys($sql_statements));
648 if ($deactivated)
650 set_config_count('num_users', $deactivated * (-1), true);
653 if ($activated)
655 set_config_count('num_users', $activated, true);
658 // Update latest username
659 update_last_username();
663 * Add a ban or ban exclusion to the banlist. Bans either a user, an IP or an email address
665 * @param string $mode Type of ban. One of the following: user, ip, email
666 * @param mixed $ban Banned entity. Either string or array with usernames, ips or email addresses
667 * @param int $ban_len Ban length in minutes
668 * @param string $ban_len_other Ban length as a date (YYYY-MM-DD)
669 * @param boolean $ban_exclude Exclude these entities from banning?
670 * @param string $ban_reason String describing the reason for this ban
671 * @return boolean
673 function user_ban($mode, $ban, $ban_len, $ban_len_other, $ban_exclude, $ban_reason, $ban_give_reason = '')
675 // Delete stale bans
676 $sql = 'DELETE FROM ' . BANLIST_TABLE . '
677 WHERE ban_end < ' . time() . '
678 AND ban_end <> 0';
679 phpbb::$db->sql_query($sql);
681 $ban_list = (!is_array($ban)) ? array_unique(explode("\n", $ban)) : $ban;
682 $ban_list_log = implode(', ', $ban_list);
684 $current_time = time();
686 // Set $ban_end to the unix time when the ban should end. 0 is a permanent ban.
687 if ($ban_len)
689 if ($ban_len != -1 || !$ban_len_other)
691 $ban_end = max($current_time, $current_time + ($ban_len) * 60);
693 else
695 $ban_other = explode('-', $ban_len_other);
696 if (sizeof($ban_other) == 3 && ((int)$ban_other[0] < 9999) &&
697 (strlen($ban_other[0]) == 4) && (strlen($ban_other[1]) == 2) && (strlen($ban_other[2]) == 2))
699 $ban_end = max($current_time, gmmktime(0, 0, 0, (int)$ban_other[1], (int)$ban_other[2], (int)$ban_other[0]));
701 else
703 trigger_error('LENGTH_BAN_INVALID');
707 else
709 $ban_end = 0;
712 $founder = $founder_names = array();
714 if (!$ban_exclude)
716 // Create a list of founder...
717 $sql = 'SELECT user_id, user_email, username_clean
718 FROM ' . USERS_TABLE . '
719 WHERE user_type = ' . phpbb::USER_FOUNDER;
720 $result = phpbb::$db->sql_query($sql);
722 while ($row = phpbb::$db->sql_fetchrow($result))
724 $founder[$row['user_id']] = $row['user_email'];
725 $founder_names[$row['user_id']] = $row['username_clean'];
727 phpbb::$db->sql_freeresult($result);
730 $banlist_ary = array();
732 switch ($mode)
734 case 'user':
735 $type = 'ban_userid';
737 // At the moment we do not support wildcard username banning
739 // Select the relevant user_ids.
740 $sql_usernames = array();
742 foreach ($ban_list as $username)
744 $username = trim($username);
745 if ($username != '')
747 $clean_name = utf8_clean_string($username);
748 if ($clean_name == phpbb::$user->data['username_clean'])
750 trigger_error('CANNOT_BAN_YOURSELF', E_USER_WARNING);
752 if (in_array($clean_name, $founder_names))
754 trigger_error('CANNOT_BAN_FOUNDER', E_USER_WARNING);
756 $sql_usernames[] = $clean_name;
760 // Make sure we have been given someone to ban
761 if (!sizeof($sql_usernames))
763 trigger_error('NO_USER_SPECIFIED');
766 $sql = 'SELECT user_id
767 FROM ' . USERS_TABLE . '
768 WHERE ' . phpbb::$db->sql_in_set('username_clean', $sql_usernames);
770 // Do not allow banning yourself
771 if (sizeof($founder))
773 $sql .= ' AND ' . phpbb::$db->sql_in_set('user_id', array_merge(array_keys($founder), array(phpbb::$user->data['user_id'])), true);
775 else
777 $sql .= ' AND user_id <> ' . phpbb::$user->data['user_id'];
780 $result = phpbb::$db->sql_query($sql);
782 if ($row = phpbb::$db->sql_fetchrow($result))
786 $banlist_ary[] = (int) $row['user_id'];
788 while ($row = phpbb::$db->sql_fetchrow($result));
790 else
792 phpbb::$db->sql_freeresult($result);
793 trigger_error('NO_USERS');
795 phpbb::$db->sql_freeresult($result);
796 break;
798 case 'ip':
799 $type = 'ban_ip';
801 foreach ($ban_list as $ban_item)
803 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))
805 // This is an IP range
806 // Don't ask about all this, just don't ask ... !
807 $ip_1_counter = $ip_range_explode[1];
808 $ip_1_end = $ip_range_explode[5];
810 while ($ip_1_counter <= $ip_1_end)
812 $ip_2_counter = ($ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[2] : 0;
813 $ip_2_end = ($ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[6];
815 if ($ip_2_counter == 0 && $ip_2_end == 254)
817 $ip_2_counter = 256;
818 $ip_2_fragment = 256;
820 $banlist_ary[] = "$ip_1_counter.*";
823 while ($ip_2_counter <= $ip_2_end)
825 $ip_3_counter = ($ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[3] : 0;
826 $ip_3_end = ($ip_2_counter < $ip_2_end || $ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[7];
828 if ($ip_3_counter == 0 && $ip_3_end == 254)
830 $ip_3_counter = 256;
831 $ip_3_fragment = 256;
833 $banlist_ary[] = "$ip_1_counter.$ip_2_counter.*";
836 while ($ip_3_counter <= $ip_3_end)
838 $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;
839 $ip_4_end = ($ip_3_counter < $ip_3_end || $ip_2_counter < $ip_2_end) ? 254 : $ip_range_explode[8];
841 if ($ip_4_counter == 0 && $ip_4_end == 254)
843 $ip_4_counter = 256;
844 $ip_4_fragment = 256;
846 $banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.*";
849 while ($ip_4_counter <= $ip_4_end)
851 $banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.$ip_4_counter";
852 $ip_4_counter++;
854 $ip_3_counter++;
856 $ip_2_counter++;
858 $ip_1_counter++;
861 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)))
863 // Normal IP address
864 $banlist_ary[] = trim($ban_item);
866 else if (preg_match('#^\*$#', trim($ban_item)))
868 // Ban all IPs
869 $banlist_ary[] = '*';
871 else if (preg_match('#^([\w\-_]\.?){2,}$#is', trim($ban_item)))
873 // hostname
874 $ip_ary = gethostbynamel(trim($ban_item));
876 if (!empty($ip_ary))
878 foreach ($ip_ary as $ip)
880 if ($ip)
882 if (strlen($ip) > 40)
884 continue;
887 $banlist_ary[] = $ip;
892 else
894 trigger_error('NO_IPS_DEFINED');
897 break;
899 case 'email':
900 $type = 'ban_email';
902 foreach ($ban_list as $ban_item)
904 $ban_item = trim($ban_item);
906 if (preg_match('#^.*?@*|(([a-z0-9\-]+\.)+([a-z]{2,3}))$#i', $ban_item))
908 if (strlen($ban_item) > 100)
910 continue;
913 if (!sizeof($founder) || !in_array($ban_item, $founder))
915 $banlist_ary[] = $ban_item;
920 if (sizeof($ban_list) == 0)
922 trigger_error('NO_EMAILS_DEFINED');
924 break;
926 default:
927 trigger_error('NO_MODE');
928 break;
931 // Fetch currently set bans of the specified type and exclude state. Prevent duplicate bans.
932 $sql_where = ($type == 'ban_userid') ? 'ban_userid <> 0' : "$type <> ''";
934 $sql = "SELECT $type
935 FROM " . BANLIST_TABLE . "
936 WHERE $sql_where
937 AND ban_exclude = " . (int) $ban_exclude;
938 $result = phpbb::$db->sql_query($sql);
940 // Reset $sql_where, because we use it later...
941 $sql_where = '';
943 if ($row = phpbb::$db->sql_fetchrow($result))
945 $banlist_ary_tmp = array();
948 switch ($mode)
950 case 'user':
951 $banlist_ary_tmp[] = $row['ban_userid'];
952 break;
954 case 'ip':
955 $banlist_ary_tmp[] = $row['ban_ip'];
956 break;
958 case 'email':
959 $banlist_ary_tmp[] = $row['ban_email'];
960 break;
963 while ($row = phpbb::$db->sql_fetchrow($result));
965 $banlist_ary = array_unique(array_diff($banlist_ary, $banlist_ary_tmp));
966 unset($banlist_ary_tmp);
968 phpbb::$db->sql_freeresult($result);
970 // We have some entities to ban
971 if (sizeof($banlist_ary))
973 $sql_ary = array();
975 foreach ($banlist_ary as $ban_entry)
977 $sql_ary[] = array(
978 $type => $ban_entry,
979 'ban_start' => (int) $current_time,
980 'ban_end' => (int) $ban_end,
981 'ban_exclude' => (int) $ban_exclude,
982 'ban_reason' => (string) $ban_reason,
983 'ban_give_reason' => (string) $ban_give_reason,
987 phpbb::$db->sql_multi_insert(BANLIST_TABLE, $sql_ary);
989 // If we are banning we want to logout anyone matching the ban
990 if (!$ban_exclude)
992 switch ($mode)
994 case 'user':
995 $sql_where = 'WHERE ' . phpbb::$db->sql_in_set('session_user_id', $banlist_ary);
996 break;
998 case 'ip':
999 $sql_where = 'WHERE ' . phpbb::$db->sql_in_set('session_ip', $banlist_ary);
1000 break;
1002 case 'email':
1003 $banlist_ary_sql = array();
1005 foreach ($banlist_ary as $ban_entry)
1007 $banlist_ary_sql[] = (string) str_replace('*', '%', $ban_entry);
1010 $sql = 'SELECT user_id
1011 FROM ' . USERS_TABLE . '
1012 WHERE ' . phpbb::$db->sql_in_set('user_email', $banlist_ary_sql);
1013 $result = phpbb::$db->sql_query($sql);
1015 $sql_in = array();
1017 if ($row = phpbb::$db->sql_fetchrow($result))
1021 $sql_in[] = $row['user_id'];
1023 while ($row = phpbb::$db->sql_fetchrow($result));
1025 $sql_where = 'WHERE ' . phpbb::$db->sql_in_set('session_user_id', $sql_in);
1027 phpbb::$db->sql_freeresult($result);
1028 break;
1031 if (isset($sql_where) && $sql_where)
1033 $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
1034 $sql_where";
1035 phpbb::$db->sql_query($sql);
1037 if ($mode == 'user')
1039 $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . ' ' . ((in_array('*', $banlist_ary)) ? '' : 'WHERE ' . phpbb::$db->sql_in_set('user_id', $banlist_ary));
1040 phpbb::$db->sql_query($sql);
1045 // Update log
1046 $log_entry = ($ban_exclude) ? 'LOG_BAN_EXCLUDE_' : 'LOG_BAN_';
1048 // Add to moderator and admin log
1049 add_log('admin', $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
1050 add_log('mod', 0, 0, $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
1052 phpbb::$acm->destroy_sql(BANLIST_TABLE);
1054 return true;
1057 // There was nothing to ban/exclude. But destroying the cache because of the removal of stale bans.
1058 phpbb::$acm->destroy_sql(BANLIST_TABLE);
1060 return false;
1064 * Unban User
1066 function user_unban($mode, $ban)
1068 // Delete stale bans
1069 $sql = 'DELETE FROM ' . BANLIST_TABLE . '
1070 WHERE ban_end < ' . time() . '
1071 AND ban_end <> 0';
1072 phpbb::$db->sql_query($sql);
1074 if (!is_array($ban))
1076 $ban = array($ban);
1079 $unban_sql = array_map('intval', $ban);
1081 if (sizeof($unban_sql))
1083 // Grab details of bans for logging information later
1084 switch ($mode)
1086 case 'user':
1087 $sql = 'SELECT u.username AS unban_info
1088 FROM ' . USERS_TABLE . ' u, ' . BANLIST_TABLE . ' b
1089 WHERE ' . phpbb::$db->sql_in_set('b.ban_id', $unban_sql) . '
1090 AND u.user_id = b.ban_userid';
1091 break;
1093 case 'email':
1094 $sql = 'SELECT ban_email AS unban_info
1095 FROM ' . BANLIST_TABLE . '
1096 WHERE ' . phpbb::$db->sql_in_set('ban_id', $unban_sql);
1097 break;
1099 case 'ip':
1100 $sql = 'SELECT ban_ip AS unban_info
1101 FROM ' . BANLIST_TABLE . '
1102 WHERE ' . phpbb::$db->sql_in_set('ban_id', $unban_sql);
1103 break;
1105 $result = phpbb::$db->sql_query($sql);
1107 $l_unban_list = '';
1108 while ($row = phpbb::$db->sql_fetchrow($result))
1110 $l_unban_list .= (($l_unban_list != '') ? ', ' : '') . $row['unban_info'];
1112 phpbb::$db->sql_freeresult($result);
1114 $sql = 'DELETE FROM ' . BANLIST_TABLE . '
1115 WHERE ' . phpbb::$db->sql_in_set('ban_id', $unban_sql);
1116 phpbb::$db->sql_query($sql);
1118 // Add to moderator and admin log
1119 add_log('admin', 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
1120 add_log('mod', 0, 0, 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
1123 phpbb::$acm->destroy_sql(BANLIST_TABLE);
1125 return false;
1129 * Whois facility
1131 * @link http://tools.ietf.org/html/rfc3912 RFC3912: WHOIS Protocol Specification
1133 function user_ipwhois($ip)
1135 $ipwhois = '';
1137 // Check IP
1138 // Only supporting IPv4 at the moment...
1139 if (empty($ip) || !preg_match(get_preg_expression('ipv4'), $ip))
1141 return '';
1144 if (($fsk = @fsockopen('whois.arin.net', 43)))
1146 // CRLF as per RFC3912
1147 fputs($fsk, "$ip\r\n");
1148 while (!feof($fsk))
1150 $ipwhois .= fgets($fsk, 1024);
1152 @fclose($fsk);
1155 $match = array();
1157 // Test for referrals from ARIN to other whois databases, roll on rwhois
1158 if (preg_match('#ReferralServer: whois://(.+)#im', $ipwhois, $match))
1160 if (strpos($match[1], ':') !== false)
1162 $pos = strrpos($match[1], ':');
1163 $server = substr($match[1], 0, $pos);
1164 $port = (int) substr($match[1], $pos + 1);
1165 unset($pos);
1167 else
1169 $server = $match[1];
1170 $port = 43;
1173 $buffer = '';
1175 if (($fsk = @fsockopen($server, $port)))
1177 fputs($fsk, "$ip\r\n");
1178 while (!feof($fsk))
1180 $buffer .= fgets($fsk, 1024);
1182 @fclose($fsk);
1185 // Use the result from ARIN if we don't get any result here
1186 $ipwhois = (empty($buffer)) ? $ipwhois : $buffer;
1189 $ipwhois = htmlspecialchars($ipwhois);
1191 // Magic URL ;)
1192 return trim(make_clickable($ipwhois, false, ''));
1196 * Data validation ... used primarily but not exclusively by ucp modules
1198 * "Master" function for validating a range of data types
1200 function validate_data($data, $val_ary)
1202 $error = array();
1204 foreach ($val_ary as $var => $val_seq)
1206 if (!is_array($val_seq[0]))
1208 $val_seq = array($val_seq);
1211 foreach ($val_seq as $validate)
1213 $function = array_shift($validate);
1214 array_unshift($validate, $data[$var]);
1216 if ($result = call_user_func_array('validate_' . $function, $validate))
1218 // Since errors are checked later for their language file existence, we need to make sure custom errors are not adjusted.
1219 $error[] = (empty(phpbb::$user->lang[$result . '_' . strtoupper($var)])) ? $result : $result . '_' . strtoupper($var);
1224 return $error;
1228 * Validate String
1230 * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1232 function validate_string($string, $optional = false, $min = 0, $max = 0)
1234 if (empty($string) && $optional)
1236 return false;
1239 if ($min && utf8_strlen(htmlspecialchars_decode($string)) < $min)
1241 return 'TOO_SHORT';
1243 else if ($max && utf8_strlen(htmlspecialchars_decode($string)) > $max)
1245 return 'TOO_LONG';
1248 return false;
1252 * Validate Number
1254 * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1256 function validate_num($num, $optional = false, $min = 0, $max = 1E99)
1258 if (empty($num) && $optional)
1260 return false;
1263 if ($num < $min)
1265 return 'TOO_SMALL';
1267 else if ($num > $max)
1269 return 'TOO_LARGE';
1272 return false;
1276 * Validate Date
1277 * @param String $string a date in the dd-mm-yyyy format
1278 * @return boolean
1280 function validate_date($date_string, $optional = false)
1282 $date = explode('-', $date_string);
1283 if ((empty($date) || sizeof($date) != 3) && $optional)
1285 return false;
1287 else if ($optional)
1289 for ($field = 0; $field <= 1; $field++)
1291 $date[$field] = (int) $date[$field];
1292 if (empty($date[$field]))
1294 $date[$field] = 1;
1297 $date[2] = (int) $date[2];
1298 // assume an arbitrary leap year
1299 if (empty($date[2]))
1301 $date[2] = 1980;
1305 if (sizeof($date) != 3 || !checkdate($date[1], $date[0], $date[2]))
1307 return 'INVALID';
1310 return false;
1315 * Validate Match
1317 * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1319 function validate_match($string, $optional = false, $match = '')
1321 if (empty($string) && $optional)
1323 return false;
1326 if (empty($match))
1328 return false;
1331 if (!preg_match($match, $string))
1333 return 'WRONG_DATA';
1336 return false;
1340 * Check to see if the username has been taken, or if it is disallowed.
1341 * Also checks if it includes the " character, which we don't allow in usernames.
1342 * Used for registering, changing names, and posting anonymously with a username
1344 * @param string $username The username to check
1345 * @param string $allowed_username An allowed username, default being phpbb::$user->data['username']
1347 * @return mixed Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1349 function validate_username($username, $allowed_username = false)
1351 $clean_username = utf8_clean_string($username);
1352 $allowed_username = ($allowed_username === false) ? phpbb::$user->data['username_clean'] : utf8_clean_string($allowed_username);
1354 if ($allowed_username == $clean_username)
1356 return false;
1359 // ... fast checks first.
1360 if (strpos($username, '&quot;') !== false || strpos($username, '"') !== false || empty($clean_username))
1362 return 'INVALID_CHARS';
1365 $mbstring = $pcre = false;
1367 // generic UTF-8 character types supported
1368 switch (phpbb::$config['allow_name_chars'])
1370 case 'USERNAME_CHARS_ANY':
1371 $regex = '.+';
1372 break;
1374 case 'USERNAME_ALPHA_ONLY':
1375 $regex = '[A-Za-z0-9]+';
1376 break;
1378 case 'USERNAME_ALPHA_SPACERS':
1379 $regex = '[A-Za-z0-9-[\]_+ ]+';
1380 break;
1382 case 'USERNAME_LETTER_NUM':
1383 $regex = '[\p{Lu}\p{Ll}\p{N}]+';
1384 break;
1386 case 'USERNAME_LETTER_NUM_SPACERS':
1387 $regex = '[-\]_+ [\p{Lu}\p{Ll}\p{N}]+';
1388 break;
1390 case 'USERNAME_ASCII':
1391 default:
1392 $regex = '[\x01-\x7F]+';
1393 break;
1396 if (!preg_match('#^' . $regex . '$#u', $username))
1398 return 'INVALID_CHARS';
1401 $sql = 'SELECT username
1402 FROM ' . USERS_TABLE . "
1403 WHERE username_clean = '" . phpbb::$db->sql_escape($clean_username) . "'";
1404 $result = phpbb::$db->sql_query($sql);
1405 $row = phpbb::$db->sql_fetchrow($result);
1406 phpbb::$db->sql_freeresult($result);
1408 if ($row)
1410 return 'USERNAME_TAKEN';
1413 $sql = 'SELECT group_name
1414 FROM ' . GROUPS_TABLE . "
1415 WHERE group_name = '" . phpbb::$db->sql_escape($clean_username) . "'";
1416 $result = phpbb::$db->sql_query($sql);
1417 $row = phpbb::$db->sql_fetchrow($result);
1418 phpbb::$db->sql_freeresult($result);
1420 if ($row)
1422 return 'USERNAME_TAKEN';
1425 $bad_usernames = phpbb_cache::obtain_disallowed_usernames();
1427 foreach ($bad_usernames as $bad_username)
1429 if (preg_match('#^' . $bad_username . '$#', $clean_username))
1431 return 'USERNAME_DISALLOWED';
1435 return false;
1439 * Check to see if the password meets the complexity settings
1441 * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1443 function validate_password($password)
1445 if (!$password)
1447 return false;
1450 // generic UTF-8 character types supported
1451 $upp = '\p{Lu}';
1452 $low = '\p{Ll}';
1453 $let = '\p{L}';
1454 $num = '\p{N}';
1455 $sym = '[^\p{Lu}\p{Ll}\p{N}]';
1457 $chars = array();
1459 switch (phpbb::$config['pass_complex'])
1461 case 'PASS_TYPE_CASE':
1462 $chars[] = $low;
1463 $chars[] = $upp;
1464 break;
1466 case 'PASS_TYPE_ALPHA':
1467 $chars[] = $let;
1468 $chars[] = $num;
1469 break;
1471 case 'PASS_TYPE_SYMBOL':
1472 $chars[] = $low;
1473 $chars[] = $upp;
1474 $chars[] = $num;
1475 $chars[] = $sym;
1476 break;
1479 if ($pcre)
1481 foreach ($chars as $char)
1483 if (!preg_match('#' . $char . '#u', $password))
1485 return 'INVALID_CHARS';
1489 else if ($mbstring)
1491 foreach ($chars as $char)
1493 if (mb_ereg($char, $password) === false)
1495 return 'INVALID_CHARS';
1500 return false;
1504 * Check to see if email address is banned or already present in the DB
1506 * @param string $email The email to check
1507 * @param string $allowed_email An allowed email, default being phpbb::$user->data['user_email']
1509 * @return mixed Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1511 function validate_email($email, $allowed_email = false)
1513 $email = strtolower($email);
1514 $allowed_email = ($allowed_email === false) ? strtolower(phpbb::$user->data['user_email']) : strtolower($allowed_email);
1516 if ($allowed_email == $email)
1518 return false;
1521 if (!preg_match('/^' . get_preg_expression('email') . '$/i', $email))
1523 return 'EMAIL_INVALID';
1526 // Check MX record.
1527 // The idea for this is from reading the UseBB blog/announcement. :)
1528 if (phpbb::$config['email_check_mx'])
1530 list(, $domain) = explode('@', $email);
1532 if (phpbb_checkdnsrr($domain, 'A') === false && phpbb_checkdnsrr($domain, 'MX') === false)
1534 return 'DOMAIN_NO_MX_RECORD';
1538 if (($ban_reason = phpbb::$user->check_ban(false, false, $email, true)) !== false)
1540 return ($ban_reason === true) ? 'EMAIL_BANNED' : $ban_reason;
1543 if (!phpbb::$config['allow_emailreuse'])
1545 $sql = 'SELECT user_email_hash
1546 FROM ' . USERS_TABLE . "
1547 WHERE user_email_hash = " . hexdec(crc32($email) . strlen($email));
1548 $result = phpbb::$db->sql_query($sql);
1549 $row = phpbb::$db->sql_fetchrow($result);
1550 phpbb::$db->sql_freeresult($result);
1552 if ($row)
1554 return 'EMAIL_TAKEN';
1558 return false;
1562 * Validate jabber address
1563 * Taken from the jabber class within flyspray (see author notes)
1565 * @author flyspray.org
1567 function validate_jabber($jid)
1569 if (!$jid)
1571 return false;
1574 $seperator_pos = strpos($jid, '@');
1576 if ($seperator_pos === false)
1578 return 'WRONG_DATA';
1581 $username = substr($jid, 0, $seperator_pos);
1582 $realm = substr($jid, $seperator_pos + 1);
1584 if (strlen($username) == 0 || strlen($realm) < 3)
1586 return 'WRONG_DATA';
1589 $arr = explode('.', $realm);
1591 if (sizeof($arr) == 0)
1593 return 'WRONG_DATA';
1596 foreach ($arr as $part)
1598 if (substr($part, 0, 1) == '-' || substr($part, -1, 1) == '-')
1600 return 'WRONG_DATA';
1603 if (!preg_match("@^[a-zA-Z0-9-.]+$@", $part))
1605 return 'WRONG_DATA';
1609 $boundary = array(array(0, 127), array(192, 223), array(224, 239), array(240, 247), array(248, 251), array(252, 253));
1611 // Prohibited Characters RFC3454 + RFC3920
1612 $prohibited = array(
1613 // Table C.1.1
1614 array(0x0020, 0x0020), // SPACE
1615 // Table C.1.2
1616 array(0x00A0, 0x00A0), // NO-BREAK SPACE
1617 array(0x1680, 0x1680), // OGHAM SPACE MARK
1618 array(0x2000, 0x2001), // EN QUAD
1619 array(0x2001, 0x2001), // EM QUAD
1620 array(0x2002, 0x2002), // EN SPACE
1621 array(0x2003, 0x2003), // EM SPACE
1622 array(0x2004, 0x2004), // THREE-PER-EM SPACE
1623 array(0x2005, 0x2005), // FOUR-PER-EM SPACE
1624 array(0x2006, 0x2006), // SIX-PER-EM SPACE
1625 array(0x2007, 0x2007), // FIGURE SPACE
1626 array(0x2008, 0x2008), // PUNCTUATION SPACE
1627 array(0x2009, 0x2009), // THIN SPACE
1628 array(0x200A, 0x200A), // HAIR SPACE
1629 array(0x200B, 0x200B), // ZERO WIDTH SPACE
1630 array(0x202F, 0x202F), // NARROW NO-BREAK SPACE
1631 array(0x205F, 0x205F), // MEDIUM MATHEMATICAL SPACE
1632 array(0x3000, 0x3000), // IDEOGRAPHIC SPACE
1633 // Table C.2.1
1634 array(0x0000, 0x001F), // [CONTROL CHARACTERS]
1635 array(0x007F, 0x007F), // DELETE
1636 // Table C.2.2
1637 array(0x0080, 0x009F), // [CONTROL CHARACTERS]
1638 array(0x06DD, 0x06DD), // ARABIC END OF AYAH
1639 array(0x070F, 0x070F), // SYRIAC ABBREVIATION MARK
1640 array(0x180E, 0x180E), // MONGOLIAN VOWEL SEPARATOR
1641 array(0x200C, 0x200C), // ZERO WIDTH NON-JOINER
1642 array(0x200D, 0x200D), // ZERO WIDTH JOINER
1643 array(0x2028, 0x2028), // LINE SEPARATOR
1644 array(0x2029, 0x2029), // PARAGRAPH SEPARATOR
1645 array(0x2060, 0x2060), // WORD JOINER
1646 array(0x2061, 0x2061), // FUNCTION APPLICATION
1647 array(0x2062, 0x2062), // INVISIBLE TIMES
1648 array(0x2063, 0x2063), // INVISIBLE SEPARATOR
1649 array(0x206A, 0x206F), // [CONTROL CHARACTERS]
1650 array(0xFEFF, 0xFEFF), // ZERO WIDTH NO-BREAK SPACE
1651 array(0xFFF9, 0xFFFC), // [CONTROL CHARACTERS]
1652 array(0x1D173, 0x1D17A), // [MUSICAL CONTROL CHARACTERS]
1653 // Table C.3
1654 array(0xE000, 0xF8FF), // [PRIVATE USE, PLANE 0]
1655 array(0xF0000, 0xFFFFD), // [PRIVATE USE, PLANE 15]
1656 array(0x100000, 0x10FFFD), // [PRIVATE USE, PLANE 16]
1657 // Table C.4
1658 array(0xFDD0, 0xFDEF), // [NONCHARACTER CODE POINTS]
1659 array(0xFFFE, 0xFFFF), // [NONCHARACTER CODE POINTS]
1660 array(0x1FFFE, 0x1FFFF), // [NONCHARACTER CODE POINTS]
1661 array(0x2FFFE, 0x2FFFF), // [NONCHARACTER CODE POINTS]
1662 array(0x3FFFE, 0x3FFFF), // [NONCHARACTER CODE POINTS]
1663 array(0x4FFFE, 0x4FFFF), // [NONCHARACTER CODE POINTS]
1664 array(0x5FFFE, 0x5FFFF), // [NONCHARACTER CODE POINTS]
1665 array(0x6FFFE, 0x6FFFF), // [NONCHARACTER CODE POINTS]
1666 array(0x7FFFE, 0x7FFFF), // [NONCHARACTER CODE POINTS]
1667 array(0x8FFFE, 0x8FFFF), // [NONCHARACTER CODE POINTS]
1668 array(0x9FFFE, 0x9FFFF), // [NONCHARACTER CODE POINTS]
1669 array(0xAFFFE, 0xAFFFF), // [NONCHARACTER CODE POINTS]
1670 array(0xBFFFE, 0xBFFFF), // [NONCHARACTER CODE POINTS]
1671 array(0xCFFFE, 0xCFFFF), // [NONCHARACTER CODE POINTS]
1672 array(0xDFFFE, 0xDFFFF), // [NONCHARACTER CODE POINTS]
1673 array(0xEFFFE, 0xEFFFF), // [NONCHARACTER CODE POINTS]
1674 array(0xFFFFE, 0xFFFFF), // [NONCHARACTER CODE POINTS]
1675 array(0x10FFFE, 0x10FFFF), // [NONCHARACTER CODE POINTS]
1676 // Table C.5
1677 array(0xD800, 0xDFFF), // [SURROGATE CODES]
1678 // Table C.6
1679 array(0xFFF9, 0xFFF9), // INTERLINEAR ANNOTATION ANCHOR
1680 array(0xFFFA, 0xFFFA), // INTERLINEAR ANNOTATION SEPARATOR
1681 array(0xFFFB, 0xFFFB), // INTERLINEAR ANNOTATION TERMINATOR
1682 array(0xFFFC, 0xFFFC), // OBJECT REPLACEMENT CHARACTER
1683 array(0xFFFD, 0xFFFD), // REPLACEMENT CHARACTER
1684 // Table C.7
1685 array(0x2FF0, 0x2FFB), // [IDEOGRAPHIC DESCRIPTION CHARACTERS]
1686 // Table C.8
1687 array(0x0340, 0x0340), // COMBINING GRAVE TONE MARK
1688 array(0x0341, 0x0341), // COMBINING ACUTE TONE MARK
1689 array(0x200E, 0x200E), // LEFT-TO-RIGHT MARK
1690 array(0x200F, 0x200F), // RIGHT-TO-LEFT MARK
1691 array(0x202A, 0x202A), // LEFT-TO-RIGHT EMBEDDING
1692 array(0x202B, 0x202B), // RIGHT-TO-LEFT EMBEDDING
1693 array(0x202C, 0x202C), // POP DIRECTIONAL FORMATTING
1694 array(0x202D, 0x202D), // LEFT-TO-RIGHT OVERRIDE
1695 array(0x202E, 0x202E), // RIGHT-TO-LEFT OVERRIDE
1696 array(0x206A, 0x206A), // INHIBIT SYMMETRIC SWAPPING
1697 array(0x206B, 0x206B), // ACTIVATE SYMMETRIC SWAPPING
1698 array(0x206C, 0x206C), // INHIBIT ARABIC FORM SHAPING
1699 array(0x206D, 0x206D), // ACTIVATE ARABIC FORM SHAPING
1700 array(0x206E, 0x206E), // NATIONAL DIGIT SHAPES
1701 array(0x206F, 0x206F), // NOMINAL DIGIT SHAPES
1702 // Table C.9
1703 array(0xE0001, 0xE0001), // LANGUAGE TAG
1704 array(0xE0020, 0xE007F), // [TAGGING CHARACTERS]
1705 // RFC3920
1706 array(0x22, 0x22), // "
1707 array(0x26, 0x26), // &
1708 array(0x27, 0x27), // '
1709 array(0x2F, 0x2F), // /
1710 array(0x3A, 0x3A), // :
1711 array(0x3C, 0x3C), // <
1712 array(0x3E, 0x3E), // >
1713 array(0x40, 0x40) // @
1716 $pos = 0;
1717 $result = true;
1719 // @todo: rewrite this!
1720 while ($pos < strlen($username))
1722 $len = $uni = 0;
1723 for ($i = 0; $i <= 5; $i++)
1725 if (ord($username[$pos]) >= $boundary[$i][0] && ord($username[$pos]) <= $boundary[$i][1])
1727 $len = $i + 1;
1728 $uni = (ord($username[$pos]) - $boundary[$i][0]) * pow(2, $i * 6);
1730 for ($k = 1; $k < $len; $k++)
1732 $uni += (ord($username[$pos + $k]) - 128) * pow(2, ($i - $k) * 6);
1735 break;
1739 if ($len == 0)
1741 return 'WRONG_DATA';
1744 foreach ($prohibited as $pval)
1746 if ($uni >= $pval[0] && $uni <= $pval[1])
1748 $result = false;
1749 break 2;
1753 $pos = $pos + $len;
1756 if (!$result)
1758 return 'WRONG_DATA';
1761 return false;
1765 * Remove avatar
1767 function avatar_delete($mode, $row, $clean_db = false)
1769 // Check if the users avatar is actually *not* a group avatar
1770 if ($mode == 'user')
1772 if (strpos($row['user_avatar'], 'g') === 0 || (((int)$row['user_avatar'] !== 0) && ((int)$row['user_avatar'] !== (int)$row['user_id'])))
1774 return false;
1778 if ($clean_db)
1780 avatar_remove_db($row[$mode . '_avatar']);
1782 $filename = get_avatar_filename($row[$mode . '_avatar']);
1783 if (file_exists(PHPBB_ROOT_PATH . phpbb::$config['avatar_path'] . '/' . $filename))
1785 @unlink(PHPBB_ROOT_PATH . phpbb::$config['avatar_path'] . '/' . $filename);
1786 return true;
1789 return false;
1793 * Remote avatar linkage
1795 function avatar_remote($data, &$error)
1797 if (!preg_match('#^(http|https|ftp)://#i', $data['remotelink']))
1799 $data['remotelink'] = 'http://' . $data['remotelink'];
1801 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']))
1803 $error[] = phpbb::$user->lang['AVATAR_URL_INVALID'];
1804 return false;
1807 // Make sure getimagesize works...
1808 if (($image_data = @getimagesize($data['remotelink'])) === false && (empty($data['width']) || empty($data['height'])))
1810 $error[] = phpbb::$user->lang['UNABLE_GET_IMAGE_SIZE'];
1811 return false;
1814 if (!empty($image_data) && ($image_data[0] < 2 || $image_data[1] < 2))
1816 $error[] = phpbb::$user->lang['AVATAR_NO_SIZE'];
1817 return false;
1820 $width = ($data['width'] && $data['height']) ? $data['width'] : $image_data[0];
1821 $height = ($data['width'] && $data['height']) ? $data['height'] : $image_data[1];
1823 if ($width < 2 || $height < 2)
1825 $error[] = phpbb::$user->lang['AVATAR_NO_SIZE'];
1826 return false;
1829 // Check image type
1830 include_once(PHPBB_ROOT_PATH . 'includes/functions_upload.' . PHP_EXT);
1831 $types = fileupload::image_types();
1832 $extension = strtolower(filespec::get_extension($data['remotelink']));
1834 if (!empty($image_data) && (!isset($types[$image_data[2]]) || !in_array($extension, $types[$image_data[2]])))
1836 if (!isset($types[$image_data[2]]))
1838 $error[] = phpbb::$user->lang['UNABLE_GET_IMAGE_SIZE'];
1840 else
1842 $error[] = sprintf(phpbb::$user->lang['IMAGE_FILETYPE_MISMATCH'], $types[$image_data[2]][0], $extension);
1844 return false;
1847 if (phpbb::$config['avatar_max_width'] || phpbb::$config['avatar_max_height'])
1849 if ($width > phpbb::$config['avatar_max_width'] || $height > phpbb::$config['avatar_max_height'])
1851 $error[] = sprintf(phpbb::$user->lang['AVATAR_WRONG_SIZE'], phpbb::$config['avatar_min_width'], phpbb::$config['avatar_min_height'], phpbb::$config['avatar_max_width'], phpbb::$config['avatar_max_height'], $width, $height);
1852 return false;
1856 if (phpbb::$config['avatar_min_width'] || phpbb::$config['avatar_min_height'])
1858 if ($width < phpbb::$config['avatar_min_width'] || $height < phpbb::$config['avatar_min_height'])
1860 $error[] = sprintf(phpbb::$user->lang['AVATAR_WRONG_SIZE'], phpbb::$config['avatar_min_width'], phpbb::$config['avatar_min_height'], phpbb::$config['avatar_max_width'], phpbb::$config['avatar_max_height'], $width, $height);
1861 return false;
1865 return array(AVATAR_REMOTE, $data['remotelink'], $width, $height);
1869 * Avatar upload using the upload class
1871 function avatar_upload($data, &$error)
1873 // Init upload class
1874 include_once(PHPBB_ROOT_PATH . 'includes/functions_upload.' . PHP_EXT);
1875 $upload = new fileupload('AVATAR_', array('jpg', 'jpeg', 'gif', 'png'), phpbb::$config['avatar_filesize'], phpbb::$config['avatar_min_width'], phpbb::$config['avatar_min_height'], phpbb::$config['avatar_max_width'], phpbb::$config['avatar_max_height'], explode('|', phpbb::$config['mime_triggers']));
1877 if (!empty($_FILES['uploadfile']['name']))
1879 $file = $upload->form_upload('uploadfile');
1881 else
1883 $file = $upload->remote_upload($data['uploadurl']);
1886 $prefix = phpbb::$config['avatar_salt'] . '_';
1887 $file->clean_filename('avatar', $prefix, $data['user_id']);
1889 $destination = phpbb::$config['avatar_path'];
1891 // Adjust destination path (no trailing slash)
1892 if (substr($destination, -1, 1) == '/' || substr($destination, -1, 1) == '\\')
1894 $destination = substr($destination, 0, -1);
1897 $destination = str_replace(array('../', '..\\', './', '.\\'), '', $destination);
1898 if ($destination && ($destination[0] == '/' || $destination[0] == "\\"))
1900 $destination = '';
1903 // Move file and overwrite any existing image
1904 $file->move_file($destination, true);
1906 if (sizeof($file->error))
1908 $file->remove();
1909 $error = array_merge($error, $file->error);
1912 return array(AVATAR_UPLOAD, $data['user_id'] . '_' . time() . '.' . $file->get('extension'), $file->get('width'), $file->get('height'));
1916 * Generates avatar filename from the database entry
1918 function get_avatar_filename($avatar_entry)
1920 if ($avatar_entry[0] === 'g')
1922 $avatar_group = true;
1923 $avatar_entry = substr($avatar_entry, 1);
1925 else
1927 $avatar_group = false;
1929 $ext = substr(strrchr($avatar_entry, '.'), 1);
1930 $avatar_entry = intval($avatar_entry);
1931 return phpbb::$config['avatar_salt'] . '_' . (($avatar_group) ? 'g' : '') . $avatar_entry . '.' . $ext;
1935 * Avatar Gallery
1937 function avatar_gallery($category, $avatar_select, $items_per_column, $block_var = 'avatar_row')
1939 $avatar_list = array();
1941 $path = PHPBB_ROOT_PATH . phpbb::$config['avatar_gallery_path'];
1943 if (!file_exists($path) || !is_dir($path))
1945 $avatar_list = array(phpbb::$user->lang['NO_AVATAR_CATEGORY'] => array());
1947 else
1949 // Collect images
1950 $dp = @opendir($path);
1952 if (!$dp)
1954 return array(phpbb::$user->lang['NO_AVATAR_CATEGORY'] => array());
1957 while (($file = readdir($dp)) !== false)
1959 if ($file[0] != '.' && preg_match('#^[^&"\'<>]+$#i', $file) && is_dir("$path/$file"))
1961 $avatar_row_count = $avatar_col_count = 0;
1963 if ($dp2 = @opendir("$path/$file"))
1965 while (($sub_file = readdir($dp2)) !== false)
1967 if (preg_match('#^[^&\'"<>]+\.(?:gif|png|jpe?g)$#i', $sub_file))
1969 $avatar_list[$file][$avatar_row_count][$avatar_col_count] = array(
1970 'file' => "$file/$sub_file",
1971 'filename' => $sub_file,
1972 'name' => ucfirst(str_replace('_', ' ', preg_replace('#^(.*)\..*$#', '\1', $sub_file))),
1974 $avatar_col_count++;
1975 if ($avatar_col_count == $items_per_column)
1977 $avatar_row_count++;
1978 $avatar_col_count = 0;
1982 closedir($dp2);
1986 closedir($dp);
1989 if (!sizeof($avatar_list))
1991 $avatar_list = array(phpbb::$user->lang['NO_AVATAR_CATEGORY'] => array());
1994 @ksort($avatar_list);
1996 $category = (!$category) ? key($avatar_list) : $category;
1997 $avatar_categories = array_keys($avatar_list);
1999 $s_category_options = '';
2000 foreach ($avatar_categories as $cat)
2002 $s_category_options .= '<option value="' . $cat . '"' . (($cat == $category) ? ' selected="selected"' : '') . '>' . $cat . '</option>';
2005 phpbb::$template->assign_vars(array(
2006 'S_AVATARS_ENABLED' => true,
2007 'S_IN_AVATAR_GALLERY' => true,
2008 'S_CAT_OPTIONS' => $s_category_options,
2011 $avatar_list = (isset($avatar_list[$category])) ? $avatar_list[$category] : array();
2013 foreach ($avatar_list as $avatar_row_ary)
2015 phpbb::$template->assign_block_vars($block_var, array());
2017 foreach ($avatar_row_ary as $avatar_col_ary)
2019 phpbb::$template->assign_block_vars($block_var . '.avatar_column', array(
2020 'AVATAR_IMAGE' => PHPBB_ROOT_PATH . phpbb::$config['avatar_gallery_path'] . '/' . $avatar_col_ary['file'],
2021 'AVATAR_NAME' => $avatar_col_ary['name'],
2022 'AVATAR_FILE' => $avatar_col_ary['filename'],
2025 phpbb::$template->assign_block_vars($block_var . '.avatar_option_column', array(
2026 'AVATAR_IMAGE' => PHPBB_ROOT_PATH . phpbb::$config['avatar_gallery_path'] . '/' . $avatar_col_ary['file'],
2027 'S_OPTIONS_AVATAR' => $avatar_col_ary['filename'],
2032 return $avatar_list;
2037 * Tries to (re-)establish avatar dimensions
2039 function avatar_get_dimensions($avatar, $avatar_type, &$error, $current_x = 0, $current_y = 0)
2041 switch ($avatar_type)
2043 case AVATAR_REMOTE :
2044 break;
2046 case AVATAR_UPLOAD :
2047 $avatar = PHPBB_ROOT_PATH . phpbb::$config['avatar_path'] . '/' . get_avatar_filename($avatar);
2048 break;
2050 case AVATAR_GALLERY :
2051 $avatar = PHPBB_ROOT_PATH . phpbb::$config['avatar_gallery_path'] . '/' . $avatar ;
2052 break;
2055 // Make sure getimagesize works...
2056 if (($image_data = @getimagesize($avatar)) === false)
2058 $error[] = phpbb::$user->lang['UNABLE_GET_IMAGE_SIZE'];
2059 return false;
2062 if ($image_data[0] < 2 || $image_data[1] < 2)
2064 $error[] = phpbb::$user->lang['AVATAR_NO_SIZE'];
2065 return false;
2068 // try to maintain ratio
2069 if (!(empty($current_x) && empty($current_y)))
2071 if ($current_x != 0)
2073 $image_data[1] = (int) floor(($current_x / $image_data[0]) * $image_data[1]);
2074 $image_data[1] = min(phpbb::$config['avatar_max_height'], $image_data[1]);
2075 $image_data[1] = max(phpbb::$config['avatar_min_height'], $image_data[1]);
2077 if ($current_y != 0)
2079 $image_data[0] = (int) floor(($current_y / $image_data[1]) * $image_data[0]);
2080 $image_data[0] = min(phpbb::$config['avatar_max_width'], $image_data[1]);
2081 $image_data[0] = max(phpbb::$config['avatar_min_width'], $image_data[1]);
2084 return array($image_data[0], $image_data[1]);
2088 * Uploading/Changing user avatar
2090 function avatar_process_user(&$error, $custom_userdata = false)
2092 $data = array(
2093 'uploadurl' => request_var('uploadurl', ''),
2094 'remotelink' => request_var('remotelink', ''),
2095 'width' => request_var('width', 0),
2096 'height' => request_var('height', 0),
2099 $error = validate_data($data, array(
2100 'uploadurl' => array('string', true, 5, 255),
2101 'remotelink' => array('string', true, 5, 255),
2102 'width' => array('string', true, 1, 3),
2103 'height' => array('string', true, 1, 3),
2106 if (sizeof($error))
2108 return false;
2111 $sql_ary = array();
2113 if ($custom_userdata === false)
2115 $userdata = &phpbb::$user->data;
2117 else
2119 $userdata = &$custom_userdata;
2122 $data['user_id'] = $userdata['user_id'];
2123 $change_avatar = ($custom_userdata === false) ? phpbb::$acl->acl_get('u_chgavatar') : true;
2124 $avatar_select = basename(request_var('avatar_select', ''));
2126 // Can we upload?
2127 $can_upload = (phpbb::$config['allow_avatar_upload'] && file_exists(PHPBB_ROOT_PATH . phpbb::$config['avatar_path']) && @is_writable(PHPBB_ROOT_PATH . phpbb::$config['avatar_path']) && $change_avatar && (@ini_get('file_uploads') || strtolower(@ini_get('file_uploads')) == 'on')) ? true : false;
2129 if ((!empty($_FILES['uploadfile']['name']) || $data['uploadurl']) && $can_upload)
2131 list($sql_ary['user_avatar_type'], $sql_ary['user_avatar'], $sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = avatar_upload($data, $error);
2133 else if ($data['remotelink'] && $change_avatar && phpbb::$config['allow_avatar_remote'])
2135 list($sql_ary['user_avatar_type'], $sql_ary['user_avatar'], $sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = avatar_remote($data, $error);
2137 else if ($avatar_select && $change_avatar && phpbb::$config['allow_avatar_local'])
2139 $category = basename(request_var('category', ''));
2141 $sql_ary['user_avatar_type'] = AVATAR_GALLERY;
2142 $sql_ary['user_avatar'] = $avatar_select;
2144 // check avatar gallery
2145 if (!is_dir(PHPBB_ROOT_PATH . phpbb::$config['avatar_gallery_path'] . '/' . $category))
2147 $sql_ary['user_avatar'] = '';
2148 $sql_ary['user_avatar_type'] = $sql_ary['user_avatar_width'] = $sql_ary['user_avatar_height'] = 0;
2150 else
2152 list($sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = getimagesize(PHPBB_ROOT_PATH . phpbb::$config['avatar_gallery_path'] . '/' . $category . '/' . $sql_ary['user_avatar']);
2153 $sql_ary['user_avatar'] = $category . '/' . $sql_ary['user_avatar'];
2156 else if (phpbb_request::is_set_post('delete') && $change_avatar)
2158 $sql_ary['user_avatar'] = '';
2159 $sql_ary['user_avatar_type'] = $sql_ary['user_avatar_width'] = $sql_ary['user_avatar_height'] = 0;
2161 else if (!empty($userdata['user_avatar']))
2163 // Only update the dimensions
2165 if (empty($data['width']) || empty($data['height']))
2167 if ($dims = avatar_get_dimensions($userdata['user_avatar'], $userdata['user_avatar_type'], $error, $data['width'], $data['height']))
2169 list($guessed_x, $guessed_y) = $dims;
2170 if (empty($data['width']))
2172 $data['width'] = $guessed_x;
2174 if (empty($data['height']))
2176 $data['height'] = $guessed_y;
2180 if ((phpbb::$config['avatar_max_width'] || phpbb::$config['avatar_max_height']) &&
2181 (($data['width'] != $userdata['user_avatar_width']) || $data['height'] != $userdata['user_avatar_height']))
2183 if ($data['width'] > phpbb::$config['avatar_max_width'] || $data['height'] > phpbb::$config['avatar_max_height'])
2185 $error[] = sprintf(phpbb::$user->lang['AVATAR_WRONG_SIZE'], phpbb::$config['avatar_min_width'], phpbb::$config['avatar_min_height'], phpbb::$config['avatar_max_width'], phpbb::$config['avatar_max_height'], $data['width'], $data['height']);
2189 if (!sizeof($error))
2191 if (phpbb::$config['avatar_min_width'] || phpbb::$config['avatar_min_height'])
2193 if ($data['width'] < phpbb::$config['avatar_min_width'] || $data['height'] < phpbb::$config['avatar_min_height'])
2195 $error[] = sprintf(phpbb::$user->lang['AVATAR_WRONG_SIZE'], phpbb::$config['avatar_min_width'], phpbb::$config['avatar_min_height'], phpbb::$config['avatar_max_width'], phpbb::$config['avatar_max_height'], $data['width'], $data['height']);
2200 if (!sizeof($error))
2202 $sql_ary['user_avatar_width'] = $data['width'];
2203 $sql_ary['user_avatar_height'] = $data['height'];
2207 if (!sizeof($error))
2209 // Do we actually have any data to update?
2210 if (sizeof($sql_ary))
2212 $ext_new = $ext_old = '';
2213 if (isset($sql_ary['user_avatar']))
2215 $userdata = ($custom_userdata === false) ? phpbb::$user->data : $custom_userdata;
2216 $ext_new = (empty($sql_ary['user_avatar'])) ? '' : substr(strrchr($sql_ary['user_avatar'], '.'), 1);
2217 $ext_old = (empty($userdata['user_avatar'])) ? '' : substr(strrchr($userdata['user_avatar'], '.'), 1);
2219 if ($userdata['user_avatar_type'] == AVATAR_UPLOAD)
2221 // Delete old avatar if present
2222 if ((!empty($userdata['user_avatar']) && empty($sql_ary['user_avatar']))
2223 || ( !empty($userdata['user_avatar']) && !empty($sql_ary['user_avatar']) && $ext_new !== $ext_old))
2225 avatar_delete('user', $userdata);
2230 $sql = 'UPDATE ' . USERS_TABLE . '
2231 SET ' . phpbb::$db->sql_build_array('UPDATE', $sql_ary) . '
2232 WHERE user_id = ' . (($custom_userdata === false) ? phpbb::$user->data['user_id'] : $custom_userdata['user_id']);
2233 phpbb::$db->sql_query($sql);
2238 return (sizeof($error)) ? false : true;
2242 // Usergroup functions
2246 * Add or edit a group. If we're editing a group we only update user
2247 * parameters such as rank, etc. if they are changed
2249 function group_create(&$group_id, $type, $name, $desc, $group_attributes, $allow_desc_bbcode = false, $allow_desc_urls = false, $allow_desc_smilies = false)
2251 global $file_upload;
2253 $error = array();
2254 $attribute_ary = array(
2255 'group_colour' => 'string',
2256 'group_rank' => 'int',
2257 'group_avatar' => 'string',
2258 'group_avatar_type' => 'int',
2259 'group_avatar_width' => 'int',
2260 'group_avatar_height' => 'int',
2262 'group_receive_pm' => 'int',
2263 'group_legend' => 'int',
2264 'group_message_limit' => 'int',
2265 'group_max_recipients' => 'int',
2267 'group_founder_manage' => 'int',
2270 // Those are group-only attributes
2271 $group_only_ary = array('group_receive_pm', 'group_legend', 'group_message_limit', 'group_max_recipients', 'group_founder_manage');
2273 // Check data. Limit group name length.
2274 if (!utf8_strlen($name) || utf8_strlen($name) > 60)
2276 $error[] = (!utf8_strlen($name)) ? phpbb::$user->lang['GROUP_ERR_USERNAME'] : phpbb::$user->lang['GROUP_ERR_USER_LONG'];
2279 $err = group_validate_groupname($group_id, $name);
2280 if (!empty($err))
2282 $error[] = phpbb::$user->lang[$err];
2285 if (!in_array($type, array(GROUP_OPEN, GROUP_CLOSED, GROUP_HIDDEN, GROUP_SPECIAL, GROUP_FREE)))
2287 $error[] = phpbb::$user->lang['GROUP_ERR_TYPE'];
2290 if (!sizeof($error))
2292 $user_ary = array();
2293 $sql_ary = array(
2294 'group_name' => (string) $name,
2295 'group_name_clean' => (string) utf8_clean_string($name),
2296 'group_desc' => (string) $desc,
2297 'group_desc_uid' => '',
2298 'group_desc_bitfield' => '',
2299 'group_type' => (int) $type,
2302 // Parse description
2303 if ($desc)
2305 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);
2308 if (sizeof($group_attributes))
2310 foreach ($attribute_ary as $attribute => $_type)
2312 if (isset($group_attributes[$attribute]))
2314 settype($group_attributes[$attribute], $_type);
2315 $sql_ary[$attribute] = $group_attributes[$attribute];
2320 // Setting the log message before we set the group id (if group gets added)
2321 $log = ($group_id) ? 'LOG_GROUP_UPDATED' : 'LOG_GROUP_CREATED';
2323 $query = '';
2325 if ($group_id)
2327 $sql = 'SELECT user_id
2328 FROM ' . USERS_TABLE . '
2329 WHERE group_id = ' . $group_id;
2330 $result = phpbb::$db->sql_query($sql);
2332 while ($row = phpbb::$db->sql_fetchrow($result))
2334 $user_ary[] = $row['user_id'];
2336 phpbb::$db->sql_freeresult($result);
2338 if (isset($sql_ary['group_avatar']) && !$sql_ary['group_avatar'])
2340 remove_default_avatar($group_id, $user_ary);
2342 if (isset($sql_ary['group_rank']) && !$sql_ary['group_rank'])
2344 remove_default_rank($group_id, $user_ary);
2347 $sql = 'UPDATE ' . GROUPS_TABLE . '
2348 SET ' . phpbb::$db->sql_build_array('UPDATE', $sql_ary) . "
2349 WHERE group_id = $group_id";
2350 phpbb::$db->sql_query($sql);
2352 // Since we may update the name too, we need to do this on other tables too...
2353 $sql = 'UPDATE ' . MODERATOR_CACHE_TABLE . "
2354 SET group_name = '" . phpbb::$db->sql_escape($sql_ary['group_name']) . "'
2355 WHERE group_id = $group_id";
2356 phpbb::$db->sql_query($sql);
2358 else
2360 $sql = 'INSERT INTO ' . GROUPS_TABLE . ' ' . phpbb::$db->sql_build_array('INSERT', $sql_ary);
2361 phpbb::$db->sql_query($sql);
2364 if (!$group_id)
2366 $group_id = phpbb::$db->sql_nextid();
2367 if (isset($sql_ary['group_avatar_type']) && $sql_ary['group_avatar_type'] == AVATAR_UPLOAD)
2369 group_correct_avatar($group_id, $sql_ary['group_avatar']);
2373 // Set user attributes
2374 $sql_ary = array();
2375 if (sizeof($group_attributes))
2377 foreach ($attribute_ary as $attribute => $_type)
2379 if (isset($group_attributes[$attribute]) && !in_array($attribute, $group_only_ary))
2381 // If we are about to set an avatar, we will not overwrite user avatars if no group avatar is set...
2382 if (strpos($attribute, 'group_avatar') === 0 && !$group_attributes[$attribute])
2384 continue;
2387 $sql_ary[$attribute] = $group_attributes[$attribute];
2392 if (sizeof($sql_ary) && sizeof($user_ary))
2394 group_set_user_default($group_id, $user_ary, $sql_ary);
2397 $name = ($type == GROUP_SPECIAL) ? phpbb::$user->lang['G_' . $name] : $name;
2398 add_log('admin', $log, $name);
2400 group_update_listings($group_id);
2403 return (sizeof($error)) ? $error : false;
2408 * Changes a group avatar's filename to conform to the naming scheme
2410 function group_correct_avatar($group_id, $old_entry)
2412 $group_id = (int)$group_id;
2413 $ext = substr(strrchr($old_entry, '.'), 1);
2414 $old_filename = get_avatar_filename($old_entry);
2415 $new_filename = phpbb::$config['avatar_salt'] . "_g$group_id.$ext";
2416 $new_entry = 'g' . $group_id . '_' . substr(time(), -5) . ".$ext";
2418 $avatar_path = PHPBB_ROOT_PATH . phpbb::$config['avatar_path'];
2419 if (@rename($avatar_path . '/'. $old_filename, $avatar_path . '/' . $new_filename))
2421 $sql = 'UPDATE ' . GROUPS_TABLE . '
2422 SET group_avatar = \'' . phpbb::$db->sql_escape($new_entry) . "'
2423 WHERE group_id = $group_id";
2424 phpbb::$db->sql_query($sql);
2430 * Remove avatar also for users not having the group as default
2432 function avatar_remove_db($avatar_name)
2434 $sql = 'UPDATE ' . USERS_TABLE . "
2435 SET user_avatar = '',
2436 user_avatar_type = 0
2437 WHERE user_avatar = '" . phpbb::$db->sql_escape($avatar_name) . '\'';
2438 phpbb::$db->sql_query($sql);
2443 * Group Delete
2445 function group_delete($group_id, $group_name = false)
2447 if (!$group_name)
2449 $group_name = get_group_name($group_id);
2452 $start = 0;
2456 $user_id_ary = $username_ary = array();
2458 // Batch query for group members, call group_user_del
2459 $sql = 'SELECT u.user_id, u.username
2460 FROM ' . USER_GROUP_TABLE . ' ug, ' . USERS_TABLE . " u
2461 WHERE ug.group_id = $group_id
2462 AND u.user_id = ug.user_id";
2463 $result = phpbb::$db->sql_query_limit($sql, 200, $start);
2465 if ($row = phpbb::$db->sql_fetchrow($result))
2469 $user_id_ary[] = $row['user_id'];
2470 $username_ary[] = $row['username'];
2472 $start++;
2474 while ($row = phpbb::$db->sql_fetchrow($result));
2476 group_user_del($group_id, $user_id_ary, $username_ary, $group_name);
2478 else
2480 $start = 0;
2482 phpbb::$db->sql_freeresult($result);
2484 while ($start);
2486 // Delete group
2487 $sql = 'DELETE FROM ' . GROUPS_TABLE . "
2488 WHERE group_id = $group_id";
2489 phpbb::$db->sql_query($sql);
2491 // Delete auth entries from the groups table
2492 $sql = 'DELETE FROM ' . ACL_GROUPS_TABLE . "
2493 WHERE group_id = $group_id";
2494 phpbb::$db->sql_query($sql);
2496 // Re-cache moderators
2497 if (!function_exists('cache_moderators'))
2499 include(PHPBB_ROOT_PATH . 'includes/functions_admin.' . PHP_EXT);
2502 cache_moderators();
2504 add_log('admin', 'LOG_GROUP_DELETE', $group_name);
2506 // Return false - no error
2507 return false;
2511 * Add user(s) to group
2513 * @return mixed false if no errors occurred, else the user lang string for the relevant error, for example 'NO_USER'
2515 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)
2517 // We need both username and user_id info
2518 $result = user_get_id_name($user_id_ary, $username_ary);
2520 if (!sizeof($user_id_ary) || $result !== false)
2522 return 'NO_USER';
2525 // Remove users who are already members of this group
2526 $sql = 'SELECT user_id, group_leader
2527 FROM ' . USER_GROUP_TABLE . '
2528 WHERE ' . phpbb::$db->sql_in_set('user_id', $user_id_ary) . "
2529 AND group_id = $group_id";
2530 $result = phpbb::$db->sql_query($sql);
2532 $add_id_ary = $update_id_ary = array();
2533 while ($row = phpbb::$db->sql_fetchrow($result))
2535 $add_id_ary[] = (int) $row['user_id'];
2537 if ($leader && !$row['group_leader'])
2539 $update_id_ary[] = (int) $row['user_id'];
2542 phpbb::$db->sql_freeresult($result);
2544 // Do all the users exist in this group?
2545 $add_id_ary = array_diff($user_id_ary, $add_id_ary);
2547 // If we have no users
2548 if (!sizeof($add_id_ary) && !sizeof($update_id_ary))
2550 return 'GROUP_USERS_EXIST';
2553 phpbb::$db->sql_transaction('begin');
2555 // Insert the new users
2556 if (sizeof($add_id_ary))
2558 $sql_ary = array();
2560 foreach ($add_id_ary as $user_id)
2562 $sql_ary[] = array(
2563 'user_id' => (int) $user_id,
2564 'group_id' => (int) $group_id,
2565 'group_leader' => (int) $leader,
2566 'user_pending' => (int) $pending,
2570 phpbb::$db->sql_multi_insert(USER_GROUP_TABLE, $sql_ary);
2573 if (sizeof($update_id_ary))
2575 $sql = 'UPDATE ' . USER_GROUP_TABLE . '
2576 SET group_leader = 1
2577 WHERE ' . phpbb::$db->sql_in_set('user_id', $update_id_ary) . "
2578 AND group_id = $group_id";
2579 phpbb::$db->sql_query($sql);
2582 if ($default)
2584 group_set_user_default($group_id, $user_id_ary, $group_attributes);
2587 phpbb::$db->sql_transaction('commit');
2589 // Clear permissions cache of relevant users
2590 phpbb::$acl->acl_clear_prefetch($user_id_ary);
2592 if (!$group_name)
2594 $group_name = get_group_name($group_id);
2597 $log = ($leader) ? 'LOG_MODS_ADDED' : 'LOG_USERS_ADDED';
2599 add_log('admin', $log, $group_name, implode(', ', $username_ary));
2601 group_update_listings($group_id);
2603 // Return false - no error
2604 return false;
2608 * Remove a user/s from a given group. When we remove users we update their
2609 * default group_id. We do this by examining which "special" groups they belong
2610 * to. The selection is made based on a reasonable priority system
2612 * @return false if no errors occurred, else the user lang string for the relevant error, for example 'NO_USER'
2614 function group_user_del($group_id, $user_id_ary = false, $username_ary = false, $group_name = false)
2616 if (phpbb::$config['coppa_enable'])
2618 $group_order = array('ADMINISTRATORS', 'GLOBAL_MODERATORS', 'REGISTERED_COPPA', 'REGISTERED', 'BOTS', 'GUESTS');
2620 else
2622 $group_order = array('ADMINISTRATORS', 'GLOBAL_MODERATORS', 'REGISTERED', 'BOTS', 'GUESTS');
2625 // We need both username and user_id info
2626 $result = user_get_id_name($user_id_ary, $username_ary);
2628 if (!sizeof($user_id_ary) || $result !== false)
2630 return 'NO_USER';
2633 $clean_group_order = array_map('utf8_clean_string', $group_order);
2635 $sql = 'SELECT *
2636 FROM ' . GROUPS_TABLE . '
2637 WHERE ' . phpbb::$db->sql_in_set('group_name_clean', $clean_group_order);
2638 $result = phpbb::$db->sql_query($sql);
2640 $group_order_id = $special_group_data = array();
2641 while ($row = phpbb::$db->sql_fetchrow($result))
2643 $group_order_id[$row['group_name']] = $row['group_id'];
2645 $special_group_data[$row['group_id']] = array(
2646 'group_colour' => $row['group_colour'],
2647 'group_rank' => $row['group_rank'],
2650 // Only set the group avatar if one is defined...
2651 if ($row['group_avatar'])
2653 $special_group_data[$row['group_id']] = array_merge($special_group_data[$row['group_id']], array(
2654 'group_avatar' => $row['group_avatar'],
2655 'group_avatar_type' => $row['group_avatar_type'],
2656 'group_avatar_width' => $row['group_avatar_width'],
2657 'group_avatar_height' => $row['group_avatar_height'])
2661 phpbb::$db->sql_freeresult($result);
2663 // 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
2664 $sql = 'SELECT user_id, group_id
2665 FROM ' . USERS_TABLE . '
2666 WHERE ' . phpbb::$db->sql_in_set('user_id', $user_id_ary);
2667 $result = phpbb::$db->sql_query($sql);
2669 $default_groups = array();
2670 while ($row = phpbb::$db->sql_fetchrow($result))
2672 $default_groups[$row['user_id']] = $row['group_id'];
2674 phpbb::$db->sql_freeresult($result);
2676 // What special group memberships exist for these users?
2677 $sql = 'SELECT g.group_id, g.group_name_clean, ug.user_id
2678 FROM ' . USER_GROUP_TABLE . ' ug, ' . GROUPS_TABLE . ' g
2679 WHERE ' . phpbb::$db->sql_in_set('ug.user_id', $user_id_ary) . "
2680 AND g.group_id = ug.group_id
2681 AND g.group_id <> $group_id
2682 AND g.group_type = " . GROUP_SPECIAL . '
2683 ORDER BY ug.user_id, g.group_id';
2684 $result = phpbb::$db->sql_query($sql);
2686 $temp_ary = array();
2687 while ($row = phpbb::$db->sql_fetchrow($result))
2689 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']]))
2691 $temp_ary[$row['user_id']] = $row['group_id'];
2694 phpbb::$db->sql_freeresult($result);
2696 // sql_where_ary holds the new default groups and their users
2697 $sql_where_ary = array();
2698 foreach ($temp_ary as $uid => $gid)
2700 $sql_where_ary[$gid][] = $uid;
2702 unset($temp_ary);
2704 foreach ($special_group_data as $gid => $default_data_ary)
2706 if (isset($sql_where_ary[$gid]) && sizeof($sql_where_ary[$gid]))
2708 remove_default_rank($gid, $sql_where_ary[$gid]);
2709 remove_default_avatar($group_id, $sql_where_ary[$gid]);
2710 group_set_user_default($gid, $sql_where_ary[$gid], $default_data_ary);
2713 unset($special_group_data);
2715 $sql = 'DELETE FROM ' . USER_GROUP_TABLE . "
2716 WHERE group_id = $group_id
2717 AND " . phpbb::$db->sql_in_set('user_id', $user_id_ary);
2718 phpbb::$db->sql_query($sql);
2720 // Clear permissions cache of relevant users
2721 phpbb::$acl->acl_clear_prefetch($user_id_ary);
2723 if (!$group_name)
2725 $group_name = get_group_name($group_id);
2728 $log = 'LOG_GROUP_REMOVE';
2730 add_log('admin', $log, $group_name, implode(', ', $username_ary));
2732 group_update_listings($group_id);
2734 // Return false - no error
2735 return false;
2740 * Removes the group avatar of the default group from the users in user_ids who have that group as default.
2742 function remove_default_avatar($group_id, $user_ids)
2744 if (!is_array($user_ids))
2746 $user_ids = array($user_ids);
2748 if (empty($user_ids))
2750 return false;
2753 $user_ids = array_map('intval', $user_ids);
2755 $sql = 'SELECT *
2756 FROM ' . GROUPS_TABLE . '
2757 WHERE group_id = ' . (int)$group_id;
2758 $result = phpbb::$db->sql_query($sql);
2759 if (!$row = phpbb::$db->sql_fetchrow($result))
2761 phpbb::$db->sql_freeresult($result);
2762 return false;
2764 phpbb::$db->sql_freeresult($result);
2766 $sql = 'UPDATE ' . USERS_TABLE . "
2767 SET user_avatar = '',
2768 user_avatar_type = 0,
2769 user_avatar_width = 0,
2770 user_avatar_height = 0
2771 WHERE group_id = " . (int) $group_id . "
2772 AND user_avatar = '" . phpbb::$db->sql_escape($row['group_avatar']) . "'
2773 AND " . phpbb::$db->sql_in_set('user_id', $user_ids);
2775 phpbb::$db->sql_query($sql);
2779 * Removes the group rank of the default group from the users in user_ids who have that group as default.
2781 function remove_default_rank($group_id, $user_ids)
2783 if (!is_array($user_ids))
2785 $user_ids = array($user_ids);
2787 if (empty($user_ids))
2789 return false;
2792 $user_ids = array_map('intval', $user_ids);
2794 $sql = 'SELECT *
2795 FROM ' . GROUPS_TABLE . '
2796 WHERE group_id = ' . (int)$group_id;
2797 $result = phpbb::$db->sql_query($sql);
2798 if (!$row = phpbb::$db->sql_fetchrow($result))
2800 phpbb::$db->sql_freeresult($result);
2801 return false;
2803 phpbb::$db->sql_freeresult($result);
2805 $sql = 'UPDATE ' . USERS_TABLE . '
2806 SET user_rank = 0
2807 WHERE group_id = ' . (int)$group_id . '
2808 AND user_rank <> 0
2809 AND user_rank = ' . (int)$row['group_rank'] . '
2810 AND ' . phpbb::$db->sql_in_set('user_id', $user_ids);
2811 phpbb::$db->sql_query($sql);
2815 * This is used to promote (to leader), demote or set as default a member/s
2817 function group_user_attributes($action, $group_id, $user_id_ary = false, $username_ary = false, $group_name = false, $group_attributes = false)
2819 // We need both username and user_id info
2820 $result = user_get_id_name($user_id_ary, $username_ary);
2822 if (!sizeof($user_id_ary) || $result !== false)
2824 return 'NO_USERS';
2827 if (!$group_name)
2829 $group_name = get_group_name($group_id);
2832 switch ($action)
2834 case 'demote':
2835 case 'promote':
2837 $sql = 'SELECT user_id FROM ' . USER_GROUP_TABLE . "
2838 WHERE group_id = $group_id
2839 AND user_pending = 1
2840 AND " . phpbb::$db->sql_in_set('user_id', $user_id_ary);
2841 $result = phpbb::$db->sql_query_limit($sql, 1);
2842 $not_empty = (phpbb::$db->sql_fetchrow($result));
2843 phpbb::$db->sql_freeresult($result);
2844 if ($not_empty)
2846 return 'NO_VALID_USERS';
2849 $sql = 'UPDATE ' . USER_GROUP_TABLE . '
2850 SET group_leader = ' . (($action == 'promote') ? 1 : 0) . "
2851 WHERE group_id = $group_id
2852 AND user_pending = 0
2853 AND " . phpbb::$db->sql_in_set('user_id', $user_id_ary);
2854 phpbb::$db->sql_query($sql);
2856 $log = ($action == 'promote') ? 'LOG_GROUP_PROMOTED' : 'LOG_GROUP_DEMOTED';
2857 break;
2859 case 'approve':
2860 // Make sure we only approve those which are pending ;)
2861 $sql = 'SELECT u.user_id, u.user_email, u.username, u.username_clean, u.user_notify_type, u.user_jabber, u.user_lang
2862 FROM ' . USERS_TABLE . ' u, ' . USER_GROUP_TABLE . ' ug
2863 WHERE ug.group_id = ' . $group_id . '
2864 AND ug.user_pending = 1
2865 AND ug.user_id = u.user_id
2866 AND ' . phpbb::$db->sql_in_set('ug.user_id', $user_id_ary);
2867 $result = phpbb::$db->sql_query($sql);
2869 $user_id_ary = $email_users = array();
2870 while ($row = phpbb::$db->sql_fetchrow($result))
2872 $user_id_ary[] = $row['user_id'];
2873 $email_users[] = $row;
2875 phpbb::$db->sql_freeresult($result);
2877 if (!sizeof($user_id_ary))
2879 return false;
2882 $sql = 'UPDATE ' . USER_GROUP_TABLE . "
2883 SET user_pending = 0
2884 WHERE group_id = $group_id
2885 AND " . phpbb::$db->sql_in_set('user_id', $user_id_ary);
2886 phpbb::$db->sql_query($sql);
2888 // Send approved email to users...
2889 include_once(PHPBB_ROOT_PATH . 'includes/functions_messenger.' . PHP_EXT);
2890 $messenger = new messenger();
2892 foreach ($email_users as $row)
2894 $messenger->template('group_approved', $row['user_lang']);
2896 $messenger->to($row['user_email'], $row['username']);
2897 $messenger->im($row['user_jabber'], $row['username']);
2899 $messenger->assign_vars(array(
2900 'USERNAME' => htmlspecialchars_decode($row['username']),
2901 'GROUP_NAME' => htmlspecialchars_decode($group_name),
2902 'U_GROUP' => generate_board_url() . '/ucp.' . PHP_EXT . '?i=groups&mode=membership',
2905 $messenger->send($row['user_notify_type']);
2908 $messenger->save_queue();
2910 $log = 'LOG_USERS_APPROVED';
2911 break;
2913 case 'default':
2914 $sql = 'SELECT user_id, group_id FROM ' . USERS_TABLE . '
2915 WHERE ' . phpbb::$db->sql_in_set('user_id', $user_id_ary, false, true);
2916 $result = phpbb::$db->sql_query($sql);
2918 $groups = array();
2919 while ($row = phpbb::$db->sql_fetchrow($result))
2921 if (!isset($groups[$row['group_id']]))
2923 $groups[$row['group_id']] = array();
2925 $groups[$row['group_id']][] = $row['user_id'];
2927 phpbb::$db->sql_freeresult($result);
2929 foreach ($groups as $gid => $uids)
2931 remove_default_rank($gid, $uids);
2932 remove_default_avatar($gid, $uids);
2934 group_set_user_default($group_id, $user_id_ary, $group_attributes);
2935 $log = 'LOG_GROUP_DEFAULTS';
2936 break;
2939 // Clear permissions cache of relevant users
2940 phpbb::$acl->acl_clear_prefetch($user_id_ary);
2942 add_log('admin', $log, $group_name, implode(', ', $username_ary));
2944 group_update_listings($group_id);
2946 return false;
2950 * A small version of validate_username to check for a group name's existence. To be called directly.
2952 function group_validate_groupname($group_id, $group_name)
2954 $group_name = utf8_clean_string($group_name);
2956 if (!empty($group_id))
2958 $sql = 'SELECT group_name_clean
2959 FROM ' . GROUPS_TABLE . '
2960 WHERE group_id = ' . (int) $group_id;
2961 $result = phpbb::$db->sql_query($sql);
2962 $row = phpbb::$db->sql_fetchrow($result);
2963 phpbb::$db->sql_freeresult($result);
2965 if (!$row)
2967 return false;
2970 $allowed_groupname = utf8_clean_string($row['group_name']);
2972 if ($allowed_groupname == $group_name)
2974 return false;
2978 $sql = 'SELECT group_name
2979 FROM ' . GROUPS_TABLE . "
2980 WHERE group_name_clean = '" . phpbb::$db->sql_escape(utf8_clean_string($group_name)) . "'";
2981 $result = phpbb::$db->sql_query($sql);
2982 $row = phpbb::$db->sql_fetchrow($result);
2983 phpbb::$db->sql_freeresult($result);
2985 if ($row)
2987 return 'GROUP_NAME_TAKEN';
2990 return false;
2994 * Set users default group
2996 * @access private
2998 function group_set_user_default($group_id, $user_id_ary, $group_attributes = false, $update_listing = false)
3000 if (empty($user_id_ary))
3002 return;
3005 $attribute_ary = array(
3006 'group_colour' => 'string',
3007 'group_rank' => 'int',
3008 'group_avatar' => 'string',
3009 'group_avatar_type' => 'int',
3010 'group_avatar_width' => 'int',
3011 'group_avatar_height' => 'int',
3014 $sql_ary = array(
3015 'group_id' => $group_id
3018 // Were group attributes passed to the function? If not we need to obtain them
3019 if ($group_attributes === false)
3021 $sql = 'SELECT ' . implode(', ', array_keys($attribute_ary)) . '
3022 FROM ' . GROUPS_TABLE . "
3023 WHERE group_id = $group_id";
3024 $result = phpbb::$db->sql_query($sql);
3025 $group_attributes = phpbb::$db->sql_fetchrow($result);
3026 phpbb::$db->sql_freeresult($result);
3029 foreach ($attribute_ary as $attribute => $type)
3031 if (isset($group_attributes[$attribute]))
3033 // 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
3034 if ((strpos($attribute, 'group_avatar') === 0 || strpos($attribute, 'group_rank') === 0) && !$group_attributes[$attribute])
3036 continue;
3039 settype($group_attributes[$attribute], $type);
3040 $sql_ary[str_replace('group_', 'user_', $attribute)] = $group_attributes[$attribute];
3044 // Before we update the user attributes, we will make a list of those having now the group avatar assigned
3045 if (isset($sql_ary['user_avatar']))
3047 // Ok, get the original avatar data from users having an uploaded one (we need to remove these from the filesystem)
3048 $sql = 'SELECT user_id, group_id, user_avatar
3049 FROM ' . USERS_TABLE . '
3050 WHERE ' . phpbb::$db->sql_in_set('user_id', $user_id_ary) . '
3051 AND user_avatar_type = ' . AVATAR_UPLOAD;
3052 $result = phpbb::$db->sql_query($sql);
3054 while ($row = phpbb::$db->sql_fetchrow($result))
3056 avatar_delete('user', $row);
3058 phpbb::$db->sql_freeresult($result);
3060 else
3062 unset($sql_ary['user_avatar_type']);
3063 unset($sql_ary['user_avatar_height']);
3064 unset($sql_ary['user_avatar_width']);
3067 $sql = 'UPDATE ' . USERS_TABLE . ' SET ' . phpbb::$db->sql_build_array('UPDATE', $sql_ary) . '
3068 WHERE ' . phpbb::$db->sql_in_set('user_id', $user_id_ary);
3069 phpbb::$db->sql_query($sql);
3071 if (isset($sql_ary['user_colour']))
3073 // Update any cached colour information for these users
3074 $sql = 'UPDATE ' . FORUMS_TABLE . " SET forum_last_poster_colour = '" . phpbb::$db->sql_escape($sql_ary['user_colour']) . "'
3075 WHERE " . phpbb::$db->sql_in_set('forum_last_poster_id', $user_id_ary);
3076 phpbb::$db->sql_query($sql);
3078 $sql = 'UPDATE ' . TOPICS_TABLE . " SET topic_first_poster_colour = '" . phpbb::$db->sql_escape($sql_ary['user_colour']) . "'
3079 WHERE " . phpbb::$db->sql_in_set('topic_poster', $user_id_ary);
3080 phpbb::$db->sql_query($sql);
3082 $sql = 'UPDATE ' . TOPICS_TABLE . " SET topic_last_poster_colour = '" . phpbb::$db->sql_escape($sql_ary['user_colour']) . "'
3083 WHERE " . phpbb::$db->sql_in_set('topic_last_poster_id', $user_id_ary);
3084 phpbb::$db->sql_query($sql);
3086 if (in_array(phpbb::$config['newest_user_id'], $user_id_ary))
3088 set_config('newest_user_colour', $sql_ary['user_colour'], true);
3092 if ($update_listing)
3094 group_update_listings($group_id);
3099 * Get group name
3101 function get_group_name($group_id)
3103 $sql = 'SELECT group_name, group_type
3104 FROM ' . GROUPS_TABLE . '
3105 WHERE group_id = ' . (int) $group_id;
3106 $result = phpbb::$db->sql_query($sql);
3107 $row = phpbb::$db->sql_fetchrow($result);
3108 phpbb::$db->sql_freeresult($result);
3110 if (!$row)
3112 return '';
3115 return ($row['group_type'] == GROUP_SPECIAL) ? phpbb::$user->lang['G_' . $row['group_name']] : $row['group_name'];
3119 * Obtain either the members of a specified group, the groups the specified user is subscribed to
3120 * or checking if a specified user is in a specified group. This function does not return pending memberships.
3122 * Note: Never use this more than once... first group your users/groups
3124 function group_memberships($group_id_ary = false, $user_id_ary = false, $return_bool = false)
3126 if (!$group_id_ary && !$user_id_ary)
3128 return true;
3131 if ($user_id_ary)
3133 $user_id_ary = (!is_array($user_id_ary)) ? array($user_id_ary) : $user_id_ary;
3136 if ($group_id_ary)
3138 $group_id_ary = (!is_array($group_id_ary)) ? array($group_id_ary) : $group_id_ary;
3141 $sql = 'SELECT ug.*, u.username, u.username_clean, u.user_email
3142 FROM ' . USER_GROUP_TABLE . ' ug, ' . USERS_TABLE . ' u
3143 WHERE ug.user_id = u.user_id
3144 AND ug.user_pending = 0 AND ';
3146 if ($group_id_ary)
3148 $sql .= ' ' . phpbb::$db->sql_in_set('ug.group_id', $group_id_ary);
3151 if ($user_id_ary)
3153 $sql .= ($group_id_ary) ? ' AND ' : ' ';
3154 $sql .= phpbb::$db->sql_in_set('ug.user_id', $user_id_ary);
3157 $result = ($return_bool) ? phpbb::$db->sql_query_limit($sql, 1) : phpbb::$db->sql_query($sql);
3159 $row = phpbb::$db->sql_fetchrow($result);
3161 if ($return_bool)
3163 phpbb::$db->sql_freeresult($result);
3164 return ($row) ? true : false;
3167 if (!$row)
3169 return false;
3172 $return = array();
3176 $return[] = $row;
3178 while ($row = phpbb::$db->sql_fetchrow($result));
3180 phpbb::$db->sql_freeresult($result);
3182 return $return;
3186 * Re-cache moderators and foes if group has a_ or m_ permissions
3188 function group_update_listings($group_id)
3190 $hold_ary = phpbb::$acl->acl_group_raw_data($group_id, array('a_', 'm_'));
3192 if (!sizeof($hold_ary))
3194 return;
3197 $mod_permissions = $admin_permissions = false;
3199 foreach ($hold_ary as $g_id => $forum_ary)
3201 foreach ($forum_ary as $forum_id => $auth_ary)
3203 foreach ($auth_ary as $auth_option => $setting)
3205 if ($mod_permissions && $admin_permissions)
3207 break 3;
3210 if ($setting != phpbb::ACL_YES)
3212 continue;
3215 if ($auth_option == 'm_')
3217 $mod_permissions = true;
3220 if ($auth_option == 'a_')
3222 $admin_permissions = true;
3228 if ($mod_permissions)
3230 if (!function_exists('cache_moderators'))
3232 include(PHPBB_ROOT_PATH . 'includes/functions_admin.' . PHP_EXT);
3234 cache_moderators();
3237 if ($mod_permissions || $admin_permissions)
3239 if (!function_exists('update_foes'))
3241 include(PHPBB_ROOT_PATH . 'includes/functions_admin.' . PHP_EXT);
3243 update_foes(array($group_id));