[ Index ]

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


Generated: Tue Apr 7 19:44:41 2020 Cross-referenced by PHPXref 0.7.1