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


Generated : Thu May 9 08:20:02 2024 Cross-referenced by PHPXref