class-wp-user-query.php 39 KB

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