PageRenderTime 54ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/user.php

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

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