class-wp-user-query.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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. 'meta_key' => '',
  87. 'meta_value' => '',
  88. 'meta_compare' => '',
  89. 'include' => array(),
  90. 'exclude' => array(),
  91. 'search' => '',
  92. 'search_columns' => array(),
  93. 'orderby' => 'login',
  94. 'order' => 'ASC',
  95. 'offset' => '',
  96. 'number' => '',
  97. 'paged' => 1,
  98. 'count_total' => true,
  99. 'fields' => 'all',
  100. 'who' => '',
  101. 'has_published_posts' => null,
  102. 'nicename' => '',
  103. 'nicename__in' => array(),
  104. 'nicename__not_in' => array(),
  105. 'login' => '',
  106. 'login__in' => array(),
  107. 'login__not_in' => array(),
  108. );
  109. return wp_parse_args( $args, $defaults );
  110. }
  111. /**
  112. * Prepare the query variables.
  113. *
  114. * @since 3.1.0
  115. * @since 4.1.0 Added the ability to order by the `include` value.
  116. * @since 4.2.0 Added 'meta_value_num' support for `$orderby` parameter. Added multi-dimensional array syntax
  117. * for `$orderby` parameter.
  118. * @since 4.3.0 Added 'has_published_posts' parameter.
  119. * @since 4.4.0 Added 'paged', 'role__in', and 'role__not_in' parameters. The 'role' parameter was updated to
  120. * permit an array or comma-separated list of values. The 'number' parameter was updated to support
  121. * querying for all users with using -1.
  122. * @since 4.7.0 Added 'nicename', 'nicename__in', 'nicename__not_in', 'login', 'login__in',
  123. * and 'login__not_in' parameters.
  124. *
  125. * @global wpdb $wpdb WordPress database abstraction object.
  126. * @global int $blog_id
  127. *
  128. * @param string|array $query {
  129. * Optional. Array or string of Query parameters.
  130. *
  131. * @type int $blog_id The site ID. Default is the current site.
  132. * @type string|array $role An array or a comma-separated list of role names that users must match
  133. * to be included in results. Note that this is an inclusive list: users
  134. * must match *each* role. Default empty.
  135. * @type array $role__in An array of role names. Matched users must have at least one of these
  136. * roles. Default empty array.
  137. * @type array $role__not_in An array of role names to exclude. Users matching one or more of these
  138. * roles will not be included in results. Default empty array.
  139. * @type string $meta_key User meta key. Default empty.
  140. * @type string $meta_value User meta value. Default empty.
  141. * @type string $meta_compare Comparison operator to test the `$meta_value`. Accepts '=', '!=',
  142. * '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
  143. * 'BETWEEN', 'NOT BETWEEN', 'EXISTS', 'NOT EXISTS', 'REGEXP',
  144. * 'NOT REGEXP', or 'RLIKE'. Default '='.
  145. * @type array $include An array of user IDs to include. Default empty array.
  146. * @type array $exclude An array of user IDs to exclude. Default empty array.
  147. * @type string $search Search keyword. Searches for possible string matches on columns.
  148. * When `$search_columns` is left empty, it tries to determine which
  149. * column to search in based on search string. Default empty.
  150. * @type array $search_columns Array of column names to be searched. Accepts 'ID', 'user_login',
  151. * 'user_email', 'user_url', 'user_nicename', 'display_name'.
  152. * Default empty array.
  153. * @type string|array $orderby Field(s) to sort the retrieved users by. May be a single value,
  154. * an array of values, or a multi-dimensional array with fields as
  155. * keys and orders ('ASC' or 'DESC') as values. Accepted values are
  156. * 'ID', 'display_name' (or 'name'), 'include', 'user_login'
  157. * (or 'login'), 'login__in', 'user_nicename' (or 'nicename'),
  158. * 'nicename__in', 'user_email (or 'email'), 'user_url' (or 'url'),
  159. * 'user_registered' (or 'registered'), 'post_count', 'meta_value',
  160. * 'meta_value_num', the value of `$meta_key`, or an array key of
  161. * `$meta_query`. To use 'meta_value' or 'meta_value_num', `$meta_key`
  162. * must be also be defined. Default 'user_login'.
  163. * @type string $order Designates ascending or descending order of users. Order values
  164. * passed as part of an `$orderby` array take precedence over this
  165. * parameter. Accepts 'ASC', 'DESC'. Default 'ASC'.
  166. * @type int $offset Number of users to offset in retrieved results. Can be used in
  167. * conjunction with pagination. Default 0.
  168. * @type int $number Number of users to limit the query for. Can be used in
  169. * conjunction with pagination. Value -1 (all) is supported, but
  170. * should be used with caution on larger sites.
  171. * Default -1 (all users).
  172. * @type int $paged When used with number, defines the page of results to return.
  173. * Default 1.
  174. * @type bool $count_total Whether to count the total number of users found. If pagination
  175. * is not needed, setting this to false can improve performance.
  176. * Default true.
  177. * @type string|array $fields Which fields to return. Single or all fields (string), or array
  178. * of fields. Accepts 'ID', 'display_name', 'user_login',
  179. * 'user_nicename', 'user_email', 'user_url', 'user_registered'.
  180. * Use 'all' for all fields and 'all_with_meta' to include
  181. * meta fields. Default 'all'.
  182. * @type string $who Type of users to query. Accepts 'authors'.
  183. * Default empty (all users).
  184. * @type bool|array $has_published_posts Pass an array of post types to filter results to users who have
  185. * published posts in those post types. `true` is an alias for all
  186. * public post types.
  187. * @type string $nicename The user nicename. Default empty.
  188. * @type array $nicename__in An array of nicenames to include. Users matching one of these
  189. * nicenames will be included in results. Default empty array.
  190. * @type array $nicename__not_in An array of nicenames to exclude. Users matching one of these
  191. * nicenames will not be included in results. Default empty array.
  192. * @type string $login The user login. Default empty.
  193. * @type array $login__in An array of logins to include. Users matching one of these
  194. * logins will be included in results. Default empty array.
  195. * @type array $login__not_in An array of logins to exclude. Users matching one of these
  196. * logins will not be included in results. Default empty array.
  197. * }
  198. */
  199. public function prepare_query( $query = array() ) {
  200. global $wpdb;
  201. if ( empty( $this->query_vars ) || ! empty( $query ) ) {
  202. $this->query_limit = null;
  203. $this->query_vars = $this->fill_query_vars( $query );
  204. }
  205. /**
  206. * Fires before the WP_User_Query has been parsed.
  207. *
  208. * The passed WP_User_Query object contains the query variables, not
  209. * yet passed into SQL.
  210. *
  211. * @since 4.0.0
  212. *
  213. * @param WP_User_Query $this The current WP_User_Query instance,
  214. * passed by reference.
  215. */
  216. do_action( 'pre_get_users', $this );
  217. // Ensure that query vars are filled after 'pre_get_users'.
  218. $qv =& $this->query_vars;
  219. $qv = $this->fill_query_vars( $qv );
  220. if ( is_array( $qv['fields'] ) ) {
  221. $qv['fields'] = array_unique( $qv['fields'] );
  222. $this->query_fields = array();
  223. foreach ( $qv['fields'] as $field ) {
  224. $field = 'ID' === $field ? 'ID' : sanitize_key( $field );
  225. $this->query_fields[] = "$wpdb->users.$field";
  226. }
  227. $this->query_fields = implode( ',', $this->query_fields );
  228. } elseif ( 'all' == $qv['fields'] ) {
  229. $this->query_fields = "$wpdb->users.*";
  230. } else {
  231. $this->query_fields = "$wpdb->users.ID";
  232. }
  233. if ( isset( $qv['count_total'] ) && $qv['count_total'] ) {
  234. $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
  235. }
  236. $this->query_from = "FROM $wpdb->users";
  237. $this->query_where = 'WHERE 1=1';
  238. // Parse and sanitize 'include', for use by 'orderby' as well as 'include' below.
  239. if ( ! empty( $qv['include'] ) ) {
  240. $include = wp_parse_id_list( $qv['include'] );
  241. } else {
  242. $include = false;
  243. }
  244. $blog_id = 0;
  245. if ( isset( $qv['blog_id'] ) ) {
  246. $blog_id = absint( $qv['blog_id'] );
  247. }
  248. if ( $qv['has_published_posts'] && $blog_id ) {
  249. if ( true === $qv['has_published_posts'] ) {
  250. $post_types = get_post_types( array( 'public' => true ) );
  251. } else {
  252. $post_types = (array) $qv['has_published_posts'];
  253. }
  254. foreach ( $post_types as &$post_type ) {
  255. $post_type = $wpdb->prepare( '%s', $post_type );
  256. }
  257. $posts_table = $wpdb->get_blog_prefix( $blog_id ) . 'posts';
  258. $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 ( " . join( ', ', $post_types ) . ' ) )';
  259. }
  260. // nicename
  261. if ( '' !== $qv['nicename'] ) {
  262. $this->query_where .= $wpdb->prepare( ' AND user_nicename = %s', $qv['nicename'] );
  263. }
  264. if ( ! empty( $qv['nicename__in'] ) ) {
  265. $sanitized_nicename__in = array_map( 'esc_sql', $qv['nicename__in'] );
  266. $nicename__in = implode( "','", $sanitized_nicename__in );
  267. $this->query_where .= " AND user_nicename IN ( '$nicename__in' )";
  268. }
  269. if ( ! empty( $qv['nicename__not_in'] ) ) {
  270. $sanitized_nicename__not_in = array_map( 'esc_sql', $qv['nicename__not_in'] );
  271. $nicename__not_in = implode( "','", $sanitized_nicename__not_in );
  272. $this->query_where .= " AND user_nicename NOT IN ( '$nicename__not_in' )";
  273. }
  274. // login
  275. if ( '' !== $qv['login'] ) {
  276. $this->query_where .= $wpdb->prepare( ' AND user_login = %s', $qv['login'] );
  277. }
  278. if ( ! empty( $qv['login__in'] ) ) {
  279. $sanitized_login__in = array_map( 'esc_sql', $qv['login__in'] );
  280. $login__in = implode( "','", $sanitized_login__in );
  281. $this->query_where .= " AND user_login IN ( '$login__in' )";
  282. }
  283. if ( ! empty( $qv['login__not_in'] ) ) {
  284. $sanitized_login__not_in = array_map( 'esc_sql', $qv['login__not_in'] );
  285. $login__not_in = implode( "','", $sanitized_login__not_in );
  286. $this->query_where .= " AND user_login NOT IN ( '$login__not_in' )";
  287. }
  288. // Meta query.
  289. $this->meta_query = new WP_Meta_Query();
  290. $this->meta_query->parse_query_vars( $qv );
  291. if ( isset( $qv['who'] ) && 'authors' == $qv['who'] && $blog_id ) {
  292. $who_query = array(
  293. 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'user_level',
  294. 'value' => 0,
  295. 'compare' => '!=',
  296. );
  297. // Prevent extra meta query.
  298. $qv['blog_id'] = 0;
  299. $blog_id = 0;
  300. if ( empty( $this->meta_query->queries ) ) {
  301. $this->meta_query->queries = array( $who_query );
  302. } else {
  303. // Append the cap query to the original queries and reparse the query.
  304. $this->meta_query->queries = array(
  305. 'relation' => 'AND',
  306. array( $this->meta_query->queries, $who_query ),
  307. );
  308. }
  309. $this->meta_query->parse_query_vars( $this->meta_query->queries );
  310. }
  311. $roles = array();
  312. if ( isset( $qv['role'] ) ) {
  313. if ( is_array( $qv['role'] ) ) {
  314. $roles = $qv['role'];
  315. } elseif ( is_string( $qv['role'] ) && ! empty( $qv['role'] ) ) {
  316. $roles = array_map( 'trim', explode( ',', $qv['role'] ) );
  317. }
  318. }
  319. $role__in = array();
  320. if ( isset( $qv['role__in'] ) ) {
  321. $role__in = (array) $qv['role__in'];
  322. }
  323. $role__not_in = array();
  324. if ( isset( $qv['role__not_in'] ) ) {
  325. $role__not_in = (array) $qv['role__not_in'];
  326. }
  327. if ( $blog_id && ( ! empty( $roles ) || ! empty( $role__in ) || ! empty( $role__not_in ) || is_multisite() ) ) {
  328. $role_queries = array();
  329. $roles_clauses = array( 'relation' => 'AND' );
  330. if ( ! empty( $roles ) ) {
  331. foreach ( $roles as $role ) {
  332. $roles_clauses[] = array(
  333. 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
  334. 'value' => '"' . $role . '"',
  335. 'compare' => 'LIKE',
  336. );
  337. }
  338. $role_queries[] = $roles_clauses;
  339. }
  340. $role__in_clauses = array( 'relation' => 'OR' );
  341. if ( ! empty( $role__in ) ) {
  342. foreach ( $role__in as $role ) {
  343. $role__in_clauses[] = array(
  344. 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
  345. 'value' => '"' . $role . '"',
  346. 'compare' => 'LIKE',
  347. );
  348. }
  349. $role_queries[] = $role__in_clauses;
  350. }
  351. $role__not_in_clauses = array( 'relation' => 'AND' );
  352. if ( ! empty( $role__not_in ) ) {
  353. foreach ( $role__not_in as $role ) {
  354. $role__not_in_clauses[] = array(
  355. 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
  356. 'value' => '"' . $role . '"',
  357. 'compare' => 'NOT LIKE',
  358. );
  359. }
  360. $role_queries[] = $role__not_in_clauses;
  361. }
  362. // If there are no specific roles named, make sure the user is a member of the site.
  363. if ( empty( $role_queries ) ) {
  364. $role_queries[] = array(
  365. 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
  366. 'compare' => 'EXISTS',
  367. );
  368. }
  369. // Specify that role queries should be joined with AND.
  370. $role_queries['relation'] = 'AND';
  371. if ( empty( $this->meta_query->queries ) ) {
  372. $this->meta_query->queries = $role_queries;
  373. } else {
  374. // Append the cap query to the original queries and reparse the query.
  375. $this->meta_query->queries = array(
  376. 'relation' => 'AND',
  377. array( $this->meta_query->queries, $role_queries ),
  378. );
  379. }
  380. $this->meta_query->parse_query_vars( $this->meta_query->queries );
  381. }
  382. if ( ! empty( $this->meta_query->queries ) ) {
  383. $clauses = $this->meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
  384. $this->query_from .= $clauses['join'];
  385. $this->query_where .= $clauses['where'];
  386. if ( $this->meta_query->has_or_relation() ) {
  387. $this->query_fields = 'DISTINCT ' . $this->query_fields;
  388. }
  389. }
  390. // sorting
  391. $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
  392. $order = $this->parse_order( $qv['order'] );
  393. if ( empty( $qv['orderby'] ) ) {
  394. // Default order is by 'user_login'.
  395. $ordersby = array( 'user_login' => $order );
  396. } elseif ( is_array( $qv['orderby'] ) ) {
  397. $ordersby = $qv['orderby'];
  398. } else {
  399. // 'orderby' values may be a comma- or space-separated list.
  400. $ordersby = preg_split( '/[,\s]+/', $qv['orderby'] );
  401. }
  402. $orderby_array = array();
  403. foreach ( $ordersby as $_key => $_value ) {
  404. if ( ! $_value ) {
  405. continue;
  406. }
  407. if ( is_int( $_key ) ) {
  408. // Integer key means this is a flat array of 'orderby' fields.
  409. $_orderby = $_value;
  410. $_order = $order;
  411. } else {
  412. // Non-integer key means this the key is the field and the value is ASC/DESC.
  413. $_orderby = $_key;
  414. $_order = $_value;
  415. }
  416. $parsed = $this->parse_orderby( $_orderby );
  417. if ( ! $parsed ) {
  418. continue;
  419. }
  420. if ( 'nicename__in' === $_orderby || 'login__in' === $_orderby ) {
  421. $orderby_array[] = $parsed;
  422. } else {
  423. $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
  424. }
  425. }
  426. // If no valid clauses were found, order by user_login.
  427. if ( empty( $orderby_array ) ) {
  428. $orderby_array[] = "user_login $order";
  429. }
  430. $this->query_orderby = 'ORDER BY ' . implode( ', ', $orderby_array );
  431. // limit
  432. if ( isset( $qv['number'] ) && $qv['number'] > 0 ) {
  433. if ( $qv['offset'] ) {
  434. $this->query_limit = $wpdb->prepare( 'LIMIT %d, %d', $qv['offset'], $qv['number'] );
  435. } else {
  436. $this->query_limit = $wpdb->prepare( 'LIMIT %d, %d', $qv['number'] * ( $qv['paged'] - 1 ), $qv['number'] );
  437. }
  438. }
  439. $search = '';
  440. if ( isset( $qv['search'] ) ) {
  441. $search = trim( $qv['search'] );
  442. }
  443. if ( $search ) {
  444. $leading_wild = ( ltrim( $search, '*' ) != $search );
  445. $trailing_wild = ( rtrim( $search, '*' ) != $search );
  446. if ( $leading_wild && $trailing_wild ) {
  447. $wild = 'both';
  448. } elseif ( $leading_wild ) {
  449. $wild = 'leading';
  450. } elseif ( $trailing_wild ) {
  451. $wild = 'trailing';
  452. } else {
  453. $wild = false;
  454. }
  455. if ( $wild ) {
  456. $search = trim( $search, '*' );
  457. }
  458. $search_columns = array();
  459. if ( $qv['search_columns'] ) {
  460. $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename', 'display_name' ) );
  461. }
  462. if ( ! $search_columns ) {
  463. if ( false !== strpos( $search, '@' ) ) {
  464. $search_columns = array( 'user_email' );
  465. } elseif ( is_numeric( $search ) ) {
  466. $search_columns = array( 'user_login', 'ID' );
  467. } elseif ( preg_match( '|^https?://|', $search ) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) ) {
  468. $search_columns = array( 'user_url' );
  469. } else {
  470. $search_columns = array( 'user_login', 'user_url', 'user_email', 'user_nicename', 'display_name' );
  471. }
  472. }
  473. /**
  474. * Filters the columns to search in a WP_User_Query search.
  475. *
  476. * The default columns depend on the search term, and include 'ID', 'user_login',
  477. * 'user_email', 'user_url', 'user_nicename', and 'display_name'.
  478. *
  479. * @since 3.6.0
  480. *
  481. * @param string[] $search_columns Array of column names to be searched.
  482. * @param string $search Text being searched.
  483. * @param WP_User_Query $this The current WP_User_Query instance.
  484. */
  485. $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
  486. $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
  487. }
  488. if ( ! empty( $include ) ) {
  489. // Sanitized earlier.
  490. $ids = implode( ',', $include );
  491. $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
  492. } elseif ( ! empty( $qv['exclude'] ) ) {
  493. $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
  494. $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
  495. }
  496. // Date queries are allowed for the user_registered field.
  497. if ( ! empty( $qv['date_query'] ) && is_array( $qv['date_query'] ) ) {
  498. $date_query = new WP_Date_Query( $qv['date_query'], 'user_registered' );
  499. $this->query_where .= $date_query->get_sql();
  500. }
  501. /**
  502. * Fires after the WP_User_Query has been parsed, and before
  503. * the query is executed.
  504. *
  505. * The passed WP_User_Query object contains SQL parts formed
  506. * from parsing the given query.
  507. *
  508. * @since 3.1.0
  509. *
  510. * @param WP_User_Query $this The current WP_User_Query instance,
  511. * passed by reference.
  512. */
  513. do_action_ref_array( 'pre_user_query', array( &$this ) );
  514. }
  515. /**
  516. * Execute the query, with the current variables.
  517. *
  518. * @since 3.1.0
  519. *
  520. * @global wpdb $wpdb WordPress database abstraction object.
  521. */
  522. public function query() {
  523. global $wpdb;
  524. $qv =& $this->query_vars;
  525. /**
  526. * Filters the users array before the query takes place.
  527. *
  528. * Return a non-null value to bypass WordPress's default user queries.
  529. * Filtering functions that require pagination information are encouraged to set
  530. * the `total_users` property of the WP_User_Query object, passed to the filter
  531. * by reference. If WP_User_Query does not perform a database query, it will not
  532. * have enough information to generate these values itself.
  533. *
  534. * @since 5.1.0
  535. *
  536. * @param array|null $results Return an array of user data to short-circuit WP's user query
  537. * or null to allow WP to run its normal queries.
  538. * @param WP_User_Query $this The WP_User_Query instance (passed by reference).
  539. */
  540. $this->results = apply_filters_ref_array( 'users_pre_query', array( null, &$this ) );
  541. if ( null === $this->results ) {
  542. $this->request = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
  543. if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
  544. $this->results = $wpdb->get_results( $this->request );
  545. } else {
  546. $this->results = $wpdb->get_col( $this->request );
  547. }
  548. if ( isset( $qv['count_total'] ) && $qv['count_total'] ) {
  549. /**
  550. * Filters SELECT FOUND_ROWS() query for the current WP_User_Query instance.
  551. *
  552. * @since 3.2.0
  553. * @since 5.1.0 Added the `$this` parameter.
  554. *
  555. * @global wpdb $wpdb WordPress database abstraction object.
  556. *
  557. * @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
  558. * @param WP_User_Query $this The current WP_User_Query instance.
  559. */
  560. $found_users_query = apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()', $this );
  561. $this->total_users = (int) $wpdb->get_var( $found_users_query );
  562. }
  563. }
  564. if ( ! $this->results ) {
  565. return;
  566. }
  567. if ( 'all_with_meta' == $qv['fields'] ) {
  568. cache_users( $this->results );
  569. $r = array();
  570. foreach ( $this->results as $userid ) {
  571. $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
  572. }
  573. $this->results = $r;
  574. } elseif ( 'all' == $qv['fields'] ) {
  575. foreach ( $this->results as $key => $user ) {
  576. $this->results[ $key ] = new WP_User( $user, '', $qv['blog_id'] );
  577. }
  578. }
  579. }
  580. /**
  581. * Retrieve query variable.
  582. *
  583. * @since 3.5.0
  584. *
  585. * @param string $query_var Query variable key.
  586. * @return mixed
  587. */
  588. public function get( $query_var ) {
  589. if ( isset( $this->query_vars[ $query_var ] ) ) {
  590. return $this->query_vars[ $query_var ];
  591. }
  592. return null;
  593. }
  594. /**
  595. * Set query variable.
  596. *
  597. * @since 3.5.0
  598. *
  599. * @param string $query_var Query variable key.
  600. * @param mixed $value Query variable value.
  601. */
  602. public function set( $query_var, $value ) {
  603. $this->query_vars[ $query_var ] = $value;
  604. }
  605. /**
  606. * Used internally to generate an SQL string for searching across multiple columns
  607. *
  608. * @since 3.1.0
  609. *
  610. * @global wpdb $wpdb WordPress database abstraction object.
  611. *
  612. * @param string $string
  613. * @param array $cols
  614. * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for single site.
  615. * Single site allows leading and trailing wildcards, Network Admin only trailing.
  616. * @return string
  617. */
  618. protected function get_search_sql( $string, $cols, $wild = false ) {
  619. global $wpdb;
  620. $searches = array();
  621. $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
  622. $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
  623. $like = $leading_wild . $wpdb->esc_like( $string ) . $trailing_wild;
  624. foreach ( $cols as $col ) {
  625. if ( 'ID' == $col ) {
  626. $searches[] = $wpdb->prepare( "$col = %s", $string );
  627. } else {
  628. $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
  629. }
  630. }
  631. return ' AND (' . implode( ' OR ', $searches ) . ')';
  632. }
  633. /**
  634. * Return the list of users.
  635. *
  636. * @since 3.1.0
  637. *
  638. * @return array Array of results.
  639. */
  640. public function get_results() {
  641. return $this->results;
  642. }
  643. /**
  644. * Return the total number of users for the current query.
  645. *
  646. * @since 3.1.0
  647. *
  648. * @return int Number of total users.
  649. */
  650. public function get_total() {
  651. return $this->total_users;
  652. }
  653. /**
  654. * Parse and sanitize 'orderby' keys passed to the user query.
  655. *
  656. * @since 4.2.0
  657. *
  658. * @global wpdb $wpdb WordPress database abstraction object.
  659. *
  660. * @param string $orderby Alias for the field to order by.
  661. * @return string Value to used in the ORDER clause, if `$orderby` is valid.
  662. */
  663. protected function parse_orderby( $orderby ) {
  664. global $wpdb;
  665. $meta_query_clauses = $this->meta_query->get_clauses();
  666. $_orderby = '';
  667. if ( in_array( $orderby, array( 'login', 'nicename', 'email', 'url', 'registered' ) ) ) {
  668. $_orderby = 'user_' . $orderby;
  669. } elseif ( in_array( $orderby, array( 'user_login', 'user_nicename', 'user_email', 'user_url', 'user_registered' ) ) ) {
  670. $_orderby = $orderby;
  671. } elseif ( 'name' == $orderby || 'display_name' == $orderby ) {
  672. $_orderby = 'display_name';
  673. } elseif ( 'post_count' == $orderby ) {
  674. // todo: avoid the JOIN
  675. $where = get_posts_by_author_sql( 'post' );
  676. $this->query_from .= " LEFT OUTER JOIN (
  677. SELECT post_author, COUNT(*) as post_count
  678. FROM $wpdb->posts
  679. $where
  680. GROUP BY post_author
  681. ) p ON ({$wpdb->users}.ID = p.post_author)
  682. ";
  683. $_orderby = 'post_count';
  684. } elseif ( 'ID' == $orderby || 'id' == $orderby ) {
  685. $_orderby = 'ID';
  686. } elseif ( 'meta_value' == $orderby || $this->get( 'meta_key' ) == $orderby ) {
  687. $_orderby = "$wpdb->usermeta.meta_value";
  688. } elseif ( 'meta_value_num' == $orderby ) {
  689. $_orderby = "$wpdb->usermeta.meta_value+0";
  690. } elseif ( 'include' === $orderby && ! empty( $this->query_vars['include'] ) ) {
  691. $include = wp_parse_id_list( $this->query_vars['include'] );
  692. $include_sql = implode( ',', $include );
  693. $_orderby = "FIELD( $wpdb->users.ID, $include_sql )";
  694. } elseif ( 'nicename__in' === $orderby ) {
  695. $sanitized_nicename__in = array_map( 'esc_sql', $this->query_vars['nicename__in'] );
  696. $nicename__in = implode( "','", $sanitized_nicename__in );
  697. $_orderby = "FIELD( user_nicename, '$nicename__in' )";
  698. } elseif ( 'login__in' === $orderby ) {
  699. $sanitized_login__in = array_map( 'esc_sql', $this->query_vars['login__in'] );
  700. $login__in = implode( "','", $sanitized_login__in );
  701. $_orderby = "FIELD( user_login, '$login__in' )";
  702. } elseif ( isset( $meta_query_clauses[ $orderby ] ) ) {
  703. $meta_clause = $meta_query_clauses[ $orderby ];
  704. $_orderby = sprintf( 'CAST(%s.meta_value AS %s)', esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
  705. }
  706. return $_orderby;
  707. }
  708. /**
  709. * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
  710. *
  711. * @since 4.2.0
  712. *
  713. * @param string $order The 'order' query variable.
  714. * @return string The sanitized 'order' query variable.
  715. */
  716. protected function parse_order( $order ) {
  717. if ( ! is_string( $order ) || empty( $order ) ) {
  718. return 'DESC';
  719. }
  720. if ( 'ASC' === strtoupper( $order ) ) {
  721. return 'ASC';
  722. } else {
  723. return 'DESC';
  724. }
  725. }
  726. /**
  727. * Make private properties readable for backward compatibility.
  728. *
  729. * @since 4.0.0
  730. *
  731. * @param string $name Property to get.
  732. * @return mixed Property.
  733. */
  734. public function __get( $name ) {
  735. if ( in_array( $name, $this->compat_fields ) ) {
  736. return $this->$name;
  737. }
  738. }
  739. /**
  740. * Make private properties settable for backward compatibility.
  741. *
  742. * @since 4.0.0
  743. *
  744. * @param string $name Property to check if set.
  745. * @param mixed $value Property value.
  746. * @return mixed Newly-set property.
  747. */
  748. public function __set( $name, $value ) {
  749. if ( in_array( $name, $this->compat_fields ) ) {
  750. return $this->$name = $value;
  751. }
  752. }
  753. /**
  754. * Make private properties checkable for backward compatibility.
  755. *
  756. * @since 4.0.0
  757. *
  758. * @param string $name Property to check if set.
  759. * @return bool Whether the property is set.
  760. */
  761. public function __isset( $name ) {
  762. if ( in_array( $name, $this->compat_fields ) ) {
  763. return isset( $this->$name );
  764. }
  765. }
  766. /**
  767. * Make private properties un-settable for backward compatibility.
  768. *
  769. * @since 4.0.0
  770. *
  771. * @param string $name Property to unset.
  772. */
  773. public function __unset( $name ) {
  774. if ( in_array( $name, $this->compat_fields ) ) {
  775. unset( $this->$name );
  776. }
  777. }
  778. /**
  779. * Make private/protected methods readable for backward compatibility.
  780. *
  781. * @since 4.0.0
  782. *
  783. * @param string $name Method to call.
  784. * @param array $arguments Arguments to pass when calling.
  785. * @return mixed Return value of the callback, false otherwise.
  786. */
  787. public function __call( $name, $arguments ) {
  788. if ( 'get_search_sql' === $name ) {
  789. return $this->get_search_sql( ...$arguments );
  790. }
  791. return false;
  792. }
  793. }