PageRenderTime 59ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/APP/wp-includes/user.php

https://bitbucket.org/AFelipeTrujillo/goblog
PHP | 2072 lines | 883 code | 268 blank | 921 comment | 249 complexity | add9afdf35d75d49f0e96163dc5d0657 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1

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

  1. <?php
  2. /**
  3. * WordPress User API
  4. *
  5. * @package WordPress
  6. * @subpackage Users
  7. */
  8. /**
  9. * Authenticate user with remember capability.
  10. *
  11. * The credentials is an array that has 'user_login', 'user_password', and
  12. * 'remember' indices. If the credentials is not given, then the log in form
  13. * will be assumed and used if set.
  14. *
  15. * The various authentication cookies will be set by this function and will be
  16. * set for a longer period depending on if the 'remember' credential is set to
  17. * true.
  18. *
  19. * @since 2.5.0
  20. *
  21. * @param array $credentials Optional. User info in order to sign on.
  22. * @param bool $secure_cookie Optional. Whether to use secure cookie.
  23. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  24. */
  25. function wp_signon( $credentials = array(), $secure_cookie = '' ) {
  26. if ( empty($credentials) ) {
  27. if ( ! empty($_POST['log']) )
  28. $credentials['user_login'] = $_POST['log'];
  29. if ( ! empty($_POST['pwd']) )
  30. $credentials['user_password'] = $_POST['pwd'];
  31. if ( ! empty($_POST['rememberme']) )
  32. $credentials['remember'] = $_POST['rememberme'];
  33. }
  34. if ( !empty($credentials['remember']) )
  35. $credentials['remember'] = true;
  36. else
  37. $credentials['remember'] = false;
  38. /**
  39. * Fires before the user is authenticated.
  40. *
  41. * The variables passed to the callbacks are passed by reference,
  42. * and can be modified by callback functions.
  43. *
  44. * @since 1.5.1
  45. *
  46. * @todo Decide whether to deprecate the wp_authenticate action.
  47. *
  48. * @param string $user_login Username, passed by reference.
  49. * @param string $user_password User password, passed by reference.
  50. */
  51. do_action_ref_array( 'wp_authenticate', array( &$credentials['user_login'], &$credentials['user_password'] ) );
  52. if ( '' === $secure_cookie )
  53. $secure_cookie = is_ssl();
  54. /**
  55. * Filter whether to use a secure sign-on cookie.
  56. *
  57. * @since 3.1.0
  58. *
  59. * @param bool $secure_cookie Whether to use a secure sign-on cookie.
  60. * @param array $credentials {
  61. * Array of entered sign-on data.
  62. *
  63. * @type string $user_login Username.
  64. * @type string $user_password Password entered.
  65. * @type bool $remember Whether to 'remember' the user. Increases the time
  66. * that the cookie will be kept. Default false.
  67. * }
  68. */
  69. $secure_cookie = apply_filters( 'secure_signon_cookie', $secure_cookie, $credentials );
  70. global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
  71. $auth_secure_cookie = $secure_cookie;
  72. add_filter('authenticate', 'wp_authenticate_cookie', 30, 3);
  73. $user = wp_authenticate($credentials['user_login'], $credentials['user_password']);
  74. if ( is_wp_error($user) ) {
  75. if ( $user->get_error_codes() == array('empty_username', 'empty_password') ) {
  76. $user = new WP_Error('', '');
  77. }
  78. return $user;
  79. }
  80. wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
  81. /**
  82. * Fires after the user has successfully logged in.
  83. *
  84. * @since 1.5.0
  85. *
  86. * @param string $user_login Username.
  87. * @param WP_User $user WP_User object of the logged-in user.
  88. */
  89. do_action( 'wp_login', $user->user_login, $user );
  90. return $user;
  91. }
  92. /**
  93. * Authenticate the user using the username and password.
  94. *
  95. * @since 2.8.0
  96. *
  97. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  98. * @param string $username Username for authentication.
  99. * @param string $password Password for authentication.
  100. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  101. */
  102. function wp_authenticate_username_password($user, $username, $password) {
  103. if ( is_a( $user, 'WP_User' ) ) {
  104. return $user;
  105. }
  106. if ( empty($username) || empty($password) ) {
  107. if ( is_wp_error( $user ) )
  108. return $user;
  109. $error = new WP_Error();
  110. if ( empty($username) )
  111. $error->add('empty_username', __('<strong>ERROR</strong>: The username field is empty.'));
  112. if ( empty($password) )
  113. $error->add('empty_password', __('<strong>ERROR</strong>: The password field is empty.'));
  114. return $error;
  115. }
  116. $user = get_user_by('login', $username);
  117. if ( !$user )
  118. return new WP_Error( 'invalid_username', sprintf( __( '<strong>ERROR</strong>: Invalid username. <a href="%s" title="Password Lost and Found">Lost your password</a>?' ), wp_lostpassword_url() ) );
  119. /**
  120. * Filter whether the given user can be authenticated with the provided $password.
  121. *
  122. * @since 2.5.0
  123. *
  124. * @param WP_User|WP_Error $user WP_User or WP_Error object if a previous
  125. * callback failed authentication.
  126. * @param string $password Password to check against the user.
  127. */
  128. $user = apply_filters( 'wp_authenticate_user', $user, $password );
  129. if ( is_wp_error($user) )
  130. return $user;
  131. if ( !wp_check_password($password, $user->user_pass, $user->ID) )
  132. return new WP_Error( 'incorrect_password', sprintf( __( '<strong>ERROR</strong>: The password you entered for the username <strong>%1$s</strong> is incorrect. <a href="%2$s" title="Password Lost and Found">Lost your password</a>?' ),
  133. $username, wp_lostpassword_url() ) );
  134. return $user;
  135. }
  136. /**
  137. * Authenticate the user using the WordPress auth cookie.
  138. *
  139. * @since 2.8.0
  140. *
  141. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  142. * @param string $username Username. If not empty, cancels the cookie authentication.
  143. * @param string $password Password. If not empty, cancels the cookie authentication.
  144. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  145. */
  146. function wp_authenticate_cookie($user, $username, $password) {
  147. if ( is_a( $user, 'WP_User' ) ) {
  148. return $user;
  149. }
  150. if ( empty($username) && empty($password) ) {
  151. $user_id = wp_validate_auth_cookie();
  152. if ( $user_id )
  153. return new WP_User($user_id);
  154. global $auth_secure_cookie;
  155. if ( $auth_secure_cookie )
  156. $auth_cookie = SECURE_AUTH_COOKIE;
  157. else
  158. $auth_cookie = AUTH_COOKIE;
  159. if ( !empty($_COOKIE[$auth_cookie]) )
  160. return new WP_Error('expired_session', __('Please log in again.'));
  161. // If the cookie is not set, be silent.
  162. }
  163. return $user;
  164. }
  165. /**
  166. * For Multisite blogs, check if the authenticated user has been marked as a
  167. * spammer, or if the user's primary blog has been marked as spam.
  168. *
  169. * @since 3.7.0
  170. *
  171. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  172. * @return WP_User|WP_Error WP_User on success, WP_Error if the user is considered a spammer.
  173. */
  174. function wp_authenticate_spam_check( $user ) {
  175. if ( $user && is_a( $user, 'WP_User' ) && is_multisite() ) {
  176. /**
  177. * Filter whether the user has been marked as a spammer.
  178. *
  179. * @since 3.7.0
  180. *
  181. * @param bool $spammed Whether the user is considered a spammer.
  182. * @param WP_User $user User to check against.
  183. */
  184. $spammed = apply_filters( 'check_is_user_spammed', is_user_spammy(), $user );
  185. if ( $spammed )
  186. return new WP_Error( 'spammer_account', __( '<strong>ERROR</strong>: Your account has been marked as a spammer.' ) );
  187. }
  188. return $user;
  189. }
  190. /**
  191. * Validate the logged-in cookie.
  192. *
  193. * Checks the logged-in cookie if the previous auth cookie could not be
  194. * validated and parsed.
  195. *
  196. * This is a callback for the determine_current_user filter, rather than API.
  197. *
  198. * @since 3.9.0
  199. *
  200. * @param int|bool $user The user ID (or false) as received from the
  201. * determine_current_user filter.
  202. * @return int|bool User ID if validated, false otherwise. If a user ID from
  203. * an earlier filter callback is received, that value is returned.
  204. */
  205. function wp_validate_logged_in_cookie( $user_id ) {
  206. if ( $user_id ) {
  207. return $user_id;
  208. }
  209. if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[LOGGED_IN_COOKIE] ) ) {
  210. return false;
  211. }
  212. return wp_validate_auth_cookie( $_COOKIE[LOGGED_IN_COOKIE], 'logged_in' );
  213. }
  214. /**
  215. * Number of posts user has written.
  216. *
  217. * @since 3.0.0
  218. *
  219. * @global wpdb $wpdb WordPress database object for queries.
  220. *
  221. * @param int $userid User ID.
  222. * @return int Amount of posts user has written.
  223. */
  224. function count_user_posts($userid) {
  225. global $wpdb;
  226. $where = get_posts_by_author_sql('post', true, $userid);
  227. $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
  228. /**
  229. * Filter the number of posts a user has written.
  230. *
  231. * @since 2.7.0
  232. *
  233. * @param int $count The user's post count.
  234. * @param int $userid User ID.
  235. */
  236. return apply_filters( 'get_usernumposts', $count, $userid );
  237. }
  238. /**
  239. * Number of posts written by a list of users.
  240. *
  241. * @since 3.0.0
  242. *
  243. * @param array $users Array of user IDs.
  244. * @param string $post_type Optional. Post type to check. Defaults to post.
  245. * @param bool $public_only Optional. Only return counts for public posts. Defaults to false.
  246. * @return array Amount of posts each user has written.
  247. */
  248. function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
  249. global $wpdb;
  250. $count = array();
  251. if ( empty( $users ) || ! is_array( $users ) )
  252. return $count;
  253. $userlist = implode( ',', array_map( 'absint', $users ) );
  254. $where = get_posts_by_author_sql( $post_type, true, null, $public_only );
  255. $result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
  256. foreach ( $result as $row ) {
  257. $count[ $row[0] ] = $row[1];
  258. }
  259. foreach ( $users as $id ) {
  260. if ( ! isset( $count[ $id ] ) )
  261. $count[ $id ] = 0;
  262. }
  263. return $count;
  264. }
  265. //
  266. // User option functions
  267. //
  268. /**
  269. * Get the current user's ID
  270. *
  271. * @since MU
  272. *
  273. * @uses wp_get_current_user
  274. *
  275. * @return int The current user's ID
  276. */
  277. function get_current_user_id() {
  278. if ( ! function_exists( 'wp_get_current_user' ) )
  279. return 0;
  280. $user = wp_get_current_user();
  281. return ( isset( $user->ID ) ? (int) $user->ID : 0 );
  282. }
  283. /**
  284. * Retrieve user option that can be either per Site or per Network.
  285. *
  286. * If the user ID is not given, then the current user will be used instead. If
  287. * the user ID is given, then the user data will be retrieved. The filter for
  288. * the result, will also pass the original option name and finally the user data
  289. * object as the third parameter.
  290. *
  291. * The option will first check for the per site name and then the per Network name.
  292. *
  293. * @since 2.0.0
  294. *
  295. * @global wpdb $wpdb WordPress database object for queries.
  296. *
  297. * @param string $option User option name.
  298. * @param int $user Optional. User ID.
  299. * @param bool $deprecated Use get_option() to check for an option in the options table.
  300. * @return mixed User option value on success, false on failure.
  301. */
  302. function get_user_option( $option, $user = 0, $deprecated = '' ) {
  303. global $wpdb;
  304. if ( !empty( $deprecated ) )
  305. _deprecated_argument( __FUNCTION__, '3.0' );
  306. if ( empty( $user ) )
  307. $user = get_current_user_id();
  308. if ( ! $user = get_userdata( $user ) )
  309. return false;
  310. $prefix = $wpdb->get_blog_prefix();
  311. if ( $user->has_prop( $prefix . $option ) ) // Blog specific
  312. $result = $user->get( $prefix . $option );
  313. elseif ( $user->has_prop( $option ) ) // User specific and cross-blog
  314. $result = $user->get( $option );
  315. else
  316. $result = false;
  317. /**
  318. * Filter a specific user option value.
  319. *
  320. * The dynamic portion of the hook name, $option, refers to the user option name.
  321. *
  322. * @since 2.5.0
  323. *
  324. * @param mixed $result Value for the user's option.
  325. * @param string $option Name of the option being retrieved.
  326. * @param WP_User $user WP_User object of the user whose option is being retrieved.
  327. */
  328. return apply_filters( "get_user_option_{$option}", $result, $option, $user );
  329. }
  330. /**
  331. * Update user option with global blog capability.
  332. *
  333. * User options are just like user metadata except that they have support for
  334. * global blog options. If the 'global' parameter is false, which it is by default
  335. * it will prepend the WordPress table prefix to the option name.
  336. *
  337. * Deletes the user option if $newvalue is empty.
  338. *
  339. * @since 2.0.0
  340. *
  341. * @global wpdb $wpdb WordPress database object for queries.
  342. *
  343. * @param int $user_id User ID.
  344. * @param string $option_name User option name.
  345. * @param mixed $newvalue User option value.
  346. * @param bool $global Optional. Whether option name is global or blog specific.
  347. * Default false (blog specific).
  348. * @return int|bool User meta ID if the option didn't exist, true on successful update,
  349. * false on failure.
  350. */
  351. function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
  352. global $wpdb;
  353. if ( !$global )
  354. $option_name = $wpdb->get_blog_prefix() . $option_name;
  355. return update_user_meta( $user_id, $option_name, $newvalue );
  356. }
  357. /**
  358. * Delete user option with global blog capability.
  359. *
  360. * User options are just like user metadata except that they have support for
  361. * global blog options. If the 'global' parameter is false, which it is by default
  362. * it will prepend the WordPress table prefix to the option name.
  363. *
  364. * @since 3.0.0
  365. *
  366. * @global wpdb $wpdb WordPress database object for queries.
  367. *
  368. * @param int $user_id User ID
  369. * @param string $option_name User option name.
  370. * @param bool $global Optional. Whether option name is global or blog specific.
  371. * Default false (blog specific).
  372. * @return bool True on success, false on failure.
  373. */
  374. function delete_user_option( $user_id, $option_name, $global = false ) {
  375. global $wpdb;
  376. if ( !$global )
  377. $option_name = $wpdb->get_blog_prefix() . $option_name;
  378. return delete_user_meta( $user_id, $option_name );
  379. }
  380. /**
  381. * WordPress User Query class.
  382. *
  383. * @since 3.1.0
  384. */
  385. class WP_User_Query {
  386. /**
  387. * Query vars, after parsing
  388. *
  389. * @since 3.5.0
  390. * @access public
  391. * @var array
  392. */
  393. var $query_vars = array();
  394. /**
  395. * List of found user ids
  396. *
  397. * @since 3.1.0
  398. * @access private
  399. * @var array
  400. */
  401. var $results;
  402. /**
  403. * Total number of found users for the current query
  404. *
  405. * @since 3.1.0
  406. * @access private
  407. * @var int
  408. */
  409. var $total_users = 0;
  410. // SQL clauses
  411. var $query_fields;
  412. var $query_from;
  413. var $query_where;
  414. var $query_orderby;
  415. var $query_limit;
  416. /**
  417. * PHP5 constructor.
  418. *
  419. * @since 3.1.0
  420. *
  421. * @param string|array $args Optional. The query variables.
  422. * @return WP_User_Query
  423. */
  424. function __construct( $query = null ) {
  425. if ( ! empty( $query ) ) {
  426. $this->prepare_query( $query );
  427. $this->query();
  428. }
  429. }
  430. /**
  431. * Prepare the query variables.
  432. *
  433. * @since 3.1.0
  434. *
  435. * @param string|array $args Optional. The query variables.
  436. */
  437. function prepare_query( $query = array() ) {
  438. global $wpdb;
  439. if ( empty( $this->query_vars ) || ! empty( $query ) ) {
  440. $this->query_limit = null;
  441. $this->query_vars = wp_parse_args( $query, array(
  442. 'blog_id' => $GLOBALS['blog_id'],
  443. 'role' => '',
  444. 'meta_key' => '',
  445. 'meta_value' => '',
  446. 'meta_compare' => '',
  447. 'include' => array(),
  448. 'exclude' => array(),
  449. 'search' => '',
  450. 'search_columns' => array(),
  451. 'orderby' => 'login',
  452. 'order' => 'ASC',
  453. 'offset' => '',
  454. 'number' => '',
  455. 'count_total' => true,
  456. 'fields' => 'all',
  457. 'who' => ''
  458. ) );
  459. }
  460. $qv =& $this->query_vars;
  461. if ( is_array( $qv['fields'] ) ) {
  462. $qv['fields'] = array_unique( $qv['fields'] );
  463. $this->query_fields = array();
  464. foreach ( $qv['fields'] as $field ) {
  465. $field = 'ID' === $field ? 'ID' : sanitize_key( $field );
  466. $this->query_fields[] = "$wpdb->users.$field";
  467. }
  468. $this->query_fields = implode( ',', $this->query_fields );
  469. } elseif ( 'all' == $qv['fields'] ) {
  470. $this->query_fields = "$wpdb->users.*";
  471. } else {
  472. $this->query_fields = "$wpdb->users.ID";
  473. }
  474. if ( isset( $qv['count_total'] ) && $qv['count_total'] )
  475. $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
  476. $this->query_from = "FROM $wpdb->users";
  477. $this->query_where = "WHERE 1=1";
  478. // sorting
  479. if ( isset( $qv['orderby'] ) ) {
  480. if ( in_array( $qv['orderby'], array('nicename', 'email', 'url', 'registered') ) ) {
  481. $orderby = 'user_' . $qv['orderby'];
  482. } elseif ( in_array( $qv['orderby'], array('user_nicename', 'user_email', 'user_url', 'user_registered') ) ) {
  483. $orderby = $qv['orderby'];
  484. } elseif ( 'name' == $qv['orderby'] || 'display_name' == $qv['orderby'] ) {
  485. $orderby = 'display_name';
  486. } elseif ( 'post_count' == $qv['orderby'] ) {
  487. // todo: avoid the JOIN
  488. $where = get_posts_by_author_sql('post');
  489. $this->query_from .= " LEFT OUTER JOIN (
  490. SELECT post_author, COUNT(*) as post_count
  491. FROM $wpdb->posts
  492. $where
  493. GROUP BY post_author
  494. ) p ON ({$wpdb->users}.ID = p.post_author)
  495. ";
  496. $orderby = 'post_count';
  497. } elseif ( 'ID' == $qv['orderby'] || 'id' == $qv['orderby'] ) {
  498. $orderby = 'ID';
  499. } elseif ( 'meta_value' == $qv['orderby'] ) {
  500. $orderby = "$wpdb->usermeta.meta_value";
  501. } else {
  502. $orderby = 'user_login';
  503. }
  504. }
  505. if ( empty( $orderby ) )
  506. $orderby = 'user_login';
  507. $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
  508. if ( 'ASC' == $qv['order'] )
  509. $order = 'ASC';
  510. else
  511. $order = 'DESC';
  512. $this->query_orderby = "ORDER BY $orderby $order";
  513. // limit
  514. if ( isset( $qv['number'] ) && $qv['number'] ) {
  515. if ( $qv['offset'] )
  516. $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
  517. else
  518. $this->query_limit = $wpdb->prepare("LIMIT %d", $qv['number']);
  519. }
  520. $search = '';
  521. if ( isset( $qv['search'] ) )
  522. $search = trim( $qv['search'] );
  523. if ( $search ) {
  524. $leading_wild = ( ltrim($search, '*') != $search );
  525. $trailing_wild = ( rtrim($search, '*') != $search );
  526. if ( $leading_wild && $trailing_wild )
  527. $wild = 'both';
  528. elseif ( $leading_wild )
  529. $wild = 'leading';
  530. elseif ( $trailing_wild )
  531. $wild = 'trailing';
  532. else
  533. $wild = false;
  534. if ( $wild )
  535. $search = trim($search, '*');
  536. $search_columns = array();
  537. if ( $qv['search_columns'] )
  538. $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename' ) );
  539. if ( ! $search_columns ) {
  540. if ( false !== strpos( $search, '@') )
  541. $search_columns = array('user_email');
  542. elseif ( is_numeric($search) )
  543. $search_columns = array('user_login', 'ID');
  544. elseif ( preg_match('|^https?://|', $search) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) )
  545. $search_columns = array('user_url');
  546. else
  547. $search_columns = array('user_login', 'user_nicename');
  548. }
  549. /**
  550. * Filter the columns to search in a WP_User_Query search.
  551. *
  552. * The default columns depend on the search term, and include 'user_email',
  553. * 'user_login', 'ID', 'user_url', and 'user_nicename'.
  554. *
  555. * @since 3.6.0
  556. *
  557. * @param array $search_columns Array of column names to be searched.
  558. * @param string $search Text being searched.
  559. * @param WP_User_Query $this The current WP_User_Query instance.
  560. */
  561. $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
  562. $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
  563. }
  564. $blog_id = 0;
  565. if ( isset( $qv['blog_id'] ) )
  566. $blog_id = absint( $qv['blog_id'] );
  567. if ( isset( $qv['who'] ) && 'authors' == $qv['who'] && $blog_id ) {
  568. $qv['meta_key'] = $wpdb->get_blog_prefix( $blog_id ) . 'user_level';
  569. $qv['meta_value'] = 0;
  570. $qv['meta_compare'] = '!=';
  571. $qv['blog_id'] = $blog_id = 0; // Prevent extra meta query
  572. }
  573. $role = '';
  574. if ( isset( $qv['role'] ) )
  575. $role = trim( $qv['role'] );
  576. if ( $blog_id && ( $role || is_multisite() ) ) {
  577. $cap_meta_query = array();
  578. $cap_meta_query['key'] = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities';
  579. if ( $role ) {
  580. $cap_meta_query['value'] = '"' . $role . '"';
  581. $cap_meta_query['compare'] = 'like';
  582. }
  583. if ( empty( $qv['meta_query'] ) || ! in_array( $cap_meta_query, $qv['meta_query'], true ) ) {
  584. $qv['meta_query'][] = $cap_meta_query;
  585. }
  586. }
  587. $meta_query = new WP_Meta_Query();
  588. $meta_query->parse_query_vars( $qv );
  589. if ( !empty( $meta_query->queries ) ) {
  590. $clauses = $meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
  591. $this->query_from .= $clauses['join'];
  592. $this->query_where .= $clauses['where'];
  593. if ( 'OR' == $meta_query->relation )
  594. $this->query_fields = 'DISTINCT ' . $this->query_fields;
  595. }
  596. if ( ! empty( $qv['include'] ) ) {
  597. $ids = implode( ',', wp_parse_id_list( $qv['include'] ) );
  598. $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
  599. } elseif ( ! empty( $qv['exclude'] ) ) {
  600. $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
  601. $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
  602. }
  603. /**
  604. * Fires after the WP_User_Query has been parsed, and before
  605. * the query is executed.
  606. *
  607. * The passed WP_User_Query object contains SQL parts formed
  608. * from parsing the given query.
  609. *
  610. * @since 3.1.0
  611. *
  612. * @param WP_User_Query $this The current WP_User_Query instance,
  613. * passed by reference.
  614. */
  615. do_action_ref_array( 'pre_user_query', array( &$this ) );
  616. }
  617. /**
  618. * Execute the query, with the current variables.
  619. *
  620. * @since 3.1.0
  621. *
  622. * @global wpdb $wpdb WordPress database object for queries.
  623. */
  624. function query() {
  625. global $wpdb;
  626. $qv =& $this->query_vars;
  627. $query = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
  628. if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
  629. $this->results = $wpdb->get_results( $query );
  630. } else {
  631. $this->results = $wpdb->get_col( $query );
  632. }
  633. /**
  634. * Filter SELECT FOUND_ROWS() query for the current WP_User_Query instance.
  635. *
  636. * @since 3.2.0
  637. *
  638. * @global wpdb $wpdb WordPress database object.
  639. *
  640. * @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
  641. */
  642. if ( isset( $qv['count_total'] ) && $qv['count_total'] )
  643. $this->total_users = $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) );
  644. if ( !$this->results )
  645. return;
  646. if ( 'all_with_meta' == $qv['fields'] ) {
  647. cache_users( $this->results );
  648. $r = array();
  649. foreach ( $this->results as $userid )
  650. $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
  651. $this->results = $r;
  652. } elseif ( 'all' == $qv['fields'] ) {
  653. foreach ( $this->results as $key => $user ) {
  654. $this->results[ $key ] = new WP_User( $user );
  655. }
  656. }
  657. }
  658. /**
  659. * Retrieve query variable.
  660. *
  661. * @since 3.5.0
  662. * @access public
  663. *
  664. * @param string $query_var Query variable key.
  665. * @return mixed
  666. */
  667. function get( $query_var ) {
  668. if ( isset( $this->query_vars[$query_var] ) )
  669. return $this->query_vars[$query_var];
  670. return null;
  671. }
  672. /**
  673. * Set query variable.
  674. *
  675. * @since 3.5.0
  676. * @access public
  677. *
  678. * @param string $query_var Query variable key.
  679. * @param mixed $value Query variable value.
  680. */
  681. function set( $query_var, $value ) {
  682. $this->query_vars[$query_var] = $value;
  683. }
  684. /**
  685. * Used internally to generate an SQL string for searching across multiple columns
  686. *
  687. * @access protected
  688. * @since 3.1.0
  689. *
  690. * @param string $string
  691. * @param array $cols
  692. * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for
  693. * single site. Single site allows leading and trailing wildcards, Network Admin only trailing.
  694. * @return string
  695. */
  696. function get_search_sql( $string, $cols, $wild = false ) {
  697. $string = esc_sql( $string );
  698. $searches = array();
  699. $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
  700. $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
  701. foreach ( $cols as $col ) {
  702. if ( 'ID' == $col )
  703. $searches[] = "$col = '$string'";
  704. else
  705. $searches[] = "$col LIKE '$leading_wild" . like_escape($string) . "$trailing_wild'";
  706. }
  707. return ' AND (' . implode(' OR ', $searches) . ')';
  708. }
  709. /**
  710. * Return the list of users.
  711. *
  712. * @since 3.1.0
  713. * @access public
  714. *
  715. * @return array Array of results.
  716. */
  717. function get_results() {
  718. return $this->results;
  719. }
  720. /**
  721. * Return the total number of users for the current query.
  722. *
  723. * @since 3.1.0
  724. * @access public
  725. *
  726. * @return array Array of total users.
  727. */
  728. function get_total() {
  729. return $this->total_users;
  730. }
  731. }
  732. /**
  733. * Retrieve list of users matching criteria.
  734. *
  735. * @since 3.1.0
  736. *
  737. * @uses WP_User_Query See for default arguments and information.
  738. *
  739. * @param array $args Optional. Array of arguments.
  740. * @return array List of users.
  741. */
  742. function get_users( $args = array() ) {
  743. $args = wp_parse_args( $args );
  744. $args['count_total'] = false;
  745. $user_search = new WP_User_Query($args);
  746. return (array) $user_search->get_results();
  747. }
  748. /**
  749. * Get the blogs a user belongs to.
  750. *
  751. * @since 3.0.0
  752. *
  753. * @global wpdb $wpdb WordPress database object for queries.
  754. *
  755. * @param int $user_id User ID
  756. * @param bool $all Whether to retrieve all blogs, or only blogs that are not
  757. * marked as deleted, archived, or spam.
  758. * @return array A list of the user's blogs. An empty array if the user doesn't exist
  759. * or belongs to no blogs.
  760. */
  761. function get_blogs_of_user( $user_id, $all = false ) {
  762. global $wpdb;
  763. $user_id = (int) $user_id;
  764. // Logged out users can't have blogs
  765. if ( empty( $user_id ) )
  766. return array();
  767. $keys = get_user_meta( $user_id );
  768. if ( empty( $keys ) )
  769. return array();
  770. if ( ! is_multisite() ) {
  771. $blog_id = get_current_blog_id();
  772. $blogs = array( $blog_id => new stdClass );
  773. $blogs[ $blog_id ]->userblog_id = $blog_id;
  774. $blogs[ $blog_id ]->blogname = get_option('blogname');
  775. $blogs[ $blog_id ]->domain = '';
  776. $blogs[ $blog_id ]->path = '';
  777. $blogs[ $blog_id ]->site_id = 1;
  778. $blogs[ $blog_id ]->siteurl = get_option('siteurl');
  779. $blogs[ $blog_id ]->archived = 0;
  780. $blogs[ $blog_id ]->spam = 0;
  781. $blogs[ $blog_id ]->deleted = 0;
  782. return $blogs;
  783. }
  784. $blogs = array();
  785. if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
  786. $blog = get_blog_details( 1 );
  787. if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
  788. $blogs[ 1 ] = (object) array(
  789. 'userblog_id' => 1,
  790. 'blogname' => $blog->blogname,
  791. 'domain' => $blog->domain,
  792. 'path' => $blog->path,
  793. 'site_id' => $blog->site_id,
  794. 'siteurl' => $blog->siteurl,
  795. 'archived' => 0,
  796. 'spam' => 0,
  797. 'deleted' => 0
  798. );
  799. }
  800. unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
  801. }
  802. $keys = array_keys( $keys );
  803. foreach ( $keys as $key ) {
  804. if ( 'capabilities' !== substr( $key, -12 ) )
  805. continue;
  806. if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) )
  807. continue;
  808. $blog_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
  809. if ( ! is_numeric( $blog_id ) )
  810. continue;
  811. $blog_id = (int) $blog_id;
  812. $blog = get_blog_details( $blog_id );
  813. if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
  814. $blogs[ $blog_id ] = (object) array(
  815. 'userblog_id' => $blog_id,
  816. 'blogname' => $blog->blogname,
  817. 'domain' => $blog->domain,
  818. 'path' => $blog->path,
  819. 'site_id' => $blog->site_id,
  820. 'siteurl' => $blog->siteurl,
  821. 'archived' => 0,
  822. 'spam' => 0,
  823. 'deleted' => 0
  824. );
  825. }
  826. }
  827. /**
  828. * Filter the list of blogs a user belongs to.
  829. *
  830. * @since MU
  831. *
  832. * @param array $blogs An array of blog objects belonging to the user.
  833. * @param int $user_id User ID.
  834. * @param bool $all Whether the returned blogs array should contain all blogs, including
  835. * those marked 'deleted', 'archived', or 'spam'. Default false.
  836. */
  837. return apply_filters( 'get_blogs_of_user', $blogs, $user_id, $all );
  838. }
  839. /**
  840. * Find out whether a user is a member of a given blog.
  841. *
  842. * @since MU 1.1
  843. * @uses get_blogs_of_user()
  844. *
  845. * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
  846. * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
  847. * @return bool
  848. */
  849. function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
  850. $user_id = (int) $user_id;
  851. $blog_id = (int) $blog_id;
  852. if ( empty( $user_id ) )
  853. $user_id = get_current_user_id();
  854. if ( empty( $blog_id ) )
  855. $blog_id = get_current_blog_id();
  856. $blogs = get_blogs_of_user( $user_id );
  857. return array_key_exists( $blog_id, $blogs );
  858. }
  859. /**
  860. * Add meta data field to a user.
  861. *
  862. * Post meta data is called "Custom Fields" on the Administration Screens.
  863. *
  864. * @since 3.0.0
  865. * @uses add_metadata()
  866. * @link http://codex.wordpress.org/Function_Reference/add_user_meta
  867. *
  868. * @param int $user_id User ID.
  869. * @param string $meta_key Metadata name.
  870. * @param mixed $meta_value Metadata value.
  871. * @param bool $unique Optional, default is false. Whether the same key should not be added.
  872. * @return int|bool Meta ID on success, false on failure.
  873. */
  874. function add_user_meta($user_id, $meta_key, $meta_value, $unique = false) {
  875. return add_metadata('user', $user_id, $meta_key, $meta_value, $unique);
  876. }
  877. /**
  878. * Remove metadata matching criteria from a user.
  879. *
  880. * You can match based on the key, or key and value. Removing based on key and
  881. * value, will keep from removing duplicate metadata with the same key. It also
  882. * allows removing all metadata matching key, if needed.
  883. *
  884. * @since 3.0.0
  885. * @uses delete_metadata()
  886. * @link http://codex.wordpress.org/Function_Reference/delete_user_meta
  887. *
  888. * @param int $user_id user ID
  889. * @param string $meta_key Metadata name.
  890. * @param mixed $meta_value Optional. Metadata value.
  891. * @return bool True on success, false on failure.
  892. */
  893. function delete_user_meta($user_id, $meta_key, $meta_value = '') {
  894. return delete_metadata('user', $user_id, $meta_key, $meta_value);
  895. }
  896. /**
  897. * Retrieve user meta field for a user.
  898. *
  899. * @since 3.0.0
  900. * @uses get_metadata()
  901. * @link http://codex.wordpress.org/Function_Reference/get_user_meta
  902. *
  903. * @param int $user_id User ID.
  904. * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
  905. * @param bool $single Whether to return a single value.
  906. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
  907. * is true.
  908. */
  909. function get_user_meta($user_id, $key = '', $single = false) {
  910. return get_metadata('user', $user_id, $key, $single);
  911. }
  912. /**
  913. * Update user meta field based on user ID.
  914. *
  915. * Use the $prev_value parameter to differentiate between meta fields with the
  916. * same key and user ID.
  917. *
  918. * If the meta field for the user does not exist, it will be added.
  919. *
  920. * @since 3.0.0
  921. * @uses update_metadata
  922. * @link http://codex.wordpress.org/Function_Reference/update_user_meta
  923. *
  924. * @param int $user_id User ID.
  925. * @param string $meta_key Metadata key.
  926. * @param mixed $meta_value Metadata value.
  927. * @param mixed $prev_value Optional. Previous value to check before removing.
  928. * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
  929. */
  930. function update_user_meta($user_id, $meta_key, $meta_value, $prev_value = '') {
  931. return update_metadata('user', $user_id, $meta_key, $meta_value, $prev_value);
  932. }
  933. /**
  934. * Count number of users who have each of the user roles.
  935. *
  936. * Assumes there are neither duplicated nor orphaned capabilities meta_values.
  937. * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
  938. * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
  939. * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
  940. *
  941. * @since 3.0.0
  942. * @param string $strategy 'time' or 'memory'
  943. * @return array Includes a grand total and an array of counts indexed by role strings.
  944. */
  945. function count_users($strategy = 'time') {
  946. global $wpdb, $wp_roles;
  947. // Initialize
  948. $id = get_current_blog_id();
  949. $blog_prefix = $wpdb->get_blog_prefix($id);
  950. $result = array();
  951. if ( 'time' == $strategy ) {
  952. global $wp_roles;
  953. if ( ! isset( $wp_roles ) )
  954. $wp_roles = new WP_Roles();
  955. $avail_roles = $wp_roles->get_names();
  956. // Build a CPU-intensive query that will return concise information.
  957. $select_count = array();
  958. foreach ( $avail_roles as $this_role => $name ) {
  959. $select_count[] = "COUNT(NULLIF(`meta_value` LIKE '%\"" . like_escape( $this_role ) . "\"%', false))";
  960. }
  961. $select_count = implode(', ', $select_count);
  962. // Add the meta_value index to the selection list, then run the query.
  963. $row = $wpdb->get_row( "SELECT $select_count, COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'", ARRAY_N );
  964. // Run the previous loop again to associate results with role names.
  965. $col = 0;
  966. $role_counts = array();
  967. foreach ( $avail_roles as $this_role => $name ) {
  968. $count = (int) $row[$col++];
  969. if ($count > 0) {
  970. $role_counts[$this_role] = $count;
  971. }
  972. }
  973. // Get the meta_value index from the end of the result set.
  974. $total_users = (int) $row[$col];
  975. $result['total_users'] = $total_users;
  976. $result['avail_roles'] =& $role_counts;
  977. } else {
  978. $avail_roles = array();
  979. $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" );
  980. foreach ( $users_of_blog as $caps_meta ) {
  981. $b_roles = maybe_unserialize($caps_meta);
  982. if ( ! is_array( $b_roles ) )
  983. continue;
  984. foreach ( $b_roles as $b_role => $val ) {
  985. if ( isset($avail_roles[$b_role]) ) {
  986. $avail_roles[$b_role]++;
  987. } else {
  988. $avail_roles[$b_role] = 1;
  989. }
  990. }
  991. }
  992. $result['total_users'] = count( $users_of_blog );
  993. $result['avail_roles'] =& $avail_roles;
  994. }
  995. return $result;
  996. }
  997. //
  998. // Private helper functions
  999. //
  1000. /**
  1001. * Set up global user vars.
  1002. *
  1003. * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
  1004. *
  1005. * @since 2.0.4
  1006. * @global string $userdata User description.
  1007. * @global string $user_login The user username for logging in
  1008. * @global int $user_level The level of the user
  1009. * @global int $user_ID The ID of the user
  1010. * @global string $user_email The email address of the user
  1011. * @global string $user_url The url in the user's profile
  1012. * @global string $user_identity The display name of the user
  1013. *
  1014. * @param int $for_user_id Optional. User ID to set up global data.
  1015. */
  1016. function setup_userdata($for_user_id = '') {
  1017. global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
  1018. if ( '' == $for_user_id )
  1019. $for_user_id = get_current_user_id();
  1020. $user = get_userdata( $for_user_id );
  1021. if ( ! $user ) {
  1022. $user_ID = 0;
  1023. $user_level = 0;
  1024. $userdata = null;
  1025. $user_login = $user_email = $user_url = $user_identity = '';
  1026. return;
  1027. }
  1028. $user_ID = (int) $user->ID;
  1029. $user_level = (int) $user->user_level;
  1030. $userdata = $user;
  1031. $user_login = $user->user_login;
  1032. $user_email = $user->user_email;
  1033. $user_url = $user->user_url;
  1034. $user_identity = $user->display_name;
  1035. }
  1036. /**
  1037. * Create dropdown HTML content of users.
  1038. *
  1039. * The content can either be displayed, which it is by default or retrieved by
  1040. * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
  1041. * need to be used; all users will be displayed in that case. Only one can be
  1042. * used, either 'include' or 'exclude', but not both.
  1043. *
  1044. * The available arguments are as follows:
  1045. * <ol>
  1046. * <li>show_option_all - Text to show all and whether HTML option exists.</li>
  1047. * <li>show_option_none - Text for show none and whether HTML option exists.</li>
  1048. * <li>hide_if_only_one_author - Don't create the dropdown if there is only one user.</li>
  1049. * <li>orderby - SQL order by clause for what order the users appear. Default is 'display_name'.</li>
  1050. * <li>order - Default is 'ASC'. Can also be 'DESC'.</li>
  1051. * <li>include - User IDs to include.</li>
  1052. * <li>exclude - User IDs to exclude.</li>
  1053. * <li>multi - Default is 'false'. Whether to skip the ID attribute on the 'select' element. A 'true' value is overridden when id argument is set.</li>
  1054. * <li>show - Default is 'display_name'. User table column to display. If the selected item is empty then the user_login will be displayed in parentheses</li>
  1055. * <li>echo - Default is '1'. Whether to display or retrieve content.</li>
  1056. * <li>selected - Which User ID is selected.</li>
  1057. * <li>include_selected - Always include the selected user ID in the dropdown. Default is false.</li>
  1058. * <li>name - Default is 'user'. Name attribute of select element.</li>
  1059. * <li>id - Default is the value of the 'name' parameter. ID attribute of select element.</li>
  1060. * <li>class - Class attribute of select element.</li>
  1061. * <li>blog_id - ID of blog (Multisite only). Defaults to ID of current blog.</li>
  1062. * <li>who - Which users to query. Currently only 'authors' is supported. Default is all users.</li>
  1063. * </ol>
  1064. *
  1065. * @since 2.3.0
  1066. *
  1067. * @global wpdb $wpdb WordPress database object for queries.
  1068. *
  1069. * @todo Hash-notate arguments array.
  1070. *
  1071. * @param string|array $args Optional. Array of user arguments.
  1072. * @return string|null Null on display. String of HTML content on retrieve.
  1073. */
  1074. function wp_dropdown_users( $args = '' ) {
  1075. $defaults = array(
  1076. 'show_option_all' => '', 'show_option_none' => '', 'hide_if_only_one_author' => '',
  1077. 'orderby' => 'display_name', 'order' => 'ASC',
  1078. 'include' => '', 'exclude' => '', 'multi' => 0,
  1079. 'show' => 'display_name', 'echo' => 1,
  1080. 'selected' => 0, 'name' => 'user', 'class' => '', 'id' => '',
  1081. 'blog_id' => $GLOBALS['blog_id'], 'who' => '', 'include_selected' => false
  1082. );
  1083. $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
  1084. $r = wp_parse_args( $args, $defaults );
  1085. extract( $r, EXTR_SKIP );
  1086. $query_args = wp_array_slice_assoc( $r, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who' ) );
  1087. $query_args['fields'] = array( 'ID', 'user_login', $show );
  1088. $users = get_users( $query_args );
  1089. $output = '';
  1090. if ( !empty($users) && ( empty($hide_if_only_one_author) || count($users) > 1 ) ) {
  1091. $name = esc_attr( $name );
  1092. if ( $multi && ! $id )
  1093. $id = '';
  1094. else
  1095. $id = $id ? " id='" . esc_attr( $id ) . "'" : " id='$name'";
  1096. $output = "<select name='{$name}'{$id} class='$class'>\n";
  1097. if ( $show_option_all )
  1098. $output .= "\t<option value='0'>$show_option_all</option>\n";
  1099. if ( $show_option_none ) {
  1100. $_selected = selected( -1, $selected, false );
  1101. $output .= "\t<option value='-1'$_selected>$show_option_none</option>\n";
  1102. }
  1103. $found_selected = false;
  1104. foreach ( (array) $users as $user ) {
  1105. $user->ID = (int) $user->ID;
  1106. $_selected = selected( $user->ID, $selected, false );
  1107. if ( $_selected )
  1108. $found_selected = true;
  1109. $display = !empty($user->$show) ? $user->$show : '('. $user->user_login . ')';
  1110. $output .= "\t<option value='$user->ID'$_selected>" . esc_html($display) . "</option>\n";
  1111. }
  1112. if ( $include_selected && ! $found_selected && ( $selected > 0 ) ) {
  1113. $user = get_userdata( $selected );
  1114. $_selected = selected( $user->ID, $selected, false );
  1115. $display = !empty($user->$show) ? $user->$show : '('. $user->user_login . ')';
  1116. $output .= "\t<option value='$user->ID'$_selected>" . esc_html($display) . "</option>\n";
  1117. }
  1118. $output .= "</select>";
  1119. }
  1120. /**
  1121. * Filter the wp_dropdown_users() HTML output.
  1122. *
  1123. * @since 2.3.0
  1124. *
  1125. * @param string $output HTML output generated by wp_dropdown_users().
  1126. */
  1127. $output = apply_filters( 'wp_dropdown_users', $output );
  1128. if ( $echo )
  1129. echo $output;
  1130. return $output;
  1131. }
  1132. /**
  1133. * Sanitize user field based on context.
  1134. *
  1135. * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
  1136. * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
  1137. * when calling filters.
  1138. *
  1139. * @since 2.3.0
  1140. *
  1141. * @param string $field The user Object field name.
  1142. * @param mixed $value The user Object value.
  1143. * @param int $user_id user ID.
  1144. * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
  1145. * 'attribute' and 'js'.
  1146. * @return mixed Sanitized value.
  1147. */
  1148. function sanitize_user_field($field, $value, $user_id, $context) {
  1149. $int_fields = array('ID');
  1150. if ( in_array($field, $int_fields) )
  1151. $value = (int) $value;
  1152. if ( 'raw' == $context )
  1153. return $value;
  1154. if ( !is_string($value) && !is_numeric($value) )
  1155. return $value;
  1156. $prefixed = false !== strpos( $field, 'user_' );
  1157. if ( 'edit' == $context ) {
  1158. if ( $prefixed ) {
  1159. /** This filter is documented in wp-includes/post.php */
  1160. $value = apply_filters( "edit_{$field}", $value, $user_id );
  1161. } else {
  1162. /**
  1163. * Filter a user field value in the 'edit' context.
  1164. *
  1165. * The dynamic portion of the hook name, $field, refers to the prefixed user
  1166. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1167. *
  1168. * @since 2.9.0
  1169. *
  1170. * @param mixed $value Value of the prefixed user field.
  1171. * @param int $user_id User ID.
  1172. */
  1173. $value = apply_filters( "edit_user_{$field}", $value, $user_id );
  1174. }
  1175. if ( 'description' == $field )
  1176. $value = esc_html( $value ); // textarea_escaped?
  1177. else
  1178. $value = esc_attr($value);
  1179. } else if ( 'db' == $context ) {
  1180. if ( $prefixed ) {
  1181. /** This filter is documented in wp-includes/post.php */
  1182. $value = apply_filters( "pre_{$field}", $value );
  1183. } else {
  1184. /**
  1185. * Filter the value of a user field in the 'db' context.
  1186. *
  1187. * The dynamic portion of the hook name, $field, refers to the prefixed user
  1188. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1189. *
  1190. * @since 2.9.0
  1191. *
  1192. * @param mixed $value Value of the prefixed user field.
  1193. */
  1194. $value = apply_filters( "pre_user_{$field}", $value );
  1195. }
  1196. } else {
  1197. // Use display filters by default.
  1198. if ( $prefixed ) {
  1199. /** This filter is documented in wp-includes/post.php */
  1200. $value = apply_filters( $field, $value, $user_id, $context );
  1201. } else {
  1202. /**
  1203. * Filter the value of a user field in a standard context.
  1204. *
  1205. * The dynamic portion of the hook name, $field, refers to the prefixed user
  1206. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1207. *
  1208. * @since 2.9.0
  1209. *
  1210. * @param mixed $value The user object value to sanitize.
  1211. * @param int $user_id User ID.
  1212. * @param string $context The context to filter within.
  1213. */
  1214. $value = apply_filters( "user_{$field}", $value, $user_id, $context );
  1215. }
  1216. }
  1217. if ( 'user_url' == $field )
  1218. $value = esc_url($value);
  1219. if ( 'attribute' == $context )
  1220. $value = esc_attr($value);
  1221. else if ( 'js' == $context )
  1222. $value = esc_js($value);
  1223. return $value;
  1224. }
  1225. /**
  1226. * Update all user caches
  1227. *
  1228. * @since 3.0.0
  1229. *
  1230. * @param object $user User object to be cached
  1231. */
  1232. function update_user_caches($user) {
  1233. wp_cache_add($user->ID, $user, 'users');
  1234. wp_cache_add($user->user_login, $user->ID, 'userlogins');
  1235. wp_cache_add($user->user_email, $user->ID, 'useremail');
  1236. wp_cache_add($user->user_nicename, $user->ID, 'userslugs');
  1237. }
  1238. /**
  1239. * Clean all user caches
  1240. *
  1241. * @since 3.0.0
  1242. *
  1243. * @param WP_User|int $user User object or ID to be cleaned from the cache
  1244. */
  1245. function clean_user_cache( $user ) {
  1246. if ( is_numeric( $user ) )
  1247. $user = new WP_User( $user );
  1248. if ( ! $user->exists() )
  1249. return;
  1250. wp_cache_delete( $user->ID, 'users' );
  1251. wp_cache_delete( $user->user_login, 'userlogins' );
  1252. wp_cache_delete( $user->user_email, 'useremail' );
  1253. wp_cache_delete( $user->user_nicename, 'userslugs' );
  1254. }
  1255. /**
  1256. * Checks whether the given username exists.
  1257. *
  1258. * @since 2.0.0
  1259. *
  1260. * @param string $username Username.
  1261. * @return null|int The user's ID on success, and null on failure.
  1262. */
  1263. function username_exists( $username ) {
  1264. if ( $user = get_user_by('login', $username ) ) {
  1265. return $user->ID;
  1266. } else {
  1267. return null;
  1268. }
  1269. }
  1270. /**
  1271. * Checks whether the given email exists.
  1272. *
  1273. * @since 2.1.0
  1274. *
  1275. * @param string $email Email.
  1276. * @return bool|int The user's ID on success, and false on failure.
  1277. */
  1278. function email_exists( $email ) {
  1279. if ( $user = get_user_by('email', $email) )
  1280. return $user->ID;
  1281. return false;
  1282. }
  1283. /**
  1284. * Checks whether an username is valid.
  1285. *
  1286. * @since 2.0.1
  1287. * @uses apply_filters() Calls 'validate_username' hook on $valid check and $username as parameters
  1288. *
  1289. * @param string $username Username.
  1290. * @return bool Whether username given is valid
  1291. */
  1292. function validate_username( $username ) {
  1293. $sanitized = sanitize_user( $username, true );
  1294. $valid = ( $sanitized == $username );
  1295. /**
  1296. * Filter whether the provided username is valid or not.
  1297. *
  1298. * @since 2.0.1
  1299. *
  1300. * @param bool $valid Whether given username is valid.
  1301. * @param string $username Username to check.
  1302. */
  1303. return apply_filters( 'validate_username', $valid, $username );
  1304. }
  1305. /**
  1306. * Insert an user into the database.
  1307. *
  1308. * Most of the $userdata array fields have filters associated with the values.
  1309. * The exceptions are 'rich_editing', 'role', 'jabber', 'aim', 'yim',
  1310. * 'user_registered', and 'ID'. The filters have the prefix 'pre_user_' followed
  1311. * by the field name. An example using 'description' would have the filter
  1312. * called, 'pre_user_description' that can be hooked into.
  1313. *
  1314. * The $userdata array can contain the following fields:
  1315. * 'ID' - An integer that will be used for updating an existing user.
  1316. * 'user_pass' - A string that contains the plain text password for the user.
  1317. * 'user_login' - A string that contains the user's username for logging in.
  1318. * 'user_nicename' - A string that contains a URL-friendly name for the user.
  1319. * The default is the user's username.
  1320. * 'user_url' - A string containing the user's URL for the user's web site.
  1321. * 'user_email' - A string containing the user's email address.
  1322. * 'display_name' - A string that will be shown on the site. Defaults to user's
  1323. * username. It is likely that you will want to change this, for appearance.
  1324. * 'nickname' - The user's nickname, defaults to the user's username.
  1325. * 'first_name' - The user's first name.
  1326. * 'last_name' - The user's last name.
  1327. * 'description' - A string containing content about the user.
  1328. * 'rich_editing' - A string for whether to enable the rich editor. False
  1329. * if not empty.
  1330. * 'user_registered' - The date the user registered. Format is 'Y-m-d H:i:s'.
  1331. * 'role' - A string used to set the user's role.
  1332. * 'jabber' - User's Jabber account.
  1333. * 'aim' - User's AOL IM account.
  1334. * 'yim' - User's Yahoo IM account.
  1335. *
  1336. * @since 2.0.0
  1337. *
  1338. * @global wpdb $wpdb WordPress database object for queries.
  1339. *
  1340. * @todo Hash-notate arguments array.
  1341. *
  1342. * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User.
  1343. * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not be created.
  1344. */
  1345. function wp_insert_user( $userdata ) {
  1346. global $wpdb;
  1347. if ( is_a( $userdata, 'stdClass' ) )
  1348. $userdata = get_object_vars( $userdata );
  1349. elseif ( is_a( $userdata, 'WP_User' ) )
  1350. $userdata = $userdata->to_array();
  1351. extract( $userdata, EXTR_SKIP );
  1352. // Are we updating or creating?
  1353. if ( !empty($ID) ) {
  1354. $ID = (int) $ID;
  1355. $update = true;
  1356. $old_user_data = WP_User::get_data_by( 'id', $ID );
  1357. } else {
  1358. $update = false;
  1359. // Hash the password
  1360. $user_pass = wp_hash_password($user_pass);
  1361. }
  1362. $user_login = sanitize_user($user_login, true);
  1363. /**
  1364. * Filter a username after it has been sanitized.
  1365. *
  1366. * This filter is called before the user is created or updated.
  1367. *
  1368. * @since 2.0.3
  1369. *
  1370. * @param string $user_login Username after it has been sanitized.
  1371. */
  1372. $user_login = apply_filters( 'pre_user_login', $user_login );
  1373. //Remove any non-printable chars from the login string to see if we have ended up with an empty username
  1374. $user_login = trim($user_login);
  1375. if ( empty($user_login) )
  1376. return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') );
  1377. if ( !$update && username_exists( $user_login ) )
  1378. return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
  1379. if ( empty($user_nicename) )
  1380. $user_nicename = sanitize_title( $user_login );
  1381. /**
  1382. * Filter a user's nicename before the user is created or updated.
  1383. *
  1384. * @since 2.0.3
  1385. *
  1386. * @param string $user_nicename The user's nicename.
  1387. */
  1388. $user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );
  1389. if ( empty($user_url) )
  1390. $user_url = '';
  1391. /**
  1392. * Filter a user's URL before the user is created or updated.
  1393. *
  1394. * @since 2.0.3
  1395. *
  1396. * @param string $user_url The user's URL.
  1397. */
  1398. $user_url = apply_filters( 'pre_user_url', $user_url );
  1399. if ( empty($user_email) )
  1400. $user_email = '';
  1401. /**
  1402. * Filter a user's email before the user is created or updated.
  1403. *
  1404. * @since 2.0.3
  1405. *
  1406. * @param string $user_email The user's email.
  1407. */
  1408. $user_email = apply_filters( 'pre_user_email', $user_email );
  1409. if ( !$update && ! defined( 'WP_IMPORTING' ) && email_exists($user_email) )
  1410. return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
  1411. if ( empty($nickname) )
  1412. $nickname = $user_login;
  1413. /**
  1414. * Filter a user's nickname before the user is created or updated.
  1415. *
  1416. * @since 2.0.3
  1417. *
  1418. * @param string $nickname The user's nickname.
  1419. */
  1420. $nickname = apply_filters( 'pre_user_nickname', $nickname );
  1421. if ( empty($first_name) )
  1422. $first_name = '';
  1423. /**
  1424. * Filter a user's first name before the user is created or updated.
  1425. *
  1426. * @since 2.0.3
  1427. *
  1428. * @param string $first_name The user's first name.
  1429. */
  1430. $first_name = apply_filters( 'pre_user_first_name', $first_name );
  1431. if ( empty($last_name) )
  1432. $last_name = '';
  1433. /**
  1434. * Filter a user's last name before the user is created or updated.
  1435. *
  1436. * @since 2.0.3
  1437. *
  1438. * @param string $last_name The user's last name.
  1439. */
  1440. $last_name = apply_filters( 'pre_user_last_name', $last_name );
  1441. if ( empty( $display_name ) ) {
  1442. if ( $update )
  1443. $display_name

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