class-wp-user-query.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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. *
  126. * @global wpdb $wpdb WordPress database abstraction object.
  127. * @global int $blog_id
  128. *
  129. * @param string|array $query {
  130. * Optional. Array or string of Query parameters.
  131. *
  132. * @type int $blog_id The site ID. Default is the current site.
  133. * @type string|array $role An array or a comma-separated list of role names that users must match
  134. * to be included in results. Note that this is an inclusive list: users
  135. * must match *each* role. Default empty.
  136. * @type array $role__in An array of role names. Matched users must have at least one of these
  137. * roles. Default empty array.
  138. * @type array $role__not_in An array of role names to exclude. Users matching one or more of these
  139. * roles will not be included in results. Default empty array.
  140. * @type string $meta_key User meta key. Default empty.
  141. * @type string $meta_value User meta value. Default empty.
  142. * @type string $meta_compare Comparison operator to test the `$meta_value`. Accepts '=', '!=',
  143. * '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
  144. * 'BETWEEN', 'NOT BETWEEN', 'EXISTS', 'NOT EXISTS', 'REGEXP',
  145. * 'NOT REGEXP', or 'RLIKE'. Default '='.
  146. * @type array $include An array of user IDs to include. Default empty array.
  147. * @type array $exclude An array of user IDs to exclude. Default empty array.
  148. * @type string $search Search keyword. Searches for possible string matches on columns.
  149. * When `$search_columns` is left empty, it tries to determine which
  150. * column to search in based on search string. Default empty.
  151. * @type array $search_columns Array of column names to be searched. Accepts 'ID', 'login',
  152. * 'nicename', 'email', 'url'. 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 empty (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. $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 ( " . join( ", ", $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'] = $blog_id = 0;
  298. if ( empty( $this->meta_query->queries ) ) {
  299. $this->meta_query->queries = array( $who_query );
  300. } else {
  301. // Append the cap query to the original queries and reparse the query.
  302. $this->meta_query->queries = array(
  303. 'relation' => 'AND',
  304. array( $this->meta_query->queries, $who_query ),
  305. );
  306. }
  307. $this->meta_query->parse_query_vars( $this->meta_query->queries );
  308. }
  309. $roles = array();
  310. if ( isset( $qv['role'] ) ) {
  311. if ( is_array( $qv['role'] ) ) {
  312. $roles = $qv['role'];
  313. } elseif ( is_string( $qv['role'] ) && ! empty( $qv['role'] ) ) {
  314. $roles = array_map( 'trim', explode( ',', $qv['role'] ) );
  315. }
  316. }
  317. $role__in = array();
  318. if ( isset( $qv['role__in'] ) ) {
  319. $role__in = (array) $qv['role__in'];
  320. }
  321. $role__not_in = array();
  322. if ( isset( $qv['role__not_in'] ) ) {
  323. $role__not_in = (array) $qv['role__not_in'];
  324. }
  325. if ( $blog_id && ( ! empty( $roles ) || ! empty( $role__in ) || ! empty( $role__not_in ) || is_multisite() ) ) {
  326. $role_queries = array();
  327. $roles_clauses = array( 'relation' => 'AND' );
  328. if ( ! empty( $roles ) ) {
  329. foreach ( $roles as $role ) {
  330. $roles_clauses[] = array(
  331. 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
  332. 'value' => '"' . $role . '"',
  333. 'compare' => 'LIKE',
  334. );
  335. }
  336. $role_queries[] = $roles_clauses;
  337. }
  338. $role__in_clauses = array( 'relation' => 'OR' );
  339. if ( ! empty( $role__in ) ) {
  340. foreach ( $role__in as $role ) {
  341. $role__in_clauses[] = array(
  342. 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
  343. 'value' => '"' . $role . '"',
  344. 'compare' => 'LIKE',
  345. );
  346. }
  347. $role_queries[] = $role__in_clauses;
  348. }
  349. $role__not_in_clauses = array( 'relation' => 'AND' );
  350. if ( ! empty( $role__not_in ) ) {
  351. foreach ( $role__not_in as $role ) {
  352. $role__not_in_clauses[] = array(
  353. 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
  354. 'value' => '"' . $role . '"',
  355. 'compare' => 'NOT LIKE',
  356. );
  357. }
  358. $role_queries[] = $role__not_in_clauses;
  359. }
  360. // If there are no specific roles named, make sure the user is a member of the site.
  361. if ( empty( $role_queries ) ) {
  362. $role_queries[] = array(
  363. 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
  364. 'compare' => 'EXISTS',
  365. );
  366. }
  367. // Specify that role queries should be joined with AND.
  368. $role_queries['relation'] = 'AND';
  369. if ( empty( $this->meta_query->queries ) ) {
  370. $this->meta_query->queries = $role_queries;
  371. } else {
  372. // Append the cap query to the original queries and reparse the query.
  373. $this->meta_query->queries = array(
  374. 'relation' => 'AND',
  375. array( $this->meta_query->queries, $role_queries ),
  376. );
  377. }
  378. $this->meta_query->parse_query_vars( $this->meta_query->queries );
  379. }
  380. if ( ! empty( $this->meta_query->queries ) ) {
  381. $clauses = $this->meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
  382. $this->query_from .= $clauses['join'];
  383. $this->query_where .= $clauses['where'];
  384. if ( $this->meta_query->has_or_relation() ) {
  385. $this->query_fields = 'DISTINCT ' . $this->query_fields;
  386. }
  387. }
  388. // sorting
  389. $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
  390. $order = $this->parse_order( $qv['order'] );
  391. if ( empty( $qv['orderby'] ) ) {
  392. // Default order is by 'user_login'.
  393. $ordersby = array( 'user_login' => $order );
  394. } elseif ( is_array( $qv['orderby'] ) ) {
  395. $ordersby = $qv['orderby'];
  396. } else {
  397. // 'orderby' values may be a comma- or space-separated list.
  398. $ordersby = preg_split( '/[,\s]+/', $qv['orderby'] );
  399. }
  400. $orderby_array = array();
  401. foreach ( $ordersby as $_key => $_value ) {
  402. if ( ! $_value ) {
  403. continue;
  404. }
  405. if ( is_int( $_key ) ) {
  406. // Integer key means this is a flat array of 'orderby' fields.
  407. $_orderby = $_value;
  408. $_order = $order;
  409. } else {
  410. // Non-integer key means this the key is the field and the value is ASC/DESC.
  411. $_orderby = $_key;
  412. $_order = $_value;
  413. }
  414. $parsed = $this->parse_orderby( $_orderby );
  415. if ( ! $parsed ) {
  416. continue;
  417. }
  418. if ( 'nicename__in' === $_orderby || 'login__in' === $_orderby ) {
  419. $orderby_array[] = $parsed;
  420. } else {
  421. $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
  422. }
  423. }
  424. // If no valid clauses were found, order by user_login.
  425. if ( empty( $orderby_array ) ) {
  426. $orderby_array[] = "user_login $order";
  427. }
  428. $this->query_orderby = 'ORDER BY ' . implode( ', ', $orderby_array );
  429. // limit
  430. if ( isset( $qv['number'] ) && $qv['number'] > 0 ) {
  431. if ( $qv['offset'] ) {
  432. $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
  433. } else {
  434. $this->query_limit = $wpdb->prepare( "LIMIT %d, %d", $qv['number'] * ( $qv['paged'] - 1 ), $qv['number'] );
  435. }
  436. }
  437. $search = '';
  438. if ( isset( $qv['search'] ) )
  439. $search = trim( $qv['search'] );
  440. if ( $search ) {
  441. $leading_wild = ( ltrim($search, '*') != $search );
  442. $trailing_wild = ( rtrim($search, '*') != $search );
  443. if ( $leading_wild && $trailing_wild )
  444. $wild = 'both';
  445. elseif ( $leading_wild )
  446. $wild = 'leading';
  447. elseif ( $trailing_wild )
  448. $wild = 'trailing';
  449. else
  450. $wild = false;
  451. if ( $wild )
  452. $search = trim($search, '*');
  453. $search_columns = array();
  454. if ( $qv['search_columns'] ) {
  455. $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename', 'display_name' ) );
  456. }
  457. if ( ! $search_columns ) {
  458. if ( false !== strpos( $search, '@') )
  459. $search_columns = array('user_email');
  460. elseif ( is_numeric($search) )
  461. $search_columns = array('user_login', 'ID');
  462. elseif ( preg_match('|^https?://|', $search) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) )
  463. $search_columns = array('user_url');
  464. else
  465. $search_columns = array('user_login', 'user_url', 'user_email', 'user_nicename', 'display_name');
  466. }
  467. /**
  468. * Filters the columns to search in a WP_User_Query search.
  469. *
  470. * The default columns depend on the search term, and include 'user_email',
  471. * 'user_login', 'ID', 'user_url', 'display_name', and 'user_nicename'.
  472. *
  473. * @since 3.6.0
  474. *
  475. * @param array $search_columns Array of column names to be searched.
  476. * @param string $search Text being searched.
  477. * @param WP_User_Query $this The current WP_User_Query instance.
  478. */
  479. $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
  480. $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
  481. }
  482. if ( ! empty( $include ) ) {
  483. // Sanitized earlier.
  484. $ids = implode( ',', $include );
  485. $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
  486. } elseif ( ! empty( $qv['exclude'] ) ) {
  487. $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
  488. $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
  489. }
  490. // Date queries are allowed for the user_registered field.
  491. if ( ! empty( $qv['date_query'] ) && is_array( $qv['date_query'] ) ) {
  492. $date_query = new WP_Date_Query( $qv['date_query'], 'user_registered' );
  493. $this->query_where .= $date_query->get_sql();
  494. }
  495. /**
  496. * Fires after the WP_User_Query has been parsed, and before
  497. * the query is executed.
  498. *
  499. * The passed WP_User_Query object contains SQL parts formed
  500. * from parsing the given query.
  501. *
  502. * @since 3.1.0
  503. *
  504. * @param WP_User_Query $this The current WP_User_Query instance,
  505. * passed by reference.
  506. */
  507. do_action_ref_array( 'pre_user_query', array( &$this ) );
  508. }
  509. /**
  510. * Execute the query, with the current variables.
  511. *
  512. * @since 3.1.0
  513. *
  514. * @global wpdb $wpdb WordPress database abstraction object.
  515. */
  516. public function query() {
  517. global $wpdb;
  518. $qv =& $this->query_vars;
  519. $this->request = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
  520. if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
  521. $this->results = $wpdb->get_results( $this->request );
  522. } else {
  523. $this->results = $wpdb->get_col( $this->request );
  524. }
  525. /**
  526. * Filters SELECT FOUND_ROWS() query for the current WP_User_Query instance.
  527. *
  528. * @since 3.2.0
  529. *
  530. * @global wpdb $wpdb WordPress database abstraction object.
  531. *
  532. * @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
  533. */
  534. if ( isset( $qv['count_total'] ) && $qv['count_total'] )
  535. $this->total_users = (int) $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) );
  536. if ( !$this->results )
  537. return;
  538. if ( 'all_with_meta' == $qv['fields'] ) {
  539. cache_users( $this->results );
  540. $r = array();
  541. foreach ( $this->results as $userid )
  542. $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
  543. $this->results = $r;
  544. } elseif ( 'all' == $qv['fields'] ) {
  545. foreach ( $this->results as $key => $user ) {
  546. $this->results[ $key ] = new WP_User( $user, '', $qv['blog_id'] );
  547. }
  548. }
  549. }
  550. /**
  551. * Retrieve query variable.
  552. *
  553. * @since 3.5.0
  554. *
  555. * @param string $query_var Query variable key.
  556. * @return mixed
  557. */
  558. public function get( $query_var ) {
  559. if ( isset( $this->query_vars[$query_var] ) )
  560. return $this->query_vars[$query_var];
  561. return null;
  562. }
  563. /**
  564. * Set query variable.
  565. *
  566. * @since 3.5.0
  567. *
  568. * @param string $query_var Query variable key.
  569. * @param mixed $value Query variable value.
  570. */
  571. public function set( $query_var, $value ) {
  572. $this->query_vars[$query_var] = $value;
  573. }
  574. /**
  575. * Used internally to generate an SQL string for searching across multiple columns
  576. *
  577. * @since 3.1.0
  578. *
  579. * @global wpdb $wpdb WordPress database abstraction object.
  580. *
  581. * @param string $string
  582. * @param array $cols
  583. * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for single site.
  584. * Single site allows leading and trailing wildcards, Network Admin only trailing.
  585. * @return string
  586. */
  587. protected function get_search_sql( $string, $cols, $wild = false ) {
  588. global $wpdb;
  589. $searches = array();
  590. $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
  591. $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
  592. $like = $leading_wild . $wpdb->esc_like( $string ) . $trailing_wild;
  593. foreach ( $cols as $col ) {
  594. if ( 'ID' == $col ) {
  595. $searches[] = $wpdb->prepare( "$col = %s", $string );
  596. } else {
  597. $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
  598. }
  599. }
  600. return ' AND (' . implode(' OR ', $searches) . ')';
  601. }
  602. /**
  603. * Return the list of users.
  604. *
  605. * @since 3.1.0
  606. *
  607. * @return array Array of results.
  608. */
  609. public function get_results() {
  610. return $this->results;
  611. }
  612. /**
  613. * Return the total number of users for the current query.
  614. *
  615. * @since 3.1.0
  616. *
  617. * @return int Number of total users.
  618. */
  619. public function get_total() {
  620. return $this->total_users;
  621. }
  622. /**
  623. * Parse and sanitize 'orderby' keys passed to the user query.
  624. *
  625. * @since 4.2.0
  626. *
  627. * @global wpdb $wpdb WordPress database abstraction object.
  628. *
  629. * @param string $orderby Alias for the field to order by.
  630. * @return string Value to used in the ORDER clause, if `$orderby` is valid.
  631. */
  632. protected function parse_orderby( $orderby ) {
  633. global $wpdb;
  634. $meta_query_clauses = $this->meta_query->get_clauses();
  635. $_orderby = '';
  636. if ( in_array( $orderby, array( 'login', 'nicename', 'email', 'url', 'registered' ) ) ) {
  637. $_orderby = 'user_' . $orderby;
  638. } elseif ( in_array( $orderby, array( 'user_login', 'user_nicename', 'user_email', 'user_url', 'user_registered' ) ) ) {
  639. $_orderby = $orderby;
  640. } elseif ( 'name' == $orderby || 'display_name' == $orderby ) {
  641. $_orderby = 'display_name';
  642. } elseif ( 'post_count' == $orderby ) {
  643. // todo: avoid the JOIN
  644. $where = get_posts_by_author_sql( 'post' );
  645. $this->query_from .= " LEFT OUTER JOIN (
  646. SELECT post_author, COUNT(*) as post_count
  647. FROM $wpdb->posts
  648. $where
  649. GROUP BY post_author
  650. ) p ON ({$wpdb->users}.ID = p.post_author)
  651. ";
  652. $_orderby = 'post_count';
  653. } elseif ( 'ID' == $orderby || 'id' == $orderby ) {
  654. $_orderby = 'ID';
  655. } elseif ( 'meta_value' == $orderby || $this->get( 'meta_key' ) == $orderby ) {
  656. $_orderby = "$wpdb->usermeta.meta_value";
  657. } elseif ( 'meta_value_num' == $orderby ) {
  658. $_orderby = "$wpdb->usermeta.meta_value+0";
  659. } elseif ( 'include' === $orderby && ! empty( $this->query_vars['include'] ) ) {
  660. $include = wp_parse_id_list( $this->query_vars['include'] );
  661. $include_sql = implode( ',', $include );
  662. $_orderby = "FIELD( $wpdb->users.ID, $include_sql )";
  663. } elseif ( 'nicename__in' === $orderby ) {
  664. $sanitized_nicename__in = array_map( 'esc_sql', $this->query_vars['nicename__in'] );
  665. $nicename__in = implode( "','", $sanitized_nicename__in );
  666. $_orderby = "FIELD( user_nicename, '$nicename__in' )";
  667. } elseif ( 'login__in' === $orderby ) {
  668. $sanitized_login__in = array_map( 'esc_sql', $this->query_vars['login__in'] );
  669. $login__in = implode( "','", $sanitized_login__in );
  670. $_orderby = "FIELD( user_login, '$login__in' )";
  671. } elseif ( isset( $meta_query_clauses[ $orderby ] ) ) {
  672. $meta_clause = $meta_query_clauses[ $orderby ];
  673. $_orderby = sprintf( "CAST(%s.meta_value AS %s)", esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
  674. }
  675. return $_orderby;
  676. }
  677. /**
  678. * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
  679. *
  680. * @since 4.2.0
  681. *
  682. * @param string $order The 'order' query variable.
  683. * @return string The sanitized 'order' query variable.
  684. */
  685. protected function parse_order( $order ) {
  686. if ( ! is_string( $order ) || empty( $order ) ) {
  687. return 'DESC';
  688. }
  689. if ( 'ASC' === strtoupper( $order ) ) {
  690. return 'ASC';
  691. } else {
  692. return 'DESC';
  693. }
  694. }
  695. /**
  696. * Make private properties readable for backward compatibility.
  697. *
  698. * @since 4.0.0
  699. *
  700. * @param string $name Property to get.
  701. * @return mixed Property.
  702. */
  703. public function __get( $name ) {
  704. if ( in_array( $name, $this->compat_fields ) ) {
  705. return $this->$name;
  706. }
  707. }
  708. /**
  709. * Make private properties settable for backward compatibility.
  710. *
  711. * @since 4.0.0
  712. *
  713. * @param string $name Property to check if set.
  714. * @param mixed $value Property value.
  715. * @return mixed Newly-set property.
  716. */
  717. public function __set( $name, $value ) {
  718. if ( in_array( $name, $this->compat_fields ) ) {
  719. return $this->$name = $value;
  720. }
  721. }
  722. /**
  723. * Make private properties checkable for backward compatibility.
  724. *
  725. * @since 4.0.0
  726. *
  727. * @param string $name Property to check if set.
  728. * @return bool Whether the property is set.
  729. */
  730. public function __isset( $name ) {
  731. if ( in_array( $name, $this->compat_fields ) ) {
  732. return isset( $this->$name );
  733. }
  734. }
  735. /**
  736. * Make private properties un-settable for backward compatibility.
  737. *
  738. * @since 4.0.0
  739. *
  740. * @param string $name Property to unset.
  741. */
  742. public function __unset( $name ) {
  743. if ( in_array( $name, $this->compat_fields ) ) {
  744. unset( $this->$name );
  745. }
  746. }
  747. /**
  748. * Make private/protected methods readable for backward compatibility.
  749. *
  750. * @since 4.0.0
  751. *
  752. * @param callable $name Method to call.
  753. * @param array $arguments Arguments to pass when calling.
  754. * @return mixed Return value of the callback, false otherwise.
  755. */
  756. public function __call( $name, $arguments ) {
  757. if ( 'get_search_sql' === $name ) {
  758. return call_user_func_array( array( $this, $name ), $arguments );
  759. }
  760. return false;
  761. }
  762. }