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

/wp-includes/user.php

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