PageRenderTime 29ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/user.php

https://bitbucket.org/acipriani/madeinapulia.com
PHP | 2337 lines | 968 code | 283 blank | 1086 comment | 251 complexity | ce7d9c841a8885991858466919cfa3f8 MD5 | raw file
Possible License(s): GPL-3.0, MIT, BSD-3-Clause, LGPL-2.1, GPL-2.0, Apache-2.0
  1. <?php
  2. /**
  3. * WordPress User API
  4. *
  5. * @package WordPress
  6. * @subpackage Users
  7. */
  8. /**
  9. * Authenticate user with remember capability.
  10. *
  11. * The credentials is an array that has 'user_login', 'user_password', and
  12. * 'remember' indices. If the credentials is not given, then the log in form
  13. * will be assumed and used if set.
  14. *
  15. * The various authentication cookies will be set by this function and will be
  16. * set for a longer period depending on if the 'remember' credential is set to
  17. * true.
  18. *
  19. * @since 2.5.0
  20. *
  21. * @param array $credentials Optional. User info in order to sign on.
  22. * @param string|bool $secure_cookie Optional. Whether to use secure cookie.
  23. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  24. */
  25. function wp_signon( $credentials = array(), $secure_cookie = '' ) {
  26. if ( empty($credentials) ) {
  27. if ( ! empty($_POST['log']) )
  28. $credentials['user_login'] = $_POST['log'];
  29. if ( ! empty($_POST['pwd']) )
  30. $credentials['user_password'] = $_POST['pwd'];
  31. if ( ! empty($_POST['rememberme']) )
  32. $credentials['remember'] = $_POST['rememberme'];
  33. }
  34. if ( !empty($credentials['remember']) )
  35. $credentials['remember'] = true;
  36. else
  37. $credentials['remember'] = false;
  38. /**
  39. * Fires before the user is authenticated.
  40. *
  41. * The variables passed to the callbacks are passed by reference,
  42. * and can be modified by callback functions.
  43. *
  44. * @since 1.5.1
  45. *
  46. * @todo Decide whether to deprecate the wp_authenticate action.
  47. *
  48. * @param string $user_login Username, passed by reference.
  49. * @param string $user_password User password, passed by reference.
  50. */
  51. do_action_ref_array( 'wp_authenticate', array( &$credentials['user_login'], &$credentials['user_password'] ) );
  52. if ( '' === $secure_cookie )
  53. $secure_cookie = is_ssl();
  54. /**
  55. * Filter whether to use a secure sign-on cookie.
  56. *
  57. * @since 3.1.0
  58. *
  59. * @param bool $secure_cookie Whether to use a secure sign-on cookie.
  60. * @param array $credentials {
  61. * Array of entered sign-on data.
  62. *
  63. * @type string $user_login Username.
  64. * @type string $user_password Password entered.
  65. * @type bool $remember Whether to 'remember' the user. Increases the time
  66. * that the cookie will be kept. Default false.
  67. * }
  68. */
  69. $secure_cookie = apply_filters( 'secure_signon_cookie', $secure_cookie, $credentials );
  70. global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
  71. $auth_secure_cookie = $secure_cookie;
  72. add_filter('authenticate', 'wp_authenticate_cookie', 30, 3);
  73. $user = wp_authenticate($credentials['user_login'], $credentials['user_password']);
  74. if ( is_wp_error($user) ) {
  75. if ( $user->get_error_codes() == array('empty_username', 'empty_password') ) {
  76. $user = new WP_Error('', '');
  77. }
  78. return $user;
  79. }
  80. wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
  81. /**
  82. * Fires after the user has successfully logged in.
  83. *
  84. * @since 1.5.0
  85. *
  86. * @param string $user_login Username.
  87. * @param WP_User $user WP_User object of the logged-in user.
  88. */
  89. do_action( 'wp_login', $user->user_login, $user );
  90. return $user;
  91. }
  92. /**
  93. * Authenticate the user using the username and password.
  94. *
  95. * @since 2.8.0
  96. *
  97. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  98. * @param string $username Username for authentication.
  99. * @param string $password Password for authentication.
  100. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  101. */
  102. function wp_authenticate_username_password($user, $username, $password) {
  103. if ( is_a( $user, 'WP_User' ) ) {
  104. return $user;
  105. }
  106. if ( empty($username) || empty($password) ) {
  107. if ( is_wp_error( $user ) )
  108. return $user;
  109. $error = new WP_Error();
  110. if ( empty($username) )
  111. $error->add('empty_username', __('<strong>ERROR</strong>: The username field is empty.'));
  112. if ( empty($password) )
  113. $error->add('empty_password', __('<strong>ERROR</strong>: The password field is empty.'));
  114. return $error;
  115. }
  116. $user = get_user_by('login', $username);
  117. if ( !$user )
  118. return new WP_Error( 'invalid_username', sprintf( __( '<strong>ERROR</strong>: Invalid username. <a href="%s">Lost your password</a>?' ), wp_lostpassword_url() ) );
  119. /**
  120. * Filter whether the given user can be authenticated with the provided $password.
  121. *
  122. * @since 2.5.0
  123. *
  124. * @param WP_User|WP_Error $user WP_User or WP_Error object if a previous
  125. * callback failed authentication.
  126. * @param string $password Password to check against the user.
  127. */
  128. $user = apply_filters( 'wp_authenticate_user', $user, $password );
  129. if ( is_wp_error($user) )
  130. return $user;
  131. if ( !wp_check_password($password, $user->user_pass, $user->ID) )
  132. return new WP_Error( 'incorrect_password', sprintf( __( '<strong>ERROR</strong>: The password you entered for the username <strong>%1$s</strong> is incorrect. <a href="%2$s">Lost your password</a>?' ),
  133. $username, wp_lostpassword_url() ) );
  134. return $user;
  135. }
  136. /**
  137. * Authenticate the user using the WordPress auth cookie.
  138. *
  139. * @since 2.8.0
  140. *
  141. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  142. * @param string $username Username. If not empty, cancels the cookie authentication.
  143. * @param string $password Password. If not empty, cancels the cookie authentication.
  144. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  145. */
  146. function wp_authenticate_cookie($user, $username, $password) {
  147. if ( is_a( $user, 'WP_User' ) ) {
  148. return $user;
  149. }
  150. if ( empty($username) && empty($password) ) {
  151. $user_id = wp_validate_auth_cookie();
  152. if ( $user_id )
  153. return new WP_User($user_id);
  154. global $auth_secure_cookie;
  155. if ( $auth_secure_cookie )
  156. $auth_cookie = SECURE_AUTH_COOKIE;
  157. else
  158. $auth_cookie = AUTH_COOKIE;
  159. if ( !empty($_COOKIE[$auth_cookie]) )
  160. return new WP_Error('expired_session', __('Please log in again.'));
  161. // If the cookie is not set, be silent.
  162. }
  163. return $user;
  164. }
  165. /**
  166. * For Multisite blogs, check if the authenticated user has been marked as a
  167. * spammer, or if the user's primary blog has been marked as spam.
  168. *
  169. * @since 3.7.0
  170. *
  171. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  172. * @return WP_User|WP_Error WP_User on success, WP_Error if the user is considered a spammer.
  173. */
  174. function wp_authenticate_spam_check( $user ) {
  175. if ( $user && is_a( $user, 'WP_User' ) && is_multisite() ) {
  176. /**
  177. * Filter whether the user has been marked as a spammer.
  178. *
  179. * @since 3.7.0
  180. *
  181. * @param bool $spammed Whether the user is considered a spammer.
  182. * @param WP_User $user User to check against.
  183. */
  184. $spammed = apply_filters( 'check_is_user_spammed', is_user_spammy(), $user );
  185. if ( $spammed )
  186. return new WP_Error( 'spammer_account', __( '<strong>ERROR</strong>: Your account has been marked as a spammer.' ) );
  187. }
  188. return $user;
  189. }
  190. /**
  191. * Validate the logged-in cookie.
  192. *
  193. * Checks the logged-in cookie if the previous auth cookie could not be
  194. * validated and parsed.
  195. *
  196. * This is a callback for the determine_current_user filter, rather than API.
  197. *
  198. * @since 3.9.0
  199. *
  200. * @param int|bool $user_id The user ID (or false) as received from the
  201. * determine_current_user filter.
  202. * @return int|bool User ID if validated, false otherwise. If a user ID from
  203. * an earlier filter callback is received, that value is returned.
  204. */
  205. function wp_validate_logged_in_cookie( $user_id ) {
  206. if ( $user_id ) {
  207. return $user_id;
  208. }
  209. if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[LOGGED_IN_COOKIE] ) ) {
  210. return false;
  211. }
  212. return wp_validate_auth_cookie( $_COOKIE[LOGGED_IN_COOKIE], 'logged_in' );
  213. }
  214. /**
  215. * Number of posts user has written.
  216. *
  217. * @since 3.0.0
  218. * @since 4.1.0 Added `$post_type` argument.
  219. *
  220. * @global wpdb $wpdb WordPress database object for queries.
  221. *
  222. * @param int $userid User ID.
  223. * @param string $post_type Optional. Post type to count the number of posts for. Default 'post'.
  224. * @return int Number of posts the user has written in this post type.
  225. */
  226. function count_user_posts( $userid, $post_type = 'post' ) {
  227. global $wpdb;
  228. $where = get_posts_by_author_sql( $post_type, true, $userid );
  229. $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
  230. /**
  231. * Filter the number of posts a user has written.
  232. *
  233. * @since 2.7.0
  234. * @since 4.1.0 Added `$post_type` argument.
  235. *
  236. * @param int $count The user's post count.
  237. * @param int $userid User ID.
  238. * @param string $post_type Post type to count the number of posts for.
  239. */
  240. return apply_filters( 'get_usernumposts', $count, $userid, $post_type );
  241. }
  242. /**
  243. * Number of posts written by a list of users.
  244. *
  245. * @since 3.0.0
  246. *
  247. * @param array $users Array of user IDs.
  248. * @param string $post_type Optional. Post type to check. Defaults to post.
  249. * @param bool $public_only Optional. Only return counts for public posts. Defaults to false.
  250. * @return array Amount of posts each user has written.
  251. */
  252. function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
  253. global $wpdb;
  254. $count = array();
  255. if ( empty( $users ) || ! is_array( $users ) )
  256. return $count;
  257. $userlist = implode( ',', array_map( 'absint', $users ) );
  258. $where = get_posts_by_author_sql( $post_type, true, null, $public_only );
  259. $result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
  260. foreach ( $result as $row ) {
  261. $count[ $row[0] ] = $row[1];
  262. }
  263. foreach ( $users as $id ) {
  264. if ( ! isset( $count[ $id ] ) )
  265. $count[ $id ] = 0;
  266. }
  267. return $count;
  268. }
  269. //
  270. // User option functions
  271. //
  272. /**
  273. * Get the current user's ID
  274. *
  275. * @since MU
  276. *
  277. * @return int The current user's ID
  278. */
  279. function get_current_user_id() {
  280. if ( ! function_exists( 'wp_get_current_user' ) )
  281. return 0;
  282. $user = wp_get_current_user();
  283. return ( isset( $user->ID ) ? (int) $user->ID : 0 );
  284. }
  285. /**
  286. * Retrieve user option that can be either per Site or per Network.
  287. *
  288. * If the user ID is not given, then the current user will be used instead. If
  289. * the user ID is given, then the user data will be retrieved. The filter for
  290. * the result, will also pass the original option name and finally the user data
  291. * object as the third parameter.
  292. *
  293. * The option will first check for the per site name and then the per Network name.
  294. *
  295. * @since 2.0.0
  296. *
  297. * @global wpdb $wpdb WordPress database object for queries.
  298. *
  299. * @param string $option User option name.
  300. * @param int $user Optional. User ID.
  301. * @param string $deprecated Use get_option() to check for an option in the options table.
  302. * @return mixed User option value on success, false on failure.
  303. */
  304. function get_user_option( $option, $user = 0, $deprecated = '' ) {
  305. global $wpdb;
  306. if ( !empty( $deprecated ) )
  307. _deprecated_argument( __FUNCTION__, '3.0' );
  308. if ( empty( $user ) )
  309. $user = get_current_user_id();
  310. if ( ! $user = get_userdata( $user ) )
  311. return false;
  312. $prefix = $wpdb->get_blog_prefix();
  313. if ( $user->has_prop( $prefix . $option ) ) // Blog specific
  314. $result = $user->get( $prefix . $option );
  315. elseif ( $user->has_prop( $option ) ) // User specific and cross-blog
  316. $result = $user->get( $option );
  317. else
  318. $result = false;
  319. /**
  320. * Filter a specific user option value.
  321. *
  322. * The dynamic portion of the hook name, `$option`, refers to the user option name.
  323. *
  324. * @since 2.5.0
  325. *
  326. * @param mixed $result Value for the user's option.
  327. * @param string $option Name of the option being retrieved.
  328. * @param WP_User $user WP_User object of the user whose option is being retrieved.
  329. */
  330. return apply_filters( "get_user_option_{$option}", $result, $option, $user );
  331. }
  332. /**
  333. * Update user option with global blog capability.
  334. *
  335. * User options are just like user metadata except that they have support for
  336. * global blog options. If the 'global' parameter is false, which it is by default
  337. * it will prepend the WordPress table prefix to the option name.
  338. *
  339. * Deletes the user option if $newvalue is empty.
  340. *
  341. * @since 2.0.0
  342. *
  343. * @global wpdb $wpdb WordPress database object for queries.
  344. *
  345. * @param int $user_id User ID.
  346. * @param string $option_name User option name.
  347. * @param mixed $newvalue User option value.
  348. * @param bool $global Optional. Whether option name is global or blog specific.
  349. * Default false (blog specific).
  350. * @return int|bool User meta ID if the option didn't exist, true on successful update,
  351. * false on failure.
  352. */
  353. function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
  354. global $wpdb;
  355. if ( !$global )
  356. $option_name = $wpdb->get_blog_prefix() . $option_name;
  357. return update_user_meta( $user_id, $option_name, $newvalue );
  358. }
  359. /**
  360. * Delete user option with global blog capability.
  361. *
  362. * User options are just like user metadata except that they have support for
  363. * global blog options. If the 'global' parameter is false, which it is by default
  364. * it will prepend the WordPress table prefix to the option name.
  365. *
  366. * @since 3.0.0
  367. *
  368. * @global wpdb $wpdb WordPress database object for queries.
  369. *
  370. * @param int $user_id User ID
  371. * @param string $option_name User option name.
  372. * @param bool $global Optional. Whether option name is global or blog specific.
  373. * Default false (blog specific).
  374. * @return bool True on success, false on failure.
  375. */
  376. function delete_user_option( $user_id, $option_name, $global = false ) {
  377. global $wpdb;
  378. if ( !$global )
  379. $option_name = $wpdb->get_blog_prefix() . $option_name;
  380. return delete_user_meta( $user_id, $option_name );
  381. }
  382. /**
  383. * WordPress User Query class.
  384. *
  385. * @since 3.1.0
  386. *
  387. * @see WP_User_Query::prepare_query() for information on accepted arguments.
  388. */
  389. class WP_User_Query {
  390. /**
  391. * Query vars, after parsing
  392. *
  393. * @since 3.5.0
  394. * @access public
  395. * @var array
  396. */
  397. public $query_vars = array();
  398. /**
  399. * List of found user ids
  400. *
  401. * @since 3.1.0
  402. * @access private
  403. * @var array
  404. */
  405. private $results;
  406. /**
  407. * Total number of found users for the current query
  408. *
  409. * @since 3.1.0
  410. * @access private
  411. * @var int
  412. */
  413. private $total_users = 0;
  414. // SQL clauses
  415. public $query_fields;
  416. public $query_from;
  417. public $query_where;
  418. public $query_orderby;
  419. public $query_limit;
  420. /**
  421. * PHP5 constructor.
  422. *
  423. * @since 3.1.0
  424. *
  425. * @param null|string|array $args Optional. The query variables.
  426. * @return WP_User_Query
  427. */
  428. public function __construct( $query = null ) {
  429. if ( ! empty( $query ) ) {
  430. $this->prepare_query( $query );
  431. $this->query();
  432. }
  433. }
  434. /**
  435. * Prepare the query variables.
  436. *
  437. * @since 3.1.0
  438. * @access public
  439. *
  440. * @param string|array $query {
  441. * Optional. Array or string of Query parameters.
  442. *
  443. * @type int $blog_id The site ID. Default is the global blog id.
  444. * @type string $role Role name. Default empty.
  445. * @type string $meta_key User meta key. Default empty.
  446. * @type string $meta_value User meta value. Default empty.
  447. * @type string $meta_compare Comparison operator to test the `$meta_value`. Accepts '=', '!=',
  448. * '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN',
  449. * 'NOT BETWEEN', 'EXISTS', 'NOT EXISTS', 'REGEXP', 'NOT REGEXP',
  450. * or 'RLIKE'. Default '='.
  451. * @type array $include An array of user IDs to include. Default empty array.
  452. * @type array $exclude An array of user IDs to exclude. Default empty array.
  453. * @type string $search Search keyword. Searches for possible string matches on columns.
  454. * When `$search_columns` is left empty, it tries to determine which
  455. * column to search in based on search string. Default empty.
  456. * @type array $search_columns Array of column names to be searched. Accepts 'ID', 'login',
  457. * 'nicename', 'email', 'url'. Default empty array.
  458. * @type string $orderby Field to sort the retrieved users by. Accepts 'ID', 'display_name',
  459. * 'login', 'nicename', 'email', 'url', 'registered', 'post_count', or
  460. * 'meta_value'. To use 'meta_value', `$meta_key` must be also be defined.
  461. * Default 'user_login'.
  462. * @type string $order Designates ascending or descending order of users. Accepts 'ASC',
  463. * 'DESC'. Default 'ASC'.
  464. * @type int $offset Number of users to offset in retrieved results. Can be used in
  465. * conjunction with pagination. Default 0.
  466. * @type int $number Number of users to limit the query for. Can be used in conjunction
  467. * with pagination. Value -1 (all) is not supported.
  468. * Default empty (all users).
  469. * @type bool $count_total Whether to count the total number of users found. If pagination is not
  470. * needed, setting this to false can improve performance. Default true.
  471. * @type string|array $fields Which fields to return. Single or all fields (string), or array
  472. * of fields. Accepts 'ID', 'display_name', 'login', 'nicename', 'email',
  473. * 'url', 'registered'. Use 'all' for all fields and 'all_with_meta' to
  474. * include meta fields. Default 'all'.
  475. * @type string $who Type of users to query. Accepts 'authors'. Default empty (all users).
  476. * }
  477. */
  478. public function prepare_query( $query = array() ) {
  479. global $wpdb;
  480. if ( empty( $this->query_vars ) || ! empty( $query ) ) {
  481. $this->query_limit = null;
  482. $this->query_vars = wp_parse_args( $query, array(
  483. 'blog_id' => $GLOBALS['blog_id'],
  484. 'role' => '',
  485. 'meta_key' => '',
  486. 'meta_value' => '',
  487. 'meta_compare' => '',
  488. 'include' => array(),
  489. 'exclude' => array(),
  490. 'search' => '',
  491. 'search_columns' => array(),
  492. 'orderby' => 'login',
  493. 'order' => 'ASC',
  494. 'offset' => '',
  495. 'number' => '',
  496. 'count_total' => true,
  497. 'fields' => 'all',
  498. 'who' => ''
  499. ) );
  500. }
  501. /**
  502. * Fires before the WP_User_Query has been parsed.
  503. *
  504. * The passed WP_User_Query object contains the query variables, not
  505. * yet passed into SQL.
  506. *
  507. * @since 4.0.0
  508. *
  509. * @param WP_User_Query $this The current WP_User_Query instance,
  510. * passed by reference.
  511. */
  512. do_action( 'pre_get_users', $this );
  513. $qv =& $this->query_vars;
  514. if ( is_array( $qv['fields'] ) ) {
  515. $qv['fields'] = array_unique( $qv['fields'] );
  516. $this->query_fields = array();
  517. foreach ( $qv['fields'] as $field ) {
  518. $field = 'ID' === $field ? 'ID' : sanitize_key( $field );
  519. $this->query_fields[] = "$wpdb->users.$field";
  520. }
  521. $this->query_fields = implode( ',', $this->query_fields );
  522. } elseif ( 'all' == $qv['fields'] ) {
  523. $this->query_fields = "$wpdb->users.*";
  524. } else {
  525. $this->query_fields = "$wpdb->users.ID";
  526. }
  527. if ( isset( $qv['count_total'] ) && $qv['count_total'] )
  528. $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
  529. $this->query_from = "FROM $wpdb->users";
  530. $this->query_where = "WHERE 1=1";
  531. // Parse and sanitize 'include', for use by 'orderby' as well as 'include' below.
  532. if ( ! empty( $qv['include'] ) ) {
  533. $include = wp_parse_id_list( $qv['include'] );
  534. } else {
  535. $include = false;
  536. }
  537. // sorting
  538. if ( isset( $qv['orderby'] ) ) {
  539. if ( in_array( $qv['orderby'], array('nicename', 'email', 'url', 'registered') ) ) {
  540. $orderby = 'user_' . $qv['orderby'];
  541. } elseif ( in_array( $qv['orderby'], array('user_nicename', 'user_email', 'user_url', 'user_registered') ) ) {
  542. $orderby = $qv['orderby'];
  543. } elseif ( 'name' == $qv['orderby'] || 'display_name' == $qv['orderby'] ) {
  544. $orderby = 'display_name';
  545. } elseif ( 'post_count' == $qv['orderby'] ) {
  546. // todo: avoid the JOIN
  547. $where = get_posts_by_author_sql('post');
  548. $this->query_from .= " LEFT OUTER JOIN (
  549. SELECT post_author, COUNT(*) as post_count
  550. FROM $wpdb->posts
  551. $where
  552. GROUP BY post_author
  553. ) p ON ({$wpdb->users}.ID = p.post_author)
  554. ";
  555. $orderby = 'post_count';
  556. } elseif ( 'ID' == $qv['orderby'] || 'id' == $qv['orderby'] ) {
  557. $orderby = 'ID';
  558. } elseif ( 'meta_value' == $qv['orderby'] ) {
  559. $orderby = "$wpdb->usermeta.meta_value";
  560. } else if ( 'include' === $qv['orderby'] && ! empty( $include ) ) {
  561. // Sanitized earlier.
  562. $include_sql = implode( ',', $include );
  563. $orderby = "FIELD( $wpdb->users.ID, $include_sql )";
  564. } else {
  565. $orderby = 'user_login';
  566. }
  567. }
  568. if ( empty( $orderby ) )
  569. $orderby = 'user_login';
  570. $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
  571. if ( 'ASC' == $qv['order'] )
  572. $order = 'ASC';
  573. else
  574. $order = 'DESC';
  575. $this->query_orderby = "ORDER BY $orderby $order";
  576. // limit
  577. if ( isset( $qv['number'] ) && $qv['number'] ) {
  578. if ( $qv['offset'] )
  579. $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
  580. else
  581. $this->query_limit = $wpdb->prepare("LIMIT %d", $qv['number']);
  582. }
  583. $search = '';
  584. if ( isset( $qv['search'] ) )
  585. $search = trim( $qv['search'] );
  586. if ( $search ) {
  587. $leading_wild = ( ltrim($search, '*') != $search );
  588. $trailing_wild = ( rtrim($search, '*') != $search );
  589. if ( $leading_wild && $trailing_wild )
  590. $wild = 'both';
  591. elseif ( $leading_wild )
  592. $wild = 'leading';
  593. elseif ( $trailing_wild )
  594. $wild = 'trailing';
  595. else
  596. $wild = false;
  597. if ( $wild )
  598. $search = trim($search, '*');
  599. $search_columns = array();
  600. if ( $qv['search_columns'] )
  601. $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename' ) );
  602. if ( ! $search_columns ) {
  603. if ( false !== strpos( $search, '@') )
  604. $search_columns = array('user_email');
  605. elseif ( is_numeric($search) )
  606. $search_columns = array('user_login', 'ID');
  607. elseif ( preg_match('|^https?://|', $search) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) )
  608. $search_columns = array('user_url');
  609. else
  610. $search_columns = array('user_login', 'user_nicename');
  611. }
  612. /**
  613. * Filter the columns to search in a WP_User_Query search.
  614. *
  615. * The default columns depend on the search term, and include 'user_email',
  616. * 'user_login', 'ID', 'user_url', and 'user_nicename'.
  617. *
  618. * @since 3.6.0
  619. *
  620. * @param array $search_columns Array of column names to be searched.
  621. * @param string $search Text being searched.
  622. * @param WP_User_Query $this The current WP_User_Query instance.
  623. */
  624. $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
  625. $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
  626. }
  627. $blog_id = 0;
  628. if ( isset( $qv['blog_id'] ) )
  629. $blog_id = absint( $qv['blog_id'] );
  630. if ( isset( $qv['who'] ) && 'authors' == $qv['who'] && $blog_id ) {
  631. $qv['meta_key'] = $wpdb->get_blog_prefix( $blog_id ) . 'user_level';
  632. $qv['meta_value'] = 0;
  633. $qv['meta_compare'] = '!=';
  634. $qv['blog_id'] = $blog_id = 0; // Prevent extra meta query
  635. }
  636. $meta_query = new WP_Meta_Query();
  637. $meta_query->parse_query_vars( $qv );
  638. $role = '';
  639. if ( isset( $qv['role'] ) )
  640. $role = trim( $qv['role'] );
  641. if ( $blog_id && ( $role || is_multisite() ) ) {
  642. $cap_meta_query = array();
  643. $cap_meta_query['key'] = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities';
  644. if ( $role ) {
  645. $cap_meta_query['value'] = '"' . $role . '"';
  646. $cap_meta_query['compare'] = 'like';
  647. }
  648. if ( empty( $meta_query->queries ) ) {
  649. $meta_query->queries = array( $cap_meta_query );
  650. } elseif ( ! in_array( $cap_meta_query, $meta_query->queries, true ) ) {
  651. // Append the cap query to the original queries and reparse the query.
  652. $meta_query->queries = array(
  653. 'relation' => 'AND',
  654. array( $meta_query->queries, $cap_meta_query ),
  655. );
  656. }
  657. $meta_query->parse_query_vars( $meta_query->queries );
  658. }
  659. if ( !empty( $meta_query->queries ) ) {
  660. $clauses = $meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
  661. $this->query_from .= $clauses['join'];
  662. $this->query_where .= $clauses['where'];
  663. if ( 'OR' == $meta_query->relation )
  664. $this->query_fields = 'DISTINCT ' . $this->query_fields;
  665. }
  666. if ( ! empty( $include ) ) {
  667. // Sanitized earlier.
  668. $ids = implode( ',', $include );
  669. $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
  670. } elseif ( ! empty( $qv['exclude'] ) ) {
  671. $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
  672. $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
  673. }
  674. // Date queries are allowed for the user_registered field.
  675. if ( ! empty( $qv['date_query'] ) && is_array( $qv['date_query'] ) ) {
  676. $date_query = new WP_Date_Query( $qv['date_query'], 'user_registered' );
  677. $this->query_where .= $date_query->get_sql();
  678. }
  679. /**
  680. * Fires after the WP_User_Query has been parsed, and before
  681. * the query is executed.
  682. *
  683. * The passed WP_User_Query object contains SQL parts formed
  684. * from parsing the given query.
  685. *
  686. * @since 3.1.0
  687. *
  688. * @param WP_User_Query $this The current WP_User_Query instance,
  689. * passed by reference.
  690. */
  691. do_action_ref_array( 'pre_user_query', array( &$this ) );
  692. }
  693. /**
  694. * Execute the query, with the current variables.
  695. *
  696. * @since 3.1.0
  697. *
  698. * @global wpdb $wpdb WordPress database object for queries.
  699. */
  700. public function query() {
  701. global $wpdb;
  702. $qv =& $this->query_vars;
  703. $query = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
  704. if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
  705. $this->results = $wpdb->get_results( $query );
  706. } else {
  707. $this->results = $wpdb->get_col( $query );
  708. }
  709. /**
  710. * Filter SELECT FOUND_ROWS() query for the current WP_User_Query instance.
  711. *
  712. * @since 3.2.0
  713. *
  714. * @global wpdb $wpdb WordPress database abstraction object.
  715. *
  716. * @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
  717. */
  718. if ( isset( $qv['count_total'] ) && $qv['count_total'] )
  719. $this->total_users = $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) );
  720. if ( !$this->results )
  721. return;
  722. if ( 'all_with_meta' == $qv['fields'] ) {
  723. cache_users( $this->results );
  724. $r = array();
  725. foreach ( $this->results as $userid )
  726. $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
  727. $this->results = $r;
  728. } elseif ( 'all' == $qv['fields'] ) {
  729. foreach ( $this->results as $key => $user ) {
  730. $this->results[ $key ] = new WP_User( $user );
  731. }
  732. }
  733. }
  734. /**
  735. * Retrieve query variable.
  736. *
  737. * @since 3.5.0
  738. * @access public
  739. *
  740. * @param string $query_var Query variable key.
  741. * @return mixed
  742. */
  743. public function get( $query_var ) {
  744. if ( isset( $this->query_vars[$query_var] ) )
  745. return $this->query_vars[$query_var];
  746. return null;
  747. }
  748. /**
  749. * Set query variable.
  750. *
  751. * @since 3.5.0
  752. * @access public
  753. *
  754. * @param string $query_var Query variable key.
  755. * @param mixed $value Query variable value.
  756. */
  757. public function set( $query_var, $value ) {
  758. $this->query_vars[$query_var] = $value;
  759. }
  760. /**
  761. * Used internally to generate an SQL string for searching across multiple columns
  762. *
  763. * @access protected
  764. * @since 3.1.0
  765. *
  766. * @param string $string
  767. * @param array $cols
  768. * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for
  769. * single site. Single site allows leading and trailing wildcards, Network Admin only trailing.
  770. * @return string
  771. */
  772. protected function get_search_sql( $string, $cols, $wild = false ) {
  773. global $wpdb;
  774. $searches = array();
  775. $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
  776. $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
  777. $like = $leading_wild . $wpdb->esc_like( $string ) . $trailing_wild;
  778. foreach ( $cols as $col ) {
  779. if ( 'ID' == $col ) {
  780. $searches[] = $wpdb->prepare( "$col = %s", $string );
  781. } else {
  782. $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
  783. }
  784. }
  785. return ' AND (' . implode(' OR ', $searches) . ')';
  786. }
  787. /**
  788. * Return the list of users.
  789. *
  790. * @since 3.1.0
  791. * @access public
  792. *
  793. * @return array Array of results.
  794. */
  795. public function get_results() {
  796. return $this->results;
  797. }
  798. /**
  799. * Return the total number of users for the current query.
  800. *
  801. * @since 3.1.0
  802. * @access public
  803. *
  804. * @return int Number of total users.
  805. */
  806. public function get_total() {
  807. return $this->total_users;
  808. }
  809. /**
  810. * Make private properties readable for backwards compatibility.
  811. *
  812. * @since 4.0.0
  813. * @access public
  814. *
  815. * @param string $name Property to get.
  816. * @return mixed Property.
  817. */
  818. public function __get( $name ) {
  819. return $this->$name;
  820. }
  821. /**
  822. * Make private properties settable for backwards compatibility.
  823. *
  824. * @since 4.0.0
  825. * @access public
  826. *
  827. * @param string $name Property to set.
  828. * @param mixed $value Property value.
  829. * @return mixed Newly-set property.
  830. */
  831. public function __set( $name, $value ) {
  832. return $this->$name = $value;
  833. }
  834. /**
  835. * Make private properties checkable for backwards compatibility.
  836. *
  837. * @since 4.0.0
  838. * @access public
  839. *
  840. * @param string $name Property to check if set.
  841. * @return bool Whether the property is set.
  842. */
  843. public function __isset( $name ) {
  844. return isset( $this->$name );
  845. }
  846. /**
  847. * Make private properties un-settable for backwards compatibility.
  848. *
  849. * @since 4.0.0
  850. * @access public
  851. *
  852. * @param string $name Property to unset.
  853. */
  854. public function __unset( $name ) {
  855. unset( $this->$name );
  856. }
  857. /**
  858. * Make private/protected methods readable for backwards compatibility.
  859. *
  860. * @since 4.0.0
  861. * @access public
  862. *
  863. * @param callable $name Method to call.
  864. * @param array $arguments Arguments to pass when calling.
  865. * @return mixed|bool Return value of the callback, false otherwise.
  866. */
  867. public function __call( $name, $arguments ) {
  868. return call_user_func_array( array( $this, $name ), $arguments );
  869. }
  870. }
  871. /**
  872. * Retrieve list of users matching criteria.
  873. *
  874. * @since 3.1.0
  875. *
  876. * @see WP_User_Query
  877. *
  878. * @param array $args Optional. Arguments to retrieve users. See {@see WP_User_Query::prepare_query()}
  879. * for more information on accepted arguments.
  880. * @return array List of users.
  881. */
  882. function get_users( $args = array() ) {
  883. $args = wp_parse_args( $args );
  884. $args['count_total'] = false;
  885. $user_search = new WP_User_Query($args);
  886. return (array) $user_search->get_results();
  887. }
  888. /**
  889. * Get the blogs a user belongs to.
  890. *
  891. * @since 3.0.0
  892. *
  893. * @global wpdb $wpdb WordPress database object for queries.
  894. *
  895. * @param int $user_id User ID
  896. * @param bool $all Whether to retrieve all blogs, or only blogs that are not
  897. * marked as deleted, archived, or spam.
  898. * @return array A list of the user's blogs. An empty array if the user doesn't exist
  899. * or belongs to no blogs.
  900. */
  901. function get_blogs_of_user( $user_id, $all = false ) {
  902. global $wpdb;
  903. $user_id = (int) $user_id;
  904. // Logged out users can't have blogs
  905. if ( empty( $user_id ) )
  906. return array();
  907. $keys = get_user_meta( $user_id );
  908. if ( empty( $keys ) )
  909. return array();
  910. if ( ! is_multisite() ) {
  911. $blog_id = get_current_blog_id();
  912. $blogs = array( $blog_id => new stdClass );
  913. $blogs[ $blog_id ]->userblog_id = $blog_id;
  914. $blogs[ $blog_id ]->blogname = get_option('blogname');
  915. $blogs[ $blog_id ]->domain = '';
  916. $blogs[ $blog_id ]->path = '';
  917. $blogs[ $blog_id ]->site_id = 1;
  918. $blogs[ $blog_id ]->siteurl = get_option('siteurl');
  919. $blogs[ $blog_id ]->archived = 0;
  920. $blogs[ $blog_id ]->spam = 0;
  921. $blogs[ $blog_id ]->deleted = 0;
  922. return $blogs;
  923. }
  924. $blogs = array();
  925. if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
  926. $blog = get_blog_details( 1 );
  927. if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
  928. $blogs[ 1 ] = (object) array(
  929. 'userblog_id' => 1,
  930. 'blogname' => $blog->blogname,
  931. 'domain' => $blog->domain,
  932. 'path' => $blog->path,
  933. 'site_id' => $blog->site_id,
  934. 'siteurl' => $blog->siteurl,
  935. 'archived' => 0,
  936. 'spam' => 0,
  937. 'deleted' => 0
  938. );
  939. }
  940. unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
  941. }
  942. $keys = array_keys( $keys );
  943. foreach ( $keys as $key ) {
  944. if ( 'capabilities' !== substr( $key, -12 ) )
  945. continue;
  946. if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) )
  947. continue;
  948. $blog_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
  949. if ( ! is_numeric( $blog_id ) )
  950. continue;
  951. $blog_id = (int) $blog_id;
  952. $blog = get_blog_details( $blog_id );
  953. if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
  954. $blogs[ $blog_id ] = (object) array(
  955. 'userblog_id' => $blog_id,
  956. 'blogname' => $blog->blogname,
  957. 'domain' => $blog->domain,
  958. 'path' => $blog->path,
  959. 'site_id' => $blog->site_id,
  960. 'siteurl' => $blog->siteurl,
  961. 'archived' => 0,
  962. 'spam' => 0,
  963. 'deleted' => 0
  964. );
  965. }
  966. }
  967. /**
  968. * Filter the list of blogs a user belongs to.
  969. *
  970. * @since MU
  971. *
  972. * @param array $blogs An array of blog objects belonging to the user.
  973. * @param int $user_id User ID.
  974. * @param bool $all Whether the returned blogs array should contain all blogs, including
  975. * those marked 'deleted', 'archived', or 'spam'. Default false.
  976. */
  977. return apply_filters( 'get_blogs_of_user', $blogs, $user_id, $all );
  978. }
  979. /**
  980. * Find out whether a user is a member of a given blog.
  981. *
  982. * @since MU 1.1
  983. *
  984. * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
  985. * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
  986. * @return bool
  987. */
  988. function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
  989. $user_id = (int) $user_id;
  990. $blog_id = (int) $blog_id;
  991. if ( empty( $user_id ) )
  992. $user_id = get_current_user_id();
  993. if ( empty( $blog_id ) )
  994. $blog_id = get_current_blog_id();
  995. $blogs = get_blogs_of_user( $user_id );
  996. return array_key_exists( $blog_id, $blogs );
  997. }
  998. /**
  999. * Add meta data field to a user.
  1000. *
  1001. * Post meta data is called "Custom Fields" on the Administration Screens.
  1002. *
  1003. * @since 3.0.0
  1004. * @link http://codex.wordpress.org/Function_Reference/add_user_meta
  1005. *
  1006. * @param int $user_id User ID.
  1007. * @param string $meta_key Metadata name.
  1008. * @param mixed $meta_value Metadata value.
  1009. * @param bool $unique Optional, default is false. Whether the same key should not be added.
  1010. * @return int|bool Meta ID on success, false on failure.
  1011. */
  1012. function add_user_meta($user_id, $meta_key, $meta_value, $unique = false) {
  1013. return add_metadata('user', $user_id, $meta_key, $meta_value, $unique);
  1014. }
  1015. /**
  1016. * Remove metadata matching criteria from a user.
  1017. *
  1018. * You can match based on the key, or key and value. Removing based on key and
  1019. * value, will keep from removing duplicate metadata with the same key. It also
  1020. * allows removing all metadata matching key, if needed.
  1021. *
  1022. * @since 3.0.0
  1023. * @link http://codex.wordpress.org/Function_Reference/delete_user_meta
  1024. *
  1025. * @param int $user_id user ID
  1026. * @param string $meta_key Metadata name.
  1027. * @param mixed $meta_value Optional. Metadata value.
  1028. * @return bool True on success, false on failure.
  1029. */
  1030. function delete_user_meta($user_id, $meta_key, $meta_value = '') {
  1031. return delete_metadata('user', $user_id, $meta_key, $meta_value);
  1032. }
  1033. /**
  1034. * Retrieve user meta field for a user.
  1035. *
  1036. * @since 3.0.0
  1037. * @link http://codex.wordpress.org/Function_Reference/get_user_meta
  1038. *
  1039. * @param int $user_id User ID.
  1040. * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
  1041. * @param bool $single Whether to return a single value.
  1042. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
  1043. * is true.
  1044. */
  1045. function get_user_meta($user_id, $key = '', $single = false) {
  1046. return get_metadata('user', $user_id, $key, $single);
  1047. }
  1048. /**
  1049. * Update user meta field based on user ID.
  1050. *
  1051. * Use the $prev_value parameter to differentiate between meta fields with the
  1052. * same key and user ID.
  1053. *
  1054. * If the meta field for the user does not exist, it will be added.
  1055. *
  1056. * @since 3.0.0
  1057. * @link http://codex.wordpress.org/Function_Reference/update_user_meta
  1058. *
  1059. * @param int $user_id User ID.
  1060. * @param string $meta_key Metadata key.
  1061. * @param mixed $meta_value Metadata value.
  1062. * @param mixed $prev_value Optional. Previous value to check before removing.
  1063. * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
  1064. */
  1065. function update_user_meta($user_id, $meta_key, $meta_value, $prev_value = '') {
  1066. return update_metadata('user', $user_id, $meta_key, $meta_value, $prev_value);
  1067. }
  1068. /**
  1069. * Count number of users who have each of the user roles.
  1070. *
  1071. * Assumes there are neither duplicated nor orphaned capabilities meta_values.
  1072. * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
  1073. * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
  1074. * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
  1075. *
  1076. * @since 3.0.0
  1077. * @param string $strategy 'time' or 'memory'
  1078. * @return array Includes a grand total and an array of counts indexed by role strings.
  1079. */
  1080. function count_users($strategy = 'time') {
  1081. global $wpdb, $wp_roles;
  1082. // Initialize
  1083. $id = get_current_blog_id();
  1084. $blog_prefix = $wpdb->get_blog_prefix($id);
  1085. $result = array();
  1086. if ( 'time' == $strategy ) {
  1087. global $wp_roles;
  1088. if ( ! isset( $wp_roles ) )
  1089. $wp_roles = new WP_Roles();
  1090. $avail_roles = $wp_roles->get_names();
  1091. // Build a CPU-intensive query that will return concise information.
  1092. $select_count = array();
  1093. foreach ( $avail_roles as $this_role => $name ) {
  1094. $select_count[] = $wpdb->prepare( "COUNT(NULLIF(`meta_value` LIKE %s, false))", '%' . $wpdb->esc_like( '"' . $this_role . '"' ) . '%');
  1095. }
  1096. $select_count = implode(', ', $select_count);
  1097. // Add the meta_value index to the selection list, then run the query.
  1098. $row = $wpdb->get_row( "SELECT $select_count, COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'", ARRAY_N );
  1099. // Run the previous loop again to associate results with role names.
  1100. $col = 0;
  1101. $role_counts = array();
  1102. foreach ( $avail_roles as $this_role => $name ) {
  1103. $count = (int) $row[$col++];
  1104. if ($count > 0) {
  1105. $role_counts[$this_role] = $count;
  1106. }
  1107. }
  1108. // Get the meta_value index from the end of the result set.
  1109. $total_users = (int) $row[$col];
  1110. $result['total_users'] = $total_users;
  1111. $result['avail_roles'] =& $role_counts;
  1112. } else {
  1113. $avail_roles = array();
  1114. $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" );
  1115. foreach ( $users_of_blog as $caps_meta ) {
  1116. $b_roles = maybe_unserialize($caps_meta);
  1117. if ( ! is_array( $b_roles ) )
  1118. continue;
  1119. foreach ( $b_roles as $b_role => $val ) {
  1120. if ( isset($avail_roles[$b_role]) ) {
  1121. $avail_roles[$b_role]++;
  1122. } else {
  1123. $avail_roles[$b_role] = 1;
  1124. }
  1125. }
  1126. }
  1127. $result['total_users'] = count( $users_of_blog );
  1128. $result['avail_roles'] =& $avail_roles;
  1129. }
  1130. return $result;
  1131. }
  1132. //
  1133. // Private helper functions
  1134. //
  1135. /**
  1136. * Set up global user vars.
  1137. *
  1138. * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
  1139. *
  1140. * @since 2.0.4
  1141. * @global string $userdata User description.
  1142. * @global string $user_login The user username for logging in
  1143. * @global int $user_level The level of the user
  1144. * @global int $user_ID The ID of the user
  1145. * @global string $user_email The email address of the user
  1146. * @global string $user_url The url in the user's profile
  1147. * @global string $user_identity The display name of the user
  1148. *
  1149. * @param int $for_user_id Optional. User ID to set up global data.
  1150. */
  1151. function setup_userdata($for_user_id = '') {
  1152. global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
  1153. if ( '' == $for_user_id )
  1154. $for_user_id = get_current_user_id();
  1155. $user = get_userdata( $for_user_id );
  1156. if ( ! $user ) {
  1157. $user_ID = 0;
  1158. $user_level = 0;
  1159. $userdata = null;
  1160. $user_login = $user_email = $user_url = $user_identity = '';
  1161. return;
  1162. }
  1163. $user_ID = (int) $user->ID;
  1164. $user_level = (int) $user->user_level;
  1165. $userdata = $user;
  1166. $user_login = $user->user_login;
  1167. $user_email = $user->user_email;
  1168. $user_url = $user->user_url;
  1169. $user_identity = $user->display_name;
  1170. }
  1171. /**
  1172. * Create dropdown HTML content of users.
  1173. *
  1174. * The content can either be displayed, which it is by default or retrieved by
  1175. * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
  1176. * need to be used; all users will be displayed in that case. Only one can be
  1177. * used, either 'include' or 'exclude', but not both.
  1178. *
  1179. * The available arguments are as follows:
  1180. *
  1181. * @since 2.3.0
  1182. *
  1183. * @global wpdb $wpdb WordPress database object for queries.
  1184. *
  1185. * @param array|string $args {
  1186. * Optional. Array or string of arguments to generate a drop-down of users.
  1187. * {@see WP_User_Query::prepare_query() for additional available arguments.
  1188. *
  1189. * @type string $show_option_all Text to show as the drop-down default (all).
  1190. * Default empty.
  1191. * @type string $show_option_none Text to show as the drop-down default when no
  1192. * users were found. Default empty.
  1193. * @type int|string $option_none_value Value to use for $show_option_non when no users
  1194. * were found. Default -1.
  1195. * @type string $hide_if_only_one_author Whether to skip generating the drop-down
  1196. * if only one user was found. Default empty.
  1197. * @type string $orderby Field to order found users by. Accepts user fields.
  1198. * Default 'display_name'.
  1199. * @type string $order Whether to order users in ascending or descending
  1200. * order. Accepts 'ASC' (ascending) or 'DESC' (descending).
  1201. * Default 'ASC'.
  1202. * @type array|string $include Array or comma-separated list of user IDs to include.
  1203. * Default empty.
  1204. * @type array|string $exclude Array or comma-separated list of user IDs to exclude.
  1205. * Default empty.
  1206. * @type bool|int $multi Whether to skip the ID attribute on the 'select' element.
  1207. * Accepts 1|true or 0|false. Default 0|false.
  1208. * @type string $show User table column to display. If the selected item is empty
  1209. * then the 'user_login' will be displayed in parentheses.
  1210. * Accepts user fields. Default 'display_name'.
  1211. * @type int|bool $echo Whether to echo or return the drop-down. Accepts 1|true (echo)
  1212. * or 0|false (return). Default 1|true.
  1213. * @type int $selected Which user ID should be selected. Default 0.
  1214. * @type bool $include_selected Whether to always include the selected user ID in the drop-
  1215. * down. Default false.
  1216. * @type string $name Name attribute of select element. Default 'user'.
  1217. * @type string $id ID attribute of the select element. Default is the value of $name.
  1218. * @type string $class Class attribute of the select element. Default empty.
  1219. * @type int $blog_id ID of blog (Multisite only). Default is ID of the current blog.
  1220. * @type string $who Which type of users to query. Accepts only an empty string or
  1221. * 'authors'. Default empty.
  1222. * }
  1223. * @return string|null Null on display. String of HTML content on retrieve.
  1224. */
  1225. function wp_dropdown_users( $args = '' ) {
  1226. $defaults = array(
  1227. 'show_option_all' => '', 'show_option_none' => '', 'hide_if_only_one_author' => '',
  1228. 'orderby' => 'display_name', 'order' => 'ASC',
  1229. 'include' => '', 'exclude' => '', 'multi' => 0,
  1230. 'show' => 'display_name', 'echo' => 1,
  1231. 'selected' => 0, 'name' => 'user', 'class' => '', 'id' => '',
  1232. 'blog_id' => $GLOBALS['blog_id'], 'who' => '', 'include_selected' => false,
  1233. 'option_none_value' => -1
  1234. );
  1235. $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
  1236. $r = wp_parse_args( $args, $defaults );
  1237. $show = $r['show'];
  1238. $show_option_all = $r['show_option_all'];
  1239. $show_option_none = $r['show_option_none'];
  1240. $option_none_value = $r['option_none_value'];
  1241. $query_args = wp_array_slice_assoc( $r, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who' ) );
  1242. $query_args['fields'] = array( 'ID', 'user_login', $show );
  1243. $users = get_users( $query_args );
  1244. $output = '';
  1245. if ( ! empty( $users ) && ( empty( $r['hide_if_only_one_author'] ) || count( $users ) > 1 ) ) {
  1246. $name = esc_attr( $r['name'] );
  1247. if ( $r['multi'] && ! $r['id'] ) {
  1248. $id = '';
  1249. } else {
  1250. $id = $r['id'] ? " id='" . esc_attr( $r['id'] ) . "'" : " id='$name'";
  1251. }
  1252. $output = "<select name='{$name}'{$id} class='" . $r['class'] . "'>\n";
  1253. if ( $show_option_all ) {
  1254. $output .= "\t<option value='0'>$show_option_all</option>\n";
  1255. }
  1256. if ( $show_option_none ) {
  1257. $_selected = selected( $option_none_value, $r['selected'], false );
  1258. $output .= "\t<option value='" . esc_attr( $option_none_value ) . "'$_selected>$show_option_none</option>\n";
  1259. }
  1260. $found_selected = false;
  1261. foreach ( (array) $users as $user ) {
  1262. $user->ID = (int) $user->ID;
  1263. $_selected = selected( $user->ID, $r['selected'], false );
  1264. if ( $_selected ) {
  1265. $found_selected = true;
  1266. }
  1267. $display = ! empty( $user->$show ) ? $user->$show : '('. $user->user_login . ')';
  1268. $output .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
  1269. }
  1270. if ( $r['include_selected'] && ! $found_selected && ( $r['selected'] > 0 ) ) {
  1271. $user = get_userdata( $r['selected'] );
  1272. $_selected = selected( $user->ID, $r['selected'], false );
  1273. $display = ! empty( $user->$show ) ? $user->$show : '('. $user->user_login . ')';
  1274. $output .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
  1275. }
  1276. $output .= "</select>";
  1277. }
  1278. /**
  1279. * Filter the wp_dropdown_users() HTML output.
  1280. *
  1281. * @since 2.3.0
  1282. *
  1283. * @param string $output HTML output generated by wp_dropdown_users().
  1284. */
  1285. $html = apply_filters( 'wp_dropdown_users', $output );
  1286. if ( $r['echo'] ) {
  1287. echo $html;
  1288. }
  1289. return $html;
  1290. }
  1291. /**
  1292. * Sanitize user field based on context.
  1293. *
  1294. * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
  1295. * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
  1296. * when calling filters.
  1297. *
  1298. * @since 2.3.0
  1299. *
  1300. * @param string $field The user Object field name.
  1301. * @param mixed $value The user Object value.
  1302. * @param int $user_id user ID.
  1303. * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
  1304. * 'attribute' and 'js'.
  1305. * @return mixed Sanitized value.
  1306. */
  1307. function sanitize_user_field($field, $value, $user_id, $context) {
  1308. $int_fields = array('ID');
  1309. if ( in_array($field, $int_fields) )
  1310. $value = (int) $value;
  1311. if ( 'raw' == $context )
  1312. return $value;
  1313. if ( !is_string($value) && !is_numeric($value) )
  1314. return $value;
  1315. $prefixed = false !== strpos( $field, 'user_' );
  1316. if ( 'edit' == $context ) {
  1317. if ( $prefixed ) {
  1318. /** This filter is documented in wp-includes/post.php */
  1319. $value = apply_filters( "edit_{$field}", $value, $user_id );
  1320. } else {
  1321. /**
  1322. * Filter a user field value in the 'edit' context.
  1323. *
  1324. * The dynamic portion of the hook name, `$field`, refers to the prefixed user
  1325. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1326. *
  1327. * @since 2.9.0
  1328. *
  1329. * @param mixed $value Value of the prefixed user field.
  1330. * @param int $user_id User ID.
  1331. */
  1332. $value = apply_filters( "edit_user_{$field}", $value, $user_id );
  1333. }
  1334. if ( 'description' == $field )
  1335. $value = esc_html( $value ); // textarea_escaped?
  1336. else
  1337. $value = esc_attr($value);
  1338. } else if ( 'db' == $context ) {
  1339. if ( $prefixed ) {
  1340. /** This filter is documented in wp-includes/post.php */
  1341. $value = apply_filters( "pre_{$field}", $value );
  1342. } else {
  1343. /**
  1344. * Filter the value of a user field in the 'db' context.
  1345. *
  1346. * The dynamic portion of the hook name, `$field`, refers to the prefixed user
  1347. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1348. *
  1349. * @since 2.9.0
  1350. *
  1351. * @param mixed $value Value of the prefixed user field.
  1352. */
  1353. $value = apply_filters( "pre_user_{$field}", $value );
  1354. }
  1355. } else {
  1356. // Use display filters by default.
  1357. if ( $prefixed ) {
  1358. /** This filter is documented in wp-includes/post.php */
  1359. $value = apply_filters( $field, $value, $user_id, $context );
  1360. } else {
  1361. /**
  1362. * Filter the value of a user field in a standard context.
  1363. *
  1364. * The dynamic portion of the hook name, `$field`, refers to the prefixed user
  1365. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1366. *
  1367. * @since 2.9.0
  1368. *
  1369. * @param mixed $value The user object value to sanitize.
  1370. * @param int $user_id User ID.
  1371. * @param string $context The context to filter within.
  1372. */
  1373. $value = apply_filters( "user_{$field}", $value, $user_id, $context );
  1374. }
  1375. }
  1376. if ( 'user_url' == $field )
  1377. $value = esc_url($value);
  1378. if ( 'attribute' == $context )
  1379. $value = esc_attr($value);
  1380. else if ( 'js' == $context )
  1381. $value = esc_js($value);
  1382. return $value;
  1383. }
  1384. /**
  1385. * Update all user caches
  1386. *
  1387. * @since 3.0.0
  1388. *
  1389. * @param object $user User object to be cached
  1390. */
  1391. function update_user_caches($user) {
  1392. wp_cache_add($user->ID, $user, 'users');
  1393. wp_cache_add($user->user_login, $user->ID, 'userlogins');
  1394. wp_cache_add($user->user_email, $user->ID, 'useremail');
  1395. wp_cache_add($user->user_nicename, $user->ID, 'userslugs');
  1396. }
  1397. /**
  1398. * Clean all user caches
  1399. *
  1400. * @since 3.0.0
  1401. *
  1402. * @param WP_User|int $user User object or ID to be cleaned from the cache
  1403. */
  1404. function clean_user_cache( $user ) {
  1405. if ( is_numeric( $user ) )
  1406. $user = new WP_User( $user );
  1407. if ( ! $user->exists() )
  1408. return;
  1409. wp_cache_delete( $user->ID, 'users' );
  1410. wp_cache_delete( $user->user_login, 'userlogins' );
  1411. wp_cache_delete( $user->user_email, 'useremail' );
  1412. wp_cache_delete( $user->user_nicename, 'userslugs' );
  1413. }
  1414. /**
  1415. * Checks whether the given username exists.
  1416. *
  1417. * @since 2.0.0
  1418. *
  1419. * @param string $username Username.
  1420. * @return null|int The user's ID on success, and null on failure.
  1421. */
  1422. function username_exists( $username ) {
  1423. if ( $user = get_user_by('login', $username ) ) {
  1424. return $user->ID;
  1425. } else {
  1426. return null;
  1427. }
  1428. }
  1429. /**
  1430. * Checks whether the given email exists.
  1431. *
  1432. * @since 2.1.0
  1433. *
  1434. * @param string $email Email.
  1435. * @return bool|int The user's ID on success, and false on failure.
  1436. */
  1437. function email_exists( $email ) {
  1438. if ( $user = get_user_by('email', $email) )
  1439. return $user->ID;
  1440. return false;
  1441. }
  1442. /**
  1443. * Checks whether an username is valid.
  1444. *
  1445. * @since 2.0.1
  1446. *
  1447. * @param string $username Username.
  1448. * @return bool Whether username given is valid
  1449. */
  1450. function validate_username( $username ) {
  1451. $sanitized = sanitize_user( $username, true );
  1452. $valid = ( $sanitized == $username );
  1453. /**
  1454. * Filter whether the provided username is valid or not.
  1455. *
  1456. * @since 2.0.1
  1457. *
  1458. * @param bool $valid Whether given username is valid.
  1459. * @param string $username Username to check.
  1460. */
  1461. return apply_filters( 'validate_username', $valid, $username );
  1462. }
  1463. /**
  1464. * Insert an user into the database.
  1465. *
  1466. * Most of the $userdata array fields have filters associated with the values.
  1467. * The exceptions are 'rich_editing', 'role', 'jabber', 'aim', 'yim',
  1468. * 'user_registered', and 'ID'. The filters have the prefix 'pre_user_' followed
  1469. * by the field name. An example using 'description' would have the filter
  1470. * called, 'pre_user_description' that can be hooked into.
  1471. *
  1472. * @since 2.0.0
  1473. *
  1474. * @global wpdb $wpdb WordPress database object for queries.
  1475. *
  1476. * @param array $userdata {
  1477. * An array, object, or WP_User object of user data arguments.
  1478. *
  1479. * @type int $ID User ID. If supplied, the user will be updated.
  1480. * @type string $user_pass The plain-text user password.
  1481. * @type string $user_login The user's login username.
  1482. * @type string $user_nicename The URL-friendly user name.
  1483. * @type string $user_url The user URL.
  1484. * @type string $user_email The user email address.
  1485. * @type string $display_name The user's display name.
  1486. * Default is the the user's username.
  1487. * @type string $nickname The user's nickname. Default
  1488. * Default is the the user's username.
  1489. * @type string $first_name The user's first name. For new users, will be used
  1490. * to build $display_name if unspecified.
  1491. * @type stirng $last_name The user's last name. For new users, will be used
  1492. * to build $display_name if unspecified.
  1493. * @type string|bool $rich_editing Whether to enable the rich-editor for the user. False
  1494. * if not empty.
  1495. * @type string $date_registered Date the user registered. Format is 'Y-m-d H:i:s'.
  1496. * @type string $role User's role.
  1497. * @type string $jabber User's Jabber account username.
  1498. * @type string $aim User's AIM account username.
  1499. * @type string $yim User's Yahoo! messenger username.
  1500. * }
  1501. * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
  1502. * be created.
  1503. */
  1504. function wp_insert_user( $userdata ) {
  1505. global $wpdb;
  1506. if ( is_a( $userdata, 'stdClass' ) ) {
  1507. $userdata = get_object_vars( $userdata );
  1508. } elseif ( is_a( $userdata, 'WP_User' ) ) {
  1509. $userdata = $userdata->to_array();
  1510. }
  1511. // Are we updating or creating?
  1512. if ( ! empty( $userdata['ID'] ) ) {
  1513. $ID = (int) $userdata['ID'];
  1514. $update = true;
  1515. $old_user_data = WP_User::get_data_by( 'id', $ID );
  1516. // hashed in wp_update_user(), plaintext if called directly
  1517. $user_pass = $userdata['user_pass'];
  1518. } else {
  1519. $update = false;
  1520. // Hash the password
  1521. $user_pass = wp_hash_password( $userdata['user_pass'] );
  1522. }
  1523. $sanitized_user_login = sanitize_user( $userdata['user_login'], true );
  1524. /**
  1525. * Filter a username after it has been sanitized.
  1526. *
  1527. * This filter is called before the user is created or updated.
  1528. *
  1529. * @since 2.0.3
  1530. *
  1531. * @param string $sanitized_user_login Username after it has been sanitized.
  1532. */
  1533. $pre_user_login = apply_filters( 'pre_user_login', $sanitized_user_login );
  1534. //Remove any non-printable chars from the login string to see if we have ended up with an empty username
  1535. $user_login = trim( $pre_user_login );
  1536. if ( empty( $user_login ) ) {
  1537. return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') );
  1538. }
  1539. if ( ! $update && username_exists( $user_login ) ) {
  1540. return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
  1541. }
  1542. // If a nicename is provided, remove unsafe user characters before
  1543. // using it. Otherwise build a nicename from the user_login.
  1544. if ( ! empty( $userdata['user_nicename'] ) ) {
  1545. $user_nicename = sanitize_user( $userdata['user_nicename'], true );
  1546. } else {
  1547. $user_nicename = $user_login;
  1548. }
  1549. $user_nicename = sanitize_title( $user_nicename );
  1550. // Store values to save in user meta.
  1551. $meta = array();
  1552. /**
  1553. * Filter a user's nicename before the user is created or updated.
  1554. *
  1555. * @since 2.0.3
  1556. *
  1557. * @param string $user_nicename The user's nicename.
  1558. */
  1559. $user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );
  1560. $raw_user_url = empty( $userdata['user_url'] ) ? '' : $userdata['user_url'];
  1561. /**
  1562. * Filter a user's URL before the user is created or updated.
  1563. *
  1564. * @since 2.0.3
  1565. *
  1566. * @param string $raw_user_url The user's URL.
  1567. */
  1568. $user_url = apply_filters( 'pre_user_url', $raw_user_url );
  1569. $raw_user_email = empty( $userdata['user_email'] ) ? '' : $userdata['user_email'];
  1570. /**
  1571. * Filter a user's email before the user is created or updated.
  1572. *
  1573. * @since 2.0.3
  1574. *
  1575. * @param string $raw_user_email The user's email.
  1576. */
  1577. $user_email = apply_filters( 'pre_user_email', $raw_user_email );
  1578. if ( ! $update && ! defined( 'WP_IMPORTING' ) && email_exists( $user_email ) ) {
  1579. return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
  1580. }
  1581. $nickname = empty( $userdata['nickname'] ) ? $user_login : $userdata['nickname'];
  1582. /**
  1583. * Filter a user's nickname before the user is created or updated.
  1584. *
  1585. * @since 2.0.3
  1586. *
  1587. * @param string $nickname The user's nickname.
  1588. */
  1589. $meta['nickname'] = apply_filters( 'pre_user_nickname', $nickname );
  1590. $first_name = empty( $userdata['first_name'] ) ? '' : $userdata['first_name'];
  1591. /**
  1592. * Filter a user's first name before the user is created or updated.
  1593. *
  1594. * @since 2.0.3
  1595. *
  1596. * @param string $first_name The user's first name.
  1597. */
  1598. $meta['first_name'] = apply_filters( 'pre_user_first_name', $first_name );
  1599. $last_name = empty( $userdata['last_name'] ) ? '' : $userdata['last_name'];
  1600. /**
  1601. * Filter a user's last name before the user is created or updated.
  1602. *
  1603. * @since 2.0.3
  1604. *
  1605. * @param string $last_name The user's last name.
  1606. */
  1607. $meta['last_name'] = apply_filters( 'pre_user_last_name', $last_name );
  1608. if ( empty( $userdata['display_name'] ) ) {
  1609. if ( $update ) {
  1610. $display_name = $user_login;
  1611. } elseif ( $meta['first_name'] && $meta['last_name'] ) {
  1612. /* translators: 1: first name, 2: last name */
  1613. $display_name = sprintf( _x( '%1$s %2$s', 'Display name based on first name and last name' ), $meta['first_name'], $meta['last_name'] );
  1614. } elseif ( $meta['first_name'] ) {
  1615. $display_name = $meta['first_name'];
  1616. } elseif ( $meta['last_name'] ) {
  1617. $display_name = $meta['last_name'];
  1618. } else {
  1619. $display_name = $user_login;
  1620. }
  1621. } else {
  1622. $display_name = $userdata['display_name'];
  1623. }
  1624. /**
  1625. * Filter a user's display name before the user is created or updated.
  1626. *
  1627. * @since 2.0.3
  1628. *
  1629. * @param string $display_name The user's display name.
  1630. */
  1631. $display_name = apply_filters( 'pre_user_display_name', $display_name );
  1632. $description = empty( $userdata['description'] ) ? '' : $userdata['description'];
  1633. /**
  1634. * Filter a user's description before the user is created or updated.
  1635. *
  1636. * @since 2.0.3
  1637. *
  1638. * @param string $description The user's description.
  1639. */
  1640. $meta['description'] = apply_filters( 'pre_user_description', $description );
  1641. $meta['rich_editing'] = empty( $userdata['rich_editing'] ) ? 'true' : $userdata['rich_editing'];
  1642. $meta['comment_shortcuts'] = empty( $userdata['comment_shortcuts'] ) ? 'false' : $userdata['comment_shortcuts'];
  1643. $admin_color = empty( $userdata['admin_color'] ) ? 'fresh' : $userdata['admin_color'];
  1644. $meta['admin_color'] = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $admin_color );
  1645. $meta['use_ssl'] = empty( $userdata['use_ssl'] ) ? 0 : $userdata['use_ssl'];
  1646. $user_registered = empty( $userdata['user_registered'] ) ? gmdate( 'Y-m-d H:i:s' ) : $userdata['user_registered'];
  1647. $meta['show_admin_bar_front'] = empty( $userdata['show_admin_bar_front'] ) ? 'true' : $userdata['show_admin_bar_front'];
  1648. $user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $user_nicename, $user_login));
  1649. if ( $user_nicename_check ) {
  1650. $suffix = 2;
  1651. while ($user_nicename_check) {
  1652. $alt_user_nicename = $user_nicename . "-$suffix";
  1653. $user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $alt_user_nicename, $user_login));
  1654. $suffix++;
  1655. }
  1656. $user_nicename = $alt_user_nicename;
  1657. }
  1658. $compacted = compact( 'user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered' );
  1659. $data = wp_unslash( $compacted );
  1660. if ( $update ) {
  1661. if ( $user_email !== $old_user_data->user_email ) {
  1662. $data['user_activation_key'] = '';
  1663. }
  1664. $wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
  1665. $user_id = (int) $ID;
  1666. } else {
  1667. $wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) );
  1668. $user_id = (int) $wpdb->insert_id;
  1669. }
  1670. $user = new WP_User( $user_id );
  1671. // Update user meta.
  1672. foreach ( $meta as $key => $value ) {
  1673. update_user_meta( $user_id, $key, $value );
  1674. }
  1675. foreach ( wp_get_user_contact_methods( $user ) as $key => $value ) {
  1676. if ( isset( $userdata[ $key ] ) ) {
  1677. update_user_meta( $user_id, $key, $userdata[ $key ] );
  1678. }
  1679. }
  1680. if ( isset( $userdata['role'] ) ) {
  1681. $user->set_role( $userdata['role'] );
  1682. } elseif ( ! $update ) {
  1683. $user->set_role(get_option('default_role'));
  1684. }
  1685. wp_cache_delete( $user_id, 'users' );
  1686. wp_cache_delete( $user_login, 'userlogins' );
  1687. if ( $update ) {
  1688. /**
  1689. * Fires immediately after an existing user is updated.
  1690. *
  1691. * @since 2.0.0
  1692. *
  1693. * @param int $user_id User ID.
  1694. * @param object $old_user_data Object containing user's data prior to update.
  1695. */
  1696. do_action( 'profile_update', $user_id, $old_user_data );
  1697. } else {
  1698. /**
  1699. * Fires immediately after a new user is registered.
  1700. *
  1701. * @since 1.5.0
  1702. *
  1703. * @param int $user_id User ID.
  1704. */
  1705. do_action( 'user_register', $user_id );
  1706. }
  1707. return $user_id;
  1708. }
  1709. /**
  1710. * Update an user in the database.
  1711. *
  1712. * It is possible to update a user's password by specifying the 'user_pass'
  1713. * value in the $userdata parameter array.
  1714. *
  1715. * If current user's password is being updated, then the cookies will be
  1716. * cleared.
  1717. *
  1718. * @since 2.0.0
  1719. *
  1720. * @see wp_insert_user() For what fields can be set in $userdata.
  1721. *
  1722. * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User.
  1723. * @return int|WP_Error The updated user's ID or a WP_Error object if the user could not be updated.
  1724. */
  1725. function wp_update_user($userdata) {
  1726. if ( is_a( $userdata, 'stdClass' ) )
  1727. $userdata = get_object_vars( $userdata );
  1728. elseif ( is_a( $userdata, 'WP_User' ) )
  1729. $userdata = $userdata->to_array();
  1730. $ID = (int) $userdata['ID'];
  1731. // First, get all of the original fields
  1732. $user_obj = get_userdata( $ID );
  1733. if ( ! $user_obj )
  1734. return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
  1735. $user = $user_obj->to_array();
  1736. // Add additional custom fields
  1737. foreach ( _get_additional_user_keys( $user_obj ) as $key ) {
  1738. $user[ $key ] = get_user_meta( $ID, $key, true );
  1739. }
  1740. // Escape data pulled from DB.
  1741. $user = add_magic_quotes( $user );
  1742. // If password is changing, hash it now.
  1743. if ( ! empty($userdata['user_pass']) ) {
  1744. $plaintext_pass = $userdata['user_pass'];
  1745. $userdata['user_pass'] = wp_hash_password($userdata['user_pass']);
  1746. }
  1747. wp_cache_delete($user[ 'user_email' ], 'useremail');
  1748. // Merge old and new fields with new fields overwriting old ones.
  1749. $userdata = array_merge($user, $userdata);
  1750. $user_id = wp_insert_user($userdata);
  1751. // Update the cookies if the password changed.
  1752. $current_user = wp_get_current_user();
  1753. if ( $current_user->ID == $ID ) {
  1754. if ( isset($plaintext_pass) ) {
  1755. wp_clear_auth_cookie();
  1756. // Here we calculate the expiration length of the current auth cookie and compare it to the default expiration.
  1757. // If it's greater than this, then we know the user checked 'Remember Me' when they logged in.
  1758. $logged_in_cookie = wp_parse_auth_cookie( '', 'logged_in' );
  1759. /** This filter is documented in wp-includes/pluggable.php */
  1760. $default_cookie_life = apply_filters( 'auth_cookie_expiration', ( 2 * DAY_IN_SECONDS ), $ID, false );
  1761. $remember = ( ( $logged_in_cookie['expiration'] - time() ) > $default_cookie_life );
  1762. wp_set_auth_cookie( $ID, $remember );
  1763. }
  1764. }
  1765. return $user_id;
  1766. }
  1767. /**
  1768. * A simpler way of inserting an user into the database.
  1769. *
  1770. * Creates a new user with just the username, password, and email. For more
  1771. * complex user creation use {@see wp_insert_user()} to specify more information.
  1772. *
  1773. * @since 2.0.0
  1774. * @see wp_insert_user() More complete way to create a new user
  1775. *
  1776. * @param string $username The user's username.
  1777. * @param string $password The user's password.
  1778. * @param string $email Optional. The user's email. Default empty.
  1779. * @return int The new user's ID.
  1780. */
  1781. function wp_create_user($username, $password, $email = '') {
  1782. $user_login = wp_slash( $username );
  1783. $user_email = wp_slash( $email );
  1784. $user_pass = $password;
  1785. $userdata = compact('user_login', 'user_email', 'user_pass');
  1786. return wp_insert_user($userdata);
  1787. }
  1788. /**
  1789. * Return a list of meta keys that wp_insert_user() is supposed to set.
  1790. *
  1791. * @since 3.3.0
  1792. * @access private
  1793. *
  1794. * @param WP_User $user WP_User instance.
  1795. * @return array
  1796. */
  1797. function _get_additional_user_keys( $user ) {
  1798. $keys = array( 'first_name', 'last_name', 'nickname', 'description', 'rich_editing', 'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front' );
  1799. return array_merge( $keys, array_keys( wp_get_user_contact_methods( $user ) ) );
  1800. }
  1801. /**
  1802. * Set up the user contact methods.
  1803. *
  1804. * Default contact methods were removed in 3.6. A filter dictates contact methods.
  1805. *
  1806. * @since 3.7.0
  1807. *
  1808. * @param WP_User $user Optional. WP_User object.
  1809. * @return array Array of contact methods and their labels.
  1810. */
  1811. function wp_get_user_contact_methods( $user = null ) {
  1812. $methods = array();
  1813. if ( get_site_option( 'initial_db_version' ) < 23588 ) {
  1814. $methods = array(
  1815. 'aim' => __( 'AIM' ),
  1816. 'yim' => __( 'Yahoo IM' ),
  1817. 'jabber' => __( 'Jabber / Google Talk' )
  1818. );
  1819. }
  1820. /**
  1821. * Filter the user contact methods.
  1822. *
  1823. * @since 2.9.0
  1824. *
  1825. * @param array $methods Array of contact methods and their labels.
  1826. * @param WP_User $user WP_User object.
  1827. */
  1828. return apply_filters( 'user_contactmethods', $methods, $user );
  1829. }
  1830. /**
  1831. * The old private function for setting up user contact methods.
  1832. *
  1833. * @since 2.9.0
  1834. * @access private
  1835. */
  1836. function _wp_get_user_contactmethods( $user = null ) {
  1837. return wp_get_user_contact_methods( $user );
  1838. }
  1839. /**
  1840. * Gets the text suggesting how to create strong passwords.
  1841. *
  1842. * @since 4.1.0
  1843. *
  1844. * @return string The password hint text.
  1845. */
  1846. function wp_get_password_hint() {
  1847. $hint = __( 'Hint: The password should be at least seven characters long. To make it stronger, use upper and lower case letters, numbers, and symbols like ! " ? $ % ^ &amp; ).' );
  1848. /**
  1849. * Filter the text describing the site's password complexity policy.
  1850. *
  1851. * @since 4.1.0
  1852. *
  1853. * @param string $hint The password hint text.
  1854. */
  1855. return apply_filters( 'password_hint', $hint );
  1856. }
  1857. /**
  1858. * Retrieves a user row based on password reset key and login
  1859. *
  1860. * A key is considered 'expired' if it exactly matches the value of the
  1861. * user_activation_key field, rather than being matched after going through the
  1862. * hashing process. This field is now hashed; old values are no longer accepted
  1863. * but have a different WP_Error code so good user feedback can be provided.
  1864. *
  1865. * @global wpdb $wpdb WordPress database object for queries.
  1866. *
  1867. * @param string $key Hash to validate sending user's password.
  1868. * @param string $login The user login.
  1869. * @return WP_User|WP_Error WP_User object on success, WP_Error object for invalid or expired keys.
  1870. */
  1871. function check_password_reset_key($key, $login) {
  1872. global $wpdb, $wp_hasher;
  1873. $key = preg_replace('/[^a-z0-9]/i', '', $key);
  1874. if ( empty( $key ) || !is_string( $key ) )
  1875. return new WP_Error('invalid_key', __('Invalid key'));
  1876. if ( empty($login) || !is_string($login) )
  1877. return new WP_Error('invalid_key', __('Invalid key'));
  1878. $row = $wpdb->get_row( $wpdb->prepare( "SELECT ID, user_activation_key FROM $wpdb->users WHERE user_login = %s", $login ) );
  1879. if ( ! $row )
  1880. return new WP_Error('invalid_key', __('Invalid key'));
  1881. if ( empty( $wp_hasher ) ) {
  1882. require_once ABSPATH . WPINC . '/class-phpass.php';
  1883. $wp_hasher = new PasswordHash( 8, true );
  1884. }
  1885. if ( $wp_hasher->CheckPassword( $key, $row->user_activation_key ) )
  1886. return get_userdata( $row->ID );
  1887. if ( $key === $row->user_activation_key ) {
  1888. $return = new WP_Error( 'expired_key', __( 'Invalid key' ) );
  1889. $user_id = $row->ID;
  1890. /**
  1891. * Filter the return value of check_password_reset_key() when an
  1892. * old-style key is used (plain-text key was stored in the database).
  1893. *
  1894. * @since 3.7.0
  1895. *
  1896. * @param WP_Error $return A WP_Error object denoting an expired key.
  1897. * Return a WP_User object to validate the key.
  1898. * @param int $user_id The matched user ID.
  1899. */
  1900. return apply_filters( 'password_reset_key_expired', $return, $user_id );
  1901. }
  1902. return new WP_Error( 'invalid_key', __( 'Invalid key' ) );
  1903. }
  1904. /**
  1905. * Handles resetting the user's password.
  1906. *
  1907. * @param object $user The user
  1908. * @param string $new_pass New password for the user in plaintext
  1909. */
  1910. function reset_password( $user, $new_pass ) {
  1911. /**
  1912. * Fires before the user's password is reset.
  1913. *
  1914. * @since 1.5.0
  1915. *
  1916. * @param object $user The user.
  1917. * @param string $new_pass New user password.
  1918. */
  1919. do_action( 'password_reset', $user, $new_pass );
  1920. wp_set_password( $new_pass, $user->ID );
  1921. update_user_option( $user->ID, 'default_password_nag', false, true );
  1922. wp_password_change_notification( $user );
  1923. }
  1924. /**
  1925. * Handles registering a new user.
  1926. *
  1927. * @param string $user_login User's username for logging in
  1928. * @param string $user_email User's email address to send password and add
  1929. * @return int|WP_Error Either user's ID or error on failure.
  1930. */
  1931. function register_new_user( $user_login, $user_email ) {
  1932. $errors = new WP_Error();
  1933. $sanitized_user_login = sanitize_user( $user_login );
  1934. /**
  1935. * Filter the email address of a user being registered.
  1936. *
  1937. * @since 2.1.0
  1938. *
  1939. * @param string $user_email The email address of the new user.
  1940. */
  1941. $user_email = apply_filters( 'user_registration_email', $user_email );
  1942. // Check the username
  1943. if ( $sanitized_user_login == '' ) {
  1944. $errors->add( 'empty_username', __( '<strong>ERROR</strong>: Please enter a username.' ) );
  1945. } elseif ( ! validate_username( $user_login ) ) {
  1946. $errors->add( 'invalid_username', __( '<strong>ERROR</strong>: This username is invalid because it uses illegal characters. Please enter a valid username.' ) );
  1947. $sanitized_user_login = '';
  1948. } elseif ( username_exists( $sanitized_user_login ) ) {
  1949. $errors->add( 'username_exists', __( '<strong>ERROR</strong>: This username is already registered. Please choose another one.' ) );
  1950. }
  1951. // Check the e-mail address
  1952. if ( $user_email == '' ) {
  1953. $errors->add( 'empty_email', __( '<strong>ERROR</strong>: Please type your e-mail address.' ) );
  1954. } elseif ( ! is_email( $user_email ) ) {
  1955. $errors->add( 'invalid_email', __( '<strong>ERROR</strong>: The email address isn&#8217;t correct.' ) );
  1956. $user_email = '';
  1957. } elseif ( email_exists( $user_email ) ) {
  1958. $errors->add( 'email_exists', __( '<strong>ERROR</strong>: This email is already registered, please choose another one.' ) );
  1959. }
  1960. /**
  1961. * Fires when submitting registration form data, before the user is created.
  1962. *
  1963. * @since 2.1.0
  1964. *
  1965. * @param string $sanitized_user_login The submitted username after being sanitized.
  1966. * @param string $user_email The submitted email.
  1967. * @param WP_Error $errors Contains any errors with submitted username and email,
  1968. * e.g., an empty field, an invalid username or email,
  1969. * or an existing username or email.
  1970. */
  1971. do_action( 'register_post', $sanitized_user_login, $user_email, $errors );
  1972. /**
  1973. * Filter the errors encountered when a new user is being registered.
  1974. *
  1975. * The filtered WP_Error object may, for example, contain errors for an invalid
  1976. * or existing username or email address. A WP_Error object should always returned,
  1977. * but may or may not contain errors.
  1978. *
  1979. * If any errors are present in $errors, this will abort the user's registration.
  1980. *
  1981. * @since 2.1.0
  1982. *
  1983. * @param WP_Error $errors A WP_Error object containing any errors encountered
  1984. * during registration.
  1985. * @param string $sanitized_user_login User's username after it has been sanitized.
  1986. * @param string $user_email User's email.
  1987. */
  1988. $errors = apply_filters( 'registration_errors', $errors, $sanitized_user_login, $user_email );
  1989. if ( $errors->get_error_code() )
  1990. return $errors;
  1991. $user_pass = wp_generate_password( 12, false );
  1992. $user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email );
  1993. if ( ! $user_id || is_wp_error( $user_id ) ) {
  1994. $errors->add( 'registerfail', sprintf( __( '<strong>ERROR</strong>: Couldn&#8217;t register you&hellip; please contact the <a href="mailto:%s">webmaster</a> !' ), get_option( 'admin_email' ) ) );
  1995. return $errors;
  1996. }
  1997. update_user_option( $user_id, 'default_password_nag', true, true ); //Set up the Password change nag.
  1998. wp_new_user_notification( $user_id, $user_pass );
  1999. return $user_id;
  2000. }
  2001. /**
  2002. * Retrieve the current session token from the logged_in cookie.
  2003. *
  2004. * @since 4.0.0
  2005. *
  2006. * @return string Token.
  2007. */
  2008. function wp_get_session_token() {
  2009. $cookie = wp_parse_auth_cookie( '', 'logged_in' );
  2010. return ! empty( $cookie['token'] ) ? $cookie['token'] : '';
  2011. }
  2012. /**
  2013. * Retrieve a list of sessions for the current user.
  2014. *
  2015. * @since 4.0.0
  2016. * @return array Array of sessions.
  2017. */
  2018. function wp_get_all_sessions() {
  2019. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  2020. return $manager->get_all();
  2021. }
  2022. /**
  2023. * Remove the current session token from the database.
  2024. *
  2025. * @since 4.0.0
  2026. */
  2027. function wp_destroy_current_session() {
  2028. $token = wp_get_session_token();
  2029. if ( $token ) {
  2030. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  2031. $manager->destroy( $token );
  2032. }
  2033. }
  2034. /**
  2035. * Remove all but the current session token for the current user for the database.
  2036. *
  2037. * @since 4.0.0
  2038. */
  2039. function wp_destroy_other_sessions() {
  2040. $token = wp_get_session_token();
  2041. if ( $token ) {
  2042. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  2043. $manager->destroy_others( $token );
  2044. }
  2045. }
  2046. /**
  2047. * Remove all session tokens for the current user from the database.
  2048. *
  2049. * @since 4.0.0
  2050. */
  2051. function wp_destroy_all_sessions() {
  2052. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  2053. $manager->destroy_all();
  2054. }