PageRenderTime 71ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/user.php

https://github.com/bbt123/WordPress
PHP | 2142 lines | 912 code | 268 blank | 962 comment | 242 complexity | 354ee57e002bfab11460983d963e154a MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.1, GPL-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 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" title="Password Lost and Found">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" title="Password Lost and Found">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. $qv =& $this->query_vars;
  461. if ( is_array( $qv['fields'] ) ) {
  462. $qv['fields'] = array_unique( $qv['fields'] );
  463. $this->query_fields = array();
  464. foreach ( $qv['fields'] as $field ) {
  465. $field = 'ID' === $field ? 'ID' : sanitize_key( $field );
  466. $this->query_fields[] = "$wpdb->users.$field";
  467. }
  468. $this->query_fields = implode( ',', $this->query_fields );
  469. } elseif ( 'all' == $qv['fields'] ) {
  470. $this->query_fields = "$wpdb->users.*";
  471. } else {
  472. $this->query_fields = "$wpdb->users.ID";
  473. }
  474. if ( isset( $qv['count_total'] ) && $qv['count_total'] )
  475. $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
  476. $this->query_from = "FROM $wpdb->users";
  477. $this->query_where = "WHERE 1=1";
  478. // sorting
  479. if ( isset( $qv['orderby'] ) ) {
  480. if ( in_array( $qv['orderby'], array('nicename', 'email', 'url', 'registered') ) ) {
  481. $orderby = 'user_' . $qv['orderby'];
  482. } elseif ( in_array( $qv['orderby'], array('user_nicename', 'user_email', 'user_url', 'user_registered') ) ) {
  483. $orderby = $qv['orderby'];
  484. } elseif ( 'name' == $qv['orderby'] || 'display_name' == $qv['orderby'] ) {
  485. $orderby = 'display_name';
  486. } elseif ( 'post_count' == $qv['orderby'] ) {
  487. // todo: avoid the JOIN
  488. $where = get_posts_by_author_sql('post');
  489. $this->query_from .= " LEFT OUTER JOIN (
  490. SELECT post_author, COUNT(*) as post_count
  491. FROM $wpdb->posts
  492. $where
  493. GROUP BY post_author
  494. ) p ON ({$wpdb->users}.ID = p.post_author)
  495. ";
  496. $orderby = 'post_count';
  497. } elseif ( 'ID' == $qv['orderby'] || 'id' == $qv['orderby'] ) {
  498. $orderby = 'ID';
  499. } elseif ( 'meta_value' == $qv['orderby'] ) {
  500. $orderby = "$wpdb->usermeta.meta_value";
  501. } else {
  502. $orderby = 'user_login';
  503. }
  504. }
  505. if ( empty( $orderby ) )
  506. $orderby = 'user_login';
  507. $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
  508. if ( 'ASC' == $qv['order'] )
  509. $order = 'ASC';
  510. else
  511. $order = 'DESC';
  512. $this->query_orderby = "ORDER BY $orderby $order";
  513. // limit
  514. if ( isset( $qv['number'] ) && $qv['number'] ) {
  515. if ( $qv['offset'] )
  516. $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
  517. else
  518. $this->query_limit = $wpdb->prepare("LIMIT %d", $qv['number']);
  519. }
  520. $search = '';
  521. if ( isset( $qv['search'] ) )
  522. $search = trim( $qv['search'] );
  523. if ( $search ) {
  524. $leading_wild = ( ltrim($search, '*') != $search );
  525. $trailing_wild = ( rtrim($search, '*') != $search );
  526. if ( $leading_wild && $trailing_wild )
  527. $wild = 'both';
  528. elseif ( $leading_wild )
  529. $wild = 'leading';
  530. elseif ( $trailing_wild )
  531. $wild = 'trailing';
  532. else
  533. $wild = false;
  534. if ( $wild )
  535. $search = trim($search, '*');
  536. $search_columns = array();
  537. if ( $qv['search_columns'] )
  538. $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename' ) );
  539. if ( ! $search_columns ) {
  540. if ( false !== strpos( $search, '@') )
  541. $search_columns = array('user_email');
  542. elseif ( is_numeric($search) )
  543. $search_columns = array('user_login', 'ID');
  544. elseif ( preg_match('|^https?://|', $search) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) )
  545. $search_columns = array('user_url');
  546. else
  547. $search_columns = array('user_login', 'user_nicename');
  548. }
  549. /**
  550. * Filter the columns to search in a WP_User_Query search.
  551. *
  552. * The default columns depend on the search term, and include 'user_email',
  553. * 'user_login', 'ID', 'user_url', and 'user_nicename'.
  554. *
  555. * @since 3.6.0
  556. *
  557. * @param array $search_columns Array of column names to be searched.
  558. * @param string $search Text being searched.
  559. * @param WP_User_Query $this The current WP_User_Query instance.
  560. */
  561. $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
  562. $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
  563. }
  564. $blog_id = 0;
  565. if ( isset( $qv['blog_id'] ) )
  566. $blog_id = absint( $qv['blog_id'] );
  567. if ( isset( $qv['who'] ) && 'authors' == $qv['who'] && $blog_id ) {
  568. $qv['meta_key'] = $wpdb->get_blog_prefix( $blog_id ) . 'user_level';
  569. $qv['meta_value'] = 0;
  570. $qv['meta_compare'] = '!=';
  571. $qv['blog_id'] = $blog_id = 0; // Prevent extra meta query
  572. }
  573. $role = '';
  574. if ( isset( $qv['role'] ) )
  575. $role = trim( $qv['role'] );
  576. if ( $blog_id && ( $role || is_multisite() ) ) {
  577. $cap_meta_query = array();
  578. $cap_meta_query['key'] = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities';
  579. if ( $role ) {
  580. $cap_meta_query['value'] = '"' . $role . '"';
  581. $cap_meta_query['compare'] = 'like';
  582. }
  583. if ( empty( $qv['meta_query'] ) || ! in_array( $cap_meta_query, $qv['meta_query'], true ) ) {
  584. $qv['meta_query'][] = $cap_meta_query;
  585. }
  586. }
  587. $meta_query = new WP_Meta_Query();
  588. $meta_query->parse_query_vars( $qv );
  589. if ( !empty( $meta_query->queries ) ) {
  590. $clauses = $meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
  591. $this->query_from .= $clauses['join'];
  592. $this->query_where .= $clauses['where'];
  593. if ( 'OR' == $meta_query->relation )
  594. $this->query_fields = 'DISTINCT ' . $this->query_fields;
  595. }
  596. if ( ! empty( $qv['include'] ) ) {
  597. $ids = implode( ',', wp_parse_id_list( $qv['include'] ) );
  598. $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
  599. } elseif ( ! empty( $qv['exclude'] ) ) {
  600. $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
  601. $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
  602. }
  603. /**
  604. * Fires after the WP_User_Query has been parsed, and before
  605. * the query is executed.
  606. *
  607. * The passed WP_User_Query object contains SQL parts formed
  608. * from parsing the given query.
  609. *
  610. * @since 3.1.0
  611. *
  612. * @param WP_User_Query $this The current WP_User_Query instance,
  613. * passed by reference.
  614. */
  615. do_action_ref_array( 'pre_user_query', array( &$this ) );
  616. }
  617. /**
  618. * Execute the query, with the current variables.
  619. *
  620. * @since 3.1.0
  621. *
  622. * @global wpdb $wpdb WordPress database object for queries.
  623. */
  624. public function query() {
  625. global $wpdb;
  626. $qv =& $this->query_vars;
  627. $query = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
  628. if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
  629. $this->results = $wpdb->get_results( $query );
  630. } else {
  631. $this->results = $wpdb->get_col( $query );
  632. }
  633. /**
  634. * Filter SELECT FOUND_ROWS() query for the current WP_User_Query instance.
  635. *
  636. * @since 3.2.0
  637. *
  638. * @global wpdb $wpdb WordPress database object.
  639. *
  640. * @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
  641. */
  642. if ( isset( $qv['count_total'] ) && $qv['count_total'] )
  643. $this->total_users = $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) );
  644. if ( !$this->results )
  645. return;
  646. if ( 'all_with_meta' == $qv['fields'] ) {
  647. cache_users( $this->results );
  648. $r = array();
  649. foreach ( $this->results as $userid )
  650. $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
  651. $this->results = $r;
  652. } elseif ( 'all' == $qv['fields'] ) {
  653. foreach ( $this->results as $key => $user ) {
  654. $this->results[ $key ] = new WP_User( $user );
  655. }
  656. }
  657. }
  658. /**
  659. * Retrieve query variable.
  660. *
  661. * @since 3.5.0
  662. * @access public
  663. *
  664. * @param string $query_var Query variable key.
  665. * @return mixed
  666. */
  667. public function get( $query_var ) {
  668. if ( isset( $this->query_vars[$query_var] ) )
  669. return $this->query_vars[$query_var];
  670. return null;
  671. }
  672. /**
  673. * Set query variable.
  674. *
  675. * @since 3.5.0
  676. * @access public
  677. *
  678. * @param string $query_var Query variable key.
  679. * @param mixed $value Query variable value.
  680. */
  681. public function set( $query_var, $value ) {
  682. $this->query_vars[$query_var] = $value;
  683. }
  684. /**
  685. * Used internally to generate an SQL string for searching across multiple columns
  686. *
  687. * @access protected
  688. * @since 3.1.0
  689. *
  690. * @param string $string
  691. * @param array $cols
  692. * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for
  693. * single site. Single site allows leading and trailing wildcards, Network Admin only trailing.
  694. * @return string
  695. */
  696. protected function get_search_sql( $string, $cols, $wild = false ) {
  697. global $wpdb;
  698. $searches = array();
  699. $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
  700. $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
  701. $like = $leading_wild . $wpdb->esc_like( $string ) . $trailing_wild;
  702. foreach ( $cols as $col ) {
  703. if ( 'ID' == $col ) {
  704. $searches[] = $wpdb->prepare( "$col = %s", $string );
  705. } else {
  706. $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
  707. }
  708. }
  709. return ' AND (' . implode(' OR ', $searches) . ')';
  710. }
  711. /**
  712. * Return the list of users.
  713. *
  714. * @since 3.1.0
  715. * @access public
  716. *
  717. * @return array Array of results.
  718. */
  719. public function get_results() {
  720. return $this->results;
  721. }
  722. /**
  723. * Return the total number of users for the current query.
  724. *
  725. * @since 3.1.0
  726. * @access public
  727. *
  728. * @return array Array of total users.
  729. */
  730. public function get_total() {
  731. return $this->total_users;
  732. }
  733. /**
  734. * Make private properties readable for backwards compatibility
  735. *
  736. * @since 4.0.0
  737. * @param string $name
  738. * @return mixed
  739. */
  740. public function __get( $name ) {
  741. return $this->$name;
  742. }
  743. /**
  744. * Make private properties setable for backwards compatibility
  745. *
  746. * @since 4.0.0
  747. * @param string $name
  748. * @param string $value
  749. * @return mixed
  750. */
  751. public function __set( $name, $value ) {
  752. return $this->$name = $value;
  753. }
  754. /**
  755. * Make private properties checkable for backwards compatibility
  756. *
  757. * @since 4.0.0
  758. * @param string $name
  759. * @return mixed
  760. */
  761. public function __isset( $name ) {
  762. return isset( $this->$name );
  763. }
  764. /**
  765. * Make private properties unsetable for backwards compatibility
  766. *
  767. * @since 4.0.0
  768. * @param string $name
  769. * @return mixed
  770. */
  771. public function __unset( $name ) {
  772. unset( $this->$name );
  773. }
  774. /**
  775. * Make private/protected methods readable for backwards compatibility
  776. *
  777. * @since 4.0.0
  778. * @param string $name
  779. * @param array $arguments
  780. * @return mixed
  781. */
  782. public function __call( $name, $arguments ) {
  783. return call_user_func_array( array( $this, $name ), $arguments );
  784. }
  785. }
  786. /**
  787. * Retrieve list of users matching criteria.
  788. *
  789. * @since 3.1.0
  790. *
  791. * @uses WP_User_Query See for default arguments and information.
  792. *
  793. * @param array $args Optional. Array of arguments.
  794. * @return array List of users.
  795. */
  796. function get_users( $args = array() ) {
  797. $args = wp_parse_args( $args );
  798. $args['count_total'] = false;
  799. $user_search = new WP_User_Query($args);
  800. return (array) $user_search->get_results();
  801. }
  802. /**
  803. * Get the blogs a user belongs to.
  804. *
  805. * @since 3.0.0
  806. *
  807. * @global wpdb $wpdb WordPress database object for queries.
  808. *
  809. * @param int $user_id User ID
  810. * @param bool $all Whether to retrieve all blogs, or only blogs that are not
  811. * marked as deleted, archived, or spam.
  812. * @return array A list of the user's blogs. An empty array if the user doesn't exist
  813. * or belongs to no blogs.
  814. */
  815. function get_blogs_of_user( $user_id, $all = false ) {
  816. global $wpdb;
  817. $user_id = (int) $user_id;
  818. // Logged out users can't have blogs
  819. if ( empty( $user_id ) )
  820. return array();
  821. $keys = get_user_meta( $user_id );
  822. if ( empty( $keys ) )
  823. return array();
  824. if ( ! is_multisite() ) {
  825. $blog_id = get_current_blog_id();
  826. $blogs = array( $blog_id => new stdClass );
  827. $blogs[ $blog_id ]->userblog_id = $blog_id;
  828. $blogs[ $blog_id ]->blogname = get_option('blogname');
  829. $blogs[ $blog_id ]->domain = '';
  830. $blogs[ $blog_id ]->path = '';
  831. $blogs[ $blog_id ]->site_id = 1;
  832. $blogs[ $blog_id ]->siteurl = get_option('siteurl');
  833. $blogs[ $blog_id ]->archived = 0;
  834. $blogs[ $blog_id ]->spam = 0;
  835. $blogs[ $blog_id ]->deleted = 0;
  836. return $blogs;
  837. }
  838. $blogs = array();
  839. if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
  840. $blog = get_blog_details( 1 );
  841. if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
  842. $blogs[ 1 ] = (object) array(
  843. 'userblog_id' => 1,
  844. 'blogname' => $blog->blogname,
  845. 'domain' => $blog->domain,
  846. 'path' => $blog->path,
  847. 'site_id' => $blog->site_id,
  848. 'siteurl' => $blog->siteurl,
  849. 'archived' => 0,
  850. 'spam' => 0,
  851. 'deleted' => 0
  852. );
  853. }
  854. unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
  855. }
  856. $keys = array_keys( $keys );
  857. foreach ( $keys as $key ) {
  858. if ( 'capabilities' !== substr( $key, -12 ) )
  859. continue;
  860. if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) )
  861. continue;
  862. $blog_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
  863. if ( ! is_numeric( $blog_id ) )
  864. continue;
  865. $blog_id = (int) $blog_id;
  866. $blog = get_blog_details( $blog_id );
  867. if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
  868. $blogs[ $blog_id ] = (object) array(
  869. 'userblog_id' => $blog_id,
  870. 'blogname' => $blog->blogname,
  871. 'domain' => $blog->domain,
  872. 'path' => $blog->path,
  873. 'site_id' => $blog->site_id,
  874. 'siteurl' => $blog->siteurl,
  875. 'archived' => 0,
  876. 'spam' => 0,
  877. 'deleted' => 0
  878. );
  879. }
  880. }
  881. /**
  882. * Filter the list of blogs a user belongs to.
  883. *
  884. * @since MU
  885. *
  886. * @param array $blogs An array of blog objects belonging to the user.
  887. * @param int $user_id User ID.
  888. * @param bool $all Whether the returned blogs array should contain all blogs, including
  889. * those marked 'deleted', 'archived', or 'spam'. Default false.
  890. */
  891. return apply_filters( 'get_blogs_of_user', $blogs, $user_id, $all );
  892. }
  893. /**
  894. * Find out whether a user is a member of a given blog.
  895. *
  896. * @since MU 1.1
  897. * @uses get_blogs_of_user()
  898. *
  899. * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
  900. * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
  901. * @return bool
  902. */
  903. function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
  904. $user_id = (int) $user_id;
  905. $blog_id = (int) $blog_id;
  906. if ( empty( $user_id ) )
  907. $user_id = get_current_user_id();
  908. if ( empty( $blog_id ) )
  909. $blog_id = get_current_blog_id();
  910. $blogs = get_blogs_of_user( $user_id );
  911. return array_key_exists( $blog_id, $blogs );
  912. }
  913. /**
  914. * Add meta data field to a user.
  915. *
  916. * Post meta data is called "Custom Fields" on the Administration Screens.
  917. *
  918. * @since 3.0.0
  919. * @uses add_metadata()
  920. * @link http://codex.wordpress.org/Function_Reference/add_user_meta
  921. *
  922. * @param int $user_id User ID.
  923. * @param string $meta_key Metadata name.
  924. * @param mixed $meta_value Metadata value.
  925. * @param bool $unique Optional, default is false. Whether the same key should not be added.
  926. * @return int|bool Meta ID on success, false on failure.
  927. */
  928. function add_user_meta($user_id, $meta_key, $meta_value, $unique = false) {
  929. return add_metadata('user', $user_id, $meta_key, $meta_value, $unique);
  930. }
  931. /**
  932. * Remove metadata matching criteria from a user.
  933. *
  934. * You can match based on the key, or key and value. Removing based on key and
  935. * value, will keep from removing duplicate metadata with the same key. It also
  936. * allows removing all metadata matching key, if needed.
  937. *
  938. * @since 3.0.0
  939. * @uses delete_metadata()
  940. * @link http://codex.wordpress.org/Function_Reference/delete_user_meta
  941. *
  942. * @param int $user_id user ID
  943. * @param string $meta_key Metadata name.
  944. * @param mixed $meta_value Optional. Metadata value.
  945. * @return bool True on success, false on failure.
  946. */
  947. function delete_user_meta($user_id, $meta_key, $meta_value = '') {
  948. return delete_metadata('user', $user_id, $meta_key, $meta_value);
  949. }
  950. /**
  951. * Retrieve user meta field for a user.
  952. *
  953. * @since 3.0.0
  954. * @uses get_metadata()
  955. * @link http://codex.wordpress.org/Function_Reference/get_user_meta
  956. *
  957. * @param int $user_id User ID.
  958. * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
  959. * @param bool $single Whether to return a single value.
  960. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
  961. * is true.
  962. */
  963. function get_user_meta($user_id, $key = '', $single = false) {
  964. return get_metadata('user', $user_id, $key, $single);
  965. }
  966. /**
  967. * Update user meta field based on user ID.
  968. *
  969. * Use the $prev_value parameter to differentiate between meta fields with the
  970. * same key and user ID.
  971. *
  972. * If the meta field for the user does not exist, it will be added.
  973. *
  974. * @since 3.0.0
  975. * @uses update_metadata
  976. * @link http://codex.wordpress.org/Function_Reference/update_user_meta
  977. *
  978. * @param int $user_id User ID.
  979. * @param string $meta_key Metadata key.
  980. * @param mixed $meta_value Metadata value.
  981. * @param mixed $prev_value Optional. Previous value to check before removing.
  982. * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
  983. */
  984. function update_user_meta($user_id, $meta_key, $meta_value, $prev_value = '') {
  985. return update_metadata('user', $user_id, $meta_key, $meta_value, $prev_value);
  986. }
  987. /**
  988. * Count number of users who have each of the user roles.
  989. *
  990. * Assumes there are neither duplicated nor orphaned capabilities meta_values.
  991. * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
  992. * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
  993. * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
  994. *
  995. * @since 3.0.0
  996. * @param string $strategy 'time' or 'memory'
  997. * @return array Includes a grand total and an array of counts indexed by role strings.
  998. */
  999. function count_users($strategy = 'time') {
  1000. global $wpdb, $wp_roles;
  1001. // Initialize
  1002. $id = get_current_blog_id();
  1003. $blog_prefix = $wpdb->get_blog_prefix($id);
  1004. $result = array();
  1005. if ( 'time' == $strategy ) {
  1006. global $wp_roles;
  1007. if ( ! isset( $wp_roles ) )
  1008. $wp_roles = new WP_Roles();
  1009. $avail_roles = $wp_roles->get_names();
  1010. // Build a CPU-intensive query that will return concise information.
  1011. $select_count = array();
  1012. foreach ( $avail_roles as $this_role => $name ) {
  1013. $select_count[] = $wpdb->prepare( "COUNT(NULLIF(`meta_value` LIKE %s, false))", '%' . $wpdb->esc_like( '"' . $this_role . '"' ) . '%');
  1014. }
  1015. $select_count = implode(', ', $select_count);
  1016. // Add the meta_value index to the selection list, then run the query.
  1017. $row = $wpdb->get_row( "SELECT $select_count, COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'", ARRAY_N );
  1018. // Run the previous loop again to associate results with role names.
  1019. $col = 0;
  1020. $role_counts = array();
  1021. foreach ( $avail_roles as $this_role => $name ) {
  1022. $count = (int) $row[$col++];
  1023. if ($count > 0) {
  1024. $role_counts[$this_role] = $count;
  1025. }
  1026. }
  1027. // Get the meta_value index from the end of the result set.
  1028. $total_users = (int) $row[$col];
  1029. $result['total_users'] = $total_users;
  1030. $result['avail_roles'] =& $role_counts;
  1031. } else {
  1032. $avail_roles = array();
  1033. $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" );
  1034. foreach ( $users_of_blog as $caps_meta ) {
  1035. $b_roles = maybe_unserialize($caps_meta);
  1036. if ( ! is_array( $b_roles ) )
  1037. continue;
  1038. foreach ( $b_roles as $b_role => $val ) {
  1039. if ( isset($avail_roles[$b_role]) ) {
  1040. $avail_roles[$b_role]++;
  1041. } else {
  1042. $avail_roles[$b_role] = 1;
  1043. }
  1044. }
  1045. }
  1046. $result['total_users'] = count( $users_of_blog );
  1047. $result['avail_roles'] =& $avail_roles;
  1048. }
  1049. return $result;
  1050. }
  1051. //
  1052. // Private helper functions
  1053. //
  1054. /**
  1055. * Set up global user vars.
  1056. *
  1057. * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
  1058. *
  1059. * @since 2.0.4
  1060. * @global string $userdata User description.
  1061. * @global string $user_login The user username for logging in
  1062. * @global int $user_level The level of the user
  1063. * @global int $user_ID The ID of the user
  1064. * @global string $user_email The email address of the user
  1065. * @global string $user_url The url in the user's profile
  1066. * @global string $user_identity The display name of the user
  1067. *
  1068. * @param int $for_user_id Optional. User ID to set up global data.
  1069. */
  1070. function setup_userdata($for_user_id = '') {
  1071. global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
  1072. if ( '' == $for_user_id )
  1073. $for_user_id = get_current_user_id();
  1074. $user = get_userdata( $for_user_id );
  1075. if ( ! $user ) {
  1076. $user_ID = 0;
  1077. $user_level = 0;
  1078. $userdata = null;
  1079. $user_login = $user_email = $user_url = $user_identity = '';
  1080. return;
  1081. }
  1082. $user_ID = (int) $user->ID;
  1083. $user_level = (int) $user->user_level;
  1084. $userdata = $user;
  1085. $user_login = $user->user_login;
  1086. $user_email = $user->user_email;
  1087. $user_url = $user->user_url;
  1088. $user_identity = $user->display_name;
  1089. }
  1090. /**
  1091. * Create dropdown HTML content of users.
  1092. *
  1093. * The content can either be displayed, which it is by default or retrieved by
  1094. * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
  1095. * need to be used; all users will be displayed in that case. Only one can be
  1096. * used, either 'include' or 'exclude', but not both.
  1097. *
  1098. * The available arguments are as follows:
  1099. * <ol>
  1100. * <li>show_option_all - Text to show all and whether HTML option exists.</li>
  1101. * <li>show_option_none - Text for show none and whether HTML option exists.</li>
  1102. * <li>option_none_value - Value to use when no option is selected.</li>
  1103. * <li>hide_if_only_one_author - Don't create the dropdown if there is only one user.</li>
  1104. * <li>orderby - SQL order by clause for what order the users appear. Default is 'display_name'.</li>
  1105. * <li>order - Default is 'ASC'. Can also be 'DESC'.</li>
  1106. * <li>include - User IDs to include.</li>
  1107. * <li>exclude - User IDs to exclude.</li>
  1108. * <li>multi - Default is 'false'. Whether to skip the ID attribute on the 'select' element. A 'true' value is overridden when id argument is set.</li>
  1109. * <li>show - Default is 'display_name'. User table column to display. If the selected item is empty then the user_login will be displayed in parentheses</li>
  1110. * <li>echo - Default is '1'. Whether to display or retrieve content.</li>
  1111. * <li>selected - Which User ID is selected.</li>
  1112. * <li>include_selected - Always include the selected user ID in the dropdown. Default is false.</li>
  1113. * <li>name - Default is 'user'. Name attribute of select element.</li>
  1114. * <li>id - Default is the value of the 'name' parameter. ID attribute of select element.</li>
  1115. * <li>class - Class attribute of select element.</li>
  1116. * <li>blog_id - ID of blog (Multisite only). Defaults to ID of current blog.</li>
  1117. * <li>who - Which users to query. Currently only 'authors' is supported. Default is all users.</li>
  1118. * </ol>
  1119. *
  1120. * @since 2.3.0
  1121. *
  1122. * @global wpdb $wpdb WordPress database object for queries.
  1123. *
  1124. * @todo Hash-notate arguments array.
  1125. *
  1126. * @param string|array $args Optional. Array of user arguments.
  1127. * @return string|null Null on display. String of HTML content on retrieve.
  1128. */
  1129. function wp_dropdown_users( $args = '' ) {
  1130. $defaults = array(
  1131. 'show_option_all' => '', 'show_option_none' => '', 'hide_if_only_one_author' => '',
  1132. 'orderby' => 'display_name', 'order' => 'ASC',
  1133. 'include' => '', 'exclude' => '', 'multi' => 0,
  1134. 'show' => 'display_name', 'echo' => 1,
  1135. 'selected' => 0, 'name' => 'user', 'class' => '', 'id' => '',
  1136. 'blog_id' => $GLOBALS['blog_id'], 'who' => '', 'include_selected' => false,
  1137. 'option_none_value' => -1
  1138. );
  1139. $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
  1140. $r = wp_parse_args( $args, $defaults );
  1141. $show = $r['show'];
  1142. $show_option_all = $r['show_option_all'];
  1143. $show_option_none = $r['show_option_none'];
  1144. $option_none_value = $r['option_none_value'];
  1145. $query_args = wp_array_slice_assoc( $r, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who' ) );
  1146. $query_args['fields'] = array( 'ID', 'user_login', $show );
  1147. $users = get_users( $query_args );
  1148. $output = '';
  1149. if ( ! empty( $users ) && ( empty( $r['hide_if_only_one_author'] ) || count( $users ) > 1 ) ) {
  1150. $name = esc_attr( $r['name'] );
  1151. if ( $r['multi'] && ! $r['id'] ) {
  1152. $id = '';
  1153. } else {
  1154. $id = $r['id'] ? " id='" . esc_attr( $r['id'] ) . "'" : " id='$name'";
  1155. }
  1156. $output = "<select name='{$name}'{$id} class='" . $r['class'] . "'>\n";
  1157. if ( $show_option_all ) {
  1158. $output .= "\t<option value='0'>$show_option_all</option>\n";
  1159. }
  1160. if ( $show_option_none ) {
  1161. $_selected = selected( $option_none_value, $r['selected'], false );
  1162. $output .= "\t<option value='" . esc_attr( $option_none_value ) . "'$_selected>$show_option_none</option>\n";
  1163. }
  1164. $found_selected = false;
  1165. foreach ( (array) $users as $user ) {
  1166. $user->ID = (int) $user->ID;
  1167. $_selected = selected( $user->ID, $r['selected'], false );
  1168. if ( $_selected ) {
  1169. $found_selected = true;
  1170. }
  1171. $display = ! empty( $user->$show ) ? $user->$show : '('. $user->user_login . ')';
  1172. $output .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
  1173. }
  1174. if ( $r['include_selected'] && ! $found_selected && ( $r['selected'] > 0 ) ) {
  1175. $user = get_userdata( $r['selected'] );
  1176. $_selected = selected( $user->ID, $r['selected'], false );
  1177. $display = ! empty( $user->$show ) ? $user->$show : '('. $user->user_login . ')';
  1178. $output .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
  1179. }
  1180. $output .= "</select>";
  1181. }
  1182. /**
  1183. * Filter the wp_dropdown_users() HTML output.
  1184. *
  1185. * @since 2.3.0
  1186. *
  1187. * @param string $output HTML output generated by wp_dropdown_users().
  1188. */
  1189. $html = apply_filters( 'wp_dropdown_users', $output );
  1190. if ( $r['echo'] ) {
  1191. echo $html;
  1192. }
  1193. return $html;
  1194. }
  1195. /**
  1196. * Sanitize user field based on context.
  1197. *
  1198. * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
  1199. * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
  1200. * when calling filters.
  1201. *
  1202. * @since 2.3.0
  1203. *
  1204. * @param string $field The user Object field name.
  1205. * @param mixed $value The user Object value.
  1206. * @param int $user_id user ID.
  1207. * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
  1208. * 'attribute' and 'js'.
  1209. * @return mixed Sanitized value.
  1210. */
  1211. function sanitize_user_field($field, $value, $user_id, $context) {
  1212. $int_fields = array('ID');
  1213. if ( in_array($field, $int_fields) )
  1214. $value = (int) $value;
  1215. if ( 'raw' == $context )
  1216. return $value;
  1217. if ( !is_string($value) && !is_numeric($value) )
  1218. return $value;
  1219. $prefixed = false !== strpos( $field, 'user_' );
  1220. if ( 'edit' == $context ) {
  1221. if ( $prefixed ) {
  1222. /** This filter is documented in wp-includes/post.php */
  1223. $value = apply_filters( "edit_{$field}", $value, $user_id );
  1224. } else {
  1225. /**
  1226. * Filter a user field value in the 'edit' context.
  1227. *
  1228. * The dynamic portion of the hook name, $field, refers to the prefixed user
  1229. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1230. *
  1231. * @since 2.9.0
  1232. *
  1233. * @param mixed $value Value of the prefixed user field.
  1234. * @param int $user_id User ID.
  1235. */
  1236. $value = apply_filters( "edit_user_{$field}", $value, $user_id );
  1237. }
  1238. if ( 'description' == $field )
  1239. $value = esc_html( $value ); // textarea_escaped?
  1240. else
  1241. $value = esc_attr($value);
  1242. } else if ( 'db' == $context ) {
  1243. if ( $prefixed ) {
  1244. /** This filter is documented in wp-includes/post.php */
  1245. $value = apply_filters( "pre_{$field}", $value );
  1246. } else {
  1247. /**
  1248. * Filter the value of a user field in the 'db' context.
  1249. *
  1250. * The dynamic portion of the hook name, $field, refers to the prefixed user
  1251. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1252. *
  1253. * @since 2.9.0
  1254. *
  1255. * @param mixed $value Value of the prefixed user field.
  1256. */
  1257. $value = apply_filters( "pre_user_{$field}", $value );
  1258. }
  1259. } else {
  1260. // Use display filters by default.
  1261. if ( $prefixed ) {
  1262. /** This filter is documented in wp-includes/post.php */
  1263. $value = apply_filters( $field, $value, $user_id, $context );
  1264. } else {
  1265. /**
  1266. * Filter the value of a user field in a standard context.
  1267. *
  1268. * The dynamic portion of the hook name, $field, refers to the prefixed user
  1269. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1270. *
  1271. * @since 2.9.0
  1272. *
  1273. * @param mixed $value The user object value to sanitize.
  1274. * @param int $user_id User ID.
  1275. * @param string $context The context to filter within.
  1276. */
  1277. $value = apply_filters( "user_{$field}", $value, $user_id, $context );
  1278. }
  1279. }
  1280. if ( 'user_url' == $field )
  1281. $value = esc_url($value);
  1282. if ( 'attribute' == $context )
  1283. $value = esc_attr($value);
  1284. else if ( 'js' == $context )
  1285. $value = esc_js($value);
  1286. return $value;
  1287. }
  1288. /**
  1289. * Update all user caches
  1290. *
  1291. * @since 3.0.0
  1292. *
  1293. * @param object $user User object to be cached
  1294. */
  1295. function update_user_caches($user) {
  1296. wp_cache_add($user->ID, $user, 'users');
  1297. wp_cache_add($user->user_login, $user->ID, 'userlogins');
  1298. wp_cache_add($user->user_email, $user->ID, 'useremail');
  1299. wp_cache_add($user->user_nicename, $user->ID, 'userslugs');
  1300. }
  1301. /**
  1302. * Clean all user caches
  1303. *
  1304. * @since 3.0.0
  1305. *
  1306. * @param WP_User|int $user User object or ID to be cleaned from the cache
  1307. */
  1308. function clean_user_cache( $user ) {
  1309. if ( is_numeric( $user ) )
  1310. $user = new WP_User( $user );
  1311. if ( ! $user->exists() )
  1312. return;
  1313. wp_cache_delete( $user->ID, 'users' );
  1314. wp_cache_delete( $user->user_login, 'userlogins' );
  1315. wp_cache_delete( $user->user_email, 'useremail' );
  1316. wp_cache_delete( $user->user_nicename, 'userslugs' );
  1317. }
  1318. /**
  1319. * Checks whether the given username exists.
  1320. *
  1321. * @since 2.0.0
  1322. *
  1323. * @param string $username Username.
  1324. * @return null|int The user's ID on success, and null on failure.
  1325. */
  1326. function username_exists( $username ) {
  1327. if ( $user = get_user_by('login', $username ) ) {
  1328. return $user->ID;
  1329. } else {
  1330. return null;
  1331. }
  1332. }
  1333. /**
  1334. * Checks whether the given email exists.
  1335. *
  1336. * @since 2.1.0
  1337. *
  1338. * @param string $email Email.
  1339. * @return bool|int The user's ID on success, and false on failure.
  1340. */
  1341. function email_exists( $email ) {
  1342. if ( $user = get_user_by('email', $email) )
  1343. return $user->ID;
  1344. return false;
  1345. }
  1346. /**
  1347. * Checks whether an username is valid.
  1348. *
  1349. * @since 2.0.1
  1350. * @uses apply_filters() Calls 'validate_username' hook on $valid check and $username as parameters
  1351. *
  1352. * @param string $username Username.
  1353. * @return bool Whether username given is valid
  1354. */
  1355. function validate_username( $username ) {
  1356. $sanitized = sanitize_user( $username, true );
  1357. $valid = ( $sanitized == $username );
  1358. /**
  1359. * Filter whether the provided username is valid or not.
  1360. *
  1361. * @since 2.0.1
  1362. *
  1363. * @param bool $valid Whether given username is valid.
  1364. * @param string $username Username to check.
  1365. */
  1366. return apply_filters( 'validate_username', $valid, $username );
  1367. }
  1368. /**
  1369. * Insert an user into the database.
  1370. *
  1371. * Most of the $userdata array fields have filters associated with the values.
  1372. * The exceptions are 'rich_editing', 'role', 'jabber', 'aim', 'yim',
  1373. * 'user_registered', and 'ID'. The filters have the prefix 'pre_user_' followed
  1374. * by the field name. An example using 'description' would have the filter
  1375. * called, 'pre_user_description' that can be hooked into.
  1376. *
  1377. * The $userdata array can contain the following fields:
  1378. * 'ID' - An integer that will be used for updating an existing user.
  1379. * 'user_pass' - A string that contains the plain text password for the user.
  1380. * 'user_login' - A string that contains the user's username for logging in.
  1381. * 'user_nicename' - A string that contains a URL-friendly name for the user.
  1382. * The default is the user's username.
  1383. * 'user_url' - A string containing the user's URL for the user's web site.
  1384. * 'user_email' - A string containing the user's email address.
  1385. * 'display_name' - A string that will be shown on the site. Defaults to user's
  1386. * username. It is likely that you will want to change this, for appearance.
  1387. * 'nickname' - The user's nickname, defaults to the user's username.
  1388. * 'first_name' - The user's first name.
  1389. * 'last_name' - The user's last name.
  1390. * 'description' - A string containing content about the user.
  1391. * 'rich_editing' - A string for whether to enable the rich editor. False
  1392. * if not empty.
  1393. * 'user_registered' - The date the user registered. Format is 'Y-m-d H:i:s'.
  1394. * 'role' - A string used to set the user's role.
  1395. * 'jabber' - User's Jabber account.
  1396. * 'aim' - User's AOL IM account.
  1397. * 'yim' - User's Yahoo IM account.
  1398. *
  1399. * @since 2.0.0
  1400. *
  1401. * @global wpdb $wpdb WordPress database object for queries.
  1402. *
  1403. * @todo Hash-notate arguments array.
  1404. *
  1405. * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User.
  1406. * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not be created.
  1407. */
  1408. function wp_insert_user( $userdata ) {
  1409. global $wpdb;
  1410. if ( is_a( $userdata, 'stdClass' ) ) {
  1411. $userdata = get_object_vars( $userdata );
  1412. } elseif ( is_a( $userdata, 'WP_User' ) ) {
  1413. $userdata = $userdata->to_array();
  1414. }
  1415. // Are we updating or creating?
  1416. if ( ! empty( $userdata['ID'] ) ) {
  1417. $ID = (int) $userdata['ID'];
  1418. $update = true;
  1419. $old_user_data = WP_User::get_data_by( 'id', $ID );
  1420. // hashed in wp_update_user(), plaintext if called directly
  1421. $user_pass = $userdata['user_pass'];
  1422. } else {
  1423. $update = false;
  1424. // Hash the password
  1425. $user_pass = wp_hash_password( $userdata['user_pass'] );
  1426. }
  1427. $sanitized_user_login = sanitize_user( $userdata['user_login'], true );
  1428. /**
  1429. * Filter a username after it has been sanitized.
  1430. *
  1431. * This filter is called before the user is created or updated.
  1432. *
  1433. * @since 2.0.3
  1434. *
  1435. * @param string $sanitized_user_login Username after it has been sanitized.
  1436. */
  1437. $pre_user_login = apply_filters( 'pre_user_login', $sanitized_user_login );
  1438. //Remove any non-printable chars from the login string to see if we have ended up with an empty username
  1439. $user_login = trim( $pre_user_login );
  1440. if ( empty( $user_login ) ) {
  1441. return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') );
  1442. }
  1443. if ( ! $update && username_exists( $user_login ) ) {
  1444. return new WP_Error( 'existing_user_login', __( 'Sorry, that user…

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