[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Sun Jun 26 01:00:03 2022 Cross-referenced by PHPXref 0.7.1