PageRenderTime 56ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/wordpress3.4.2/wp-includes/user.php

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