Brak opisu

class-wp-user-query.php 39KB

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