PageRenderTime 51ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/user.php

https://bitbucket.org/Thane2376/death-edge.ru
PHP | 2247 lines | 942 code | 276 blank | 1029 comment | 244 complexity | 05e49a4048534d8cb2a8b1ca08bc9658 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, LGPL-3.0, AGPL-1.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 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 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. *
  219. * @global wpdb $wpdb WordPress database object for queries.
  220. *
  221. * @param int $userid User ID.
  222. * @return int Amount of posts user has written.
  223. */
  224. function count_user_posts($userid) {
  225. global $wpdb;
  226. $where = get_posts_by_author_sql('post', true, $userid);
  227. $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
  228. /**
  229. * Filter the number of posts a user has written.
  230. *
  231. * @since 2.7.0
  232. *
  233. * @param int $count The user's post count.
  234. * @param int $userid User ID.
  235. */
  236. return apply_filters( 'get_usernumposts', $count, $userid );
  237. }
  238. /**
  239. * Number of posts written by a list of users.
  240. *
  241. * @since 3.0.0
  242. *
  243. * @param array $users Array of user IDs.
  244. * @param string $post_type Optional. Post type to check. Defaults to post.
  245. * @param bool $public_only Optional. Only return counts for public posts. Defaults to false.
  246. * @return array Amount of posts each user has written.
  247. */
  248. function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
  249. global $wpdb;
  250. $count = array();
  251. if ( empty( $users ) || ! is_array( $users ) )
  252. return $count;
  253. $userlist = implode( ',', array_map( 'absint', $users ) );
  254. $where = get_posts_by_author_sql( $post_type, true, null, $public_only );
  255. $result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
  256. foreach ( $result as $row ) {
  257. $count[ $row[0] ] = $row[1];
  258. }
  259. foreach ( $users as $id ) {
  260. if ( ! isset( $count[ $id ] ) )
  261. $count[ $id ] = 0;
  262. }
  263. return $count;
  264. }
  265. //
  266. // User option functions
  267. //
  268. /**
  269. * Get the current user's ID
  270. *
  271. * @since MU
  272. *
  273. * @uses wp_get_current_user
  274. *
  275. * @return int The current user's ID
  276. */
  277. function get_current_user_id() {
  278. if ( ! function_exists( 'wp_get_current_user' ) )
  279. return 0;
  280. $user = wp_get_current_user();
  281. return ( isset( $user->ID ) ? (int) $user->ID : 0 );
  282. }
  283. /**
  284. * Retrieve user option that can be either per Site or per Network.
  285. *
  286. * If the user ID is not given, then the current user will be used instead. If
  287. * the user ID is given, then the user data will be retrieved. The filter for
  288. * the result, will also pass the original option name and finally the user data
  289. * object as the third parameter.
  290. *
  291. * The option will first check for the per site name and then the per Network name.
  292. *
  293. * @since 2.0.0
  294. *
  295. * @global wpdb $wpdb WordPress database object for queries.
  296. *
  297. * @param string $option User option name.
  298. * @param int $user Optional. User ID.
  299. * @param bool $deprecated Use get_option() to check for an option in the options table.
  300. * @return mixed User option value on success, false on failure.
  301. */
  302. function get_user_option( $option, $user = 0, $deprecated = '' ) {
  303. global $wpdb;
  304. if ( !empty( $deprecated ) )
  305. _deprecated_argument( __FUNCTION__, '3.0' );
  306. if ( empty( $user ) )
  307. $user = get_current_user_id();
  308. if ( ! $user = get_userdata( $user ) )
  309. return false;
  310. $prefix = $wpdb->get_blog_prefix();
  311. if ( $user->has_prop( $prefix . $option ) ) // Blog specific
  312. $result = $user->get( $prefix . $option );
  313. elseif ( $user->has_prop( $option ) ) // User specific and cross-blog
  314. $result = $user->get( $option );
  315. else
  316. $result = false;
  317. /**
  318. * Filter a specific user option value.
  319. *
  320. * The dynamic portion of the hook name, $option, refers to the user option name.
  321. *
  322. * @since 2.5.0
  323. *
  324. * @param mixed $result Value for the user's option.
  325. * @param string $option Name of the option being retrieved.
  326. * @param WP_User $user WP_User object of the user whose option is being retrieved.
  327. */
  328. return apply_filters( "get_user_option_{$option}", $result, $option, $user );
  329. }
  330. /**
  331. * Update user option with global blog capability.
  332. *
  333. * User options are just like user metadata except that they have support for
  334. * global blog options. If the 'global' parameter is false, which it is by default
  335. * it will prepend the WordPress table prefix to the option name.
  336. *
  337. * Deletes the user option if $newvalue is empty.
  338. *
  339. * @since 2.0.0
  340. *
  341. * @global wpdb $wpdb WordPress database object for queries.
  342. *
  343. * @param int $user_id User ID.
  344. * @param string $option_name User option name.
  345. * @param mixed $newvalue User option value.
  346. * @param bool $global Optional. Whether option name is global or blog specific.
  347. * Default false (blog specific).
  348. * @return int|bool User meta ID if the option didn't exist, true on successful update,
  349. * false on failure.
  350. */
  351. function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
  352. global $wpdb;
  353. if ( !$global )
  354. $option_name = $wpdb->get_blog_prefix() . $option_name;
  355. return update_user_meta( $user_id, $option_name, $newvalue );
  356. }
  357. /**
  358. * Delete user option with global blog capability.
  359. *
  360. * User options are just like user metadata except that they have support for
  361. * global blog options. If the 'global' parameter is false, which it is by default
  362. * it will prepend the WordPress table prefix to the option name.
  363. *
  364. * @since 3.0.0
  365. *
  366. * @global wpdb $wpdb WordPress database object for queries.
  367. *
  368. * @param int $user_id User ID
  369. * @param string $option_name User option name.
  370. * @param bool $global Optional. Whether option name is global or blog specific.
  371. * Default false (blog specific).
  372. * @return bool True on success, false on failure.
  373. */
  374. function delete_user_option( $user_id, $option_name, $global = false ) {
  375. global $wpdb;
  376. if ( !$global )
  377. $option_name = $wpdb->get_blog_prefix() . $option_name;
  378. return delete_user_meta( $user_id, $option_name );
  379. }
  380. /**
  381. * WordPress User Query class.
  382. *
  383. * @since 3.1.0
  384. */
  385. class WP_User_Query {
  386. /**
  387. * Query vars, after parsing
  388. *
  389. * @since 3.5.0
  390. * @access public
  391. * @var array
  392. */
  393. public $query_vars = array();
  394. /**
  395. * List of found user ids
  396. *
  397. * @since 3.1.0
  398. * @access private
  399. * @var array
  400. */
  401. private $results;
  402. /**
  403. * Total number of found users for the current query
  404. *
  405. * @since 3.1.0
  406. * @access private
  407. * @var int
  408. */
  409. private $total_users = 0;
  410. // SQL clauses
  411. public $query_fields;
  412. public $query_from;
  413. public $query_where;
  414. public $query_orderby;
  415. public $query_limit;
  416. /**
  417. * PHP5 constructor.
  418. *
  419. * @since 3.1.0
  420. *
  421. * @param string|array $args Optional. The query variables.
  422. * @return WP_User_Query
  423. */
  424. public function __construct( $query = null ) {
  425. if ( ! empty( $query ) ) {
  426. $this->prepare_query( $query );
  427. $this->query();
  428. }
  429. }
  430. /**
  431. * Prepare the query variables.
  432. *
  433. * @since 3.1.0
  434. *
  435. * @param string|array $args Optional. The query variables.
  436. */
  437. public function prepare_query( $query = array() ) {
  438. global $wpdb;
  439. if ( empty( $this->query_vars ) || ! empty( $query ) ) {
  440. $this->query_limit = null;
  441. $this->query_vars = wp_parse_args( $query, array(
  442. 'blog_id' => $GLOBALS['blog_id'],
  443. 'role' => '',
  444. 'meta_key' => '',
  445. 'meta_value' => '',
  446. 'meta_compare' => '',
  447. 'include' => array(),
  448. 'exclude' => array(),
  449. 'search' => '',
  450. 'search_columns' => array(),
  451. 'orderby' => 'login',
  452. 'order' => 'ASC',
  453. 'offset' => '',
  454. 'number' => '',
  455. 'count_total' => true,
  456. 'fields' => 'all',
  457. 'who' => ''
  458. ) );
  459. }
  460. /**
  461. * Fires before the WP_User_Query has been parsed.
  462. *
  463. * The passed WP_User_Query object contains the query variables, not
  464. * yet passed into SQL.
  465. *
  466. * @since 4.0.0
  467. *
  468. * @param WP_User_Query $this The current WP_User_Query instance,
  469. * passed by reference.
  470. */
  471. do_action( 'pre_get_users', $this );
  472. $qv =& $this->query_vars;
  473. if ( is_array( $qv['fields'] ) ) {
  474. $qv['fields'] = array_unique( $qv['fields'] );
  475. $this->query_fields = array();
  476. foreach ( $qv['fields'] as $field ) {
  477. $field = 'ID' === $field ? 'ID' : sanitize_key( $field );
  478. $this->query_fields[] = "$wpdb->users.$field";
  479. }
  480. $this->query_fields = implode( ',', $this->query_fields );
  481. } elseif ( 'all' == $qv['fields'] ) {
  482. $this->query_fields = "$wpdb->users.*";
  483. } else {
  484. $this->query_fields = "$wpdb->users.ID";
  485. }
  486. if ( isset( $qv['count_total'] ) && $qv['count_total'] )
  487. $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
  488. $this->query_from = "FROM $wpdb->users";
  489. $this->query_where = "WHERE 1=1";
  490. // sorting
  491. if ( isset( $qv['orderby'] ) ) {
  492. if ( in_array( $qv['orderby'], array('nicename', 'email', 'url', 'registered') ) ) {
  493. $orderby = 'user_' . $qv['orderby'];
  494. } elseif ( in_array( $qv['orderby'], array('user_nicename', 'user_email', 'user_url', 'user_registered') ) ) {
  495. $orderby = $qv['orderby'];
  496. } elseif ( 'name' == $qv['orderby'] || 'display_name' == $qv['orderby'] ) {
  497. $orderby = 'display_name';
  498. } elseif ( 'post_count' == $qv['orderby'] ) {
  499. // todo: avoid the JOIN
  500. $where = get_posts_by_author_sql('post');
  501. $this->query_from .= " LEFT OUTER JOIN (
  502. SELECT post_author, COUNT(*) as post_count
  503. FROM $wpdb->posts
  504. $where
  505. GROUP BY post_author
  506. ) p ON ({$wpdb->users}.ID = p.post_author)
  507. ";
  508. $orderby = 'post_count';
  509. } elseif ( 'ID' == $qv['orderby'] || 'id' == $qv['orderby'] ) {
  510. $orderby = 'ID';
  511. } elseif ( 'meta_value' == $qv['orderby'] ) {
  512. $orderby = "$wpdb->usermeta.meta_value";
  513. } else {
  514. $orderby = 'user_login';
  515. }
  516. }
  517. if ( empty( $orderby ) )
  518. $orderby = 'user_login';
  519. $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
  520. if ( 'ASC' == $qv['order'] )
  521. $order = 'ASC';
  522. else
  523. $order = 'DESC';
  524. $this->query_orderby = "ORDER BY $orderby $order";
  525. // limit
  526. if ( isset( $qv['number'] ) && $qv['number'] ) {
  527. if ( $qv['offset'] )
  528. $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
  529. else
  530. $this->query_limit = $wpdb->prepare("LIMIT %d", $qv['number']);
  531. }
  532. $search = '';
  533. if ( isset( $qv['search'] ) )
  534. $search = trim( $qv['search'] );
  535. if ( $search ) {
  536. $leading_wild = ( ltrim($search, '*') != $search );
  537. $trailing_wild = ( rtrim($search, '*') != $search );
  538. if ( $leading_wild && $trailing_wild )
  539. $wild = 'both';
  540. elseif ( $leading_wild )
  541. $wild = 'leading';
  542. elseif ( $trailing_wild )
  543. $wild = 'trailing';
  544. else
  545. $wild = false;
  546. if ( $wild )
  547. $search = trim($search, '*');
  548. $search_columns = array();
  549. if ( $qv['search_columns'] )
  550. $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename' ) );
  551. if ( ! $search_columns ) {
  552. if ( false !== strpos( $search, '@') )
  553. $search_columns = array('user_email');
  554. elseif ( is_numeric($search) )
  555. $search_columns = array('user_login', 'ID');
  556. elseif ( preg_match('|^https?://|', $search) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) )
  557. $search_columns = array('user_url');
  558. else
  559. $search_columns = array('user_login', 'user_nicename');
  560. }
  561. /**
  562. * Filter the columns to search in a WP_User_Query search.
  563. *
  564. * The default columns depend on the search term, and include 'user_email',
  565. * 'user_login', 'ID', 'user_url', and 'user_nicename'.
  566. *
  567. * @since 3.6.0
  568. *
  569. * @param array $search_columns Array of column names to be searched.
  570. * @param string $search Text being searched.
  571. * @param WP_User_Query $this The current WP_User_Query instance.
  572. */
  573. $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
  574. $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
  575. }
  576. $blog_id = 0;
  577. if ( isset( $qv['blog_id'] ) )
  578. $blog_id = absint( $qv['blog_id'] );
  579. if ( isset( $qv['who'] ) && 'authors' == $qv['who'] && $blog_id ) {
  580. $qv['meta_key'] = $wpdb->get_blog_prefix( $blog_id ) . 'user_level';
  581. $qv['meta_value'] = 0;
  582. $qv['meta_compare'] = '!=';
  583. $qv['blog_id'] = $blog_id = 0; // Prevent extra meta query
  584. }
  585. $role = '';
  586. if ( isset( $qv['role'] ) )
  587. $role = trim( $qv['role'] );
  588. if ( $blog_id && ( $role || is_multisite() ) ) {
  589. $cap_meta_query = array();
  590. $cap_meta_query['key'] = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities';
  591. if ( $role ) {
  592. $cap_meta_query['value'] = '"' . $role . '"';
  593. $cap_meta_query['compare'] = 'like';
  594. }
  595. if ( empty( $qv['meta_query'] ) || ! in_array( $cap_meta_query, $qv['meta_query'], true ) ) {
  596. $qv['meta_query'][] = $cap_meta_query;
  597. }
  598. }
  599. $meta_query = new WP_Meta_Query();
  600. $meta_query->parse_query_vars( $qv );
  601. if ( !empty( $meta_query->queries ) ) {
  602. $clauses = $meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
  603. $this->query_from .= $clauses['join'];
  604. $this->query_where .= $clauses['where'];
  605. if ( 'OR' == $meta_query->relation )
  606. $this->query_fields = 'DISTINCT ' . $this->query_fields;
  607. }
  608. if ( ! empty( $qv['include'] ) ) {
  609. $ids = implode( ',', wp_parse_id_list( $qv['include'] ) );
  610. $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
  611. } elseif ( ! empty( $qv['exclude'] ) ) {
  612. $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
  613. $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
  614. }
  615. /**
  616. * Fires after the WP_User_Query has been parsed, and before
  617. * the query is executed.
  618. *
  619. * The passed WP_User_Query object contains SQL parts formed
  620. * from parsing the given query.
  621. *
  622. * @since 3.1.0
  623. *
  624. * @param WP_User_Query $this The current WP_User_Query instance,
  625. * passed by reference.
  626. */
  627. do_action_ref_array( 'pre_user_query', array( &$this ) );
  628. }
  629. /**
  630. * Execute the query, with the current variables.
  631. *
  632. * @since 3.1.0
  633. *
  634. * @global wpdb $wpdb WordPress database object for queries.
  635. */
  636. public function query() {
  637. global $wpdb;
  638. $qv =& $this->query_vars;
  639. $query = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
  640. if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
  641. $this->results = $wpdb->get_results( $query );
  642. } else {
  643. $this->results = $wpdb->get_col( $query );
  644. }
  645. /**
  646. * Filter SELECT FOUND_ROWS() query for the current WP_User_Query instance.
  647. *
  648. * @since 3.2.0
  649. *
  650. * @global wpdb $wpdb WordPress database object.
  651. *
  652. * @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
  653. */
  654. if ( isset( $qv['count_total'] ) && $qv['count_total'] )
  655. $this->total_users = $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) );
  656. if ( !$this->results )
  657. return;
  658. if ( 'all_with_meta' == $qv['fields'] ) {
  659. cache_users( $this->results );
  660. $r = array();
  661. foreach ( $this->results as $userid )
  662. $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
  663. $this->results = $r;
  664. } elseif ( 'all' == $qv['fields'] ) {
  665. foreach ( $this->results as $key => $user ) {
  666. $this->results[ $key ] = new WP_User( $user );
  667. }
  668. }
  669. }
  670. /**
  671. * Retrieve query variable.
  672. *
  673. * @since 3.5.0
  674. * @access public
  675. *
  676. * @param string $query_var Query variable key.
  677. * @return mixed
  678. */
  679. public function get( $query_var ) {
  680. if ( isset( $this->query_vars[$query_var] ) )
  681. return $this->query_vars[$query_var];
  682. return null;
  683. }
  684. /**
  685. * Set query variable.
  686. *
  687. * @since 3.5.0
  688. * @access public
  689. *
  690. * @param string $query_var Query variable key.
  691. * @param mixed $value Query variable value.
  692. */
  693. public function set( $query_var, $value ) {
  694. $this->query_vars[$query_var] = $value;
  695. }
  696. /**
  697. * Used internally to generate an SQL string for searching across multiple columns
  698. *
  699. * @access protected
  700. * @since 3.1.0
  701. *
  702. * @param string $string
  703. * @param array $cols
  704. * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for
  705. * single site. Single site allows leading and trailing wildcards, Network Admin only trailing.
  706. * @return string
  707. */
  708. protected function get_search_sql( $string, $cols, $wild = false ) {
  709. global $wpdb;
  710. $searches = array();
  711. $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
  712. $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
  713. $like = $leading_wild . $wpdb->esc_like( $string ) . $trailing_wild;
  714. foreach ( $cols as $col ) {
  715. if ( 'ID' == $col ) {
  716. $searches[] = $wpdb->prepare( "$col = %s", $string );
  717. } else {
  718. $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
  719. }
  720. }
  721. return ' AND (' . implode(' OR ', $searches) . ')';
  722. }
  723. /**
  724. * Return the list of users.
  725. *
  726. * @since 3.1.0
  727. * @access public
  728. *
  729. * @return array Array of results.
  730. */
  731. public function get_results() {
  732. return $this->results;
  733. }
  734. /**
  735. * Return the total number of users for the current query.
  736. *
  737. * @since 3.1.0
  738. * @access public
  739. *
  740. * @return array Array of total users.
  741. */
  742. public function get_total() {
  743. return $this->total_users;
  744. }
  745. /**
  746. * Make private properties readable for backwards compatibility.
  747. *
  748. * @since 4.0.0
  749. * @access public
  750. *
  751. * @param string $name Property to get.
  752. * @return mixed Property.
  753. */
  754. public function __get( $name ) {
  755. return $this->$name;
  756. }
  757. /**
  758. * Make private properties settable for backwards compatibility.
  759. *
  760. * @since 4.0.0
  761. * @access public
  762. *
  763. * @param string $name Property to set.
  764. * @param mixed $value Property value.
  765. * @return mixed Newly-set property.
  766. */
  767. public function __set( $name, $value ) {
  768. return $this->$name = $value;
  769. }
  770. /**
  771. * Make private properties checkable for backwards compatibility.
  772. *
  773. * @since 4.0.0
  774. * @access public
  775. *
  776. * @param string $name Property to check if set.
  777. * @return bool Whether the property is set.
  778. */
  779. public function __isset( $name ) {
  780. return isset( $this->$name );
  781. }
  782. /**
  783. * Make private properties un-settable for backwards compatibility.
  784. *
  785. * @since 4.0.0
  786. * @access public
  787. *
  788. * @param string $name Property to unset.
  789. */
  790. public function __unset( $name ) {
  791. unset( $this->$name );
  792. }
  793. /**
  794. * Make private/protected methods readable for backwards compatibility.
  795. *
  796. * @since 4.0.0
  797. * @access public
  798. *
  799. * @param callable $name Method to call.
  800. * @param array $arguments Arguments to pass when calling.
  801. * @return mixed|bool Return value of the callback, false otherwise.
  802. */
  803. public function __call( $name, $arguments ) {
  804. return call_user_func_array( array( $this, $name ), $arguments );
  805. }
  806. }
  807. /**
  808. * Retrieve list of users matching criteria.
  809. *
  810. * @since 3.1.0
  811. *
  812. * @uses WP_User_Query See for default arguments and information.
  813. *
  814. * @param array $args Optional. Array of arguments.
  815. * @return array List of users.
  816. */
  817. function get_users( $args = array() ) {
  818. $args = wp_parse_args( $args );
  819. $args['count_total'] = false;
  820. $user_search = new WP_User_Query($args);
  821. return (array) $user_search->get_results();
  822. }
  823. /**
  824. * Get the blogs a user belongs to.
  825. *
  826. * @since 3.0.0
  827. *
  828. * @global wpdb $wpdb WordPress database object for queries.
  829. *
  830. * @param int $user_id User ID
  831. * @param bool $all Whether to retrieve all blogs, or only blogs that are not
  832. * marked as deleted, archived, or spam.
  833. * @return array A list of the user's blogs. An empty array if the user doesn't exist
  834. * or belongs to no blogs.
  835. */
  836. function get_blogs_of_user( $user_id, $all = false ) {
  837. global $wpdb;
  838. $user_id = (int) $user_id;
  839. // Logged out users can't have blogs
  840. if ( empty( $user_id ) )
  841. return array();
  842. $keys = get_user_meta( $user_id );
  843. if ( empty( $keys ) )
  844. return array();
  845. if ( ! is_multisite() ) {
  846. $blog_id = get_current_blog_id();
  847. $blogs = array( $blog_id => new stdClass );
  848. $blogs[ $blog_id ]->userblog_id = $blog_id;
  849. $blogs[ $blog_id ]->blogname = get_option('blogname');
  850. $blogs[ $blog_id ]->domain = '';
  851. $blogs[ $blog_id ]->path = '';
  852. $blogs[ $blog_id ]->site_id = 1;
  853. $blogs[ $blog_id ]->siteurl = get_option('siteurl');
  854. $blogs[ $blog_id ]->archived = 0;
  855. $blogs[ $blog_id ]->spam = 0;
  856. $blogs[ $blog_id ]->deleted = 0;
  857. return $blogs;
  858. }
  859. $blogs = array();
  860. if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
  861. $blog = get_blog_details( 1 );
  862. if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
  863. $blogs[ 1 ] = (object) array(
  864. 'userblog_id' => 1,
  865. 'blogname' => $blog->blogname,
  866. 'domain' => $blog->domain,
  867. 'path' => $blog->path,
  868. 'site_id' => $blog->site_id,
  869. 'siteurl' => $blog->siteurl,
  870. 'archived' => 0,
  871. 'spam' => 0,
  872. 'deleted' => 0
  873. );
  874. }
  875. unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
  876. }
  877. $keys = array_keys( $keys );
  878. foreach ( $keys as $key ) {
  879. if ( 'capabilities' !== substr( $key, -12 ) )
  880. continue;
  881. if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) )
  882. continue;
  883. $blog_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
  884. if ( ! is_numeric( $blog_id ) )
  885. continue;
  886. $blog_id = (int) $blog_id;
  887. $blog = get_blog_details( $blog_id );
  888. if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
  889. $blogs[ $blog_id ] = (object) array(
  890. 'userblog_id' => $blog_id,
  891. 'blogname' => $blog->blogname,
  892. 'domain' => $blog->domain,
  893. 'path' => $blog->path,
  894. 'site_id' => $blog->site_id,
  895. 'siteurl' => $blog->siteurl,
  896. 'archived' => 0,
  897. 'spam' => 0,
  898. 'deleted' => 0
  899. );
  900. }
  901. }
  902. /**
  903. * Filter the list of blogs a user belongs to.
  904. *
  905. * @since MU
  906. *
  907. * @param array $blogs An array of blog objects belonging to the user.
  908. * @param int $user_id User ID.
  909. * @param bool $all Whether the returned blogs array should contain all blogs, including
  910. * those marked 'deleted', 'archived', or 'spam'. Default false.
  911. */
  912. return apply_filters( 'get_blogs_of_user', $blogs, $user_id, $all );
  913. }
  914. /**
  915. * Find out whether a user is a member of a given blog.
  916. *
  917. * @since MU 1.1
  918. * @uses get_blogs_of_user()
  919. *
  920. * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
  921. * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
  922. * @return bool
  923. */
  924. function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
  925. $user_id = (int) $user_id;
  926. $blog_id = (int) $blog_id;
  927. if ( empty( $user_id ) )
  928. $user_id = get_current_user_id();
  929. if ( empty( $blog_id ) )
  930. $blog_id = get_current_blog_id();
  931. $blogs = get_blogs_of_user( $user_id );
  932. return array_key_exists( $blog_id, $blogs );
  933. }
  934. /**
  935. * Add meta data field to a user.
  936. *
  937. * Post meta data is called "Custom Fields" on the Administration Screens.
  938. *
  939. * @since 3.0.0
  940. * @uses add_metadata()
  941. * @link http://codex.wordpress.org/Function_Reference/add_user_meta
  942. *
  943. * @param int $user_id User ID.
  944. * @param string $meta_key Metadata name.
  945. * @param mixed $meta_value Metadata value.
  946. * @param bool $unique Optional, default is false. Whether the same key should not be added.
  947. * @return int|bool Meta ID on success, false on failure.
  948. */
  949. function add_user_meta($user_id, $meta_key, $meta_value, $unique = false) {
  950. return add_metadata('user', $user_id, $meta_key, $meta_value, $unique);
  951. }
  952. /**
  953. * Remove metadata matching criteria from a user.
  954. *
  955. * You can match based on the key, or key and value. Removing based on key and
  956. * value, will keep from removing duplicate metadata with the same key. It also
  957. * allows removing all metadata matching key, if needed.
  958. *
  959. * @since 3.0.0
  960. * @uses delete_metadata()
  961. * @link http://codex.wordpress.org/Function_Reference/delete_user_meta
  962. *
  963. * @param int $user_id user ID
  964. * @param string $meta_key Metadata name.
  965. * @param mixed $meta_value Optional. Metadata value.
  966. * @return bool True on success, false on failure.
  967. */
  968. function delete_user_meta($user_id, $meta_key, $meta_value = '') {
  969. return delete_metadata('user', $user_id, $meta_key, $meta_value);
  970. }
  971. /**
  972. * Retrieve user meta field for a user.
  973. *
  974. * @since 3.0.0
  975. * @uses get_metadata()
  976. * @link http://codex.wordpress.org/Function_Reference/get_user_meta
  977. *
  978. * @param int $user_id User ID.
  979. * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
  980. * @param bool $single Whether to return a single value.
  981. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
  982. * is true.
  983. */
  984. function get_user_meta($user_id, $key = '', $single = false) {
  985. return get_metadata('user', $user_id, $key, $single);
  986. }
  987. /**
  988. * Update user meta field based on user ID.
  989. *
  990. * Use the $prev_value parameter to differentiate between meta fields with the
  991. * same key and user ID.
  992. *
  993. * If the meta field for the user does not exist, it will be added.
  994. *
  995. * @since 3.0.0
  996. * @uses update_metadata
  997. * @link http://codex.wordpress.org/Function_Reference/update_user_meta
  998. *
  999. * @param int $user_id User ID.
  1000. * @param string $meta_key Metadata key.
  1001. * @param mixed $meta_value Metadata value.
  1002. * @param mixed $prev_value Optional. Previous value to check before removing.
  1003. * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
  1004. */
  1005. function update_user_meta($user_id, $meta_key, $meta_value, $prev_value = '') {
  1006. return update_metadata('user', $user_id, $meta_key, $meta_value, $prev_value);
  1007. }
  1008. /**
  1009. * Count number of users who have each of the user roles.
  1010. *
  1011. * Assumes there are neither duplicated nor orphaned capabilities meta_values.
  1012. * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
  1013. * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
  1014. * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
  1015. *
  1016. * @since 3.0.0
  1017. * @param string $strategy 'time' or 'memory'
  1018. * @return array Includes a grand total and an array of counts indexed by role strings.
  1019. */
  1020. function count_users($strategy = 'time') {
  1021. global $wpdb, $wp_roles;
  1022. // Initialize
  1023. $id = get_current_blog_id();
  1024. $blog_prefix = $wpdb->get_blog_prefix($id);
  1025. $result = array();
  1026. if ( 'time' == $strategy ) {
  1027. global $wp_roles;
  1028. if ( ! isset( $wp_roles ) )
  1029. $wp_roles = new WP_Roles();
  1030. $avail_roles = $wp_roles->get_names();
  1031. // Build a CPU-intensive query that will return concise information.
  1032. $select_count = array();
  1033. foreach ( $avail_roles as $this_role => $name ) {
  1034. $select_count[] = $wpdb->prepare( "COUNT(NULLIF(`meta_value` LIKE %s, false))", '%' . $wpdb->esc_like( '"' . $this_role . '"' ) . '%');
  1035. }
  1036. $select_count = implode(', ', $select_count);
  1037. // Add the meta_value index to the selection list, then run the query.
  1038. $row = $wpdb->get_row( "SELECT $select_count, COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'", ARRAY_N );
  1039. // Run the previous loop again to associate results with role names.
  1040. $col = 0;
  1041. $role_counts = array();
  1042. foreach ( $avail_roles as $this_role => $name ) {
  1043. $count = (int) $row[$col++];
  1044. if ($count > 0) {
  1045. $role_counts[$this_role] = $count;
  1046. }
  1047. }
  1048. // Get the meta_value index from the end of the result set.
  1049. $total_users = (int) $row[$col];
  1050. $result['total_users'] = $total_users;
  1051. $result['avail_roles'] =& $role_counts;
  1052. } else {
  1053. $avail_roles = array();
  1054. $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" );
  1055. foreach ( $users_of_blog as $caps_meta ) {
  1056. $b_roles = maybe_unserialize($caps_meta);
  1057. if ( ! is_array( $b_roles ) )
  1058. continue;
  1059. foreach ( $b_roles as $b_role => $val ) {
  1060. if ( isset($avail_roles[$b_role]) ) {
  1061. $avail_roles[$b_role]++;
  1062. } else {
  1063. $avail_roles[$b_role] = 1;
  1064. }
  1065. }
  1066. }
  1067. $result['total_users'] = count( $users_of_blog );
  1068. $result['avail_roles'] =& $avail_roles;
  1069. }
  1070. return $result;
  1071. }
  1072. //
  1073. // Private helper functions
  1074. //
  1075. /**
  1076. * Set up global user vars.
  1077. *
  1078. * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
  1079. *
  1080. * @since 2.0.4
  1081. * @global string $userdata User description.
  1082. * @global string $user_login The user username for logging in
  1083. * @global int $user_level The level of the user
  1084. * @global int $user_ID The ID of the user
  1085. * @global string $user_email The email address of the user
  1086. * @global string $user_url The url in the user's profile
  1087. * @global string $user_identity The display name of the user
  1088. *
  1089. * @param int $for_user_id Optional. User ID to set up global data.
  1090. */
  1091. function setup_userdata($for_user_id = '') {
  1092. global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
  1093. if ( '' == $for_user_id )
  1094. $for_user_id = get_current_user_id();
  1095. $user = get_userdata( $for_user_id );
  1096. if ( ! $user ) {
  1097. $user_ID = 0;
  1098. $user_level = 0;
  1099. $userdata = null;
  1100. $user_login = $user_email = $user_url = $user_identity = '';
  1101. return;
  1102. }
  1103. $user_ID = (int) $user->ID;
  1104. $user_level = (int) $user->user_level;
  1105. $userdata = $user;
  1106. $user_login = $user->user_login;
  1107. $user_email = $user->user_email;
  1108. $user_url = $user->user_url;
  1109. $user_identity = $user->display_name;
  1110. }
  1111. /**
  1112. * Create dropdown HTML content of users.
  1113. *
  1114. * The content can either be displayed, which it is by default or retrieved by
  1115. * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
  1116. * need to be used; all users will be displayed in that case. Only one can be
  1117. * used, either 'include' or 'exclude', but not both.
  1118. *
  1119. * The available arguments are as follows:
  1120. *
  1121. * @since 2.3.0
  1122. *
  1123. * @global wpdb $wpdb WordPress database object for queries.
  1124. *
  1125. * @param array|string $args {
  1126. * Optional. Array or string of arguments to generate a drop-down of users.
  1127. * {@see WP_User_Query::prepare_query() for additional available arguments.
  1128. *
  1129. * @type string $show_option_all Text to show as the drop-down default (all).
  1130. * Default empty.
  1131. * @type string $show_option_none Text to show as the drop-down default when no
  1132. * users were found. Default empty.
  1133. * @type int|string $option_none_value Value to use for $show_option_non when no users
  1134. * were found. Default -1.
  1135. * @type string $hide_if_only_one_author Whether to skip generating the drop-down
  1136. * if only one user was found. Default empty.
  1137. * @type string $orderby Field to order found users by. Accepts user fields.
  1138. * Default 'display_name'.
  1139. * @type string $order Whether to order users in ascending or descending
  1140. * order. Accepts 'ASC' (ascending) or 'DESC' (descending).
  1141. * Default 'ASC'.
  1142. * @type array|string $include Array or comma-separated list of user IDs to include.
  1143. * Default empty.
  1144. * @type array|string $exclude Array or comma-separated list of user IDs to exclude.
  1145. * Default empty.
  1146. * @type bool|int $multi Whether to skip the ID attribute on the 'select' element.
  1147. * Accepts 1|true or 0|false. Default 0|false.
  1148. * @type string $show User table column to display. If the selected item is empty
  1149. * then the 'user_login' will be displayed in parentheses.
  1150. * Accepts user fields. Default 'display_name'.
  1151. * @type int|bool $echo Whether to echo or return the drop-down. Accepts 1|true (echo)
  1152. * or 0|false (return). Default 1|true.
  1153. * @type int $selected Which user ID should be selected. Default 0.
  1154. * @type bool $include_selected Whether to always include the selected user ID in the drop-
  1155. * down. Default false.
  1156. * @type string $name Name attribute of select element. Default 'user'.
  1157. * @type string $id ID attribute of the select element. Default is the value of $name.
  1158. * @type string $class Class attribute of the select element. Default empty.
  1159. * @type int $blog_id ID of blog (Multisite only). Default is ID of the current blog.
  1160. * @type string $who Which type of users to query. Accepts only an empty string or
  1161. * 'authors'. Default empty.
  1162. * }
  1163. * @return string|null Null on display. String of HTML content on retrieve.
  1164. */
  1165. function wp_dropdown_users( $args = '' ) {
  1166. $defaults = array(
  1167. 'show_option_all' => '', 'show_option_none' => '', 'hide_if_only_one_author' => '',
  1168. 'orderby' => 'display_name', 'order' => 'ASC',
  1169. 'include' => '', 'exclude' => '', 'multi' => 0,
  1170. 'show' => 'display_name', 'echo' => 1,
  1171. 'selected' => 0, 'name' => 'user', 'class' => '', 'id' => '',
  1172. 'blog_id' => $GLOBALS['blog_id'], 'who' => '', 'include_selected' => false,
  1173. 'option_none_value' => -1
  1174. );
  1175. $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
  1176. $r = wp_parse_args( $args, $defaults );
  1177. $show = $r['show'];
  1178. $show_option_all = $r['show_option_all'];
  1179. $show_option_none = $r['show_option_none'];
  1180. $option_none_value = $r['option_none_value'];
  1181. $query_args = wp_array_slice_assoc( $r, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who' ) );
  1182. $query_args['fields'] = array( 'ID', 'user_login', $show );
  1183. $users = get_users( $query_args );
  1184. $output = '';
  1185. if ( ! empty( $users ) && ( empty( $r['hide_if_only_one_author'] ) || count( $users ) > 1 ) ) {
  1186. $name = esc_attr( $r['name'] );
  1187. if ( $r['multi'] && ! $r['id'] ) {
  1188. $id = '';
  1189. } else {
  1190. $id = $r['id'] ? " id='" . esc_attr( $r['id'] ) . "'" : " id='$name'";
  1191. }
  1192. $output = "<select name='{$name}'{$id} class='" . $r['class'] . "'>\n";
  1193. if ( $show_option_all ) {
  1194. $output .= "\t<option value='0'>$show_option_all</option>\n";
  1195. }
  1196. if ( $show_option_none ) {
  1197. $_selected = selected( $option_none_value, $r['selected'], false );
  1198. $output .= "\t<option value='" . esc_attr( $option_none_value ) . "'$_selected>$show_option_none</option>\n";
  1199. }
  1200. $found_selected = false;
  1201. foreach ( (array) $users as $user ) {
  1202. $user->ID = (int) $user->ID;
  1203. $_selected = selected( $user->ID, $r['selected'], false );
  1204. if ( $_selected ) {
  1205. $found_selected = true;
  1206. }
  1207. $display = ! empty( $user->$show ) ? $user->$show : '('. $user->user_login . ')';
  1208. $output .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
  1209. }
  1210. if ( $r['include_selected'] && ! $found_selected && ( $r['selected'] > 0 ) ) {
  1211. $user = get_userdata( $r['selected'] );
  1212. $_selected = selected( $user->ID, $r['selected'], false );
  1213. $display = ! empty( $user->$show ) ? $user->$show : '('. $user->user_login . ')';
  1214. $output .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
  1215. }
  1216. $output .= "</select>";
  1217. }
  1218. /**
  1219. * Filter the wp_dropdown_users() HTML output.
  1220. *
  1221. * @since 2.3.0
  1222. *
  1223. * @param string $output HTML output generated by wp_dropdown_users().
  1224. */
  1225. $html = apply_filters( 'wp_dropdown_users', $output );
  1226. if ( $r['echo'] ) {
  1227. echo $html;
  1228. }
  1229. return $html;
  1230. }
  1231. /**
  1232. * Sanitize user field based on context.
  1233. *
  1234. * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
  1235. * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
  1236. * when calling filters.
  1237. *
  1238. * @since 2.3.0
  1239. *
  1240. * @param string $field The user Object field name.
  1241. * @param mixed $value The user Object value.
  1242. * @param int $user_id user ID.
  1243. * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
  1244. * 'attribute' and 'js'.
  1245. * @return mixed Sanitized value.
  1246. */
  1247. function sanitize_user_field($field, $value, $user_id, $context) {
  1248. $int_fields = array('ID');
  1249. if ( in_array($field, $int_fields) )
  1250. $value = (int) $value;
  1251. if ( 'raw' == $context )
  1252. return $value;
  1253. if ( !is_string($value) && !is_numeric($value) )
  1254. return $value;
  1255. $prefixed = false !== strpos( $field, 'user_' );
  1256. if ( 'edit' == $context ) {
  1257. if ( $prefixed ) {
  1258. /** This filter is documented in wp-includes/post.php */
  1259. $value = apply_filters( "edit_{$field}", $value, $user_id );
  1260. } else {
  1261. /**
  1262. * Filter a user field value in the 'edit' context.
  1263. *
  1264. * The dynamic portion of the hook name, $field, refers to the prefixed user
  1265. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1266. *
  1267. * @since 2.9.0
  1268. *
  1269. * @param mixed $value Value of the prefixed user field.
  1270. * @param int $user_id User ID.
  1271. */
  1272. $value = apply_filters( "edit_user_{$field}", $value, $user_id );
  1273. }
  1274. if ( 'description' == $field )
  1275. $value = esc_html( $value ); // textarea_escaped?
  1276. else
  1277. $value = esc_attr($value);
  1278. } else if ( 'db' == $context ) {
  1279. if ( $prefixed ) {
  1280. /** This filter is documented in wp-includes/post.php */
  1281. $value = apply_filters( "pre_{$field}", $value );
  1282. } else {
  1283. /**
  1284. * Filter the value of a user field in the 'db' context.
  1285. *
  1286. * The dynamic portion of the hook name, $field, refers to the prefixed user
  1287. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1288. *
  1289. * @since 2.9.0
  1290. *
  1291. * @param mixed $value Value of the prefixed user field.
  1292. */
  1293. $value = apply_filters( "pre_user_{$field}", $value );
  1294. }
  1295. } else {
  1296. // Use display filters by default.
  1297. if ( $prefixed ) {
  1298. /** This filter is documented in wp-includes/post.php */
  1299. $value = apply_filters( $field, $value, $user_id, $context );
  1300. } else {
  1301. /**
  1302. * Filter the value of a user field in a standard context.
  1303. *
  1304. * The dynamic portion of the hook name, $field, refers to the prefixed user
  1305. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1306. *
  1307. * @since 2.9.0
  1308. *
  1309. * @param mixed $value The user object value to sanitize.
  1310. * @param int $user_id User ID.
  1311. * @param string $context The context to filter within.
  1312. */
  1313. $value = apply_filters( "user_{$field}", $value, $user_id, $context );
  1314. }
  1315. }
  1316. if ( 'user_url' == $field )
  1317. $value = esc_url($value);
  1318. if ( 'attribute' == $context )
  1319. $value = esc_attr($value);
  1320. else if ( 'js' == $context )
  1321. $value = esc_js($value);
  1322. return $value;
  1323. }
  1324. /**
  1325. * Update all user caches
  1326. *
  1327. * @since 3.0.0
  1328. *
  1329. * @param object $user User object to be cached
  1330. */
  1331. function update_user_caches($user) {
  1332. wp_cache_add($user->ID, $user, 'users');
  1333. wp_cache_add($user->user_login, $user->ID, 'userlogins');
  1334. wp_cache_add($user->user_email, $user->ID, 'useremail');
  1335. wp_cache_add($user->user_nicename, $user->ID, 'userslugs');
  1336. }
  1337. /**
  1338. * Clean all user caches
  1339. *
  1340. * @since 3.0.0
  1341. *
  1342. * @param WP_User|int $user User object or ID to be cleaned from the cache
  1343. */
  1344. function clean_user_cache( $user ) {
  1345. if ( is_numeric( $user ) )
  1346. $user = new WP_User( $user );
  1347. if ( ! $user->exists() )
  1348. return;
  1349. wp_cache_delete( $user->ID, 'users' );
  1350. wp_cache_delete( $user->user_login, 'userlogins' );
  1351. wp_cache_delete( $user->user_email, 'useremail' );
  1352. wp_cache_delete( $user->user_nicename, 'userslugs' );
  1353. }
  1354. /**
  1355. * Checks whether the given username exists.
  1356. *
  1357. * @since 2.0.0
  1358. *
  1359. * @param string $username Username.
  1360. * @return null|int The user's ID on success, and null on failure.
  1361. */
  1362. function username_exists( $username ) {
  1363. if ( $user = get_user_by('login', $username ) ) {
  1364. return $user->ID;
  1365. } else {
  1366. return null;
  1367. }
  1368. }
  1369. /**
  1370. * Checks whether the given email exists.
  1371. *
  1372. * @since 2.1.0
  1373. *
  1374. * @param string $email Email.
  1375. * @return bool|int The user's ID on success, and false on failure.
  1376. */
  1377. function email_exists( $email ) {
  1378. if ( $user = get_user_by('email', $email) )
  1379. return $user->ID;
  1380. return false;
  1381. }
  1382. /**
  1383. * Checks whether an username is valid.
  1384. *
  1385. * @since 2.0.1
  1386. * @uses apply_filters() Calls 'validate_user…

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