[ Index ]

PHP Cross Reference of WordPress 3.0 beta 1

[ Index ]     [ Variables ]     [ Functions ]     [ Classes ]     [ Constants ]     [ Statistics ]

title

Body

[close]

/wp-includes/ -> user.php (source)

   1  <?php
   2  /**
   3   * WordPress User API
   4   *
   5   * @package WordPress
   6   */
   7  
   8  /**
   9   * Authenticate user with remember capability.
  10   *
  11   * The credentials is an array that has 'user_login', 'user_password', and
  12   * 'remember' indices. If the credentials is not given, then the log in form
  13   * will be assumed and used if set.
  14   *
  15   * The various authentication cookies will be set by this function and will be
  16   * set for a longer period depending on if the 'remember' credential is set to
  17   * true.
  18   *
  19   * @since 2.5.0
  20   *
  21   * @param array $credentials Optional. User info in order to sign on.
  22   * @param bool $secure_cookie Optional. Whether to use secure cookie.
  23   * @return object Either WP_Error on failure, or WP_User on success.
  24   */
  25  function wp_signon( $credentials = '', $secure_cookie = '' ) {
  26      if ( empty($credentials) ) {
  27          if ( ! empty($_POST['log']) )
  28              $credentials['user_login'] = $_POST['log'];
  29          if ( ! empty($_POST['pwd']) )
  30              $credentials['user_password'] = $_POST['pwd'];
  31          if ( ! empty($_POST['rememberme']) )
  32              $credentials['remember'] = $_POST['rememberme'];
  33      }
  34  
  35      if ( !empty($credentials['remember']) )
  36          $credentials['remember'] = true;
  37      else
  38          $credentials['remember'] = false;
  39  
  40      // TODO do we deprecate the wp_authentication action?
  41      do_action_ref_array('wp_authenticate', array(&$credentials['user_login'], &$credentials['user_password']));
  42  
  43      if ( '' === $secure_cookie )
  44          $secure_cookie = is_ssl();
  45  
  46      global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
  47      $auth_secure_cookie = $secure_cookie;
  48  
  49      add_filter('authenticate', 'wp_authenticate_cookie', 30, 3);
  50  
  51      $user = wp_authenticate($credentials['user_login'], $credentials['user_password']);
  52  
  53      if ( is_wp_error($user) ) {
  54          if ( $user->get_error_codes() == array('empty_username', 'empty_password') ) {
  55              $user = new WP_Error('', '');
  56          }
  57  
  58          return $user;
  59      }
  60  
  61      wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
  62      do_action('wp_login', $credentials['user_login']);
  63      return $user;
  64  }
  65  
  66  
  67  /**
  68   * Authenticate the user using the username and password.
  69   */
  70  add_filter('authenticate', 'wp_authenticate_username_password', 20, 3);
  71  function wp_authenticate_username_password($user, $username, $password) {
  72      if ( is_a($user, 'WP_User') ) { return $user; }
  73  
  74      if ( empty($username) || empty($password) ) {
  75          $error = new WP_Error();
  76  
  77          if ( empty($username) )
  78              $error->add('empty_username', __('<strong>ERROR</strong>: The username field is empty.'));
  79  
  80          if ( empty($password) )
  81              $error->add('empty_password', __('<strong>ERROR</strong>: The password field is empty.'));
  82  
  83          return $error;
  84      }
  85  
  86      $userdata = get_user_by('login', $username);
  87  
  88      if ( !$userdata )
  89          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')));
  90  
  91      if ( is_multisite() ) {
  92          // Is user marked as spam?
  93          if ( 1 == $userdata->spam)
  94              return new WP_Error('invalid_username', __('<strong>ERROR</strong>: Your account has been marked as a spammer.'));
  95  
  96          // Is a user's blog marked as spam?
  97          if ( !is_super_admin( $userdata->ID ) && isset($userdata->primary_blog) ) {
  98              $details = get_blog_details( $userdata->primary_blog );
  99              if ( is_object( $details ) && $details->spam == 1 )
 100                  return new WP_Error('blog_suspended', __('Blog Suspended.'));
 101          }
 102      }
 103  
 104      $userdata = apply_filters('wp_authenticate_user', $userdata, $password);
 105      if ( is_wp_error($userdata) )
 106          return $userdata;
 107  
 108      if ( !wp_check_password($password, $userdata->user_pass, $userdata->ID) )
 109          return new WP_Error('incorrect_password', sprintf(__('<strong>ERROR</strong>: Incorrect password. <a href="%s" title="Password Lost and Found">Lost your password</a>?'), site_url('wp-login.php?action=lostpassword', 'login')));
 110  
 111      $user =  new WP_User($userdata->ID);
 112      return $user;
 113  }
 114  
 115  /**
 116   * Authenticate the user using the WordPress auth cookie.
 117   */
 118  function wp_authenticate_cookie($user, $username, $password) {
 119      if ( is_a($user, 'WP_User') ) { return $user; }
 120  
 121      if ( empty($username) && empty($password) ) {
 122          $user_id = wp_validate_auth_cookie();
 123          if ( $user_id )
 124              return new WP_User($user_id);
 125  
 126          global $auth_secure_cookie;
 127  
 128          if ( $auth_secure_cookie )
 129              $auth_cookie = SECURE_AUTH_COOKIE;
 130          else
 131              $auth_cookie = AUTH_COOKIE;
 132  
 133          if ( !empty($_COOKIE[$auth_cookie]) )
 134              return new WP_Error('expired_session', __('Please log in again.'));
 135  
 136          // If the cookie is not set, be silent.
 137      }
 138  
 139      return $user;
 140  }
 141  
 142  /**
 143   * Number of posts user has written.
 144   *
 145   * @since 3.0.0
 146   * @uses $wpdb WordPress database object for queries.
 147   *
 148   * @param int $userid User ID.
 149   * @return int Amount of posts user has written.
 150   */
 151  function count_user_posts($userid) {
 152      global $wpdb;
 153  
 154      $where = get_posts_by_author_sql('post', TRUE, $userid);
 155  
 156      $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
 157  
 158      return apply_filters('get_usernumposts', $count, $userid);
 159  }
 160  
 161  /**
 162   * Number of posts written by a list of users.
 163   *
 164   * @since 3.0.0
 165   * @param array $userid User ID number list.
 166   * @return array Amount of posts each user has written.
 167   */
 168  function count_many_users_posts($users) {
 169      global $wpdb;
 170  
 171      $count = array();
 172      if ( ! is_array($users) || empty( $users ) )
 173          return $count;
 174  
 175      $userlist = implode( ',', $users );
 176      $where = get_posts_by_author_sql( 'post' );
 177  
 178      $result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
 179      foreach ( $result as $row ) {
 180          $count[ $row[0] ] = $row[1];
 181      }
 182  
 183      foreach ( $users as $id ) {
 184          if ( ! isset( $count[ $id ] ) )
 185              $count[ $id ] = 0;
 186      }
 187  
 188      return $count;
 189  }
 190  
 191  /**
 192   * Check that the user login name and password is correct.
 193   *
 194   * @since 0.71
 195   * @todo xmlrpc only. Maybe move to xmlrpc.php.
 196   *
 197   * @param string $user_login User name.
 198   * @param string $user_pass User password.
 199   * @return bool False if does not authenticate, true if username and password authenticates.
 200   */
 201  function user_pass_ok($user_login, $user_pass) {
 202      $user = wp_authenticate($user_login, $user_pass);
 203      if ( is_wp_error($user) )
 204          return false;
 205  
 206      return true;
 207  }
 208  
 209  //
 210  // User option functions
 211  //
 212  
 213  /**
 214   * Retrieve user option that can be either per Site or per Network.
 215   *
 216   * If the user ID is not given, then the current user will be used instead. If
 217   * the user ID is given, then the user data will be retrieved. The filter for
 218   * the result, will also pass the original option name and finally the user data
 219   * object as the third parameter.
 220   *
 221   * The option will first check for the per site name and then the per Network name.
 222   *
 223   * @since 2.0.0
 224   * @uses $wpdb WordPress database object for queries.
 225   * @uses apply_filters() Calls 'get_user_option_$option' hook with result,
 226   *        option parameter, and user data object.
 227   *
 228   * @param string $option User option name.
 229   * @param int $user Optional. User ID.
 230   * @param bool $deprecated Use get_option() to check for an option in the options table.
 231   * @return mixed
 232   */
 233  function get_user_option( $option, $user = 0, $deprecated = '' ) {
 234      global $wpdb;
 235  
 236      if ( !empty( $deprecated ) )
 237          _deprecated_argument( __FUNCTION__, '3.0' );
 238  
 239      if ( empty($user) )
 240          $user = wp_get_current_user();
 241      else
 242          $user = get_userdata($user);
 243  
 244      if ( isset( $user->{$wpdb->prefix . $option} ) ) // Blog specific
 245          $result = $user->{$wpdb->prefix . $option};
 246      elseif ( isset( $user->{$option} ) ) // User specific and cross-blog
 247          $result = $user->{$option};
 248      else
 249          $result = false;
 250  
 251      return apply_filters("get_user_option_{$option}", $result, $option, $user);
 252  }
 253  
 254  /**
 255   * Update user option with global blog capability.
 256   *
 257   * User options are just like user metadata except that they have support for
 258   * global blog options. If the 'global' parameter is false, which it is by default
 259   * it will prepend the WordPress table prefix to the option name.
 260   *
 261   * @since 2.0.0
 262   * @uses $wpdb WordPress database object for queries
 263   *
 264   * @param int $user_id User ID
 265   * @param string $option_name User option name.
 266   * @param mixed $newvalue User option value.
 267   * @param bool $global Optional. Whether option name is global or blog specific. Default false (blog specific).
 268   * @return unknown
 269   */
 270  function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
 271      global $wpdb;
 272  
 273      if ( !$global )
 274          $option_name = $wpdb->prefix . $option_name;
 275      return update_user_meta( $user_id, $option_name, $newvalue );
 276  }
 277  
 278  /**
 279   * Delete user option with global blog capability.
 280   *
 281   * User options are just like user metadata except that they have support for
 282   * global blog options. If the 'global' parameter is false, which it is by default
 283   * it will prepend the WordPress table prefix to the option name.
 284   *
 285   * @since 3.0.0
 286   * @uses $wpdb WordPress database object for queries
 287   *
 288   * @param int $user_id User ID
 289   * @param string $option_name User option name.
 290   * @param bool $global Optional. Whether option name is global or blog specific. Default false (blog specific).
 291   * @return unknown
 292   */
 293  function delete_user_option( $user_id, $option_name, $global = false ) {
 294      global $wpdb;
 295  
 296      if ( !$global )
 297          $option_name = $wpdb->prefix . $option_name;
 298      return delete_user_meta( $user_id, $option_name );
 299  }
 300  
 301  /**
 302   * Get users for the blog.
 303   *
 304   * For setups that use the multi-blog feature. Can be used outside of the
 305   * multi-blog feature.
 306   *
 307   * @since 2.2.0
 308   * @uses $wpdb WordPress database object for queries
 309   * @uses $blog_id The Blog id of the blog for those that use more than one blog
 310   *
 311   * @param int $id Blog ID.
 312   * @return array List of users that are part of that Blog ID
 313   */
 314  function get_users_of_blog( $id = '' ) {
 315      global $wpdb, $blog_id;
 316      if ( empty($id) )
 317          $id = (int) $blog_id;
 318      $blog_prefix = $wpdb->get_blog_prefix($id);
 319      $users = $wpdb->get_results( "SELECT user_id, user_id AS ID, user_login, display_name, user_email, meta_value FROM $wpdb->users, $wpdb->usermeta WHERE {$wpdb->users}.ID = {$wpdb->usermeta}.user_id AND meta_key = '{$blog_prefix}capabilities' ORDER BY {$wpdb->usermeta}.user_id" );
 320      return $users;
 321  }
 322  
 323  /**
 324   * Add meta data field to a user.
 325   *
 326   * Post meta data is called "Custom Fields" on the Administration Panels.
 327   *
 328   * @since 3.0.0
 329   * @uses add_metadata()
 330   * @link http://codex.wordpress.org/Function_Reference/add_user_meta
 331   *
 332   * @param int $user_id Post ID.
 333   * @param string $key Metadata name.
 334   * @param mixed $value Metadata value.
 335   * @param bool $unique Optional, default is false. Whether the same key should not be added.
 336   * @return bool False for failure. True for success.
 337   */
 338  function add_user_meta($user_id, $meta_key, $meta_value, $unique = false) {
 339      return add_metadata('user', $user_id, $meta_key, $meta_value, $unique);
 340  }
 341  
 342  /**
 343   * Remove metadata matching criteria from a user.
 344   *
 345   * You can match based on the key, or key and value. Removing based on key and
 346   * value, will keep from removing duplicate metadata with the same key. It also
 347   * allows removing all metadata matching key, if needed.
 348   *
 349   * @since 3.0.0
 350   * @uses delete_metadata()
 351   * @link http://codex.wordpress.org/Function_Reference/delete_user_meta
 352   *
 353   * @param int $user_id user ID
 354   * @param string $meta_key Metadata name.
 355   * @param mixed $meta_value Optional. Metadata value.
 356   * @return bool False for failure. True for success.
 357   */
 358  function delete_user_meta($user_id, $meta_key, $meta_value = '') {
 359      return delete_metadata('user', $user_id, $meta_key, $meta_value);
 360  }
 361  
 362  /**
 363   * Retrieve user meta field for a user.
 364   *
 365   * @since 3.0.0
 366   * @uses get_metadata()
 367   * @link http://codex.wordpress.org/Function_Reference/get_user_meta
 368   *
 369   * @param int $user_id Post ID.
 370   * @param string $key The meta key to retrieve.
 371   * @param bool $single Whether to return a single value.
 372   * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
 373   *  is true.
 374   */
 375  function get_user_meta($user_id, $key, $single = false) {
 376      return get_metadata('user', $user_id, $key, $single);
 377  }
 378  
 379  /**
 380   * Update user meta field based on user ID.
 381   *
 382   * Use the $prev_value parameter to differentiate between meta fields with the
 383   * same key and user ID.
 384   *
 385   * If the meta field for the user does not exist, it will be added.
 386   *
 387   * @since 3.0.0
 388   * @uses update_metadata
 389   * @link http://codex.wordpress.org/Function_Reference/update_user_meta
 390   *
 391   * @param int $user_id Post ID.
 392   * @param string $key Metadata key.
 393   * @param mixed $value Metadata value.
 394   * @param mixed $prev_value Optional. Previous value to check before removing.
 395   * @return bool False on failure, true if success.
 396   */
 397  function update_user_meta($user_id, $meta_key, $meta_value, $prev_value = '') {
 398      return update_metadata('user', $user_id, $meta_key, $meta_value, $prev_value);
 399  }
 400  
 401  /**
 402   * Count number of users who have each of the user roles.
 403   *
 404   * Assumes there are neither duplicated nor orphaned capabilities meta_values.
 405   * Assumes role names are unique phrases.  Same assumption made by WP_User_Search::prepare_query()
 406   * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
 407   * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
 408   *
 409   * @since 3.0.0
 410   * @param string $strategy 'time' or 'memory'
 411   * @return array Includes a grand total and an array of counts indexed by role strings.
 412   */
 413  function count_users($strategy = 'time') {
 414      global $wpdb, $blog_id, $wp_roles;
 415  
 416      // Initialize
 417      $id = (int) $blog_id;
 418      $blog_prefix = $wpdb->get_blog_prefix($id);
 419      $result = array();
 420  
 421      if ('time' == $strategy) {
 422          $avail_roles = $wp_roles->get_names();
 423  
 424          // Build a CPU-intensive query that will return concise information.
 425          $select_count = array();
 426          foreach ( $avail_roles as $this_role => $name ) {
 427              $select_count[] = "COUNT(NULLIF(`meta_value` LIKE '%" . like_escape($this_role) . "%', FALSE))";
 428          }
 429          $select_count = implode(', ', $select_count);
 430  
 431          // Add the meta_value index to the selection list, then run the query.
 432          $row = $wpdb->get_row( "SELECT $select_count, COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'", ARRAY_N );
 433  
 434          // Run the previous loop again to associate results with role names.
 435          $col = 0;
 436          $role_counts = array();
 437          foreach ( $avail_roles as $this_role => $name ) {
 438              $count = (int) $row[$col++];
 439              if ($count > 0) {
 440                  $role_counts[$this_role] = $count;
 441              }
 442          }
 443  
 444          // Get the meta_value index from the end of the result set.
 445          $total_users = (int) $row[$col];
 446  
 447          $result['total_users'] = $total_users;
 448          $result['avail_roles'] =& $role_counts;
 449      } else {
 450          $avail_roles = array();
 451  
 452          $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" );
 453  
 454          foreach ( $users_of_blog as $caps_meta ) {
 455              $b_roles = unserialize($caps_meta);
 456              if ( is_array($b_roles) ) {
 457                  foreach ( $b_roles as $b_role => $val ) {
 458                      if ( isset($avail_roles[$b_role]) ) {
 459                          $avail_roles[$b_role]++;
 460                      } else {
 461                          $avail_roles[$b_role] = 1;
 462                      }
 463                  }
 464              }
 465          }
 466  
 467          $result['total_users'] = count( $users_of_blog );
 468          $result['avail_roles'] =& $avail_roles;
 469      }
 470  
 471      return $result;
 472  }
 473  
 474  //
 475  // Private helper functions
 476  //
 477  
 478  /**
 479   * Set up global user vars.
 480   *
 481   * Used by set_current_user() for back compat. Might be deprecated in the
 482   * future.
 483   *
 484   * @since 2.0.4
 485   * @global string $userdata User description.
 486   * @global string $user_login The user username for logging in
 487   * @global int $user_level The level of the user
 488   * @global int $user_ID The ID of the user
 489   * @global string $user_email The email address of the user
 490   * @global string $user_url The url in the user's profile
 491   * @global string $user_pass_md5 MD5 of the user's password
 492   * @global string $user_identity The display name of the user
 493   *
 494   * @param int $for_user_id Optional. User ID to set up global data.
 495   */
 496  function setup_userdata($for_user_id = '') {
 497      global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_pass_md5, $user_identity;
 498  
 499      if ( '' == $for_user_id )
 500          $user = wp_get_current_user();
 501      else
 502          $user = new WP_User($for_user_id);
 503  
 504      if ( 0 == $user->ID )
 505          return;
 506  
 507      $userdata = $user->data;
 508      $user_login    = $user->user_login;
 509      $user_level    = (int) isset($user->user_level) ? $user->user_level : 0;
 510      $user_ID = (int) $user->ID;
 511      $user_email    = $user->user_email;
 512      $user_url    = $user->user_url;
 513      $user_pass_md5    = md5($user->user_pass);
 514      $user_identity    = $user->display_name;
 515  }
 516  
 517  /**
 518   * Create dropdown HTML content of users.
 519   *
 520   * The content can either be displayed, which it is by default or retrieved by
 521   * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
 522   * need to be used; all users will be displayed in that case. Only one can be
 523   * used, either 'include' or 'exclude', but not both.
 524   *
 525   * The available arguments are as follows:
 526   * <ol>
 527   * <li>show_option_all - Text to show all and whether HTML option exists.</li>
 528   * <li>show_option_none - Text for show none and whether HTML option exists.
 529   *     </li>
 530   * <li>orderby - SQL order by clause for what order the users appear. Default is
 531   * 'display_name'.</li>
 532   * <li>order - Default is 'ASC'. Can also be 'DESC'.</li>
 533   * <li>include - User IDs to include.</li>
 534   * <li>exclude - User IDs to exclude.</li>
 535   * <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>
 536   * <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 parentesis</li>
 537   * <li>echo - Default is '1'. Whether to display or retrieve content.</li>
 538   * <li>selected - Which User ID is selected.</li>
 539   * <li>name - Default is 'user'. Name attribute of select element.</li>
 540   * <li>id - Default is the value of the 'name' parameter. ID attribute of select element.</li>
 541   * <li>class - Class attribute of select element.</li>
 542   * <li>blog_id - ID of blog (Multisite only). Defaults to ID of current blog.</li>
 543   * </ol>
 544   *
 545   * @since 2.3.0
 546   * @uses $wpdb WordPress database object for queries
 547   *
 548   * @param string|array $args Optional. Override defaults.
 549   * @return string|null Null on display. String of HTML content on retrieve.
 550   */
 551  function wp_dropdown_users( $args = '' ) {
 552      global $wpdb;
 553      $defaults = array(
 554          'show_option_all' => '', 'show_option_none' => '',
 555          'orderby' => 'display_name', 'order' => 'ASC',
 556          'include' => '', 'exclude' => '', 'multi' => 0,
 557          'show' => 'display_name', 'echo' => 1,
 558          'selected' => 0, 'name' => 'user', 'class' => '', 'blog_id' => $GLOBALS['blog_id'],
 559          'id' => '',
 560      );
 561  
 562      $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
 563  
 564      $r = wp_parse_args( $args, $defaults );
 565      extract( $r, EXTR_SKIP );
 566  
 567      $blog_prefix = $wpdb->get_blog_prefix( $blog_id );
 568      $query = "SELECT {$wpdb->users}.* FROM $wpdb->users, $wpdb->usermeta WHERE {$wpdb->users}.ID = {$wpdb->usermeta}.user_id AND meta_key = '{$blog_prefix}capabilities'";
 569  
 570      $query_where = array();
 571  
 572      if ( is_array($include) )
 573          $include = join(',', $include);
 574      $include = preg_replace('/[^0-9,]/', '', $include); // (int)
 575      if ( $include )
 576          $query_where[] = "ID IN ($include)";
 577  
 578      if ( is_array($exclude) )
 579          $exclude = join(',', $exclude);
 580      $exclude = preg_replace('/[^0-9,]/', '', $exclude); // (int)
 581      if ( $exclude )
 582          $query_where[] = "ID NOT IN ($exclude)";
 583  
 584      if ( $query_where )
 585          $query .= " AND " . join(' AND', $query_where);
 586  
 587      $query .= " ORDER BY $orderby $order";
 588  
 589      $users = $wpdb->get_results( $query );
 590  
 591      $output = '';
 592      if ( !empty($users) ) {
 593          $name = esc_attr( $name );
 594          if ( $multi && ! $id )
 595              $id = '';
 596          else
 597              $id = $id ? " id='" . esc_attr( $id ) . "'" : "id='$name'";
 598  
 599          $output = "<select name='{$name}'{$id} class='$class'>\n";
 600  
 601          if ( $show_option_all )
 602              $output .= "\t<option value='0'>$show_option_all</option>\n";
 603  
 604          if ( $show_option_none )
 605              $output .= "\t<option value='-1'>$show_option_none</option>\n";
 606  
 607          foreach ( (array) $users as $user ) {
 608              $user->ID = (int) $user->ID;
 609              $_selected = $user->ID == $selected ? " selected='selected'" : '';
 610              $display = !empty($user->$show) ? $user->$show : '('. $user->user_login . ')';
 611              $output .= "\t<option value='$user->ID'$_selected>" . esc_html($display) . "</option>\n";
 612          }
 613  
 614          $output .= "</select>";
 615      }
 616  
 617      $output = apply_filters('wp_dropdown_users', $output);
 618  
 619      if ( $echo )
 620          echo $output;
 621  
 622      return $output;
 623  }
 624  
 625  /**
 626   * Add user meta data as properties to given user object.
 627   *
 628   * The finished user data is cached, but the cache is not used to fill in the
 629   * user data for the given object. Once the function has been used, the cache
 630   * should be used to retrieve user data. The intention is if the current data
 631   * had been cached already, there would be no need to call this function.
 632   *
 633   * @access private
 634   * @since 2.5.0
 635   * @uses $wpdb WordPress database object for queries
 636   *
 637   * @param object $user The user data object.
 638   */
 639  function _fill_user( &$user ) {
 640      $metavalues = get_user_metavalues(array($user->ID));
 641      _fill_single_user($user, $metavalues[$user->ID]);
 642  }
 643  
 644  /**
 645   * Perform the query to get the $metavalues array(s) needed by _fill_user and _fill_many_users
 646   *
 647   * @since 3.0.0
 648   * @param array $ids User ID numbers list.
 649   * @return array of arrays. The array is indexed by user_id, containing $metavalues object arrays.
 650   */
 651  function get_user_metavalues($ids) {
 652      global $wpdb;
 653  
 654      $clean = array_map('intval', $ids);
 655      if ( 0 == count($clean) )
 656          return $objects;
 657  
 658      $list = implode(',', $clean);
 659  
 660      $show = $wpdb->hide_errors();
 661      $metavalues = $wpdb->get_results("SELECT user_id, meta_key, meta_value FROM $wpdb->usermeta WHERE user_id IN ($list)");
 662      $wpdb->show_errors($show);
 663  
 664      $objects = array();
 665      foreach($clean as $id) {
 666          $objects[$id] = array();
 667      }
 668      foreach($metavalues as $meta_object) {
 669          $objects[$meta_object->user_id][] = $meta_object;
 670      }
 671  
 672      return $objects;
 673  }
 674  
 675  /**
 676   * Unserialize user metadata, fill $user object, then cache everything.
 677   *
 678   * @since 3.0.0
 679   * @param object $user The User object.
 680   * @param array $metavalues An array of objects provided by get_user_metavalues()
 681   */
 682  function _fill_single_user( &$user, &$metavalues ) {
 683      global $wpdb;
 684  
 685      foreach ( $metavalues as $meta ) {
 686          $value = maybe_unserialize($meta->meta_value);
 687          $user->{$meta->meta_key} = $value;
 688      }
 689  
 690      $level = $wpdb->prefix . 'user_level';
 691      if ( isset( $user->{$level} ) )
 692          $user->user_level = $user->{$level};
 693  
 694      // For backwards compat.
 695      if ( isset($user->first_name) )
 696          $user->user_firstname = $user->first_name;
 697      if ( isset($user->last_name) )
 698          $user->user_lastname = $user->last_name;
 699      if ( isset($user->description) )
 700          $user->user_description = $user->description;
 701  
 702      update_user_caches($user);
 703  }
 704  
 705  /**
 706   * Take an array of user objects, fill them with metas, and cache them.
 707   *
 708   * @since 3.0.0
 709   * @param array $users User objects
 710   * @param array $metas User metavalues objects
 711   */
 712  function _fill_many_users( &$users ) {
 713      $ids = array();
 714      foreach($users as $user_object) {
 715          $ids[] = $user_object->ID;
 716      }
 717  
 718      $metas = get_user_metavalues($ids);
 719  
 720      foreach($users as $user_object) {
 721          if (isset($metas[$user_object->ID])) {
 722              _fill_single_user($user_object, $metas[$user_object->ID]);
 723          }
 724      }
 725  }
 726  
 727  /**
 728   * Sanitize every user field.
 729   *
 730   * If the context is 'raw', then the user object or array will get minimal santization of the int fields.
 731   *
 732   * @since 2.3.0
 733   * @uses sanitize_user_field() Used to sanitize the fields.
 734   *
 735   * @param object|array $user The User Object or Array
 736   * @param string $context Optional, default is 'display'. How to sanitize user fields.
 737   * @return object|array The now sanitized User Object or Array (will be the same type as $user)
 738   */
 739  function sanitize_user_object($user, $context = 'display') {
 740      if ( is_object($user) ) {
 741          if ( !isset($user->ID) )
 742              $user->ID = 0;
 743          if ( isset($user->data) )
 744              $vars = get_object_vars( $user->data );
 745          else
 746              $vars = get_object_vars($user);
 747          foreach ( array_keys($vars) as $field ) {
 748              if ( is_string($user->$field) || is_numeric($user->$field) )
 749                  $user->$field = sanitize_user_field($field, $user->$field, $user->ID, $context);
 750          }
 751          $user->filter = $context;
 752      } else {
 753          if ( !isset($user['ID']) )
 754              $user['ID'] = 0;
 755          foreach ( array_keys($user) as $field )
 756              $user[$field] = sanitize_user_field($field, $user[$field], $user['ID'], $context);
 757          $user['filter'] = $context;
 758      }
 759  
 760      return $user;
 761  }
 762  
 763  /**
 764   * Sanitize user field based on context.
 765   *
 766   * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
 767   * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
 768   * when calling filters.
 769   *
 770   * @since 2.3.0
 771   * @uses apply_filters() Calls 'edit_$field' and '${field_no_prefix}_edit_pre' passing $value and
 772   *  $user_id if $context == 'edit' and field name prefix == 'user_'.
 773   *
 774   * @uses apply_filters() Calls 'edit_user_$field' passing $value and $user_id if $context == 'db'.
 775   * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'user_'.
 776   * @uses apply_filters() Calls '${field}_pre' passing $value if $context == 'db' and field name prefix != 'user_'.
 777   *
 778   * @uses apply_filters() Calls '$field' passing $value, $user_id and $context if $context == anything
 779   *  other than 'raw', 'edit' and 'db' and field name prefix == 'user_'.
 780   * @uses apply_filters() Calls 'user_$field' passing $value if $context == anything other than 'raw',
 781   *  'edit' and 'db' and field name prefix != 'user_'.
 782   *
 783   * @param string $field The user Object field name.
 784   * @param mixed $value The user Object value.
 785   * @param int $user_id user ID.
 786   * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
 787   *               'attribute' and 'js'.
 788   * @return mixed Sanitized value.
 789   */
 790  function sanitize_user_field($field, $value, $user_id, $context) {
 791      $int_fields = array('ID');
 792      if ( in_array($field, $int_fields) )
 793          $value = (int) $value;
 794  
 795      if ( 'raw' == $context )
 796          return $value;
 797  
 798      if ( !is_string($value) && !is_numeric($value) )
 799          return $value;
 800  
 801      $prefixed = false;
 802      if ( false !== strpos($field, 'user_') ) {
 803          $prefixed = true;
 804          $field_no_prefix = str_replace('user_', '', $field);
 805      }
 806  
 807      if ( 'edit' == $context ) {
 808          if ( $prefixed ) {
 809              $value = apply_filters("edit_$field", $value, $user_id);
 810          } else {
 811              $value = apply_filters("edit_user_$field", $value, $user_id);
 812          }
 813  
 814          if ( 'description' == $field )
 815              $value = esc_html($value);
 816          else
 817              $value = esc_attr($value);
 818      } else if ( 'db' == $context ) {
 819          if ( $prefixed ) {
 820              $value = apply_filters("pre_$field", $value);
 821          } else {
 822              $value = apply_filters("pre_user_$field", $value);
 823          }
 824      } else {
 825          // Use display filters by default.
 826          if ( $prefixed )
 827              $value = apply_filters($field, $value, $user_id, $context);
 828          else
 829              $value = apply_filters("user_$field", $value, $user_id, $context);
 830      }
 831  
 832      if ( 'user_url' == $field )
 833          $value = esc_url($value);
 834  
 835      if ( 'attribute' == $context )
 836          $value = esc_attr($value);
 837      else if ( 'js' == $context )
 838          $value = esc_js($value);
 839  
 840      return $value;
 841  }
 842  
 843  /**
 844   * Update all user caches
 845   *
 846   * @since 3.0.0
 847   *
 848   * @param object $user User object to be cached
 849   */
 850  function update_user_caches(&$user) {
 851      wp_cache_add($user->ID, $user, 'users');
 852      wp_cache_add($user->user_login, $user->ID, 'userlogins');
 853      wp_cache_add($user->user_email, $user->ID, 'useremail');
 854      wp_cache_add($user->user_nicename, $user->ID, 'userslugs');
 855  }
 856  
 857  /**
 858   * Clean all user caches
 859   *
 860   * @since 3.0.0
 861   *
 862   * @param int $id User ID
 863   */
 864  function clean_user_cache($id) {
 865      $user = new WP_User($id);
 866  
 867      wp_cache_delete($id, 'users');
 868      wp_cache_delete($user->user_login, 'userlogins');
 869      wp_cache_delete($user->user_email, 'useremail');
 870      wp_cache_delete($user->user_nicename, 'userslugs');
 871  }
 872  
 873  ?>


Generated: Mon Apr 5 14:26:09 2010 Cross-referenced by PHPXref 0.7