[ Index ]

PHP Cross Reference of BuddyPress

title

Body

[close]

/src/bp-core/classes/ -> class-bp-user-query.php (source)

   1  <?php
   2  /**
   3   * Core component classes.
   4   *
   5   * @package BuddyPress
   6   * @subpackage Core
   7   * @since 1.7.0
   8   */
   9  
  10  // Exit if accessed directly.
  11  defined( 'ABSPATH' ) || exit;
  12  
  13  /**
  14   * BuddyPress User Query class.
  15   *
  16   * Used for querying users in a BuddyPress context, in situations where WP_User_Query won't do the trick:
  17   * Member directories, the Friends component, etc.
  18   *
  19   * @since 1.7.0
  20   *
  21   * @param array $query {
  22   *     Query arguments. All items are optional.
  23   *     @type string            $type                Determines sort order. Select from 'newest', 'active', 'online',
  24   *                                                  'random', 'popular', 'alphabetical'. Default: 'newest'.
  25   *     @type int               $per_page            Number of results to return. Default: 0 (no limit).
  26   *     @type int               $page                Page offset (together with $per_page). Default: 1.
  27   *     @type int               $user_id             ID of a user. If present, and if the friends component is activated,
  28   *                                                  results will be limited to the friends of that user. Default: 0.
  29   *     @type string|bool       $search_terms        Terms to search by. Search happens across xprofile fields. Requires
  30   *                                                  XProfile component. Default: false.
  31   *     @type string            $search_wildcard     When searching with $search_terms, set where wildcards around the
  32   *                                                  term should be positioned. Accepts 'both', 'left', 'right'.
  33   *                                                  Default: 'both'.
  34   *     @type array|string|bool $include             An array or comma-separated list of user IDs to which query should
  35   *                                                  be limited. Default: false.
  36   *     @type array|string|bool $exclude             An array or comma-separated list of user IDs that will be excluded
  37   *                                                  from query results. Default: false.
  38   *     @type array|string|bool $user_ids            An array or comma-separated list of IDs corresponding to the users
  39   *                                                  that should be returned. When this parameter is passed, it will
  40   *                                                  override all others; BP User objects will be constructed using these
  41   *                                                  IDs only. Default: false.
  42   *     @type array|string      $member_type         Array or comma-separated list of member types to limit results to.
  43   *     @type array|string      $member_type__in     Array or comma-separated list of member types to limit results to.
  44   *     @type array|string      $member_type__not_in Array or comma-separated list of member types that will be
  45   *                                                         excluded from results.
  46   *     @type string|bool       $meta_key            Limit results to users that have usermeta associated with this meta_key.
  47   *                                                  Usually used with $meta_value. Default: false.
  48   *     @type string|bool       $meta_value          When used with $meta_key, limits results to users whose usermeta value
  49   *                                                  associated with $meta_key matches $meta_value. Default: false.
  50   *     @type array             $xprofile_query      Filter results by xprofile data. Requires the xprofile component.
  51   *                                                  See {@see BP_XProfile_Query} for details.
  52   *     @type bool              $populate_extras     True if you want to fetch extra metadata
  53   *                                                  about returned users, such as total group and friend counts.
  54   *     @type string            $count_total         Determines how BP_User_Query will do a count of total users matching
  55   *                                                  the other filter criteria. Default value is 'count_query', which
  56   *                                                  does a separate SELECT COUNT query to determine the total.
  57   *                                                  'sql_count_found_rows' uses SQL_COUNT_FOUND_ROWS and
  58   *                                                  SELECT FOUND_ROWS(). Pass an empty string to skip the total user
  59   *                                                  count query.
  60   * }
  61   */
  62  class BP_User_Query {
  63  
  64      /** Variables *************************************************************/
  65  
  66      /**
  67       * Unaltered params as passed to the constructor.
  68       *
  69       * @since 1.8.0
  70       * @var array
  71       */
  72      public $query_vars_raw = array();
  73  
  74      /**
  75       * Array of variables to query with.
  76       *
  77       * @since 1.7.0
  78       * @var array
  79       */
  80      public $query_vars = array();
  81  
  82      /**
  83       * List of found users and their respective data.
  84       *
  85       * @since 1.7.0
  86       * @var array
  87       */
  88      public $results = array();
  89  
  90      /**
  91       * Total number of found users for the current query.
  92       *
  93       * @since 1.7.0
  94       * @var int
  95       */
  96      public $total_users = 0;
  97  
  98      /**
  99       * List of found user IDs.
 100       *
 101       * @since 1.7.0
 102       * @var array
 103       */
 104      public $user_ids = array();
 105  
 106      /**
 107       * SQL clauses for the user ID query.
 108       *
 109       * @since 1.7.0
 110       * @var array
 111       */
 112      public $uid_clauses = array();
 113  
 114      /**
 115       * SQL table where the user ID is being fetched from.
 116       *
 117       * @since 2.2.0
 118       * @var string
 119       */
 120      public $uid_table = '';
 121  
 122      /**
 123       * SQL database column name to order by.
 124       *
 125       * @since 1.7.0
 126       * @var string
 127       */
 128      public $uid_name = '';
 129  
 130      /**
 131       * Standard response when the query should not return any rows.
 132       *
 133       * @since 1.7.0
 134       * @var string
 135       */
 136      protected $no_results = array( 'join' => '', 'where' => '0 = 1' );
 137  
 138  
 139      /** Methods ***************************************************************/
 140  
 141      /**
 142       * Constructor.
 143       *
 144       * @since 1.7.0
 145       *
 146       * @param string|array|null $query See {@link BP_User_Query}.
 147       */
 148  	public function __construct( $query = null ) {
 149  
 150          // Store the raw query vars for later access.
 151          $this->query_vars_raw = $query;
 152  
 153          // Allow extending classes to register action/filter hooks.
 154          $this->setup_hooks();
 155  
 156          if ( ! empty( $this->query_vars_raw ) ) {
 157              $this->query_vars = bp_parse_args(
 158                  $this->query_vars_raw,
 159                  array(
 160                      'type'                => 'newest',
 161                      'per_page'            => 0,
 162                      'page'                => 1,
 163                      'user_id'             => 0,
 164                      'search_terms'        => false,
 165                      'search_wildcard'     => 'both',
 166                      'include'             => false,
 167                      'exclude'             => false,
 168                      'user_ids'            => false,
 169                      'member_type'         => '',
 170                      'member_type__in'     => '',
 171                      'member_type__not_in' => '',
 172                      'meta_key'            => false,
 173                      'meta_value'          => false,
 174                      'xprofile_query'      => false,
 175                      'populate_extras'     => true,
 176                      'count_total'         => 'count_query',
 177                  )
 178              );
 179  
 180              /**
 181               * Fires before the construction of the BP_User_Query query.
 182               *
 183               * @since 1.7.0
 184               *
 185               * @param BP_User_Query $this Current instance of the BP_User_Query. Passed by reference.
 186               */
 187              do_action_ref_array( 'bp_pre_user_query_construct', array( &$this ) );
 188  
 189              // Get user ids.
 190              // If the user_ids param is present, we skip the query.
 191              if ( false !== $this->query_vars['user_ids'] ) {
 192                  $this->user_ids = wp_parse_id_list( $this->query_vars['user_ids'] );
 193              } else {
 194                  $this->prepare_user_ids_query();
 195                  $this->do_user_ids_query();
 196              }
 197          }
 198  
 199          // Bail if no user IDs were found.
 200          if ( empty( $this->user_ids ) ) {
 201              return;
 202          }
 203  
 204          // Fetch additional data. First, using WP_User_Query.
 205          $this->do_wp_user_query();
 206  
 207          // Get BuddyPress specific user data.
 208          $this->populate_extras();
 209      }
 210  
 211      /**
 212       * Allow extending classes to set up action/filter hooks.
 213       *
 214       * When extending BP_User_Query, you may need to use some of its
 215       * internal hooks to modify the output. It's not convenient to call
 216       * add_action() or add_filter() in your class constructor, because
 217       * BP_User_Query::__construct() contains a fair amount of logic that
 218       * you may not want to override in your class. Define this method in
 219       * your own class if you need a place where your extending class can
 220       * add its hooks early in the query-building process. See
 221       * {@link BP_Group_Member_Query::setup_hooks()} for an example.
 222       *
 223       * @since 1.8.0
 224       */
 225  	public function setup_hooks() {}
 226  
 227      /**
 228       * Prepare the query for user_ids.
 229       *
 230       * @since 1.7.0
 231       */
 232  	public function prepare_user_ids_query() {
 233          global $wpdb;
 234  
 235          $bp = buddypress();
 236  
 237          // Default query variables used here.
 238          $type         = '';
 239          $per_page     = 0;
 240          $page         = 1;
 241          $user_id      = 0;
 242          $include      = false;
 243          $search_terms = false;
 244          $exclude      = false;
 245          $meta_key     = false;
 246          $meta_value   = false;
 247  
 248          extract( $this->query_vars );
 249  
 250          // Setup the main SQL query container.
 251          $sql = array(
 252              'select'  => '',
 253              'where'   => array('1=1'),
 254              'orderby' => '',
 255              'order'   => '',
 256              'limit'   => ''
 257          );
 258  
 259          /* TYPE **************************************************************/
 260  
 261          // Determines the sort order, which means it also determines where the
 262          // user IDs are drawn from (the SELECT and WHERE statements).
 263          switch ( $type ) {
 264  
 265              // 'online' query happens against the last_activity usermeta key
 266              // Filter 'bp_user_query_online_interval' to modify the
 267              // number of minutes used as an interval.
 268              case 'online' :
 269                  $this->uid_name = 'user_id';
 270                  $this->uid_table = $bp->members->table_name_last_activity;
 271                  $sql['select']  = "SELECT u.{$this->uid_name} as id FROM {$this->uid_table} u";
 272                  $sql['where'][] = $wpdb->prepare( "u.component = %s AND u.type = 'last_activity'", buddypress()->members->id );
 273  
 274                  /**
 275                   * Filters the threshold for activity timestamp minutes since to indicate online status.
 276                   *
 277                   * @since 1.8.0
 278                   *
 279                   * @param int $value Amount of minutes for threshold. Default 15.
 280                   */
 281                  $sql['where'][] = $wpdb->prepare( "u.date_recorded >= DATE_SUB( UTC_TIMESTAMP(), INTERVAL %d MINUTE )", apply_filters( 'bp_user_query_online_interval', 15 ) );
 282                  $sql['orderby'] = "ORDER BY u.date_recorded";
 283                  $sql['order']   = "DESC";
 284  
 285                  break;
 286  
 287              // 'active', 'newest', and 'random' queries
 288              // all happen against the last_activity usermeta key.
 289              case 'active' :
 290              case 'newest' :
 291              case 'random' :
 292                  $this->uid_name = 'user_id';
 293                  $this->uid_table = $bp->members->table_name_last_activity;
 294                  $sql['select']  = "SELECT u.{$this->uid_name} as id FROM {$this->uid_table} u";
 295                  $sql['where'][] = $wpdb->prepare( "u.component = %s AND u.type = 'last_activity'", buddypress()->members->id );
 296  
 297                  if ( 'newest' == $type ) {
 298                      $sql['orderby'] = "ORDER BY u.user_id";
 299                      $sql['order'] = "DESC";
 300                  } elseif ( 'random' == $type ) {
 301                      $sql['orderby'] = "ORDER BY rand()";
 302                  } else {
 303                      $sql['orderby'] = "ORDER BY u.date_recorded";
 304                      $sql['order'] = "DESC";
 305                  }
 306  
 307                  break;
 308  
 309              // 'popular' sorts by the 'total_friend_count' usermeta.
 310              case 'popular' :
 311                  $this->uid_name = 'user_id';
 312                  $this->uid_table = $wpdb->usermeta;
 313                  $sql['select']  = "SELECT u.{$this->uid_name} as id FROM {$this->uid_table} u";
 314                  $sql['where'][] = $wpdb->prepare( "u.meta_key = %s", bp_get_user_meta_key( 'total_friend_count' ) );
 315                  $sql['orderby'] = "ORDER BY CONVERT(u.meta_value, SIGNED)";
 316                  $sql['order']   = "DESC";
 317  
 318                  break;
 319  
 320              // 'alphabetical' sorts depend on the xprofile setup.
 321              case 'alphabetical' :
 322  
 323                  // We prefer to do alphabetical sorts against the display_name field
 324                  // of wp_users, because the table is smaller and better indexed. We
 325                  // can do so if xprofile sync is enabled, or if xprofile is inactive.
 326                  //
 327                  // @todo remove need for bp_is_active() check.
 328                  if ( ! bp_disable_profile_sync() || ! bp_is_active( 'xprofile' ) ) {
 329                      $this->uid_name = 'ID';
 330                      $this->uid_table = $wpdb->users;
 331                      $sql['select']  = "SELECT u.{$this->uid_name} as id FROM {$this->uid_table} u";
 332                      $sql['orderby'] = "ORDER BY u.display_name";
 333                      $sql['order']   = "ASC";
 334  
 335                  // When profile sync is disabled, alphabetical sorts must happen against
 336                  // the xprofile table.
 337                  } else {
 338                      $this->uid_name = 'user_id';
 339                      $this->uid_table = $bp->profile->table_name_data;
 340                      $sql['select']  = "SELECT u.{$this->uid_name} as id FROM {$this->uid_table} u";
 341                      $sql['where'][] = $wpdb->prepare( "u.field_id = %d", bp_xprofile_fullname_field_id() );
 342                      $sql['orderby'] = "ORDER BY u.value";
 343                      $sql['order']   = "ASC";
 344                  }
 345  
 346                  // Alphabetical queries ignore last_activity, while BP uses last_activity
 347                  // to infer spam/deleted/non-activated users. To ensure that these users
 348                  // are filtered out, we add an appropriate sub-query.
 349                  $sql['where'][] = "u.{$this->uid_name} IN ( SELECT ID FROM {$wpdb->users} WHERE " . bp_core_get_status_sql( '' ) . " )";
 350  
 351                  break;
 352  
 353              // Any other 'type' falls through.
 354              default :
 355                  $this->uid_name = 'ID';
 356                  $this->uid_table = $wpdb->users;
 357                  $sql['select']  = "SELECT u.{$this->uid_name} as id FROM {$this->uid_table} u";
 358  
 359                  // In this case, we assume that a plugin is
 360                  // handling order, so we leave those clauses
 361                  // blank.
 362                  break;
 363          }
 364  
 365          /* WHERE *************************************************************/
 366  
 367          // 'include' - User ids to include in the results.
 368          $include     = false !== $include ? wp_parse_id_list( $include ) : array();
 369          $include_ids = $this->get_include_ids( $include );
 370  
 371          // An array containing nothing but 0 should always fail.
 372          if ( 1 === count( $include_ids ) && 0 == reset( $include_ids ) ) {
 373              $sql['where'][] = $this->no_results['where'];
 374          } elseif ( ! empty( $include_ids ) ) {
 375              $include_ids    = implode( ',', wp_parse_id_list( $include_ids ) );
 376              $sql['where'][] = "u.{$this->uid_name} IN ({$include_ids})";
 377          }
 378  
 379          // 'exclude' - User ids to exclude from the results.
 380          if ( ! empty( $exclude ) ) {
 381              $exclude_ids    = implode( ',', wp_parse_id_list( $exclude ) );
 382              $sql['where'][] = "u.{$this->uid_name} NOT IN ({$exclude_ids})";
 383          }
 384  
 385          // 'user_id' - When a user id is passed, limit to the friends of the user
 386          // @todo remove need for bp_is_active() check.
 387          if ( ! empty( $user_id ) && bp_is_active( 'friends' ) ) {
 388              $friend_ids = friends_get_friend_user_ids( $user_id );
 389              $friend_ids = implode( ',', wp_parse_id_list( $friend_ids ) );
 390  
 391              if ( ! empty( $friend_ids ) ) {
 392                  $sql['where'][] = "u.{$this->uid_name} IN ({$friend_ids})";
 393  
 394              // If the user has no friends, the query should always
 395              // return no users.
 396              } else {
 397                  $sql['where'][] = $this->no_results['where'];
 398              }
 399          }
 400  
 401          /* Search Terms ******************************************************/
 402  
 403          // 'search_terms' searches user_login and user_nicename
 404          // xprofile field matches happen in bp_xprofile_bp_user_query_search().
 405          if ( false !== $search_terms ) {
 406              $search_terms = bp_esc_like( wp_kses_normalize_entities( $search_terms ) );
 407  
 408              if ( $search_wildcard === 'left' ) {
 409                  $search_terms_nospace = '%' . $search_terms;
 410                  $search_terms_space   = '%' . $search_terms . ' %';
 411              } elseif ( $search_wildcard === 'right' ) {
 412                  $search_terms_nospace =        $search_terms . '%';
 413                  $search_terms_space   = '% ' . $search_terms . '%';
 414              } else {
 415                  $search_terms_nospace = '%' . $search_terms . '%';
 416                  $search_terms_space   = '%' . $search_terms . '%';
 417              }
 418  
 419              $matched_user_ids = $wpdb->get_col( $wpdb->prepare(
 420                  "SELECT ID FROM {$wpdb->users} WHERE ( user_login LIKE %s OR user_login LIKE %s OR user_nicename LIKE %s OR user_nicename LIKE %s )",
 421                  $search_terms_nospace,
 422                  $search_terms_space,
 423                  $search_terms_nospace,
 424                  $search_terms_space
 425              ) );
 426  
 427              $match_in_clause = empty( $matched_user_ids) ? 'NULL' : implode( ',', $matched_user_ids );
 428              $sql['where']['search'] = "u.{$this->uid_name} IN ({$match_in_clause})";
 429          }
 430  
 431          // Only use $member_type__in if $member_type is not set.
 432          if ( empty( $member_type ) && ! empty( $member_type__in ) ) {
 433              $member_type = $member_type__in;
 434          }
 435  
 436          // Member types to exclude. Note that this takes precedence over inclusions.
 437          if ( ! empty( $member_type__not_in ) ) {
 438              $member_type_clause = $this->get_sql_clause_for_member_types( $member_type__not_in, 'NOT IN' );
 439  
 440          // Member types to include.
 441          } elseif ( ! empty( $member_type ) ) {
 442              $member_type_clause = $this->get_sql_clause_for_member_types( $member_type, 'IN' );
 443          }
 444  
 445          if ( ! empty( $member_type_clause ) ) {
 446              $sql['where']['member_type'] = $member_type_clause;
 447          }
 448  
 449          // 'meta_key', 'meta_value' allow usermeta search
 450          // To avoid global joins, do a separate query.
 451          if ( false !== $meta_key ) {
 452              $meta_sql = $wpdb->prepare( "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s", $meta_key );
 453  
 454              if ( false !== $meta_value ) {
 455                  $meta_sql .= $wpdb->prepare( " AND meta_value = %s", $meta_value );
 456              }
 457  
 458              $found_user_ids = $wpdb->get_col( $meta_sql );
 459  
 460              if ( ! empty( $found_user_ids ) ) {
 461                  $sql['where'][] = "u.{$this->uid_name} IN (" . implode( ',', wp_parse_id_list( $found_user_ids ) ) . ")";
 462              } else {
 463                  $sql['where'][] = '1 = 0';
 464              }
 465          }
 466  
 467          // 'per_page', 'page' - handles LIMIT.
 468          if ( !empty( $per_page ) && !empty( $page ) ) {
 469              $sql['limit'] = $wpdb->prepare( "LIMIT %d, %d", intval( ( $page - 1 ) * $per_page ), intval( $per_page ) );
 470          } else {
 471              $sql['limit'] = '';
 472          }
 473  
 474          /**
 475           * Filters the clauses for the user query.
 476           *
 477           * @since 2.0.0
 478           *
 479           * @param array         $sql  Array of SQL clauses to be used in the query.
 480           * @param BP_User_Query $this Current BP_User_Query instance.
 481           */
 482          $sql = apply_filters_ref_array( 'bp_user_query_uid_clauses', array( $sql, &$this ) );
 483  
 484          // Assemble the query chunks.
 485          $this->uid_clauses['select']  = $sql['select'];
 486          $this->uid_clauses['where']   = ! empty( $sql['where'] ) ? 'WHERE ' . implode( ' AND ', $sql['where'] ) : '';
 487          $this->uid_clauses['orderby'] = $sql['orderby'];
 488          $this->uid_clauses['order']   = $sql['order'];
 489          $this->uid_clauses['limit']   = $sql['limit'];
 490  
 491          /**
 492           * Fires before the BP_User_Query query is made.
 493           *
 494           * @since 1.7.0
 495           *
 496           * @param BP_User_Query $this Current BP_User_Query instance. Passed by reference.
 497           */
 498          do_action_ref_array( 'bp_pre_user_query', array( &$this ) );
 499      }
 500  
 501      /**
 502       * Query for IDs of users that match the query parameters.
 503       *
 504       * Perform a database query to specifically get only user IDs, using
 505       * existing query variables set previously in the constructor.
 506       *
 507       * Also used to quickly perform user total counts.
 508       *
 509       * @since 1.7.0
 510       */
 511  	public function do_user_ids_query() {
 512          global $wpdb;
 513  
 514          // If counting using SQL_CALC_FOUND_ROWS, set it up here.
 515          if ( 'sql_calc_found_rows' == $this->query_vars['count_total'] ) {
 516              $this->uid_clauses['select'] = str_replace( 'SELECT', 'SELECT SQL_CALC_FOUND_ROWS', $this->uid_clauses['select'] );
 517          }
 518  
 519          // Get the specific user ids.
 520          $this->user_ids = $wpdb->get_col( "{$this->uid_clauses['select']} {$this->uid_clauses['where']} {$this->uid_clauses['orderby']} {$this->uid_clauses['order']} {$this->uid_clauses['limit']}" );
 521  
 522          // Get the total user count.
 523          if ( 'sql_calc_found_rows' == $this->query_vars['count_total'] ) {
 524  
 525              /**
 526               * Filters the found user SQL statements before query.
 527               *
 528               * If "sql_calc_found_rows" is the provided count_total query var
 529               * then the value will be "SELECT FOUND_ROWS()". Otherwise it will
 530               * use a "SELECT COUNT()" query statement.
 531               *
 532               * @since 1.7.0
 533               *
 534               * @param string        $value SQL statement to select FOUND_ROWS().
 535               * @param BP_User_Query $this  Current BP_User_Query instance.
 536               */
 537              $this->total_users = $wpdb->get_var( apply_filters( 'bp_found_user_query', "SELECT FOUND_ROWS()", $this ) );
 538          } elseif ( 'count_query' == $this->query_vars['count_total'] ) {
 539              $count_select      = preg_replace( '/^SELECT.*?FROM (\S+) u/', "SELECT COUNT(u.{$this->uid_name}) FROM $1 u", $this->uid_clauses['select'] );
 540  
 541              /** This filter is documented in bp-core/classes/class-bp-user-query.php */
 542              $this->total_users = $wpdb->get_var( apply_filters( 'bp_found_user_query', "{$count_select} {$this->uid_clauses['where']}", $this ) );
 543          }
 544      }
 545  
 546      /**
 547       * Use WP_User_Query() to pull data for the user IDs retrieved in the main query.
 548       *
 549       * @since 1.7.0
 550       */
 551  	public function do_wp_user_query() {
 552          $fields = array( 'ID', 'user_login', 'user_pass', 'user_nicename', 'user_email', 'user_url', 'user_registered', 'user_activation_key', 'user_status', 'display_name' );
 553  
 554          if ( is_multisite() ) {
 555              $fields[] = 'spam';
 556              $fields[] = 'deleted';
 557          }
 558  
 559          /**
 560           * Filters the WP User Query arguments before passing into the class.
 561           *
 562           * @since 1.7.0
 563           *
 564           * @param array         $value Array of arguments for the user query.
 565           * @param BP_User_Query $this  Current BP_User_Query instance.
 566           */
 567          $wp_user_query = new WP_User_Query( apply_filters( 'bp_wp_user_query_args', array(
 568  
 569              // Relevant.
 570              'fields'      => $fields,
 571              'include'     => $this->user_ids,
 572  
 573              // Overrides
 574              'blog_id'     => 0,    // BP does not require blog roles.
 575              'count_total' => false // We already have a count.
 576  
 577          ), $this ) );
 578  
 579          /*
 580           * We calculate total_users using a standalone query, except
 581           * when a list of specific user_ids is passed to the constructor.
 582           * This clause covers the latter situation, and ensures that
 583           * pagination works when querying by $user_ids.
 584           */
 585          if ( empty( $this->total_users ) ) {
 586              $this->total_users = count( $wp_user_query->results );
 587          }
 588  
 589          // Reindex for easier matching.
 590          $r = array();
 591          foreach ( $wp_user_query->results as $u ) {
 592              $r[ $u->ID ] = $u;
 593          }
 594  
 595          // Match up to the user ids from the main query.
 596          foreach ( $this->user_ids as $key => $uid ) {
 597              if ( isset( $r[ $uid ] ) ) {
 598                  $r[ $uid ]->ID = (int) $uid;
 599                  $r[ $uid ]->user_status = (int) $r[ $uid ]->user_status;
 600  
 601                  $this->results[ $uid ] = $r[ $uid ];
 602  
 603                  // The BP template functions expect an 'id'
 604                  // (as opposed to 'ID') property.
 605                  $this->results[ $uid ]->id = (int) $uid;
 606  
 607              // Remove user ID from original user_ids property.
 608              } else {
 609                  unset( $this->user_ids[ $key ] );
 610              }
 611          }
 612      }
 613  
 614      /**
 615       * Fetch the IDs of users to put in the IN clause of the main query.
 616       *
 617       * By default, returns the value passed to it
 618       * ($this->query_vars['include']). Having this abstracted into a
 619       * standalone method means that extending classes can override the
 620       * logic, parsing together their own user_id limits with the 'include'
 621       * ids passed to the class constructor. See {@link BP_Group_Member_Query}
 622       * for an example.
 623       *
 624       * @since 1.8.0
 625       *
 626       * @param array $include Sanitized array of user IDs, as passed to the 'include'
 627       *                       parameter of the class constructor.
 628       * @return array The list of users to which the main query should be
 629       *               limited.
 630       */
 631  	public function get_include_ids( $include = array() ) {
 632          return $include;
 633      }
 634  
 635      /**
 636       * Perform a database query to populate any extra metadata we might need.
 637       *
 638       * Different components will hook into the 'bp_user_query_populate_extras'
 639       * action to loop in the things they want.
 640       *
 641       * @since 1.7.0
 642       *
 643       * @global WPDB $wpdb Global WordPress database access object.
 644       */
 645  	public function populate_extras() {
 646          global $wpdb;
 647  
 648          // Bail if no users.
 649          if ( empty( $this->user_ids ) || empty( $this->results ) ) {
 650              return;
 651          }
 652  
 653          // Bail if the populate_extras flag is set to false
 654          // In the case of the 'popular' sort type, we force
 655          // populate_extras to true, because we need the friend counts.
 656          if ( 'popular' == $this->query_vars['type'] ) {
 657              $this->query_vars['populate_extras'] = 1;
 658          }
 659  
 660          if ( ! (bool) $this->query_vars['populate_extras'] ) {
 661              return;
 662          }
 663  
 664          // Turn user ID's into a query-usable, comma separated value.
 665          $user_ids_sql = implode( ',', wp_parse_id_list( $this->user_ids ) );
 666  
 667          /**
 668           * Allows users to independently populate custom extras.
 669           *
 670           * Note that anything you add here should query using $user_ids_sql, to
 671           * avoid running multiple queries per user in the loop.
 672           *
 673           * Two BuddyPress components currently do this:
 674           * - XProfile: To override display names.
 675           * - Friends:  To set whether or not a user is the current users friend.
 676           *
 677           * @see bp_xprofile_filter_user_query_populate_extras()
 678           * @see bp_friends_filter_user_query_populate_extras()
 679           *
 680           * @since 1.7.0
 681           *
 682           * @param BP_User_Query $this         Current BP_User_Query instance.
 683           * @param string        $user_ids_sql Comma-separated string of user IDs.
 684           */
 685          do_action_ref_array( 'bp_user_query_populate_extras', array( $this, $user_ids_sql ) );
 686  
 687          // Fetch last_active data from the activity table.
 688          $last_activities = BP_Core_User::get_last_activity( $this->user_ids );
 689  
 690          // Set a last_activity value for each user, even if it's empty.
 691          foreach ( $this->results as $user_id => $user ) {
 692              $user_last_activity = isset( $last_activities[ $user_id ]['date_recorded'] ) ? $last_activities[ $user_id ]['date_recorded'] : '';
 693              $this->results[ $user_id ]->last_activity = $user_last_activity;
 694          }
 695  
 696          // Fetch usermeta data
 697          // We want the three following pieces of info from usermeta:
 698          // - friend count
 699          // - latest update.
 700          $total_friend_count_key = bp_get_user_meta_key( 'total_friend_count' );
 701          $bp_latest_update_key   = bp_get_user_meta_key( 'bp_latest_update'   );
 702  
 703          // Total_friend_count must be set for each user, even if its
 704          // value is 0.
 705          foreach ( $this->results as $uindex => $user ) {
 706              $this->results[$uindex]->total_friend_count = 0;
 707          }
 708  
 709          // Create, prepare, and run the separate usermeta query.
 710          $user_metas = $wpdb->get_results( $wpdb->prepare( "SELECT user_id, meta_key, meta_value FROM {$wpdb->usermeta} WHERE meta_key IN (%s,%s) AND user_id IN ({$user_ids_sql})", $total_friend_count_key, $bp_latest_update_key ) );
 711  
 712          // The $members_template global expects the index key to be different
 713          // from the meta_key in some cases, so we rejig things here.
 714          foreach ( $user_metas as $user_meta ) {
 715              switch ( $user_meta->meta_key ) {
 716                  case $total_friend_count_key :
 717                      $key = 'total_friend_count';
 718                      break;
 719  
 720                  case $bp_latest_update_key :
 721                      $key = 'latest_update';
 722                      break;
 723              }
 724  
 725              if ( isset( $this->results[ $user_meta->user_id ] ) ) {
 726                  $this->results[ $user_meta->user_id ]->{$key} = $user_meta->meta_value;
 727              }
 728          }
 729  
 730          // When meta_key or meta_value have been passed to the query,
 731          // fetch the resulting values for use in the template functions.
 732          if ( ! empty( $this->query_vars['meta_key'] ) ) {
 733              $meta_sql = array(
 734                  'select' => "SELECT user_id, meta_key, meta_value",
 735                  'from'   => "FROM $wpdb->usermeta",
 736                  'where'  => $wpdb->prepare( "WHERE meta_key = %s", $this->query_vars['meta_key'] )
 737              );
 738  
 739              if ( false !== $this->query_vars['meta_value'] ) {
 740                  $meta_sql['where'] .= $wpdb->prepare( " AND meta_value = %s", $this->query_vars['meta_value'] );
 741              }
 742  
 743              $metas = $wpdb->get_results( "{$meta_sql['select']} {$meta_sql['from']} {$meta_sql['where']}" );
 744  
 745              if ( ! empty( $metas ) ) {
 746                  foreach ( $metas as $meta ) {
 747                      if ( isset( $this->results[ $meta->user_id ] ) ) {
 748                          $this->results[ $meta->user_id ]->meta_key = $meta->meta_key;
 749  
 750                          if ( ! empty( $meta->meta_value ) ) {
 751                              $this->results[ $meta->user_id ]->meta_value = $meta->meta_value;
 752                          }
 753                      }
 754                  }
 755              }
 756          }
 757      }
 758  
 759      /**
 760       * Get a SQL clause representing member_type include/exclusion.
 761       *
 762       * @since 2.4.0
 763       *
 764       * @param string|array $member_types Array or comma-separated list of member types.
 765       * @param string       $operator     'IN' or 'NOT IN'.
 766       * @return string
 767       */
 768  	protected function get_sql_clause_for_member_types( $member_types, $operator ) {
 769          global $wpdb;
 770  
 771          // Sanitize.
 772          if ( 'NOT IN' !== $operator ) {
 773              $operator = 'IN';
 774          }
 775  
 776          // Parse and sanitize types.
 777          if ( ! is_array( $member_types ) ) {
 778              $member_types = preg_split( '/[,\s+]/', $member_types );
 779          }
 780  
 781          $types = array();
 782          foreach ( $member_types as $mt ) {
 783              if ( bp_get_member_type_object( $mt ) ) {
 784                  $types[] = $mt;
 785              }
 786          }
 787  
 788          $tax_query = new WP_Tax_Query( array(
 789              array(
 790                  'taxonomy' => bp_get_member_type_tax_name(),
 791                  'field'    => 'name',
 792                  'operator' => $operator,
 793                  'terms'    => $types,
 794              ),
 795          ) );
 796  
 797          // Switch to the root blog, where member type taxonomies live.
 798          $site_id  = bp_get_taxonomy_term_site_id( bp_get_member_type_tax_name() );
 799          $switched = false;
 800          if ( $site_id !== get_current_blog_id() ) {
 801              switch_to_blog( $site_id );
 802              $switched = true;
 803          }
 804  
 805          $sql_clauses = $tax_query->get_sql( 'u', $this->uid_name );
 806  
 807          $clause = '';
 808  
 809          // The no_results clauses are the same between IN and NOT IN.
 810          if ( false !== strpos( $sql_clauses['where'], '0 = 1' ) ) {
 811              $clause = $this->no_results['where'];
 812  
 813          // The tax_query clause generated for NOT IN can be used almost as-is. We just trim the leading 'AND'.
 814          } elseif ( 'NOT IN' === $operator ) {
 815              $clause = preg_replace( '/^\s*AND\s*/', '', $sql_clauses['where'] );
 816  
 817          // IN clauses must be converted to a subquery.
 818          } elseif ( preg_match( '/' . $wpdb->term_relationships . '\.term_taxonomy_id IN \([0-9, ]+\)/', $sql_clauses['where'], $matches ) ) {
 819              $clause = "u.{$this->uid_name} IN ( SELECT object_id FROM $wpdb->term_relationships WHERE {$matches[0]} )";
 820          }
 821  
 822          if ( $switched ) {
 823              restore_current_blog();
 824          }
 825  
 826          return $clause;
 827      }
 828  }


Generated: Wed Oct 27 01:00:59 2021 Cross-referenced by PHPXref 0.7.1