Projects : mp-wp : mp-wp_genesis

mp-wp/wp-includes/user.php

Dir - Raw

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 */
25function 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['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;
41 else
42 $credentials['remember'] = false;
43
44 do_action_ref_array('wp_authenticate', array(&$credentials['user_login'], &$credentials['user_password']));
45
46 if ( '' === $secure_cookie )
47 $secure_cookie = is_ssl() ? true : false;
48
49 // If no credential info provided, check cookie.
50 if ( empty($credentials['user_login']) && empty($credentials['user_password']) ) {
51 $user = wp_validate_auth_cookie();
52 if ( $user )
53 return new WP_User($user);
54
55 if ( $secure_cookie )
56 $auth_cookie = SECURE_AUTH_COOKIE;
57 else
58 $auth_cookie = AUTH_COOKIE;
59
60 if ( !empty($_COOKIE[$auth_cookie]) )
61 return new WP_Error('expired_session', __('Please log in again.'));
62
63 // If the cookie is not set, be silent.
64 return new WP_Error();
65 }
66
67 if ( empty($credentials['user_login']) || empty($credentials['user_password']) ) {
68 $error = new WP_Error();
69
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.'));
74 return $error;
75 }
76
77 $user = wp_authenticate($credentials['user_login'], $credentials['user_password']);
78 if ( is_wp_error($user) )
79 return $user;
80
81 wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
82 do_action('wp_login', $credentials['user_login']);
83 return $user;
84}
85
86/**
87 * Retrieve user data based on field.
88 *
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.
93 *
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
98 * at least displayed.
99 *
100 * @since 1.5.0
101 * @uses $wpdb WordPress database object to create queries.
102 *
103 * @param string $field User field to retrieve.
104 * @param string $user Optional. User username.
105 * @return string The value in the field.
106 */
107function get_profile($field, $user = false) {
108 global $wpdb;
109 if ( !$user )
110 $user = $wpdb->escape($_COOKIE[USER_COOKIE]);
111 return $wpdb->get_var( $wpdb->prepare("SELECT $field FROM $wpdb->users WHERE user_login = %s", $user) );
112}
113
114/**
115 * Number of posts user has written.
116 *
117 * @since 0.71
118 * @uses $wpdb WordPress database object for queries.
119 *
120 * @param int $userid User ID.
121 * @return int Amount of posts user has written.
122 */
123function get_usernumposts($userid) {
124 global $wpdb;
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);
128}
129
130/**
131 * Check that the user login name and password is correct.
132 *
133 * @since 0.71
134 * @todo xmlrpc only. Maybe move to xmlrpc.php.
135 *
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.
139 */
140function user_pass_ok($user_login, $user_pass) {
141 $user = wp_authenticate($user_login, $user_pass);
142 if ( is_wp_error($user) )
143 return false;
144
145 return true;
146}
147
148//
149// User option functions
150//
151
152/**
153 * Retrieve user option that can be either global, user, or blog.
154 *
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.
159 *
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.
163 *
164 * @since 2.0.0
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.
168 *
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.
172 * @return mixed
173 */
174function get_user_option( $option, $user = 0, $check_blog_options = true ) {
175 global $wpdb;
176
177 $option = preg_replace('|[^a-z0-9_]|i', '', $option);
178 if ( empty($user) )
179 $user = wp_get_current_user();
180 else
181 $user = get_userdata($user);
182
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 );
189 else
190 $result = false;
191
192 return apply_filters("get_user_option_{$option}", $result, $option, $user);
193}
194
195/**
196 * Update user option with global blog capability.
197 *
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.
201 *
202 * @since 2.0.0
203 * @uses $wpdb WordPress database object for queries
204 *
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.
209 * @return unknown
210 */
211function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
212 global $wpdb;
213 if ( !$global )
214 $option_name = $wpdb->prefix . $option_name;
215 return update_usermeta( $user_id, $option_name, $newvalue );
216}
217
218/**
219 * Get users for the blog.
220 *
221 * For setups that use the multi-blog feature. Can be used outside of the
222 * multi-blog feature.
223 *
224 * @since 2.2.0
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
227 *
228 * @param int $id Blog ID.
229 * @return array List of users that are part of that Blog ID
230 */
231function get_users_of_blog( $id = '' ) {
232 global $wpdb, $blog_id;
233 if ( empty($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" );
236 return $users;
237}
238
239//
240// User meta functions
241//
242
243/**
244 * Remove user meta data.
245 *
246 * @since 2.0.0
247 * @uses $wpdb WordPress database object for queries.
248 *
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.
253 */
254function delete_usermeta( $user_id, $meta_key, $meta_value = '' ) {
255 global $wpdb;
256 if ( !is_numeric( $user_id ) )
257 return false;
258 $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key);
259
260 if ( is_array($meta_value) || is_object($meta_value) )
261 $meta_value = serialize($meta_value);
262 $meta_value = trim( $meta_value );
263
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) );
266 else
267 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $meta_key) );
268
269 wp_cache_delete($user_id, 'users');
270
271 return true;
272}
273
274/**
275 * Retrieve user metadata.
276 *
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.
281 *
282 * @since 2.0.0
283 * @uses $wpdb WordPress database object for queries.
284 *
285 * @param int $user_id User ID
286 * @param string $meta_key Optional. Metadata key.
287 * @return mixed
288 */
289function get_usermeta( $user_id, $meta_key = '') {
290 global $wpdb;
291 $user_id = (int) $user_id;
292
293 if ( !$user_id )
294 return false;
295
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);
302 else
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) );
304 } else {
305 $metas = $wpdb->get_col( $wpdb->prepare("SELECT meta_value FROM $wpdb->usermeta WHERE user_id = %d", $user_id) );
306 }
307
308 if ( empty($metas) ) {
309 if ( empty($meta_key) )
310 return array();
311 else
312 return '';
313 }
314
315 $metas = array_map('maybe_unserialize', $metas);
316
317 if ( count($metas) == 1 )
318 return $metas[0];
319 else
320 return $metas;
321}
322
323/**
324 * Update metadata of user.
325 *
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
328 * be removed.
329 *
330 * Will remove the metadata, if the meta value is empty.
331 *
332 * @since 2.0.0
333 * @uses $wpdb WordPress database object for queries
334 *
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.
339 */
340function update_usermeta( $user_id, $meta_key, $meta_value ) {
341 global $wpdb;
342 if ( !is_numeric( $user_id ) )
343 return false;
344 $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key);
345
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);
350
351 if (empty($meta_value)) {
352 return delete_usermeta($user_id, $meta_key);
353 }
354
355 $cur = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $meta_key) );
356 if ( !$cur ) {
357 $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->usermeta ( user_id, meta_key, meta_value )
358 VALUES
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) );
362 } else {
363 return false;
364 }
365
366 wp_cache_delete($user_id, 'users');
367
368 return true;
369}
370
371//
372// Private helper functions
373//
374
375/**
376 * Setup global user vars.
377 *
378 * Used by set_current_user() for back compat. Might be deprecated in the
379 * future.
380 *
381 * @since 2.0.4
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
390 *
391 * @param int $user_id Optional. User ID to setup global data.
392 */
393function setup_userdata($user_id = '') {
394 global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_pass_md5, $user_identity;
395
396 if ( '' == $user_id )
397 $user = wp_get_current_user();
398 else
399 $user = new WP_User($user_id);
400
401 if ( 0 == $user->ID )
402 return;
403
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;
412}
413
414/**
415 * Create dropdown HTML content of users.
416 *
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.
421 *
422 * The available arguments are as follows:
423 * <ol>
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.
426 * </li>
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>
438 * </ol>
439 *
440 * @since 2.3.0
441 * @uses $wpdb WordPress database object for queries
442 *
443 * @param string|array $args Optional. Override defaults.
444 * @return string|null Null on display. String of HTML content on retrieve.
445 */
446function wp_dropdown_users( $args = '' ) {
447 global $wpdb;
448 $defaults = array(
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' => ''
454 );
455
456 $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
457
458 $r = wp_parse_args( $args, $defaults );
459 extract( $r, EXTR_SKIP );
460
461 $query = "SELECT * FROM $wpdb->users";
462
463 $query_where = array();
464
465 if ( is_array($include) )
466 $include = join(',', $include);
467 $include = preg_replace('/[^0-9,]/', '', $include); // (int)
468 if ( $include )
469 $query_where[] = "ID IN ($include)";
470
471 if ( is_array($exclude) )
472 $exclude = join(',', $exclude);
473 $exclude = preg_replace('/[^0-9,]/', '', $exclude); // (int)
474 if ( $exclude )
475 $query_where[] = "ID NOT IN ($exclude)";
476
477 if ( $query_where )
478 $query .= " WHERE " . join(' AND', $query_where);
479
480 $query .= " ORDER BY $orderby $order";
481
482 $users = $wpdb->get_results( $query );
483
484 $output = '';
485 if ( !empty($users) ) {
486 $id = $multi ? "" : "id='$name'";
487
488 $output = "<select name='$name' $id class='$class'>\n";
489
490 if ( $show_option_all )
491 $output .= "\t<option value='0'>$show_option_all</option>\n";
492
493 if ( $show_option_none )
494 $output .= "\t<option value='-1'>$show_option_none</option>\n";
495
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";
501 }
502
503 $output .= "</select>";
504 }
505
506 $output = apply_filters('wp_dropdown_users', $output);
507
508 if ( $echo )
509 echo $output;
510
511 return $output;
512}
513
514/**
515 * Add user meta data as properties to given user object.
516 *
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.
521 *
522 * @access private
523 * @since 2.5.0
524 * @uses $wpdb WordPress database object for queries
525 *
526 * @param object $user The user data object.
527 */
528function _fill_user( &$user ) {
529 global $wpdb;
530
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);
534
535 if ( $metavalues ) {
536 foreach ( (array) $metavalues as $meta ) {
537 $value = maybe_unserialize($meta->meta_value);
538 $user->{$meta->meta_key} = $value;
539 }
540 }
541
542 $level = $wpdb->prefix . 'user_level';
543 if ( isset( $user->{$level} ) )
544 $user->user_level = $user->{$level};
545
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;
553
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');
557}
558
559?>