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

/wp-includes/user.php

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