[ Index ]

PHP Cross Reference of phpBB-3.2.8-deutsch

title

Body

[close]

/includes/ -> functions_user.php (source)

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


Generated: Sat Oct 26 11:28:42 2019 Cross-referenced by PHPXref 0.7.1