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

/wp-includes/user.php

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