[ Index ]

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


Generated: Wed Nov 11 20:33:01 2020 Cross-referenced by PHPXref 0.7.1