[ Index ]

PHP Cross Reference of WordPress

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


Generated: Sun Dec 5 01:00:03 2021 Cross-referenced by PHPXref 0.7.1