PageRenderTime 58ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/user.php

https://bitbucket.org/acipriani/madeinapulia.com
PHP | 2337 lines | 968 code | 283 blank | 1086 comment | 251 complexity | ce7d9c841a8885991858466919cfa3f8 MD5 | raw file
Possible License(s): GPL-3.0, MIT, BSD-3-Clause, LGPL-2.1, GPL-2.0, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * WordPress User API
  4. *
  5. * @package WordPress
  6. * @subpackage Users
  7. */
  8. /**
  9. * Authenticate user with remember capability.
  10. *
  11. * The credentials is an array that has 'user_login', 'user_password', and
  12. * 'remember' indices. If the credentials is not given, then the log in form
  13. * will be assumed and used if set.
  14. *
  15. * The various authentication cookies will be set by this function and will be
  16. * set for a longer period depending on if the 'remember' credential is set to
  17. * true.
  18. *
  19. * @since 2.5.0
  20. *
  21. * @param array $credentials Optional. User info in order to sign on.
  22. * @param string|bool $secure_cookie Optional. Whether to use secure cookie.
  23. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  24. */
  25. function wp_signon( $credentials = array(), $secure_cookie = '' ) {
  26. if ( empty($credentials) ) {
  27. if ( ! empty($_POST['log']) )
  28. $credentials['user_login'] = $_POST['log'];
  29. if ( ! empty($_POST['pwd']) )
  30. $credentials['user_password'] = $_POST['pwd'];
  31. if ( ! empty($_POST['rememberme']) )
  32. $credentials['remember'] = $_POST['rememberme'];
  33. }
  34. if ( !empty($credentials['remember']) )
  35. $credentials['remember'] = true;
  36. else
  37. $credentials['remember'] = false;
  38. /**
  39. * Fires before the user is authenticated.
  40. *
  41. * The variables passed to the callbacks are passed by reference,
  42. * and can be modified by callback functions.
  43. *
  44. * @since 1.5.1
  45. *
  46. * @todo Decide whether to deprecate the wp_authenticate action.
  47. *
  48. * @param string $user_login Username, passed by reference.
  49. * @param string $user_password User password, passed by reference.
  50. */
  51. do_action_ref_array( 'wp_authenticate', array( &$credentials['user_login'], &$credentials['user_password'] ) );
  52. if ( '' === $secure_cookie )
  53. $secure_cookie = is_ssl();
  54. /**
  55. * Filter whether to use a secure sign-on cookie.
  56. *
  57. * @since 3.1.0
  58. *
  59. * @param bool $secure_cookie Whether to use a secure sign-on cookie.
  60. * @param array $credentials {
  61. * Array of entered sign-on data.
  62. *
  63. * @type string $user_login Username.
  64. * @type string $user_password Password entered.
  65. * @type bool $remember Whether to 'remember' the user. Increases the time
  66. * that the cookie will be kept. Default false.
  67. * }
  68. */
  69. $secure_cookie = apply_filters( 'secure_signon_cookie', $secure_cookie, $credentials );
  70. global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
  71. $auth_secure_cookie = $secure_cookie;
  72. add_filter('authenticate', 'wp_authenticate_cookie', 30, 3);
  73. $user = wp_authenticate($credentials['user_login'], $credentials['user_password']);
  74. if ( is_wp_error($user) ) {
  75. if ( $user->get_error_codes() == array('empty_username', 'empty_password') ) {
  76. $user = new WP_Error('', '');
  77. }
  78. return $user;
  79. }
  80. wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
  81. /**
  82. * Fires after the user has successfully logged in.
  83. *
  84. * @since 1.5.0
  85. *
  86. * @param string $user_login Username.
  87. * @param WP_User $user WP_User object of the logged-in user.
  88. */
  89. do_action( 'wp_login', $user->user_login, $user );
  90. return $user;
  91. }
  92. /**
  93. * Authenticate the user using the username and password.
  94. *
  95. * @since 2.8.0
  96. *
  97. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  98. * @param string $username Username for authentication.
  99. * @param string $password Password for authentication.
  100. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  101. */
  102. function wp_authenticate_username_password($user, $username, $password) {
  103. if ( is_a( $user, 'WP_User' ) ) {
  104. return $user;
  105. }
  106. if ( empty($username) || empty($password) ) {
  107. if ( is_wp_error( $user ) )
  108. return $user;
  109. $error = new WP_Error();
  110. if ( empty($username) )
  111. $error->add('empty_username', __('<strong>ERROR</strong>: The username field is empty.'));
  112. if ( empty($password) )
  113. $error->add('empty_password', __('<strong>ERROR</strong>: The password field is empty.'));
  114. return $error;
  115. }
  116. $user = get_user_by('login', $username);
  117. if ( !$user )
  118. return new WP_Error( 'invalid_username', sprintf( __( '<strong>ERROR</strong>: Invalid username. <a href="%s">Lost your password</a>?' ), wp_lostpassword_url() ) );
  119. /**
  120. * Filter whether the given user can be authenticated with the provided $password.
  121. *
  122. * @since 2.5.0
  123. *
  124. * @param WP_User|WP_Error $user WP_User or WP_Error object if a previous
  125. * callback failed authentication.
  126. * @param string $password Password to check against the user.
  127. */
  128. $user = apply_filters( 'wp_authenticate_user', $user, $password );
  129. if ( is_wp_error($user) )
  130. return $user;
  131. if ( !wp_check_password($password, $user->user_pass, $user->ID) )
  132. return new WP_Error( 'incorrect_password', sprintf( __( '<strong>ERROR</strong>: The password you entered for the username <strong>%1$s</strong> is incorrect. <a href="%2$s">Lost your password</a>?' ),
  133. $username, wp_lostpassword_url() ) );
  134. return $user;
  135. }
  136. /**
  137. * Authenticate the user using the WordPress auth cookie.
  138. *
  139. * @since 2.8.0
  140. *
  141. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  142. * @param string $username Username. If not empty, cancels the cookie authentication.
  143. * @param string $password Password. If not empty, cancels the cookie authentication.
  144. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  145. */
  146. function wp_authenticate_cookie($user, $username, $password) {
  147. if ( is_a( $user, 'WP_User' ) ) {
  148. return $user;
  149. }
  150. if ( empty($username) && empty($password) ) {
  151. $user_id = wp_validate_auth_cookie();
  152. if ( $user_id )
  153. return new WP_User($user_id);
  154. global $auth_secure_cookie;
  155. if ( $auth_secure_cookie )
  156. $auth_cookie = SECURE_AUTH_COOKIE;
  157. else
  158. $auth_cookie = AUTH_COOKIE;
  159. if ( !empty($_COOKIE[$auth_cookie]) )
  160. return new WP_Error('expired_session', __('Please log in again.'));
  161. // If the cookie is not set, be silent.
  162. }
  163. return $user;
  164. }
  165. /**
  166. * For Multisite blogs, check if the authenticated user has been marked as a
  167. * spammer, or if the user's primary blog has been marked as spam.
  168. *
  169. * @since 3.7.0
  170. *
  171. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  172. * @return WP_User|WP_Error WP_User on success, WP_Error if the user is considered a spammer.
  173. */
  174. function wp_authenticate_spam_check( $user ) {
  175. if ( $user && is_a( $user, 'WP_User' ) && is_multisite() ) {
  176. /**
  177. * Filter whether the user has been marked as a spammer.
  178. *
  179. * @since 3.7.0
  180. *
  181. * @param bool $spammed Whether the user is considered a spammer.
  182. * @param WP_User $user User to check against.
  183. */
  184. $spammed = apply_filters( 'check_is_user_spammed', is_user_spammy(), $user );
  185. if ( $spammed )
  186. return new WP_Error( 'spammer_account', __( '<strong>ERROR</strong>: Your account has been marked as a spammer.' ) );
  187. }
  188. return $user;
  189. }
  190. /**
  191. * Validate the logged-in cookie.
  192. *
  193. * Checks the logged-in cookie if the previous auth cookie could not be
  194. * validated and parsed.
  195. *
  196. * This is a callback for the determine_current_user filter, rather than API.
  197. *
  198. * @since 3.9.0
  199. *
  200. * @param int|bool $user_id The user ID (or false) as received from the
  201. * determine_current_user filter.
  202. * @return int|bool User ID if validated, false otherwise. If a user ID from
  203. * an earlier filter callback is received, that value is returned.
  204. */
  205. function wp_validate_logged_in_cookie( $user_id ) {
  206. if ( $user_id ) {
  207. return $user_id;
  208. }
  209. if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[LOGGED_IN_COOKIE] ) ) {
  210. return false;
  211. }
  212. return wp_validate_auth_cookie( $_COOKIE[LOGGED_IN_COOKIE], 'logged_in' );
  213. }
  214. /**
  215. * Number of posts user has written.
  216. *
  217. * @since 3.0.0
  218. * @since 4.1.0 Added `$post_type` argument.
  219. *
  220. * @global wpdb $wpdb WordPress database object for queries.
  221. *
  222. * @param int $userid User ID.
  223. * @param string $post_type Optional. Post type to count the number of posts for. Default 'post'.
  224. * @return int Number of posts the user has written in this post type.
  225. */
  226. function count_user_posts( $userid, $post_type = 'post' ) {
  227. global $wpdb;
  228. $where = get_posts_by_author_sql( $post_type, true, $userid );
  229. $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
  230. /**
  231. * Filter the number of posts a user has written.
  232. *
  233. * @since 2.7.0
  234. * @since 4.1.0 Added `$post_type` argument.
  235. *
  236. * @param int $count The user's post count.
  237. * @param int $userid User ID.
  238. * @param string $post_type Post type to count the number of posts for.
  239. */
  240. return apply_filters( 'get_usernumposts', $count, $userid, $post_type );
  241. }
  242. /**
  243. * Number of posts written by a list of users.
  244. *
  245. * @since 3.0.0
  246. *
  247. * @param array $users Array of user IDs.
  248. * @param string $post_type Optional. Post type to check. Defaults to post.
  249. * @param bool $public_only Optional. Only return counts for public posts. Defaults to false.
  250. * @return array Amount of posts each user has written.
  251. */
  252. function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
  253. global $wpdb;
  254. $count = array();
  255. if ( empty( $users ) || ! is_array( $users ) )
  256. return $count;
  257. $userlist = implode( ',', array_map( 'absint', $users ) );
  258. $where = get_posts_by_author_sql( $post_type, true, null, $public_only );
  259. $result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
  260. foreach ( $result as $row ) {
  261. $count[ $row[0] ] = $row[1];
  262. }
  263. foreach ( $users as $id ) {
  264. if ( ! isset( $count[ $id ] ) )
  265. $count[ $id ] = 0;
  266. }
  267. return $count;
  268. }
  269. //
  270. // User option functions
  271. //
  272. /**
  273. * Get the current user's ID
  274. *
  275. * @since MU
  276. *
  277. * @return int The current user's ID
  278. */
  279. function get_current_user_id() {
  280. if ( ! function_exists( 'wp_get_current_user' ) )
  281. return 0;
  282. $user = wp_get_current_user();
  283. return ( isset( $user->ID ) ? (int) $user->ID : 0 );
  284. }
  285. /**
  286. * Retrieve user option that can be either per Site or per Network.
  287. *
  288. * If the user ID is not given, then the current user will be used instead. If
  289. * the user ID is given, then the user data will be retrieved. The filter for
  290. * the result, will also pass the original option name and finally the user data
  291. * object as the third parameter.
  292. *
  293. * The option will first check for the per site name and then the per Network name.
  294. *
  295. * @since 2.0.0
  296. *
  297. * @global wpdb $wpdb WordPress database object for queries.
  298. *
  299. * @param string $option User option name.
  300. * @param int $user Optional. User ID.
  301. * @param string $deprecated Use get_option() to check for an option in the options table.
  302. * @return mixed User option value on success, false on failure.
  303. */
  304. function get_user_option( $option, $user = 0, $deprecated = '' ) {
  305. global $wpdb;
  306. if ( !empty( $deprecated ) )
  307. _deprecated_argument( __FUNCTION__, '3.0' );
  308. if ( empty( $user ) )
  309. $user = get_current_user_id();
  310. if ( ! $user = get_userdata( $user ) )
  311. return false;
  312. $prefix = $wpdb->get_blog_prefix();
  313. if ( $user->has_prop( $prefix . $option ) ) // Blog specific
  314. $result = $user->get( $prefix . $option );
  315. elseif ( $user->has_prop( $option ) ) // User specific and cross-blog
  316. $result = $user->get( $option );
  317. else
  318. $result = false;
  319. /**
  320. * Filter a specific user option value.
  321. *
  322. * The dynamic portion of the hook name, `$option`, refers to the user option name.
  323. *
  324. * @since 2.5.0
  325. *
  326. * @param mixed $result Value for the user's option.
  327. * @param string $option Name of the option being retrieved.
  328. * @param WP_User $user WP_User object of the user whose option is being retrieved.
  329. */
  330. return apply_filters( "get_user_option_{$option}", $result, $option, $user );
  331. }
  332. /**
  333. * Update user option with global blog capability.
  334. *
  335. * User options are just like user metadata except that they have support for
  336. * global blog options. If the 'global' parameter is false, which it is by default
  337. * it will prepend the WordPress table prefix to the option name.
  338. *
  339. * Deletes the user option if $newvalue is empty.
  340. *
  341. * @since 2.0.0
  342. *
  343. * @global wpdb $wpdb WordPress database object for queries.
  344. *
  345. * @param int $user_id User ID.
  346. * @param string $option_name User option name.
  347. * @param mixed $newvalue User option value.
  348. * @param bool $global Optional. Whether option name is global or blog specific.
  349. * Default false (blog specific).
  350. * @return int|bool User meta ID if the option didn't exist, true on successful update,
  351. * false on failure.
  352. */
  353. function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
  354. global $wpdb;
  355. if ( !$global )
  356. $option_name = $wpdb->get_blog_prefix() . $option_name;
  357. return update_user_meta( $user_id, $option_name, $newvalue );
  358. }
  359. /**
  360. * Delete user option with global blog capability.
  361. *
  362. * User options are just like user metadata except that they have support for
  363. * global blog options. If the 'global' parameter is false, which it is by default
  364. * it will prepend the WordPress table prefix to the option name.
  365. *
  366. * @since 3.0.0
  367. *
  368. * @global wpdb $wpdb WordPress database object for queries.
  369. *
  370. * @param int $user_id User ID
  371. * @param string $option_name User option name.
  372. * @param bool $global Optional. Whether option name is global or blog specific.
  373. * Default false (blog specific).
  374. * @return bool True on success, false on failure.
  375. */
  376. function delete_user_option( $user_id, $option_name, $global = false ) {
  377. global $wpdb;
  378. if ( !$global )
  379. $option_name = $wpdb->get_blog_prefix() . $option_name;
  380. return delete_user_meta( $user_id, $option_name );
  381. }
  382. /**
  383. * WordPress User Query class.
  384. *
  385. * @since 3.1.0
  386. *
  387. * @see WP_User_Query::prepare_query() for information on accepted arguments.
  388. */
  389. class WP_User_Query {
  390. /**
  391. * Query vars, after parsing
  392. *
  393. * @since 3.5.0
  394. * @access public
  395. * @var array
  396. */
  397. public $query_vars = array();
  398. /**
  399. * List of found user ids
  400. *
  401. * @since 3.1.0
  402. * @access private
  403. * @var array
  404. */
  405. private $results;
  406. /**
  407. * Total number of found users for the current query
  408. *
  409. * @since 3.1.0
  410. * @access private
  411. * @var int
  412. */
  413. private $total_users = 0;
  414. // SQL clauses
  415. public $query_fields;
  416. public $query_from;
  417. public $query_where;
  418. public $query_orderby;
  419. public $query_limit;
  420. /**
  421. * PHP5 constructor.
  422. *
  423. * @since 3.1.0
  424. *
  425. * @param null|string|array $args Optional. The query variables.
  426. * @return WP_User_Query
  427. */
  428. public function __construct( $query = null ) {
  429. if ( ! empty( $query ) ) {
  430. $this->prepare_query( $query );
  431. $this->query();
  432. }
  433. }
  434. /**
  435. * Prepare the query variables.
  436. *
  437. * @since 3.1.0
  438. * @access public
  439. *
  440. * @param string|array $query {
  441. * Optional. Array or string of Query parameters.
  442. *
  443. * @type int $blog_id The site ID. Default is the global blog id.
  444. * @type string $role Role name. Default empty.
  445. * @type string $meta_key User meta key. Default empty.
  446. * @type string $meta_value User meta value. Default empty.
  447. * @type string $meta_compare Comparison operator to test the `$meta_value`. Accepts '=', '!=',
  448. * '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN',
  449. * 'NOT BETWEEN', 'EXISTS', 'NOT EXISTS', 'REGEXP', 'NOT REGEXP',
  450. * or 'RLIKE'. Default '='.
  451. * @type array $include An array of user IDs to include. Default empty array.
  452. * @type array $exclude An array of user IDs to exclude. Default empty array.
  453. * @type string $search Search keyword. Searches for possible string matches on columns.
  454. * When `$search_columns` is left empty, it tries to determine which
  455. * column to search in based on search string. Default empty.
  456. * @type array $search_columns Array of column names to be searched. Accepts 'ID', 'login',
  457. * 'nicename', 'email', 'url'. Default empty array.
  458. * @type string $orderby Field to sort the retrieved users by. Accepts 'ID', 'display_name',
  459. * 'login', 'nicename', 'email', 'url', 'registered', 'post_count', or
  460. * 'meta_value'. To use 'meta_value', `$meta_key` must be also be defined.
  461. * Default 'user_login'.
  462. * @type string $order Designates ascending or descending order of users. Accepts 'ASC',
  463. * 'DESC'. Default 'ASC'.
  464. * @type int $offset Number of users to offset in retrieved results. Can be used in
  465. * conjunction with pagination. Default 0.
  466. * @type int $number Number of users to limit the query for. Can be used in conjunction
  467. * with pagination. Value -1 (all) is not supported.
  468. * Default empty (all users).
  469. * @type bool $count_total Whether to count the total number of users found. If pagination is not
  470. * needed, setting this to false can improve performance. Default true.
  471. * @type string|array $fields Which fields to return. Single or all fields (string), or array
  472. * of fields. Accepts 'ID', 'display_name', 'login', 'nicename', 'email',
  473. * 'url', 'registered'. Use 'all' for all fields and 'all_with_meta' to
  474. * include meta fields. Default 'all'.
  475. * @type string $who Type of users to query. Accepts 'authors'. Default empty (all users).
  476. * }
  477. */
  478. public function prepare_query( $query = array() ) {
  479. global $wpdb;
  480. if ( empty( $this->query_vars ) || ! empty( $query ) ) {
  481. $this->query_limit = null;
  482. $this->query_vars = wp_parse_args( $query, array(
  483. 'blog_id' => $GLOBALS['blog_id'],
  484. 'role' => '',
  485. 'meta_key' => '',
  486. 'meta_value' => '',
  487. 'meta_compare' => '',
  488. 'include' => array(),
  489. 'exclude' => array(),
  490. 'search' => '',
  491. 'search_columns' => array(),
  492. 'orderby' => 'login',
  493. 'order' => 'ASC',
  494. 'offset' => '',
  495. 'number' => '',
  496. 'count_total' => true,
  497. 'fields' => 'all',
  498. 'who' => ''
  499. ) );
  500. }
  501. /**
  502. * Fires before the WP_User_Query has been parsed.
  503. *
  504. * The passed WP_User_Query object contains the query variables, not
  505. * yet passed into SQL.
  506. *
  507. * @since 4.0.0
  508. *
  509. * @param WP_User_Query $this The current WP_User_Query instance,
  510. * passed by reference.
  511. */
  512. do_action( 'pre_get_users', $this );
  513. $qv =& $this->query_vars;
  514. if ( is_array( $qv['fields'] ) ) {
  515. $qv['fields'] = array_unique( $qv['fields'] );
  516. $this->query_fields = array();
  517. foreach ( $qv['fields'] as $field ) {
  518. $field = 'ID' === $field ? 'ID' : sanitize_key( $field );
  519. $this->query_fields[] = "$wpdb->users.$field";
  520. }
  521. $this->query_fields = implode( ',', $this->query_fields );
  522. } elseif ( 'all' == $qv['fields'] ) {
  523. $this->query_fields = "$wpdb->users.*";
  524. } else {
  525. $this->query_fields = "$wpdb->users.ID";
  526. }
  527. if ( isset( $qv['count_total'] ) && $qv['count_total'] )
  528. $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
  529. $this->query_from = "FROM $wpdb->users";
  530. $this->query_where = "WHERE 1=1";
  531. // Parse and sanitize 'include', for use by 'orderby' as well as 'include' below.
  532. if ( ! empty( $qv['include'] ) ) {
  533. $include = wp_parse_id_list( $qv['include'] );
  534. } else {
  535. $include = false;
  536. }
  537. // sorting
  538. if ( isset( $qv['orderby'] ) ) {
  539. if ( in_array( $qv['orderby'], array('nicename', 'email', 'url', 'registered') ) ) {
  540. $orderby = 'user_' . $qv['orderby'];
  541. } elseif ( in_array( $qv['orderby'], array('user_nicename', 'user_email', 'user_url', 'user_registered') ) ) {
  542. $orderby = $qv['orderby'];
  543. } elseif ( 'name' == $qv['orderby'] || 'display_name' == $qv['orderby'] ) {
  544. $orderby = 'display_name';
  545. } elseif ( 'post_count' == $qv['orderby'] ) {
  546. // todo: avoid the JOIN
  547. $where = get_posts_by_author_sql('post');
  548. $this->query_from .= " LEFT OUTER JOIN (
  549. SELECT post_author, COUNT(*) as post_count
  550. FROM $wpdb->posts
  551. $where
  552. GROUP BY post_author
  553. ) p ON ({$wpdb->users}.ID = p.post_author)
  554. ";
  555. $orderby = 'post_count';
  556. } elseif ( 'ID' == $qv['orderby'] || 'id' == $qv['orderby'] ) {
  557. $orderby = 'ID';
  558. } elseif ( 'meta_value' == $qv['orderby'] ) {
  559. $orderby = "$wpdb->usermeta.meta_value";
  560. } else if ( 'include' === $qv['orderby'] && ! empty( $include ) ) {
  561. // Sanitized earlier.
  562. $include_sql = implode( ',', $include );
  563. $orderby = "FIELD( $wpdb->users.ID, $include_sql )";
  564. } else {
  565. $orderby = 'user_login';
  566. }
  567. }
  568. if ( empty( $orderby ) )
  569. $orderby = 'user_login';
  570. $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
  571. if ( 'ASC' == $qv['order'] )
  572. $order = 'ASC';
  573. else
  574. $order = 'DESC';
  575. $this->query_orderby = "ORDER BY $orderby $order";
  576. // limit
  577. if ( isset( $qv['number'] ) && $qv['number'] ) {
  578. if ( $qv['offset'] )
  579. $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
  580. else
  581. $this->query_limit = $wpdb->prepare("LIMIT %d", $qv['number']);
  582. }
  583. $search = '';
  584. if ( isset( $qv['search'] ) )
  585. $search = trim( $qv['search'] );
  586. if ( $search ) {
  587. $leading_wild = ( ltrim($search, '*') != $search );
  588. $trailing_wild = ( rtrim($search, '*') != $search );
  589. if ( $leading_wild && $trailing_wild )
  590. $wild = 'both';
  591. elseif ( $leading_wild )
  592. $wild = 'leading';
  593. elseif ( $trailing_wild )
  594. $wild = 'trailing';
  595. else
  596. $wild = false;
  597. if ( $wild )
  598. $search = trim($search, '*');
  599. $search_columns = array();
  600. if ( $qv['search_columns'] )
  601. $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename' ) );
  602. if ( ! $search_columns ) {
  603. if ( false !== strpos( $search, '@') )
  604. $search_columns = array('user_email');
  605. elseif ( is_numeric($search) )
  606. $search_columns = array('user_login', 'ID');
  607. elseif ( preg_match('|^https?://|', $search) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) )
  608. $search_columns = array('user_url');
  609. else
  610. $search_columns = array('user_login', 'user_nicename');
  611. }
  612. /**
  613. * Filter the columns to search in a WP_User_Query search.
  614. *
  615. * The default columns depend on the search term, and include 'user_email',
  616. * 'user_login', 'ID', 'user_url', and 'user_nicename'.
  617. *
  618. * @since 3.6.0
  619. *
  620. * @param array $search_columns Array of column names to be searched.
  621. * @param string $search Text being searched.
  622. * @param WP_User_Query $this The current WP_User_Query instance.
  623. */
  624. $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
  625. $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
  626. }
  627. $blog_id = 0;
  628. if ( isset( $qv['blog_id'] ) )
  629. $blog_id = absint( $qv['blog_id'] );
  630. if ( isset( $qv['who'] ) && 'authors' == $qv['who'] && $blog_id ) {
  631. $qv['meta_key'] = $wpdb->get_blog_prefix( $blog_id ) . 'user_level';
  632. $qv['meta_value'] = 0;
  633. $qv['meta_compare'] = '!=';
  634. $qv['blog_id'] = $blog_id = 0; // Prevent extra meta query
  635. }
  636. $meta_query = new WP_Meta_Query();
  637. $meta_query->parse_query_vars( $qv );
  638. $role = '';
  639. if ( isset( $qv['role'] ) )
  640. $role = trim( $qv['role'] );
  641. if ( $blog_id && ( $role || is_multisite() ) ) {
  642. $cap_meta_query = array();
  643. $cap_meta_query['key'] = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities';
  644. if ( $role ) {
  645. $cap_meta_query['value'] = '"' . $role . '"';
  646. $cap_meta_query['compare'] = 'like';
  647. }
  648. if ( empty( $meta_query->queries ) ) {
  649. $meta_query->queries = array( $cap_meta_query );
  650. } elseif ( ! in_array( $cap_meta_query, $meta_query->queries, true ) ) {
  651. // Append the cap query to the original queries and reparse the query.
  652. $meta_query->queries = array(
  653. 'relation' => 'AND',
  654. array( $meta_query->queries, $cap_meta_query ),
  655. );
  656. }
  657. $meta_query->parse_query_vars( $meta_query->queries );
  658. }
  659. if ( !empty( $meta_query->queries ) ) {
  660. $clauses = $meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
  661. $this->query_from .= $clauses['join'];
  662. $this->query_where .= $clauses['where'];
  663. if ( 'OR' == $meta_query->relation )
  664. $this->query_fields = 'DISTINCT ' . $this->query_fields;
  665. }
  666. if ( ! empty( $include ) ) {
  667. // Sanitized earlier.
  668. $ids = implode( ',', $include );
  669. $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
  670. } elseif ( ! empty( $qv['exclude'] ) ) {
  671. $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
  672. $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
  673. }
  674. // Date queries are allowed for the user_registered field.
  675. if ( ! empty( $qv['date_query'] ) && is_array( $qv['date_query'] ) ) {
  676. $date_query = new WP_Date_Query( $qv['date_query'], 'user_registered' );
  677. $this->query_where .= $date_query->get_sql();
  678. }
  679. /**
  680. * Fires after the WP_User_Query has been parsed, and before
  681. * the query is executed.
  682. *
  683. * The passed WP_User_Query object contains SQL parts formed
  684. * from parsing the given query.
  685. *
  686. * @since 3.1.0
  687. *
  688. * @param WP_User_Query $this The current WP_User_Query instance,
  689. * passed by reference.
  690. */
  691. do_action_ref_array( 'pre_user_query', array( &$this ) );
  692. }
  693. /**
  694. * Execute the query, with the current variables.
  695. *
  696. * @since 3.1.0
  697. *
  698. * @global wpdb $wpdb WordPress database object for queries.
  699. */
  700. public function query() {
  701. global $wpdb;
  702. $qv =& $this->query_vars;
  703. $query = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
  704. if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
  705. $this->results = $wpdb->get_results( $query );
  706. } else {
  707. $this->results = $wpdb->get_col( $query );
  708. }
  709. /**
  710. * Filter SELECT FOUND_ROWS() query for the current WP_User_Query instance.
  711. *
  712. * @since 3.2.0
  713. *
  714. * @global wpdb $wpdb WordPress database abstraction object.
  715. *
  716. * @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
  717. */
  718. if ( isset( $qv['count_total'] ) && $qv['count_total'] )
  719. $this->total_users = $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) );
  720. if ( !$this->results )
  721. return;
  722. if ( 'all_with_meta' == $qv['fields'] ) {
  723. cache_users( $this->results );
  724. $r = array();
  725. foreach ( $this->results as $userid )
  726. $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
  727. $this->results = $r;
  728. } elseif ( 'all' == $qv['fields'] ) {
  729. foreach ( $this->results as $key => $user ) {
  730. $this->results[ $key ] = new WP_User( $user );
  731. }
  732. }
  733. }
  734. /**
  735. * Retrieve query variable.
  736. *
  737. * @since 3.5.0
  738. * @access public
  739. *
  740. * @param string $query_var Query variable key.
  741. * @return mixed
  742. */
  743. public function get( $query_var ) {
  744. if ( isset( $this->query_vars[$query_var] ) )
  745. return $this->query_vars[$query_var];
  746. return null;
  747. }
  748. /**
  749. * Set query variable.
  750. *
  751. * @since 3.5.0
  752. * @access public
  753. *
  754. * @param string $query_var Query variable key.
  755. * @param mixed $value Query variable value.
  756. */
  757. public function set( $query_var, $value ) {
  758. $this->query_vars[$query_var] = $value;
  759. }
  760. /**
  761. * Used internally to generate an SQL string for searching across multiple columns
  762. *
  763. * @access protected
  764. * @since 3.1.0
  765. *
  766. * @param string $string
  767. * @param array $cols
  768. * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for
  769. * single site. Single site allows leading and trailing wildcards, Network Admin only trailing.
  770. * @return string
  771. */
  772. protected function get_search_sql( $string, $cols, $wild = false ) {
  773. global $wpdb;
  774. $searches = array();
  775. $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
  776. $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
  777. $like = $leading_wild . $wpdb->esc_like( $string ) . $trailing_wild;
  778. foreach ( $cols as $col ) {
  779. if ( 'ID' == $col ) {
  780. $searches[] = $wpdb->prepare( "$col = %s", $string );
  781. } else {
  782. $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
  783. }
  784. }
  785. return ' AND (' . implode(' OR ', $searches) . ')';
  786. }
  787. /**
  788. * Return the list of users.
  789. *
  790. * @since 3.1.0
  791. * @access public
  792. *
  793. * @return array Array of results.
  794. */
  795. public function get_results() {
  796. return $this->results;
  797. }
  798. /**
  799. * Return the total number of users for the current query.
  800. *
  801. * @since 3.1.0
  802. * @access public
  803. *
  804. * @return int Number of total users.
  805. */
  806. public function get_total() {
  807. return $this->total_users;
  808. }
  809. /**
  810. * Make private properties readable for backwards compatibility.
  811. *
  812. * @since 4.0.0
  813. * @access public
  814. *
  815. * @param string $name Property to get.
  816. * @return mixed Property.
  817. */
  818. public function __get( $name ) {
  819. return $this->$name;
  820. }
  821. /**
  822. * Make private properties settable for backwards compatibility.
  823. *
  824. * @since 4.0.0
  825. * @access public
  826. *
  827. * @param string $name Property to set.
  828. * @param mixed $value Property value.
  829. * @return mixed Newly-set property.
  830. */
  831. public function __set( $name, $value ) {
  832. return $this->$name = $value;
  833. }
  834. /**
  835. * Make private properties checkable for backwards compatibility.
  836. *
  837. * @since 4.0.0
  838. * @access public
  839. *
  840. * @param string $name Property to check if set.
  841. * @return bool Whether the property is set.
  842. */
  843. public function __isset( $name ) {
  844. return isset( $this->$name );
  845. }
  846. /**
  847. * Make private properties un-settable for backwards compatibility.
  848. *
  849. * @since 4.0.0
  850. * @access public
  851. *
  852. * @param string $name Property to unset.
  853. */
  854. public function __unset( $name ) {
  855. unset( $this->$name );
  856. }
  857. /**
  858. * Make private/protected methods readable for backwards compatibility.
  859. *
  860. * @since 4.0.0
  861. * @access public
  862. *
  863. * @param callable $name Method to call.
  864. * @param array $arguments Arguments to pass when calling.
  865. * @return mixed|bool Return value of the callback, false otherwise.
  866. */
  867. public function __call( $name, $arguments ) {
  868. return call_user_func_array( array( $this, $name ), $arguments );
  869. }
  870. }
  871. /**
  872. * Retrieve list of users matching criteria.
  873. *
  874. * @since 3.1.0
  875. *
  876. * @see WP_User_Query
  877. *
  878. * @param array $args Optional. Arguments to retrieve users. See {@see WP_User_Query::prepare_query()}
  879. * for more information on accepted arguments.
  880. * @return array List of users.
  881. */
  882. function get_users( $args = array() ) {
  883. $args = wp_parse_args( $args );
  884. $args['count_total'] = false;
  885. $user_search = new WP_User_Query($args);
  886. return (array) $user_search->get_results();
  887. }
  888. /**
  889. * Get the blogs a user belongs to.
  890. *
  891. * @since 3.0.0
  892. *
  893. * @global wpdb $wpdb WordPress database object for queries.
  894. *
  895. * @param int $user_id User ID
  896. * @param bool $all Whether to retrieve all blogs, or only blogs that are not
  897. * marked as deleted, archived, or spam.
  898. * @return array A list of the user's blogs. An empty array if the user doesn't exist
  899. * or belongs to no blogs.
  900. */
  901. function get_blogs_of_user( $user_id, $all = false ) {
  902. global $wpdb;
  903. $user_id = (int) $user_id;
  904. // Logged out users can't have blogs
  905. if ( empty( $user_id ) )
  906. return array();
  907. $keys = get_user_meta( $user_id );
  908. if ( empty( $keys ) )
  909. return array();
  910. if ( ! is_multisite() ) {
  911. $blog_id = get_current_blog_id();
  912. $blogs = array( $blog_id => new stdClass );
  913. $blogs[ $blog_id ]->userblog_id = $blog_id;
  914. $blogs[ $blog_id ]->blogname = get_option('blogname');
  915. $blogs[ $blog_id ]->domain = '';
  916. $blogs[ $blog_id ]->path = '';
  917. $blogs[ $blog_id ]->site_id = 1;
  918. $blogs[ $blog_id ]->siteurl = get_option('siteurl');
  919. $blogs[ $blog_id ]->archived = 0;
  920. $blogs[ $blog_id ]->spam = 0;
  921. $blogs[ $blog_id ]->deleted = 0;
  922. return $blogs;
  923. }
  924. $blogs = array();
  925. if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
  926. $blog = get_blog_details( 1 );
  927. if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
  928. $blogs[ 1 ] = (object) array(
  929. 'userblog_id' => 1,
  930. 'blogname' => $blog->blogname,
  931. 'domain' => $blog->domain,
  932. 'path' => $blog->path,
  933. 'site_id' => $blog->site_id,
  934. 'siteurl' => $blog->siteurl,
  935. 'archived' => 0,
  936. 'spam' => 0,
  937. 'deleted' => 0
  938. );
  939. }
  940. unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
  941. }
  942. $keys = array_keys( $keys );
  943. foreach ( $keys as $key ) {
  944. if ( 'capabilities' !== substr( $key, -12 ) )
  945. continue;
  946. if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) )
  947. continue;
  948. $blog_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
  949. if ( ! is_numeric( $blog_id ) )
  950. continue;
  951. $blog_id = (int) $blog_id;
  952. $blog = get_blog_details( $blog_id );
  953. if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
  954. $blogs[ $blog_id ] = (object) array(
  955. 'userblog_id' => $blog_id,
  956. 'blogname' => $blog->blogname,
  957. 'domain' => $blog->domain,
  958. 'path' => $blog->path,
  959. 'site_id' => $blog->site_id,
  960. 'siteurl' => $blog->siteurl,
  961. 'archived' => 0,
  962. 'spam' => 0,
  963. 'deleted' => 0
  964. );
  965. }
  966. }
  967. /**
  968. * Filter the list of blogs a user belongs to.
  969. *
  970. * @since MU
  971. *
  972. * @param array $blogs An array of blog objects belonging to the user.
  973. * @param int $user_id User ID.
  974. * @param bool $all Whether the returned blogs array should contain all blogs, including
  975. * those marked 'deleted', 'archived', or 'spam'. Default false.
  976. */
  977. return apply_filters( 'get_blogs_of_user', $blogs, $user_id, $all );
  978. }
  979. /**
  980. * Find out whether a user is a member of a given blog.
  981. *
  982. * @since MU 1.1
  983. *
  984. * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
  985. * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
  986. * @return bool
  987. */
  988. function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
  989. $user_id = (int) $user_id;
  990. $blog_id = (int) $blog_id;
  991. if ( empty( $user_id ) )
  992. $user_id = get_current_user_id();
  993. if ( empty( $blog_id ) )
  994. $blog_id = get_current_blog_id();
  995. $blogs = get_blogs_of_user( $user_id );
  996. return array_key_exists( $blog_id, $blogs );
  997. }
  998. /**
  999. * Add meta data field to a user.
  1000. *
  1001. * Post meta data is called "Custom Fields" on the Administration Screens.
  1002. *
  1003. * @since 3.0.0
  1004. * @link http://codex.wordpress.org/Function_Reference/add_user_meta
  1005. *
  1006. * @param int $user_id User ID.
  1007. * @param string $meta_key Metadata name.
  1008. * @param mixed $meta_value Metadata value.
  1009. * @param bool $unique Optional, default is false. Whether the same key should not be added.
  1010. * @return int|bool Meta ID on success, false on failure.
  1011. */
  1012. function add_user_meta($user_id, $meta_key, $meta_value, $unique = false) {
  1013. return add_metadata('user', $user_id, $meta_key, $meta_value, $unique);
  1014. }
  1015. /**
  1016. * Remove metadata matching criteria from a user.
  1017. *
  1018. * You can match based on the key, or key and value. Removing based on key and
  1019. * value, will keep from removing duplicate metadata with the same key. It also
  1020. * allows removing all metadata matching key, if needed.
  1021. *
  1022. * @since 3.0.0
  1023. * @link http://codex.wordpress.org/Function_Reference/delete_user_meta
  1024. *
  1025. * @param int $user_id user ID
  1026. * @param string $meta_key Metadata name.
  1027. * @param mixed $meta_value Optional. Metadata value.
  1028. * @return bool True on success, false on failure.
  1029. */
  1030. function delete_user_meta($user_id, $meta_key, $meta_value = '') {
  1031. return delete_metadata('user', $user_id, $meta_key, $meta_value);
  1032. }
  1033. /**
  1034. * Retrieve user meta field for a user.
  1035. *
  1036. * @since 3.0.0
  1037. * @link http://codex.wordpress.org/Function_Reference/get_user_meta
  1038. *
  1039. * @param int $user_id User ID.
  1040. * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
  1041. * @param bool $single Whether to return a single value.
  1042. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
  1043. * is true.
  1044. */
  1045. function get_user_meta($user_id, $key = '', $single = false) {
  1046. return get_metadata('user', $user_id, $key, $single);
  1047. }
  1048. /**
  1049. * Update user meta field based on user ID.
  1050. *
  1051. * Use the $prev_value parameter to differentiate between meta fields with the
  1052. * same key and user ID.
  1053. *
  1054. * If the meta field for the user does not exist, it will be added.
  1055. *
  1056. * @since 3.0.0
  1057. * @link http://codex.wordpress.org/Function_Reference/update_user_meta
  1058. *
  1059. * @param int $user_id User ID.
  1060. * @param string $meta_key Metadata key.
  1061. * @param mixed $meta_value Metadata value.
  1062. * @param mixed $prev_value Optional. Previous value to check before removing.
  1063. * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
  1064. */
  1065. function update_user_meta($user_id, $meta_key, $meta_value, $prev_value = '') {
  1066. return update_metadata('user', $user_id, $meta_key, $meta_value, $prev_value);
  1067. }
  1068. /**
  1069. * Count number of users who have each of the user roles.
  1070. *
  1071. * Assumes there are neither duplicated nor orphaned capabilities meta_values.
  1072. * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
  1073. * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
  1074. * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
  1075. *
  1076. * @since 3.0.0
  1077. * @param string $strategy 'time' or 'memory'
  1078. * @return array Includes a grand total and an array of counts indexed by role strings.
  1079. */
  1080. function count_users($strategy = 'time') {
  1081. global $wpdb, $wp_roles;
  1082. // Initialize
  1083. $id = get_current_blog_id();
  1084. $blog_prefix = $wpdb->get_blog_prefix($id);
  1085. $result = array();
  1086. if ( 'time' == $strategy ) {
  1087. global $wp_roles;
  1088. if ( ! isset( $wp_roles ) )
  1089. $wp_roles = new WP_Roles();
  1090. $avail_roles = $wp_roles->get_names();
  1091. // Build a CPU-intensive query that will return concise information.
  1092. $select_count = array();
  1093. foreach ( $avail_roles as $this_role => $name ) {
  1094. $select_count[] = $wpdb->prepare( "COUNT(NULLIF(`meta_value` LIKE %s, false))", '%' . $wpdb->esc_like( '"' . $this_role . '"' ) . '%');
  1095. }
  1096. $select_count = implode(', ', $select_count);
  1097. // Add the meta_value index to the selection list, then run the query.
  1098. $row = $wpdb->get_row( "SELECT $select_count, COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'", ARRAY_N );
  1099. // Run the previous loop again to associate results with role names.
  1100. $col = 0;
  1101. $role_counts = array();
  1102. foreach ( $avail_roles as $this_role => $name ) {
  1103. $count = (int) $row[$col++];
  1104. if ($count > 0) {
  1105. $role_counts[$this_role] = $count;
  1106. }
  1107. }
  1108. // Get the meta_value index from the end of the result set.
  1109. $total_users = (int) $row[$col];
  1110. $result['total_users'] = $total_users;
  1111. $result['avail_roles'] =& $role_counts;
  1112. } else {
  1113. $avail_roles = array();
  1114. $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" );
  1115. foreach ( $users_of_blog as $caps_meta ) {
  1116. $b_roles = maybe_unserialize($caps_meta);
  1117. if ( ! is_array( $b_roles ) )
  1118. continue;
  1119. foreach ( $b_roles as $b_role => $val ) {
  1120. if ( isset($avail_roles[$b_role]) ) {
  1121. $avail_roles[$b_role]++;
  1122. } else {
  1123. $avail_roles[$b_role] = 1;
  1124. }
  1125. }
  1126. }
  1127. $result['total_users'] = count( $users_of_blog );
  1128. $result['avail_roles'] =& $avail_roles;
  1129. }
  1130. return $result;
  1131. }
  1132. //
  1133. // Private helper functions
  1134. //
  1135. /**
  1136. * Set up global user vars.
  1137. *
  1138. * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
  1139. *
  1140. * @since 2.0.4
  1141. * @global string $userdata User description.
  1142. * @global string $user_login The user username for logging in
  1143. * @global int $user_level The level of the user
  1144. * @global int $user_ID The ID of the user
  1145. * @global string $user_email The email address of the user
  1146. * @global string $user_url The url in the user's profile
  1147. * @global string $user_identity The display name of the user
  1148. *
  1149. * @param int $for_user_id Optional. User ID to set up global data.
  1150. */
  1151. function setup_userdata($for_user_id = '') {
  1152. global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
  1153. if ( '' == $for_user_id )
  1154. $for_user_id = get_current_user_id();
  1155. $user = get_userdata( $for_user_id );
  1156. if ( ! $user ) {
  1157. $user_ID = 0;
  1158. $user_level = 0;
  1159. $userdata = null;
  1160. $user_login = $user_email = $user_url = $user_identity = '';
  1161. return;
  1162. }
  1163. $user_ID = (int) $user->ID;
  1164. $user_level = (int) $user->user_level;
  1165. $userdata = $user;
  1166. $user_login = $user->user_login;
  1167. $user_email = $user->user_email;
  1168. $user_url = $user->user_url;
  1169. $user_identity = $user->display_name;
  1170. }
  1171. /**
  1172. * Create dropdown HTML content of users.
  1173. *
  1174. * The content can either be displayed, which it is by default or retrieved by
  1175. * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
  1176. * need to be used; all users will be displayed in that case. Only one can be
  1177. * used, either 'include' or 'exclude', but not both.
  1178. *
  1179. * The available arguments are as follows:
  1180. *
  1181. * @since 2.3.0
  1182. *
  1183. * @global wpdb $wpdb WordPress database object for queries.
  1184. *
  1185. * @param array|string $args {
  1186. * Optional. Array or string of arguments to generate a drop-down of users.
  1187. * {@see WP_User_Query::prepare_query() for additional available arguments.
  1188. *
  1189. * @type string $show_option_all Text to show as the drop-down default (all).
  1190. * Default empty.
  1191. * @type string $show_option_none Text to show as the drop-down default when no
  1192. * users were found. Default empty.
  1193. * @type int|string $option_none_value Value to use for $show_option_non when no users
  1194. * were found. Default -1.
  1195. * @type string $hide_if_only_one_author Whether to skip generating the drop-down
  1196. * if only one user was found. Default empty.
  1197. * @type string $orderby Field to order found users by. Accepts user fields.
  1198. * Default 'display_name'.
  1199. * @type string $order Whether to order users in ascending or descending
  1200. * order. Accepts 'ASC' (ascending) or 'DESC' (descending).
  1201. * Default 'ASC'.
  1202. * @type array|string $include Array or comma-separated list of user IDs to include.
  1203. * Default empty.
  1204. * @type array|string $exclude Array or comma-separated list of user IDs to exclude.
  1205. * Default empty.
  1206. * @type bool|int $multi Whether to skip the ID attribute on the 'select' element.
  1207. * Accepts 1|true or 0|false. Default 0|false.
  1208. * @type string $show User table column to display. If the selected item is empty
  1209. * then the 'user_login' will be displayed in parentheses.
  1210. * Accepts user fields. Default 'display_name'.
  1211. * @type int|bool $echo Whether to echo or return the drop-down. Accepts 1|true (echo)
  1212. * or 0|false (return). Default 1|true.
  1213. * @type int $selected Which user ID should be selected. Default 0.
  1214. * @type bool $include_selected Whether to always include the selected user ID in the drop-
  1215. * down. Default false.
  1216. * @type string $name Name attribute of select element. Default 'user'.
  1217. * @type string $id ID attribute of the select element. Default is the value of $name.
  1218. * @type string $class Class attribute of the select element. Default empty.
  1219. * @type int $blog_id ID of blog (Multisite only). Default is ID of the current blog.
  1220. * @type string $who Which type of users to query. Accepts only an empty string or
  1221. * 'authors'. Default empty.
  1222. * }
  1223. * @return string|null Null on display. String of HTML content on retrieve.
  1224. */
  1225. function wp_dropdown_users( $args = '' ) {
  1226. $defaults = array(
  1227. 'show_option_all' => '', 'show_option_none' => '', 'hide_if_only_one_author' => '',
  1228. 'orderby' => 'display_name', 'order' => 'ASC',
  1229. 'include' => '', 'exclude' => '', 'multi' => 0,
  1230. 'show' => 'display_name', 'echo' => 1,
  1231. 'selected' => 0, 'name' => 'user', 'class' => '', 'id' => '',
  1232. 'blog_id' => $GLOBALS['blog_id'], 'who' => '', 'include_selected' => false,
  1233. 'option_none_value' => -1
  1234. );
  1235. $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
  1236. $r = wp_parse_args( $args, $defaults );
  1237. $show = $r['show'];
  1238. $show_option_all = $r['show_option_all'];
  1239. $show_option_none = $r['show_option_none'];
  1240. $option_none_value = $r['option_none_value'];
  1241. $query_args = wp_array_slice_assoc( $r, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who' ) );
  1242. $query_args['fields'] = array( 'ID', 'user_login', $show );
  1243. $users = get_users( $query_args );
  1244. $output = '';
  1245. if ( ! empty( $users ) && ( empty( $r['hide_if_only_one_author'] ) || count( $users ) > 1 ) ) {
  1246. $name = esc_attr( $r['name'] );
  1247. if ( $r['multi'] && ! $r['id'] ) {
  1248. $id = '';
  1249. } else {
  1250. $id = $r['id'] ? " id='" . esc_attr( $r['id'] ) . "'" : " id='$name'";
  1251. }
  1252. $output = "<select name='{$name}'{$id} class='" . $r['class'] . "'>\n";
  1253. if ( $show_option_all ) {
  1254. $output .= "\t<option value='0'>$show_option_all</option>\n";
  1255. }
  1256. if ( $show_option_none ) {
  1257. $_selected = selected( $option_none_value, $r['selected'], false );
  1258. $output .= "\t<option value='" . esc_attr( $option_none_value ) . "'$_selected>$show_option_none</option>\n";
  1259. }
  1260. $found_selected = false;
  1261. foreach ( (array) $users as $user ) {
  1262. $user->ID = (int) $user->ID;
  1263. $_selected = selected( $user->ID, $r['selected'], false );
  1264. if ( $_selected ) {
  1265. $found_selected = true;
  1266. }
  1267. $display = ! empty( $user->$show ) ? $user->$show : '('. $user->user_login . ')';
  1268. $output .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
  1269. }
  1270. if ( $r['include_selected'] && ! $found_selected && ( $r['selected'] > 0 ) ) {
  1271. $user = get_userdata( $r['selected'] );
  1272. $_selected = selected( $user->ID, $r['selected'], false );
  1273. $display = ! empty( $user->$show ) ? $user->$show : '('. $user->user_login . ')';
  1274. $output .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
  1275. }
  1276. $output .= "</select>";
  1277. }
  1278. /**
  1279. * Filter the wp_dropdown_users() HTML output.
  1280. *
  1281. * @since 2.3.0
  1282. *
  1283. * @param string $output HTML output generated by wp_dropdown_users().
  1284. */
  1285. $html = apply_filters( 'wp_dropdown_users', $output );
  1286. if ( $r['echo'] ) {
  1287. echo $html;
  1288. }
  1289. return $html;
  1290. }
  1291. /**
  1292. * Sanitize user field based on context.
  1293. *
  1294. * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
  1295. * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
  1296. * when calling filters.
  1297. *
  1298. * @since 2.3.0
  1299. *
  1300. * @param string $field The user Object field name.
  1301. * @param mixed $value The user Object value.
  1302. * @param int $user_id user ID.
  1303. * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
  1304. * 'attribute' and 'js'.
  1305. * @return mixed Sanitized value.
  1306. */
  1307. function sanitize_user_field($field, $value, $user_id, $context) {
  1308. $int_fields = array('ID');
  1309. if ( in_array($field, $int_fields) )
  1310. $value = (int) $value;
  1311. if ( 'raw' == $context )
  1312. return $value;
  1313. if ( !is_string($value) && !is_numeric($value) )
  1314. return $value;
  1315. $prefixed = false !== strpos( $field, 'user_' );
  1316. if ( 'edit' == $context ) {
  1317. if ( $prefixed ) {
  1318. /** This filter is documented in wp-includes/post.php */
  1319. $value = apply_filters( "edit_{$field}", $value, $user_id );
  1320. } else {
  1321. /**
  1322. * Filter a user field value in the 'edit' context.
  1323. *
  1324. * The dynamic portion of the hook name, `$field`, refers to the prefixed user
  1325. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1326. *
  1327. * @since 2.9.0
  1328. *
  1329. * @param mixed $value Value of the prefixed user field.
  1330. * @param int $user_id User ID.
  1331. */
  1332. $value = apply_filters( "edit_user_{$field}", $value, $user_id );
  1333. }
  1334. if ( 'description' == $field )
  1335. $value = esc_html( $value ); // textarea_escaped?
  1336. else
  1337. $value = esc_attr($value);
  1338. } else if (

Large files files are truncated, but you can click here to view the full file