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

/wp-includes/user.php

https://bitbucket.org/crypticrod/sr_wp_code
PHP | 1621 lines | 814 code | 235 blank | 572 comment | 225 complexity | 972725893588284613279c048ae928c5 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0, LGPL-2.1, GPL-3.0, LGPL-2.0, AGPL-3.0

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

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

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