[ Index ]

PHP Cross Reference of phpBB-3.2.2-deutsch

title

Body

[close]

/includes/ -> functions_user.php (source)

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


Generated: Thu Jan 11 23:14:31 2018 Cross-referenced by PHPXref 0.7.1