[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

/wp-includes/ -> class-wp-user-query.php (source)

   1  <?php
   2  /**
   3   * User API: WP_User_Query class
   4   *
   5   * @package WordPress
   6   * @subpackage Users
   7   * @since 4.4.0
   8   */
   9  
  10  /**
  11   * Core class used for querying users.
  12   *
  13   * @since 3.1.0
  14   *
  15   * @see WP_User_Query::prepare_query() for information on accepted arguments.
  16   */
  17  class WP_User_Query {
  18  
  19      /**
  20       * Query vars, after parsing
  21       *
  22       * @since 3.5.0
  23       * @var array
  24       */
  25      public $query_vars = array();
  26  
  27      /**
  28       * List of found user ids
  29       *
  30       * @since 3.1.0
  31       * @var array
  32       */
  33      private $results;
  34  
  35      /**
  36       * Total number of found users for the current query
  37       *
  38       * @since 3.1.0
  39       * @var int
  40       */
  41      private $total_users = 0;
  42  
  43      /**
  44       * Metadata query container.
  45       *
  46       * @since 4.2.0
  47       * @var WP_Meta_Query
  48       */
  49      public $meta_query = false;
  50  
  51      /**
  52       * The SQL query used to fetch matching users.
  53       *
  54       * @since 4.4.0
  55       * @var string
  56       */
  57      public $request;
  58  
  59      private $compat_fields = array( 'results', 'total_users' );
  60  
  61      // SQL clauses
  62      public $query_fields;
  63      public $query_from;
  64      public $query_where;
  65      public $query_orderby;
  66      public $query_limit;
  67  
  68      /**
  69       * PHP5 constructor.
  70       *
  71       * @since 3.1.0
  72       *
  73       * @param null|string|array $query Optional. The query variables.
  74       */
  75  	public function __construct( $query = null ) {
  76          if ( ! empty( $query ) ) {
  77              $this->prepare_query( $query );
  78              $this->query();
  79          }
  80      }
  81  
  82      /**
  83       * Fills in missing query variables with default values.
  84       *
  85       * @since 4.4.0
  86       *
  87       * @param array $args Query vars, as passed to `WP_User_Query`.
  88       * @return array Complete query variables with undefined ones filled in with defaults.
  89       */
  90  	public static function fill_query_vars( $args ) {
  91          $defaults = array(
  92              'blog_id'             => get_current_blog_id(),
  93              'role'                => '',
  94              'role__in'            => array(),
  95              'role__not_in'        => array(),
  96              'meta_key'            => '',
  97              'meta_value'          => '',
  98              'meta_compare'        => '',
  99              'include'             => array(),
 100              'exclude'             => array(),
 101              'search'              => '',
 102              'search_columns'      => array(),
 103              'orderby'             => 'login',
 104              'order'               => 'ASC',
 105              'offset'              => '',
 106              'number'              => '',
 107              'paged'               => 1,
 108              'count_total'         => true,
 109              'fields'              => 'all',
 110              'who'                 => '',
 111              'has_published_posts' => null,
 112              'nicename'            => '',
 113              'nicename__in'        => array(),
 114              'nicename__not_in'    => array(),
 115              'login'               => '',
 116              'login__in'           => array(),
 117              'login__not_in'       => array(),
 118          );
 119  
 120          return wp_parse_args( $args, $defaults );
 121      }
 122  
 123      /**
 124       * Prepare the query variables.
 125       *
 126       * @since 3.1.0
 127       * @since 4.1.0 Added the ability to order by the `include` value.
 128       * @since 4.2.0 Added 'meta_value_num' support for `$orderby` parameter. Added multi-dimensional array syntax
 129       *              for `$orderby` parameter.
 130       * @since 4.3.0 Added 'has_published_posts' parameter.
 131       * @since 4.4.0 Added 'paged', 'role__in', and 'role__not_in' parameters. The 'role' parameter was updated to
 132       *              permit an array or comma-separated list of values. The 'number' parameter was updated to support
 133       *              querying for all users with using -1.
 134       * @since 4.7.0 Added 'nicename', 'nicename__in', 'nicename__not_in', 'login', 'login__in',
 135       *              and 'login__not_in' parameters.
 136       *
 137       * @global wpdb $wpdb WordPress database abstraction object.
 138       * @global int  $blog_id
 139       *
 140       * @param string|array $query {
 141       *     Optional. Array or string of Query parameters.
 142       *
 143       *     @type int          $blog_id             The site ID. Default is the current site.
 144       *     @type string|array $role                An array or a comma-separated list of role names that users must match
 145       *                                             to be included in results. Note that this is an inclusive list: users
 146       *                                             must match *each* role. Default empty.
 147       *     @type array        $role__in            An array of role names. Matched users must have at least one of these
 148       *                                             roles. Default empty array.
 149       *     @type array        $role__not_in        An array of role names to exclude. Users matching one or more of these
 150       *                                             roles will not be included in results. Default empty array.
 151       *     @type string       $meta_key            User meta key. Default empty.
 152       *     @type string       $meta_value          User meta value. Default empty.
 153       *     @type string       $meta_compare        Comparison operator to test the `$meta_value`. Accepts '=', '!=',
 154       *                                             '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
 155       *                                             'BETWEEN', 'NOT BETWEEN', 'EXISTS', 'NOT EXISTS', 'REGEXP',
 156       *                                             'NOT REGEXP', or 'RLIKE'. Default '='.
 157       *     @type array        $include             An array of user IDs to include. Default empty array.
 158       *     @type array        $exclude             An array of user IDs to exclude. Default empty array.
 159       *     @type string       $search              Search keyword. Searches for possible string matches on columns.
 160       *                                             When `$search_columns` is left empty, it tries to determine which
 161       *                                             column to search in based on search string. Default empty.
 162       *     @type array        $search_columns      Array of column names to be searched. Accepts 'ID', 'user_login',
 163       *                                             'user_email', 'user_url', 'user_nicename', 'display_name'.
 164       *                                             Default empty array.
 165       *     @type string|array $orderby             Field(s) to sort the retrieved users by. May be a single value,
 166       *                                             an array of values, or a multi-dimensional array with fields as
 167       *                                             keys and orders ('ASC' or 'DESC') as values. Accepted values are
 168       *                                             'ID', 'display_name' (or 'name'), 'include', 'user_login'
 169       *                                             (or 'login'), 'login__in', 'user_nicename' (or 'nicename'),
 170       *                                             'nicename__in', 'user_email (or 'email'), 'user_url' (or 'url'),
 171       *                                             'user_registered' (or 'registered'), 'post_count', 'meta_value',
 172       *                                             'meta_value_num', the value of `$meta_key`, or an array key of
 173       *                                             `$meta_query`. To use 'meta_value' or 'meta_value_num', `$meta_key`
 174       *                                             must be also be defined. Default 'user_login'.
 175       *     @type string       $order               Designates ascending or descending order of users. Order values
 176       *                                             passed as part of an `$orderby` array take precedence over this
 177       *                                             parameter. Accepts 'ASC', 'DESC'. Default 'ASC'.
 178       *     @type int          $offset              Number of users to offset in retrieved results. Can be used in
 179       *                                             conjunction with pagination. Default 0.
 180       *     @type int          $number              Number of users to limit the query for. Can be used in
 181       *                                             conjunction with pagination. Value -1 (all) is supported, but
 182       *                                             should be used with caution on larger sites.
 183       *                                             Default -1 (all users).
 184       *     @type int          $paged               When used with number, defines the page of results to return.
 185       *                                             Default 1.
 186       *     @type bool         $count_total         Whether to count the total number of users found. If pagination
 187       *                                             is not needed, setting this to false can improve performance.
 188       *                                             Default true.
 189       *     @type string|array $fields              Which fields to return. Single or all fields (string), or array
 190       *                                             of fields. Accepts 'ID', 'display_name', 'user_login',
 191       *                                             'user_nicename', 'user_email', 'user_url', 'user_registered'.
 192       *                                             Use 'all' for all fields and 'all_with_meta' to include
 193       *                                             meta fields. Default 'all'.
 194       *     @type string       $who                 Type of users to query. Accepts 'authors'.
 195       *                                             Default empty (all users).
 196       *     @type bool|array   $has_published_posts Pass an array of post types to filter results to users who have
 197       *                                             published posts in those post types. `true` is an alias for all
 198       *                                             public post types.
 199       *     @type string       $nicename            The user nicename. Default empty.
 200       *     @type array        $nicename__in        An array of nicenames to include. Users matching one of these
 201       *                                             nicenames will be included in results. Default empty array.
 202       *     @type array        $nicename__not_in    An array of nicenames to exclude. Users matching one of these
 203       *                                             nicenames will not be included in results. Default empty array.
 204       *     @type string       $login               The user login. Default empty.
 205       *     @type array        $login__in           An array of logins to include. Users matching one of these
 206       *                                             logins will be included in results. Default empty array.
 207       *     @type array        $login__not_in       An array of logins to exclude. Users matching one of these
 208       *                                             logins will not be included in results. Default empty array.
 209       * }
 210       */
 211  	public function prepare_query( $query = array() ) {
 212          global $wpdb;
 213  
 214          if ( empty( $this->query_vars ) || ! empty( $query ) ) {
 215              $this->query_limit = null;
 216              $this->query_vars  = $this->fill_query_vars( $query );
 217          }
 218  
 219          /**
 220           * Fires before the WP_User_Query has been parsed.
 221           *
 222           * The passed WP_User_Query object contains the query variables, not
 223           * yet passed into SQL.
 224           *
 225           * @since 4.0.0
 226           *
 227           * @param WP_User_Query $this The current WP_User_Query instance,
 228           *                            passed by reference.
 229           */
 230          do_action( 'pre_get_users', $this );
 231  
 232          // Ensure that query vars are filled after 'pre_get_users'.
 233          $qv =& $this->query_vars;
 234          $qv = $this->fill_query_vars( $qv );
 235  
 236          if ( is_array( $qv['fields'] ) ) {
 237              $qv['fields'] = array_unique( $qv['fields'] );
 238  
 239              $this->query_fields = array();
 240              foreach ( $qv['fields'] as $field ) {
 241                  $field                = 'ID' === $field ? 'ID' : sanitize_key( $field );
 242                  $this->query_fields[] = "$wpdb->users.$field";
 243              }
 244              $this->query_fields = implode( ',', $this->query_fields );
 245          } elseif ( 'all' == $qv['fields'] ) {
 246              $this->query_fields = "$wpdb->users.*";
 247          } else {
 248              $this->query_fields = "$wpdb->users.ID";
 249          }
 250  
 251          if ( isset( $qv['count_total'] ) && $qv['count_total'] ) {
 252              $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
 253          }
 254  
 255          $this->query_from  = "FROM $wpdb->users";
 256          $this->query_where = 'WHERE 1=1';
 257  
 258          // Parse and sanitize 'include', for use by 'orderby' as well as 'include' below.
 259          if ( ! empty( $qv['include'] ) ) {
 260              $include = wp_parse_id_list( $qv['include'] );
 261          } else {
 262              $include = false;
 263          }
 264  
 265          $blog_id = 0;
 266          if ( isset( $qv['blog_id'] ) ) {
 267              $blog_id = absint( $qv['blog_id'] );
 268          }
 269  
 270          if ( $qv['has_published_posts'] && $blog_id ) {
 271              if ( true === $qv['has_published_posts'] ) {
 272                  $post_types = get_post_types( array( 'public' => true ) );
 273              } else {
 274                  $post_types = (array) $qv['has_published_posts'];
 275              }
 276  
 277              foreach ( $post_types as &$post_type ) {
 278                  $post_type = $wpdb->prepare( '%s', $post_type );
 279              }
 280  
 281              $posts_table        = $wpdb->get_blog_prefix( $blog_id ) . 'posts';
 282              $this->query_where .= " AND $wpdb->users.ID IN ( SELECT DISTINCT $posts_table.post_author FROM $posts_table WHERE $posts_table.post_status = 'publish' AND $posts_table.post_type IN ( " . join( ', ', $post_types ) . ' ) )';
 283          }
 284  
 285          // nicename
 286          if ( '' !== $qv['nicename'] ) {
 287              $this->query_where .= $wpdb->prepare( ' AND user_nicename = %s', $qv['nicename'] );
 288          }
 289  
 290          if ( ! empty( $qv['nicename__in'] ) ) {
 291              $sanitized_nicename__in = array_map( 'esc_sql', $qv['nicename__in'] );
 292              $nicename__in           = implode( "','", $sanitized_nicename__in );
 293              $this->query_where     .= " AND user_nicename IN ( '$nicename__in' )";
 294          }
 295  
 296          if ( ! empty( $qv['nicename__not_in'] ) ) {
 297              $sanitized_nicename__not_in = array_map( 'esc_sql', $qv['nicename__not_in'] );
 298              $nicename__not_in           = implode( "','", $sanitized_nicename__not_in );
 299              $this->query_where         .= " AND user_nicename NOT IN ( '$nicename__not_in' )";
 300          }
 301  
 302          // login
 303          if ( '' !== $qv['login'] ) {
 304              $this->query_where .= $wpdb->prepare( ' AND user_login = %s', $qv['login'] );
 305          }
 306  
 307          if ( ! empty( $qv['login__in'] ) ) {
 308              $sanitized_login__in = array_map( 'esc_sql', $qv['login__in'] );
 309              $login__in           = implode( "','", $sanitized_login__in );
 310              $this->query_where  .= " AND user_login IN ( '$login__in' )";
 311          }
 312  
 313          if ( ! empty( $qv['login__not_in'] ) ) {
 314              $sanitized_login__not_in = array_map( 'esc_sql', $qv['login__not_in'] );
 315              $login__not_in           = implode( "','", $sanitized_login__not_in );
 316              $this->query_where      .= " AND user_login NOT IN ( '$login__not_in' )";
 317          }
 318  
 319          // Meta query.
 320          $this->meta_query = new WP_Meta_Query();
 321          $this->meta_query->parse_query_vars( $qv );
 322  
 323          if ( isset( $qv['who'] ) && 'authors' == $qv['who'] && $blog_id ) {
 324              $who_query = array(
 325                  'key'     => $wpdb->get_blog_prefix( $blog_id ) . 'user_level',
 326                  'value'   => 0,
 327                  'compare' => '!=',
 328              );
 329  
 330              // Prevent extra meta query.
 331              $qv['blog_id'] = 0;
 332              $blog_id       = 0;
 333  
 334              if ( empty( $this->meta_query->queries ) ) {
 335                  $this->meta_query->queries = array( $who_query );
 336              } else {
 337                  // Append the cap query to the original queries and reparse the query.
 338                  $this->meta_query->queries = array(
 339                      'relation' => 'AND',
 340                      array( $this->meta_query->queries, $who_query ),
 341                  );
 342              }
 343  
 344              $this->meta_query->parse_query_vars( $this->meta_query->queries );
 345          }
 346  
 347          $roles = array();
 348          if ( isset( $qv['role'] ) ) {
 349              if ( is_array( $qv['role'] ) ) {
 350                  $roles = $qv['role'];
 351              } elseif ( is_string( $qv['role'] ) && ! empty( $qv['role'] ) ) {
 352                  $roles = array_map( 'trim', explode( ',', $qv['role'] ) );
 353              }
 354          }
 355  
 356          $role__in = array();
 357          if ( isset( $qv['role__in'] ) ) {
 358              $role__in = (array) $qv['role__in'];
 359          }
 360  
 361          $role__not_in = array();
 362          if ( isset( $qv['role__not_in'] ) ) {
 363              $role__not_in = (array) $qv['role__not_in'];
 364          }
 365  
 366          if ( $blog_id && ( ! empty( $roles ) || ! empty( $role__in ) || ! empty( $role__not_in ) || is_multisite() ) ) {
 367              $role_queries = array();
 368  
 369              $roles_clauses = array( 'relation' => 'AND' );
 370              if ( ! empty( $roles ) ) {
 371                  foreach ( $roles as $role ) {
 372                      $roles_clauses[] = array(
 373                          'key'     => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
 374                          'value'   => '"' . $role . '"',
 375                          'compare' => 'LIKE',
 376                      );
 377                  }
 378  
 379                  $role_queries[] = $roles_clauses;
 380              }
 381  
 382              $role__in_clauses = array( 'relation' => 'OR' );
 383              if ( ! empty( $role__in ) ) {
 384                  foreach ( $role__in as $role ) {
 385                      $role__in_clauses[] = array(
 386                          'key'     => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
 387                          'value'   => '"' . $role . '"',
 388                          'compare' => 'LIKE',
 389                      );
 390                  }
 391  
 392                  $role_queries[] = $role__in_clauses;
 393              }
 394  
 395              $role__not_in_clauses = array( 'relation' => 'AND' );
 396              if ( ! empty( $role__not_in ) ) {
 397                  foreach ( $role__not_in as $role ) {
 398                      $role__not_in_clauses[] = array(
 399                          'key'     => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
 400                          'value'   => '"' . $role . '"',
 401                          'compare' => 'NOT LIKE',
 402                      );
 403                  }
 404  
 405                  $role_queries[] = $role__not_in_clauses;
 406              }
 407  
 408              // If there are no specific roles named, make sure the user is a member of the site.
 409              if ( empty( $role_queries ) ) {
 410                  $role_queries[] = array(
 411                      'key'     => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
 412                      'compare' => 'EXISTS',
 413                  );
 414              }
 415  
 416              // Specify that role queries should be joined with AND.
 417              $role_queries['relation'] = 'AND';
 418  
 419              if ( empty( $this->meta_query->queries ) ) {
 420                  $this->meta_query->queries = $role_queries;
 421              } else {
 422                  // Append the cap query to the original queries and reparse the query.
 423                  $this->meta_query->queries = array(
 424                      'relation' => 'AND',
 425                      array( $this->meta_query->queries, $role_queries ),
 426                  );
 427              }
 428  
 429              $this->meta_query->parse_query_vars( $this->meta_query->queries );
 430          }
 431  
 432          if ( ! empty( $this->meta_query->queries ) ) {
 433              $clauses            = $this->meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
 434              $this->query_from  .= $clauses['join'];
 435              $this->query_where .= $clauses['where'];
 436  
 437              if ( $this->meta_query->has_or_relation() ) {
 438                  $this->query_fields = 'DISTINCT ' . $this->query_fields;
 439              }
 440          }
 441  
 442          // sorting
 443          $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
 444          $order       = $this->parse_order( $qv['order'] );
 445  
 446          if ( empty( $qv['orderby'] ) ) {
 447              // Default order is by 'user_login'.
 448              $ordersby = array( 'user_login' => $order );
 449          } elseif ( is_array( $qv['orderby'] ) ) {
 450              $ordersby = $qv['orderby'];
 451          } else {
 452              // 'orderby' values may be a comma- or space-separated list.
 453              $ordersby = preg_split( '/[,\s]+/', $qv['orderby'] );
 454          }
 455  
 456          $orderby_array = array();
 457          foreach ( $ordersby as $_key => $_value ) {
 458              if ( ! $_value ) {
 459                  continue;
 460              }
 461  
 462              if ( is_int( $_key ) ) {
 463                  // Integer key means this is a flat array of 'orderby' fields.
 464                  $_orderby = $_value;
 465                  $_order   = $order;
 466              } else {
 467                  // Non-integer key means this the key is the field and the value is ASC/DESC.
 468                  $_orderby = $_key;
 469                  $_order   = $_value;
 470              }
 471  
 472              $parsed = $this->parse_orderby( $_orderby );
 473  
 474              if ( ! $parsed ) {
 475                  continue;
 476              }
 477  
 478              if ( 'nicename__in' === $_orderby || 'login__in' === $_orderby ) {
 479                  $orderby_array[] = $parsed;
 480              } else {
 481                  $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
 482              }
 483          }
 484  
 485          // If no valid clauses were found, order by user_login.
 486          if ( empty( $orderby_array ) ) {
 487              $orderby_array[] = "user_login $order";
 488          }
 489  
 490          $this->query_orderby = 'ORDER BY ' . implode( ', ', $orderby_array );
 491  
 492          // limit
 493          if ( isset( $qv['number'] ) && $qv['number'] > 0 ) {
 494              if ( $qv['offset'] ) {
 495                  $this->query_limit = $wpdb->prepare( 'LIMIT %d, %d', $qv['offset'], $qv['number'] );
 496              } else {
 497                  $this->query_limit = $wpdb->prepare( 'LIMIT %d, %d', $qv['number'] * ( $qv['paged'] - 1 ), $qv['number'] );
 498              }
 499          }
 500  
 501          $search = '';
 502          if ( isset( $qv['search'] ) ) {
 503              $search = trim( $qv['search'] );
 504          }
 505  
 506          if ( $search ) {
 507              $leading_wild  = ( ltrim( $search, '*' ) != $search );
 508              $trailing_wild = ( rtrim( $search, '*' ) != $search );
 509              if ( $leading_wild && $trailing_wild ) {
 510                  $wild = 'both';
 511              } elseif ( $leading_wild ) {
 512                  $wild = 'leading';
 513              } elseif ( $trailing_wild ) {
 514                  $wild = 'trailing';
 515              } else {
 516                  $wild = false;
 517              }
 518              if ( $wild ) {
 519                  $search = trim( $search, '*' );
 520              }
 521  
 522              $search_columns = array();
 523              if ( $qv['search_columns'] ) {
 524                  $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename', 'display_name' ) );
 525              }
 526              if ( ! $search_columns ) {
 527                  if ( false !== strpos( $search, '@' ) ) {
 528                      $search_columns = array( 'user_email' );
 529                  } elseif ( is_numeric( $search ) ) {
 530                      $search_columns = array( 'user_login', 'ID' );
 531                  } elseif ( preg_match( '|^https?://|', $search ) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) ) {
 532                      $search_columns = array( 'user_url' );
 533                  } else {
 534                      $search_columns = array( 'user_login', 'user_url', 'user_email', 'user_nicename', 'display_name' );
 535                  }
 536              }
 537  
 538              /**
 539               * Filters the columns to search in a WP_User_Query search.
 540               *
 541               * The default columns depend on the search term, and include 'ID', 'user_login',
 542               * 'user_email', 'user_url', 'user_nicename', and 'display_name'.
 543               *
 544               * @since 3.6.0
 545               *
 546               * @param string[]      $search_columns Array of column names to be searched.
 547               * @param string        $search         Text being searched.
 548               * @param WP_User_Query $this           The current WP_User_Query instance.
 549               */
 550              $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
 551  
 552              $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
 553          }
 554  
 555          if ( ! empty( $include ) ) {
 556              // Sanitized earlier.
 557              $ids                = implode( ',', $include );
 558              $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
 559          } elseif ( ! empty( $qv['exclude'] ) ) {
 560              $ids                = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
 561              $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
 562          }
 563  
 564          // Date queries are allowed for the user_registered field.
 565          if ( ! empty( $qv['date_query'] ) && is_array( $qv['date_query'] ) ) {
 566              $date_query         = new WP_Date_Query( $qv['date_query'], 'user_registered' );
 567              $this->query_where .= $date_query->get_sql();
 568          }
 569  
 570          /**
 571           * Fires after the WP_User_Query has been parsed, and before
 572           * the query is executed.
 573           *
 574           * The passed WP_User_Query object contains SQL parts formed
 575           * from parsing the given query.
 576           *
 577           * @since 3.1.0
 578           *
 579           * @param WP_User_Query $this The current WP_User_Query instance,
 580           *                            passed by reference.
 581           */
 582          do_action_ref_array( 'pre_user_query', array( &$this ) );
 583      }
 584  
 585      /**
 586       * Execute the query, with the current variables.
 587       *
 588       * @since 3.1.0
 589       *
 590       * @global wpdb $wpdb WordPress database abstraction object.
 591       */
 592  	public function query() {
 593          global $wpdb;
 594  
 595          $qv =& $this->query_vars;
 596  
 597          /**
 598           * Filters the users array before the query takes place.
 599           *
 600           * Return a non-null value to bypass WordPress's default user queries.
 601           * Filtering functions that require pagination information are encouraged to set
 602           * the `total_users` property of the WP_User_Query object, passed to the filter
 603           * by reference. If WP_User_Query does not perform a database query, it will not
 604           * have enough information to generate these values itself.
 605           *
 606           * @since 5.1.0
 607           *
 608           * @param array|null $results Return an array of user data to short-circuit WP's user query
 609           *                            or null to allow WP to run its normal queries.
 610           * @param WP_User_Query $this The WP_User_Query instance (passed by reference).
 611           */
 612          $this->results = apply_filters_ref_array( 'users_pre_query', array( null, &$this ) );
 613  
 614          if ( null === $this->results ) {
 615              $this->request = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
 616  
 617              if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
 618                  $this->results = $wpdb->get_results( $this->request );
 619              } else {
 620                  $this->results = $wpdb->get_col( $this->request );
 621              }
 622  
 623              if ( isset( $qv['count_total'] ) && $qv['count_total'] ) {
 624                  /**
 625                   * Filters SELECT FOUND_ROWS() query for the current WP_User_Query instance.
 626                   *
 627                   * @since 3.2.0
 628                   * @since 5.1.0 Added the `$this` parameter.
 629                   *
 630                   * @global wpdb $wpdb WordPress database abstraction object.
 631                   *
 632                   * @param string $sql         The SELECT FOUND_ROWS() query for the current WP_User_Query.
 633                   * @param WP_User_Query $this The current WP_User_Query instance.
 634                   */
 635                  $found_users_query = apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()', $this );
 636  
 637                  $this->total_users = (int) $wpdb->get_var( $found_users_query );
 638              }
 639          }
 640  
 641          if ( ! $this->results ) {
 642              return;
 643          }
 644  
 645          if ( 'all_with_meta' == $qv['fields'] ) {
 646              cache_users( $this->results );
 647  
 648              $r = array();
 649              foreach ( $this->results as $userid ) {
 650                  $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
 651              }
 652  
 653              $this->results = $r;
 654          } elseif ( 'all' == $qv['fields'] ) {
 655              foreach ( $this->results as $key => $user ) {
 656                  $this->results[ $key ] = new WP_User( $user, '', $qv['blog_id'] );
 657              }
 658          }
 659      }
 660  
 661      /**
 662       * Retrieve query variable.
 663       *
 664       * @since 3.5.0
 665       *
 666       * @param string $query_var Query variable key.
 667       * @return mixed
 668       */
 669  	public function get( $query_var ) {
 670          if ( isset( $this->query_vars[ $query_var ] ) ) {
 671              return $this->query_vars[ $query_var ];
 672          }
 673  
 674          return null;
 675      }
 676  
 677      /**
 678       * Set query variable.
 679       *
 680       * @since 3.5.0
 681       *
 682       * @param string $query_var Query variable key.
 683       * @param mixed $value Query variable value.
 684       */
 685  	public function set( $query_var, $value ) {
 686          $this->query_vars[ $query_var ] = $value;
 687      }
 688  
 689      /**
 690       * Used internally to generate an SQL string for searching across multiple columns
 691       *
 692       * @since 3.1.0
 693       *
 694       * @global wpdb $wpdb WordPress database abstraction object.
 695       *
 696       * @param string $string
 697       * @param array  $cols
 698       * @param bool   $wild   Whether to allow wildcard searches. Default is false for Network Admin, true for single site.
 699       *                       Single site allows leading and trailing wildcards, Network Admin only trailing.
 700       * @return string
 701       */
 702  	protected function get_search_sql( $string, $cols, $wild = false ) {
 703          global $wpdb;
 704  
 705          $searches      = array();
 706          $leading_wild  = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
 707          $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
 708          $like          = $leading_wild . $wpdb->esc_like( $string ) . $trailing_wild;
 709  
 710          foreach ( $cols as $col ) {
 711              if ( 'ID' == $col ) {
 712                  $searches[] = $wpdb->prepare( "$col = %s", $string );
 713              } else {
 714                  $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
 715              }
 716          }
 717  
 718          return ' AND (' . implode( ' OR ', $searches ) . ')';
 719      }
 720  
 721      /**
 722       * Return the list of users.
 723       *
 724       * @since 3.1.0
 725       *
 726       * @return array Array of results.
 727       */
 728  	public function get_results() {
 729          return $this->results;
 730      }
 731  
 732      /**
 733       * Return the total number of users for the current query.
 734       *
 735       * @since 3.1.0
 736       *
 737       * @return int Number of total users.
 738       */
 739  	public function get_total() {
 740          return $this->total_users;
 741      }
 742  
 743      /**
 744       * Parse and sanitize 'orderby' keys passed to the user query.
 745       *
 746       * @since 4.2.0
 747       *
 748       * @global wpdb $wpdb WordPress database abstraction object.
 749       *
 750       * @param string $orderby Alias for the field to order by.
 751       * @return string Value to used in the ORDER clause, if `$orderby` is valid.
 752       */
 753  	protected function parse_orderby( $orderby ) {
 754          global $wpdb;
 755  
 756          $meta_query_clauses = $this->meta_query->get_clauses();
 757  
 758          $_orderby = '';
 759          if ( in_array( $orderby, array( 'login', 'nicename', 'email', 'url', 'registered' ) ) ) {
 760              $_orderby = 'user_' . $orderby;
 761          } elseif ( in_array( $orderby, array( 'user_login', 'user_nicename', 'user_email', 'user_url', 'user_registered' ) ) ) {
 762              $_orderby = $orderby;
 763          } elseif ( 'name' == $orderby || 'display_name' == $orderby ) {
 764              $_orderby = 'display_name';
 765          } elseif ( 'post_count' == $orderby ) {
 766              // todo: avoid the JOIN
 767              $where             = get_posts_by_author_sql( 'post' );
 768              $this->query_from .= " LEFT OUTER JOIN (
 769                  SELECT post_author, COUNT(*) as post_count
 770                  FROM $wpdb->posts
 771                  $where
 772                  GROUP BY post_author
 773              ) p ON ({$wpdb->users}.ID = p.post_author)
 774              ";
 775              $_orderby          = 'post_count';
 776          } elseif ( 'ID' == $orderby || 'id' == $orderby ) {
 777              $_orderby = 'ID';
 778          } elseif ( 'meta_value' == $orderby || $this->get( 'meta_key' ) == $orderby ) {
 779              $_orderby = "$wpdb->usermeta.meta_value";
 780          } elseif ( 'meta_value_num' == $orderby ) {
 781              $_orderby = "$wpdb->usermeta.meta_value+0";
 782          } elseif ( 'include' === $orderby && ! empty( $this->query_vars['include'] ) ) {
 783              $include     = wp_parse_id_list( $this->query_vars['include'] );
 784              $include_sql = implode( ',', $include );
 785              $_orderby    = "FIELD( $wpdb->users.ID, $include_sql )";
 786          } elseif ( 'nicename__in' === $orderby ) {
 787              $sanitized_nicename__in = array_map( 'esc_sql', $this->query_vars['nicename__in'] );
 788              $nicename__in           = implode( "','", $sanitized_nicename__in );
 789              $_orderby               = "FIELD( user_nicename, '$nicename__in' )";
 790          } elseif ( 'login__in' === $orderby ) {
 791              $sanitized_login__in = array_map( 'esc_sql', $this->query_vars['login__in'] );
 792              $login__in           = implode( "','", $sanitized_login__in );
 793              $_orderby            = "FIELD( user_login, '$login__in' )";
 794          } elseif ( isset( $meta_query_clauses[ $orderby ] ) ) {
 795              $meta_clause = $meta_query_clauses[ $orderby ];
 796              $_orderby    = sprintf( 'CAST(%s.meta_value AS %s)', esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
 797          }
 798  
 799          return $_orderby;
 800      }
 801  
 802      /**
 803       * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
 804       *
 805       * @since 4.2.0
 806       *
 807       * @param string $order The 'order' query variable.
 808       * @return string The sanitized 'order' query variable.
 809       */
 810  	protected function parse_order( $order ) {
 811          if ( ! is_string( $order ) || empty( $order ) ) {
 812              return 'DESC';
 813          }
 814  
 815          if ( 'ASC' === strtoupper( $order ) ) {
 816              return 'ASC';
 817          } else {
 818              return 'DESC';
 819          }
 820      }
 821  
 822      /**
 823       * Make private properties readable for backward compatibility.
 824       *
 825       * @since 4.0.0
 826       *
 827       * @param string $name Property to get.
 828       * @return mixed Property.
 829       */
 830  	public function __get( $name ) {
 831          if ( in_array( $name, $this->compat_fields ) ) {
 832              return $this->$name;
 833          }
 834      }
 835  
 836      /**
 837       * Make private properties settable for backward compatibility.
 838       *
 839       * @since 4.0.0
 840       *
 841       * @param string $name  Property to check if set.
 842       * @param mixed  $value Property value.
 843       * @return mixed Newly-set property.
 844       */
 845  	public function __set( $name, $value ) {
 846          if ( in_array( $name, $this->compat_fields ) ) {
 847              return $this->$name = $value;
 848          }
 849      }
 850  
 851      /**
 852       * Make private properties checkable for backward compatibility.
 853       *
 854       * @since 4.0.0
 855       *
 856       * @param string $name Property to check if set.
 857       * @return bool Whether the property is set.
 858       */
 859  	public function __isset( $name ) {
 860          if ( in_array( $name, $this->compat_fields ) ) {
 861              return isset( $this->$name );
 862          }
 863      }
 864  
 865      /**
 866       * Make private properties un-settable for backward compatibility.
 867       *
 868       * @since 4.0.0
 869       *
 870       * @param string $name Property to unset.
 871       */
 872  	public function __unset( $name ) {
 873          if ( in_array( $name, $this->compat_fields ) ) {
 874              unset( $this->$name );
 875          }
 876      }
 877  
 878      /**
 879       * Make private/protected methods readable for backward compatibility.
 880       *
 881       * @since 4.0.0
 882       *
 883       * @param string   $name      Method to call.
 884       * @param array    $arguments Arguments to pass when calling.
 885       * @return mixed Return value of the callback, false otherwise.
 886       */
 887  	public function __call( $name, $arguments ) {
 888          if ( 'get_search_sql' === $name ) {
 889              return $this->get_search_sql( ...$arguments );
 890          }
 891          return false;
 892      }
 893  }


Generated: Wed Oct 16 08:20:01 2019 Cross-referenced by PHPXref 0.7