9 * Authenticate user with remember capability.
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.
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
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.
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'];
35 if ( !empty($credentials['user_login']) )
36 $credentials['user_login'] = sanitize_user($credentials['user_login']);
37 if ( !empty($credentials['user_password']) )
38 $credentials['user_password'] = trim($credentials['user_password']);
39 if ( !empty($credentials['remember']) )
40 $credentials['remember'] = true;
42 $credentials['remember'] = false;
44 do_action_ref_array('wp_authenticate', array(&$credentials['user_login'], &$credentials['user_password']));
46 if ( '' === $secure_cookie )
47 $secure_cookie = is_ssl() ? true : false;
49 // If no credential info provided, check cookie.
50 if ( empty($credentials['user_login']) && empty($credentials['user_password']) ) {
51 $user = wp_validate_auth_cookie();
53 return new WP_User($user);
56 $auth_cookie = SECURE_AUTH_COOKIE;
58 $auth_cookie = AUTH_COOKIE;
60 if ( !empty($_COOKIE[$auth_cookie]) )
61 return new WP_Error('expired_session', __('Please log in again.'));
63 // If the cookie is not set, be silent.
64 return new WP_Error();
67 if ( empty($credentials['user_login']) || empty($credentials['user_password']) ) {
68 $error = new WP_Error();
70 if ( empty($credentials['user_login']) )
71 $error->add('empty_username', __('<strong>ERROR</strong>: The username field is empty.'));
72 if ( empty($credentials['user_password']) )
73 $error->add('empty_password', __('<strong>ERROR</strong>: The password field is empty.'));
77 $user = wp_authenticate($credentials['user_login'], $credentials['user_password']);
78 if ( is_wp_error($user) )
81 wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
82 do_action('wp_login', $credentials['user_login']);
87 * Retrieve user data based on field.
89 * Use get_profile() will make a database query to get the value of the table
90 * column. The value might be cached using the query cache, but care should be
91 * taken when using the function to not make a lot of queries for retrieving
92 * user profile information.
94 * If the $user parameter is not used, then the user will be retrieved from a
95 * cookie of the user. Therefore, if the cookie does not exist, then no value
96 * might be returned. Sanity checking must be done to ensure that when using
97 * get_profile() that empty/null/false values are handled and that something is
101 * @uses $wpdb WordPress database object to create queries.
103 * @param string $field User field to retrieve.
104 * @param string $user Optional. User username.
105 * @return string The value in the field.
107 function get_profile($field, $user = false) {
110 $user = $wpdb->escape($_COOKIE[USER_COOKIE]);
111 return $wpdb->get_var( $wpdb->prepare("SELECT $field FROM $wpdb->users WHERE user_login = %s", $user) );
115 * Number of posts user has written.
118 * @uses $wpdb WordPress database object for queries.
120 * @param int $userid User ID.
121 * @return int Amount of posts user has written.
123 function get_usernumposts($userid) {
125 $userid = (int) $userid;
126 $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = %d AND post_type = 'post' AND ", $userid) . get_private_posts_cap_sql('post'));
127 return apply_filters('get_usernumposts', $count, $userid);
131 * Check that the user login name and password is correct.
134 * @todo xmlrpc only. Maybe move to xmlrpc.php.
136 * @param string $user_login User name.
137 * @param string $user_pass User password.
138 * @return bool False if does not authenticate, true if username and password authenticates.
140 function user_pass_ok($user_login, $user_pass) {
141 $user = wp_authenticate($user_login, $user_pass);
142 if ( is_wp_error($user) )
149 // User option functions
153 * Retrieve user option that can be either global, user, or blog.
155 * If the user ID is not given, then the current user will be used instead. If
156 * the user ID is given, then the user data will be retrieved. The filter for
157 * the result, will also pass the original option name and finally the user data
158 * object as the third parameter.
160 * The option will first check for the non-global name, then the global name,
161 * and if it still doesn't find it, it will try the blog option. The option can
162 * either be modified or set by a plugin.
165 * @uses $wpdb WordPress database object for queries.
166 * @uses apply_filters() Calls 'get_user_option_$option' hook with result,
167 * option parameter, and user data object.
169 * @param string $option User option name.
170 * @param int $user Optional. User ID.
171 * @param bool $check_blog_options Whether to check for an option in the options table if a per-user option does not exist. Default is true.
174 function get_user_option( $option, $user = 0, $check_blog_options = true ) {
177 $option = preg_replace('|[^a-z0-9_]|i', '', $option);
179 $user = wp_get_current_user();
181 $user = get_userdata($user);
183 if ( isset( $user->{$wpdb->prefix . $option} ) ) // Blog specific
184 $result = $user->{$wpdb->prefix . $option};
185 elseif ( isset( $user->{$option} ) ) // User specific and cross-blog
186 $result = $user->{$option};
187 elseif ( $check_blog_options ) // Blog global
188 $result = get_option( $option );
192 return apply_filters("get_user_option_{$option}", $result, $option, $user);
196 * Update user option with global blog capability.
198 * User options are just like user metadata except that they have support for
199 * global blog options. If the 'global' parameter is false, which it is by false
200 * it will prepend the WordPress table prefix to the option name.
203 * @uses $wpdb WordPress database object for queries
205 * @param int $user_id User ID
206 * @param string $option_name User option name.
207 * @param mixed $newvalue User option value.
208 * @param bool $global Optional. Whether option name is blog specific or not.
211 function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
214 $option_name = $wpdb->prefix . $option_name;
215 return update_usermeta( $user_id, $option_name, $newvalue );
219 * Get users for the blog.
221 * For setups that use the multi-blog feature. Can be used outside of the
222 * multi-blog feature.
225 * @uses $wpdb WordPress database object for queries
226 * @uses $blog_id The Blog id of the blog for those that use more than one blog
228 * @param int $id Blog ID.
229 * @return array List of users that are part of that Blog ID
231 function get_users_of_blog( $id = '' ) {
232 global $wpdb, $blog_id;
234 $id = (int) $blog_id;
235 $users = $wpdb->get_results( "SELECT user_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 = '" . $wpdb->prefix . "capabilities' ORDER BY {$wpdb->usermeta}.user_id" );
240 // User meta functions
244 * Remove user meta data.
247 * @uses $wpdb WordPress database object for queries.
249 * @param int $user_id User ID.
250 * @param string $meta_key Metadata key.
251 * @param mixed $meta_value Metadata value.
252 * @return bool True deletion completed and false if user_id is not a number.
254 function delete_usermeta( $user_id, $meta_key, $meta_value = '' ) {
256 if ( !is_numeric( $user_id ) )
258 $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key);
260 if ( is_array($meta_value) || is_object($meta_value) )
261 $meta_value = serialize($meta_value);
262 $meta_value = trim( $meta_value );
264 if ( ! empty($meta_value) )
265 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s AND meta_value = %s", $user_id, $meta_key, $meta_value) );
267 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $meta_key) );
269 wp_cache_delete($user_id, 'users');
275 * Retrieve user metadata.
277 * If $user_id is not a number, then the function will fail over with a 'false'
278 * boolean return value. Other returned values depend on whether there is only
279 * one item to be returned, which be that single item type. If there is more
280 * than one metadata value, then it will be list of metadata values.
283 * @uses $wpdb WordPress database object for queries.
285 * @param int $user_id User ID
286 * @param string $meta_key Optional. Metadata key.
289 function get_usermeta( $user_id, $meta_key = '') {
291 $user_id = (int) $user_id;
296 if ( !empty($meta_key) ) {
297 $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key);
298 $user = wp_cache_get($user_id, 'users');
299 // Check the cached user object
300 if ( false !== $user && isset($user->$meta_key) )
301 $metas = array($user->$meta_key);
303 $metas = $wpdb->get_col( $wpdb->prepare("SELECT meta_value FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $meta_key) );
305 $metas = $wpdb->get_col( $wpdb->prepare("SELECT meta_value FROM $wpdb->usermeta WHERE user_id = %d", $user_id) );
308 if ( empty($metas) ) {
309 if ( empty($meta_key) )
315 $metas = array_map('maybe_unserialize', $metas);
317 if ( count($metas) == 1 )
324 * Update metadata of user.
326 * There is no need to serialize values, they will be serialized if it is
327 * needed. The metadata key can only be a string with underscores. All else will
330 * Will remove the metadata, if the meta value is empty.
333 * @uses $wpdb WordPress database object for queries
335 * @param int $user_id User ID
336 * @param string $meta_key Metadata key.
337 * @param mixed $meta_value Metadata value.
338 * @return bool True on successful update, false on failure.
340 function update_usermeta( $user_id, $meta_key, $meta_value ) {
342 if ( !is_numeric( $user_id ) )
344 $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key);
346 /** @todo Might need fix because usermeta data is assumed to be already escaped */
347 if ( is_string($meta_value) )
348 $meta_value = stripslashes($meta_value);
349 $meta_value = maybe_serialize($meta_value);
351 if (empty($meta_value)) {
352 return delete_usermeta($user_id, $meta_key);
355 $cur = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $meta_key) );
357 $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->usermeta ( user_id, meta_key, meta_value )
359 ( %d, %s, %s )", $user_id, $meta_key, $meta_value) );
360 } else if ( $cur->meta_value != $meta_value ) {
361 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->usermeta SET meta_value = %s WHERE user_id = %d AND meta_key = %s", $meta_value, $user_id, $meta_key) );
366 wp_cache_delete($user_id, 'users');
372 // Private helper functions
376 * Setup global user vars.
378 * Used by set_current_user() for back compat. Might be deprecated in the
382 * @global string $userdata User description.
383 * @global string $user_login The user username for logging in
384 * @global int $user_level The level of the user
385 * @global int $user_ID The ID of the user
386 * @global string $user_email The email address of the user
387 * @global string $user_url The url in the user's profile
388 * @global string $user_pass_md5 MD5 of the user's password
389 * @global string $user_identity The display name of the user
391 * @param int $user_id Optional. User ID to setup global data.
393 function setup_userdata($user_id = '') {
394 global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_pass_md5, $user_identity;
396 if ( '' == $user_id )
397 $user = wp_get_current_user();
399 $user = new WP_User($user_id);
401 if ( 0 == $user->ID )
404 $userdata = $user->data;
405 $user_login = $user->user_login;
406 $user_level = (int) isset($user->user_level) ? $user->user_level : 0;
407 $user_ID = (int) $user->ID;
408 $user_email = $user->user_email;
409 $user_url = $user->user_url;
410 $user_pass_md5 = md5($user->user_pass);
411 $user_identity = $user->display_name;
415 * Create dropdown HTML content of users.
417 * The content can either be displayed, which it is by default or retrieved by
418 * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
419 * need to be used; all users will be displayed in that case. Only one can be
420 * used, either 'include' or 'exclude', but not both.
422 * The available arguments are as follows:
424 * <li>show_option_all - Text to show all and whether HTML option exists.</li>
425 * <li>show_option_none - Text for show none and whether HTML option exists.
427 * <li>orderby - SQL order by clause for what order the users appear. Default is
428 * 'display_name'.</li>
429 * <li>order - Default is 'ASC'. Can also be 'DESC'.</li>
430 * <li>include - User IDs to include.</li>
431 * <li>exclude - User IDs to exclude.</li>
432 * <li>multi - Default is 'false'. Whether to skip the ID attribute on the 'select' element.</li>
433 * <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>
434 * <li>echo - Default is '1'. Whether to display or retrieve content.</li>
435 * <li>selected - Which User ID is selected.</li>
436 * <li>name - Default is 'user'. Name attribute of select element.</li>
437 * <li>class - Class attribute of select element.</li>
441 * @uses $wpdb WordPress database object for queries
443 * @param string|array $args Optional. Override defaults.
444 * @return string|null Null on display. String of HTML content on retrieve.
446 function wp_dropdown_users( $args = '' ) {
449 'show_option_all' => '', 'show_option_none' => '',
450 'orderby' => 'display_name', 'order' => 'ASC',
451 'include' => '', 'exclude' => '', 'multi' => 0,
452 'show' => 'display_name', 'echo' => 1,
453 'selected' => 0, 'name' => 'user', 'class' => ''
456 $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
458 $r = wp_parse_args( $args, $defaults );
459 extract( $r, EXTR_SKIP );
461 $query = "SELECT * FROM $wpdb->users";
463 $query_where = array();
465 if ( is_array($include) )
466 $include = join(',', $include);
467 $include = preg_replace('/[^0-9,]/', '', $include); // (int)
469 $query_where[] = "ID IN ($include)";
471 if ( is_array($exclude) )
472 $exclude = join(',', $exclude);
473 $exclude = preg_replace('/[^0-9,]/', '', $exclude); // (int)
475 $query_where[] = "ID NOT IN ($exclude)";
478 $query .= " WHERE " . join(' AND', $query_where);
480 $query .= " ORDER BY $orderby $order";
482 $users = $wpdb->get_results( $query );
485 if ( !empty($users) ) {
486 $id = $multi ? "" : "id='$name'";
488 $output = "<select name='$name' $id class='$class'>\n";
490 if ( $show_option_all )
491 $output .= "\t<option value='0'>$show_option_all</option>\n";
493 if ( $show_option_none )
494 $output .= "\t<option value='-1'>$show_option_none</option>\n";
496 foreach ( (array) $users as $user ) {
497 $user->ID = (int) $user->ID;
498 $_selected = $user->ID == $selected ? " selected='selected'" : '';
499 $display = !empty($user->$show) ? $user->$show : '('. $user->user_login . ')';
500 $output .= "\t<option value='$user->ID'$_selected>" . wp_specialchars($display) . "</option>\n";
503 $output .= "</select>";
506 $output = apply_filters('wp_dropdown_users', $output);
515 * Add user meta data as properties to given user object.
517 * The finished user data is cached, but the cache is not used to fill in the
518 * user data for the given object. Once the function has been used, the cache
519 * should be used to retrieve user data. The purpose seems then to be to ensure
520 * that the data in the object is always fresh.
524 * @uses $wpdb WordPress database object for queries
526 * @param object $user The user data object.
528 function _fill_user( &$user ) {
531 $show = $wpdb->hide_errors();
532 $metavalues = $wpdb->get_results($wpdb->prepare("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = %d", $user->ID));
533 $wpdb->show_errors($show);
536 foreach ( (array) $metavalues as $meta ) {
537 $value = maybe_unserialize($meta->meta_value);
538 $user->{$meta->meta_key} = $value;
542 $level = $wpdb->prefix . 'user_level';
543 if ( isset( $user->{$level} ) )
544 $user->user_level = $user->{$level};
546 // For backwards compat.
547 if ( isset($user->first_name) )
548 $user->user_firstname = $user->first_name;
549 if ( isset($user->last_name) )
550 $user->user_lastname = $user->last_name;
551 if ( isset($user->description) )
552 $user->user_description = $user->description;
554 wp_cache_add($user->ID, $user, 'users');
555 wp_cache_add($user->user_login, $user->ID, 'userlogins');
556 wp_cache_add($user->user_email, $user->ID, 'useremail');