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

/wp-includes/user.php

https://bitbucket.org/aukhanev/xdn-wordpress31
PHP | 1620 lines | 811 code | 233 blank | 576 comment | 222 complexity | 3967afb632fb09487a6b04ccdd27c98e MD5 | raw file

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

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

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