Ei kuvausta

class-wp-user-query.php 31KB

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