[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

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


Generated : Fri Aug 19 08:20:02 2022 Cross-referenced by PHPXref