comparison modules/user/user.module @ 1:c1f4ac30525a 6.0

Drupal 6.0
author Franck Deroche <webmaster@defr.org>
date Tue, 23 Dec 2008 14:28:28 +0100
parents
children 2427550111ae
comparison
equal deleted inserted replaced
0:5a113a1c4740 1:c1f4ac30525a
1 <?php
2 // $Id: user.module,v 1.892 2008/02/03 19:23:01 goba Exp $
3
4 /**
5 * @file
6 * Enables the user registration and login system.
7 */
8
9 define('USERNAME_MAX_LENGTH', 60);
10 define('EMAIL_MAX_LENGTH', 64);
11
12 /**
13 * Invokes hook_user() in every module.
14 *
15 * We cannot use module_invoke() for this, because the arguments need to
16 * be passed by reference.
17 */
18 function user_module_invoke($type, &$array, &$user, $category = NULL) {
19 foreach (module_list() as $module) {
20 $function = $module .'_user';
21 if (function_exists($function)) {
22 $function($type, $array, $user, $category);
23 }
24 }
25 }
26
27 /**
28 * Implementation of hook_theme().
29 */
30 function user_theme() {
31 return array(
32 'user_picture' => array(
33 'arguments' => array('account' => NULL),
34 'template' => 'user-picture',
35 ),
36 'user_profile' => array(
37 'arguments' => array('account' => NULL),
38 'template' => 'user-profile',
39 'file' => 'user.pages.inc',
40 ),
41 'user_profile_category' => array(
42 'arguments' => array('element' => NULL),
43 'template' => 'user-profile-category',
44 'file' => 'user.pages.inc',
45 ),
46 'user_profile_item' => array(
47 'arguments' => array('element' => NULL),
48 'template' => 'user-profile-item',
49 'file' => 'user.pages.inc',
50 ),
51 'user_list' => array(
52 'arguments' => array('users' => NULL, 'title' => NULL),
53 ),
54 'user_admin_perm' => array(
55 'arguments' => array('form' => NULL),
56 'file' => 'user.admin.inc',
57 ),
58 'user_admin_new_role' => array(
59 'arguments' => array('form' => NULL),
60 'file' => 'user.admin.inc',
61 ),
62 'user_admin_account' => array(
63 'arguments' => array('form' => NULL),
64 'file' => 'user.admin.inc',
65 ),
66 'user_filter_form' => array(
67 'arguments' => array('form' => NULL),
68 'file' => 'user.admin.inc',
69 ),
70 'user_filters' => array(
71 'arguments' => array('form' => NULL),
72 'file' => 'user.admin.inc',
73 ),
74 'user_signature' => array(
75 'arguments' => array('signature' => NULL),
76 ),
77 );
78 }
79
80 function user_external_load($authname) {
81 $result = db_query("SELECT uid FROM {authmap} WHERE authname = '%s'", $authname);
82
83 if ($user = db_fetch_array($result)) {
84 return user_load($user);
85 }
86 else {
87 return 0;
88 }
89 }
90
91 /**
92 * Perform standard Drupal login operations for a user object.
93 *
94 * The user object must already be authenticated. This function verifies
95 * that the user account is not blocked/denied and then performs the login,
96 * updates the login timestamp in the database, invokes hook_user('login'),
97 * and regenerates the session.
98 *
99 * @param $account
100 * An authenticated user object to be set as the currently logged
101 * in user.
102 * @param $edit
103 * The array of form values submitted by the user, if any.
104 * This array is passed to hook_user op login.
105 * @return boolean
106 * TRUE if the login succeeds, FALSE otherwise.
107 */
108 function user_external_login($account, $edit = array()) {
109 $form = drupal_get_form('user_login');
110
111 $state['values'] = $edit;
112 if (empty($state['values']['name'])) {
113 $state['values']['name'] = $account->name;
114 }
115
116 // Check if user is blocked or denied by access rules.
117 user_login_name_validate($form, $state, (array)$account);
118 if (form_get_errors()) {
119 // Invalid login.
120 return FALSE;
121 }
122
123 // Valid login.
124 global $user;
125 $user = $account;
126 user_authenticate_finalize($state['values']);
127 return TRUE;
128 }
129
130 /**
131 * Fetch a user object.
132 *
133 * @param $array
134 * An associative array of attributes to search for in selecting the
135 * user, such as user name or e-mail address.
136 *
137 * @return
138 * A fully-loaded $user object upon successful user load or FALSE if user
139 * cannot be loaded.
140 */
141 function user_load($array = array()) {
142 // Dynamically compose a SQL query:
143 $query = array();
144 $params = array();
145
146 if (is_numeric($array)) {
147 $array = array('uid' => $array);
148 }
149 elseif (!is_array($array)) {
150 return FALSE;
151 }
152
153 foreach ($array as $key => $value) {
154 if ($key == 'uid' || $key == 'status') {
155 $query[] = "$key = %d";
156 $params[] = $value;
157 }
158 else if ($key == 'pass') {
159 $query[] = "pass = '%s'";
160 $params[] = md5($value);
161 }
162 else {
163 $query[]= "LOWER($key) = LOWER('%s')";
164 $params[] = $value;
165 }
166 }
167 $result = db_query('SELECT * FROM {users} u WHERE '. implode(' AND ', $query), $params);
168
169 if ($user = db_fetch_object($result)) {
170 $user = drupal_unpack($user);
171
172 $user->roles = array();
173 if ($user->uid) {
174 $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
175 }
176 else {
177 $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
178 }
179 $result = db_query('SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = %d', $user->uid);
180 while ($role = db_fetch_object($result)) {
181 $user->roles[$role->rid] = $role->name;
182 }
183 user_module_invoke('load', $array, $user);
184 }
185 else {
186 $user = FALSE;
187 }
188
189 return $user;
190 }
191
192 /**
193 * Save changes to a user account or add a new user.
194 *
195 * @param $account
196 * The $user object for the user to modify or add. If $user->uid is
197 * omitted, a new user will be added.
198 *
199 * @param $array
200 * (optional) An array of fields and values to save. For example,
201 * array('name' => 'My name'); Setting a field to NULL deletes it from
202 * the data column.
203 *
204 * @param $category
205 * (optional) The category for storing profile information in.
206 *
207 * @return
208 * A fully-loaded $user object upon successful save or FALSE if the save failed.
209 */
210 function user_save($account, $array = array(), $category = 'account') {
211 // Dynamically compose a SQL query:
212 $user_fields = user_fields();
213 if (is_object($account) && $account->uid) {
214 user_module_invoke('update', $array, $account, $category);
215 $query = '';
216 $data = unserialize(db_result(db_query('SELECT data FROM {users} WHERE uid = %d', $account->uid)));
217 // Consider users edited by an administrator as logged in, if they haven't
218 // already, so anonymous users can view the profile (if allowed).
219 if (empty($array['access']) && empty($account->access) && user_access('administer users')) {
220 $array['access'] = time();
221 }
222 foreach ($array as $key => $value) {
223 if ($key == 'pass' && !empty($value)) {
224 $query .= "$key = '%s', ";
225 $v[] = md5($value);
226 }
227 else if ((substr($key, 0, 4) !== 'auth') && ($key != 'pass')) {
228 if (in_array($key, $user_fields)) {
229 // Save standard fields.
230 $query .= "$key = '%s', ";
231 $v[] = $value;
232 }
233 else if ($key != 'roles') {
234 // Roles is a special case: it used below.
235 if ($value === NULL) {
236 unset($data[$key]);
237 }
238 else {
239 $data[$key] = $value;
240 }
241 }
242 }
243 }
244 $query .= "data = '%s' ";
245 $v[] = serialize($data);
246
247 $success = db_query("UPDATE {users} SET $query WHERE uid = %d", array_merge($v, array($account->uid)));
248 if (!$success) {
249 // The query failed - better to abort the save than risk further data loss.
250 return FALSE;
251 }
252
253 // Reload user roles if provided.
254 if (isset($array['roles']) && is_array($array['roles'])) {
255 db_query('DELETE FROM {users_roles} WHERE uid = %d', $account->uid);
256
257 foreach (array_keys($array['roles']) as $rid) {
258 if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
259 db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $account->uid, $rid);
260 }
261 }
262 }
263
264 // Delete a blocked user's sessions to kick them if they are online.
265 if (isset($array['status']) && $array['status'] == 0) {
266 sess_destroy_uid($account->uid);
267 }
268
269 // If the password changed, delete all open sessions and recreate
270 // the current one.
271 if (!empty($array['pass'])) {
272 sess_destroy_uid($account->uid);
273 sess_regenerate();
274 }
275
276 // Refresh user object.
277 $user = user_load(array('uid' => $account->uid));
278
279 // Send emails after we have the new user object.
280 if (isset($array['status']) && $array['status'] != $account->status) {
281 // The user's status is changing; conditionally send notification email.
282 $op = $array['status'] == 1 ? 'status_activated' : 'status_blocked';
283 _user_mail_notify($op, $user);
284 }
285
286 user_module_invoke('after_update', $array, $user, $category);
287 }
288 else {
289 // Allow 'created' to be set by the caller.
290 if (!isset($array['created'])) {
291 $array['created'] = time();
292 }
293 // Consider users created by an administrator as already logged in, so
294 // anonymous users can view the profile (if allowed).
295 if (empty($array['access']) && user_access('administer users')) {
296 $array['access'] = time();
297 }
298
299 // Note: we wait to save the data column to prevent module-handled
300 // fields from being saved there. We cannot invoke hook_user('insert') here
301 // because we don't have a fully initialized user object yet.
302 foreach ($array as $key => $value) {
303 switch ($key) {
304 case 'pass':
305 $fields[] = $key;
306 $values[] = md5($value);
307 $s[] = "'%s'";
308 break;
309 case 'mode': case 'sort': case 'timezone':
310 case 'threshold': case 'created': case 'access':
311 case 'login': case 'status':
312 $fields[] = $key;
313 $values[] = $value;
314 $s[] = "%d";
315 break;
316 default:
317 if (substr($key, 0, 4) !== 'auth' && in_array($key, $user_fields)) {
318 $fields[] = $key;
319 $values[] = $value;
320 $s[] = "'%s'";
321 }
322 break;
323 }
324 }
325 $success = db_query('INSERT INTO {users} ('. implode(', ', $fields) .') VALUES ('. implode(', ', $s) .')', $values);
326 if (!$success) {
327 // On a failed INSERT some other existing user's uid may be returned.
328 // We must abort to avoid overwriting their account.
329 return FALSE;
330 }
331
332 // Build the initial user object.
333 $array['uid'] = db_last_insert_id('users', 'uid');
334 $user = user_load(array('uid' => $array['uid']));
335
336 user_module_invoke('insert', $array, $user, $category);
337
338 // Build and save the serialized data field now.
339 $data = array();
340 foreach ($array as $key => $value) {
341 if ((substr($key, 0, 4) !== 'auth') && ($key != 'roles') && (!in_array($key, $user_fields)) && ($value !== NULL)) {
342 $data[$key] = $value;
343 }
344 }
345 db_query("UPDATE {users} SET data = '%s' WHERE uid = %d", serialize($data), $user->uid);
346
347 // Save user roles (delete just to be safe).
348 if (isset($array['roles']) && is_array($array['roles'])) {
349 db_query('DELETE FROM {users_roles} WHERE uid = %d', $array['uid']);
350 foreach (array_keys($array['roles']) as $rid) {
351 if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
352 db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $array['uid'], $rid);
353 }
354 }
355 }
356
357 // Build the finished user object.
358 $user = user_load(array('uid' => $array['uid']));
359 }
360
361 // Save distributed authentication mappings.
362 $authmaps = array();
363 foreach ($array as $key => $value) {
364 if (substr($key, 0, 4) == 'auth') {
365 $authmaps[$key] = $value;
366 }
367 }
368 if (sizeof($authmaps) > 0) {
369 user_set_authmaps($user, $authmaps);
370 }
371
372 return $user;
373 }
374
375 /**
376 * Verify the syntax of the given name.
377 */
378 function user_validate_name($name) {
379 if (!strlen($name)) return t('You must enter a username.');
380 if (substr($name, 0, 1) == ' ') return t('The username cannot begin with a space.');
381 if (substr($name, -1) == ' ') return t('The username cannot end with a space.');
382 if (strpos($name, ' ') !== FALSE) return t('The username cannot contain multiple spaces in a row.');
383 if (ereg("[^\x80-\xF7 [:alnum:]@_.-]", $name)) return t('The username contains an illegal character.');
384 if (preg_match('/[\x{80}-\x{A0}'. // Non-printable ISO-8859-1 + NBSP
385 '\x{AD}'. // Soft-hyphen
386 '\x{2000}-\x{200F}'. // Various space characters
387 '\x{2028}-\x{202F}'. // Bidirectional text overrides
388 '\x{205F}-\x{206F}'. // Various text hinting characters
389 '\x{FEFF}'. // Byte order mark
390 '\x{FF01}-\x{FF60}'. // Full-width latin
391 '\x{FFF9}-\x{FFFD}'. // Replacement characters
392 '\x{0}]/u', // NULL byte
393 $name)) {
394 return t('The username contains an illegal character.');
395 }
396 if (strpos($name, '@') !== FALSE && !eregi('@([0-9a-z](-?[0-9a-z])*.)+[a-z]{2}([zmuvtg]|fo|me)?$', $name)) return t('The username is not a valid authentication ID.');
397 if (strlen($name) > USERNAME_MAX_LENGTH) return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
398 }
399
400 function user_validate_mail($mail) {
401 if (!$mail) return t('You must enter an e-mail address.');
402 if (!valid_email_address($mail)) {
403 return t('The e-mail address %mail is not valid.', array('%mail' => $mail));
404 }
405 }
406
407 function user_validate_picture(&$form, &$form_state) {
408 // If required, validate the uploaded picture.
409 $validators = array(
410 'file_validate_is_image' => array(),
411 'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
412 'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
413 );
414 if ($file = file_save_upload('picture_upload', $validators)) {
415 // Remove the old picture.
416 if (isset($form_state['values']['_account']->picture) && file_exists($form_state['values']['_account']->picture)) {
417 file_delete($form_state['values']['_account']->picture);
418 }
419
420 // The image was saved using file_save_upload() and was added to the
421 // files table as a temporary file. We'll make a copy and let the garbage
422 // collector delete the original upload.
423 $info = image_get_info($file->filepath);
424 $destination = variable_get('user_picture_path', 'pictures') .'/picture-'. $form['#uid'] .'.'. $info['extension'];
425 if (file_copy($file, $destination, FILE_EXISTS_REPLACE)) {
426 $form_state['values']['picture'] = $file->filepath;
427 }
428 else {
429 form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('user_picture_path', 'pictures'))));
430 }
431 }
432 }
433
434 /**
435 * Generate a random alphanumeric password.
436 */
437 function user_password($length = 10) {
438 // This variable contains the list of allowable characters for the
439 // password. Note that the number 0 and the letter 'O' have been
440 // removed to avoid confusion between the two. The same is true
441 // of 'I', 1, and 'l'.
442 $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
443
444 // Zero-based count of characters in the allowable list:
445 $len = strlen($allowable_characters) - 1;
446
447 // Declare the password as a blank string.
448 $pass = '';
449
450 // Loop the number of times specified by $length.
451 for ($i = 0; $i < $length; $i++) {
452
453 // Each iteration, pick a random character from the
454 // allowable string and append it to the password:
455 $pass .= $allowable_characters[mt_rand(0, $len)];
456 }
457
458 return $pass;
459 }
460
461 /**
462 * Determine whether the user has a given privilege.
463 *
464 * @param $string
465 * The permission, such as "administer nodes", being checked for.
466 * @param $account
467 * (optional) The account to check, if not given use currently logged in user.
468 * @param $reset
469 * (optional) Resets the user's permissions cache, which will result in a
470 * recalculation of the user's permissions. This is necessary to support
471 * dynamically added user roles.
472 *
473 * @return
474 * Boolean TRUE if the current user has the requested permission.
475 *
476 * All permission checks in Drupal should go through this function. This
477 * way, we guarantee consistent behavior, and ensure that the superuser
478 * can perform all actions.
479 */
480 function user_access($string, $account = NULL, $reset = FALSE) {
481 global $user;
482 static $perm = array();
483
484 if ($reset) {
485 unset($perm);
486 }
487
488 if (is_null($account)) {
489 $account = $user;
490 }
491
492 // User #1 has all privileges:
493 if ($account->uid == 1) {
494 return TRUE;
495 }
496
497 // To reduce the number of SQL queries, we cache the user's permissions
498 // in a static variable.
499 if (!isset($perm[$account->uid])) {
500 $result = db_query("SELECT p.perm FROM {role} r INNER JOIN {permission} p ON p.rid = r.rid WHERE r.rid IN (". db_placeholders($account->roles) .")", array_keys($account->roles));
501
502 $perms = array();
503 while ($row = db_fetch_object($result)) {
504 $perms += array_flip(explode(', ', $row->perm));
505 }
506 $perm[$account->uid] = $perms;
507 }
508
509 return isset($perm[$account->uid][$string]);
510 }
511
512 /**
513 * Checks for usernames blocked by user administration.
514 *
515 * @return boolean TRUE for blocked users, FALSE for active.
516 */
517 function user_is_blocked($name) {
518 $deny = db_fetch_object(db_query("SELECT name FROM {users} WHERE status = 0 AND name = LOWER('%s')", $name));
519
520 return $deny;
521 }
522
523 function user_fields() {
524 static $fields;
525
526 if (!$fields) {
527 $result = db_query('SELECT * FROM {users} WHERE uid = 1');
528 if ($field = db_fetch_array($result)) {
529 $fields = array_keys($field);
530 }
531 else {
532 // Make sure we return the default fields at least.
533 $fields = array('uid', 'name', 'pass', 'mail', 'picture', 'mode', 'sort', 'threshold', 'theme', 'signature', 'created', 'access', 'login', 'status', 'timezone', 'language', 'init', 'data');
534 }
535 }
536
537 return $fields;
538 }
539
540 /**
541 * Implementation of hook_perm().
542 */
543 function user_perm() {
544 return array('administer permissions', 'administer users', 'access user profiles', 'change own username');
545 }
546
547 /**
548 * Implementation of hook_file_download().
549 *
550 * Ensure that user pictures (avatars) are always downloadable.
551 */
552 function user_file_download($file) {
553 if (strpos($file, variable_get('user_picture_path', 'pictures') .'/picture-') === 0) {
554 $info = image_get_info(file_create_path($file));
555 return array('Content-type: '. $info['mime_type']);
556 }
557 }
558
559 /**
560 * Implementation of hook_search().
561 */
562 function user_search($op = 'search', $keys = NULL, $skip_access_check = FALSE) {
563 switch ($op) {
564 case 'name':
565 if ($skip_access_check || user_access('access user profiles')) {
566 return t('Users');
567 }
568 case 'search':
569 if (user_access('access user profiles')) {
570 $find = array();
571 // Replace wildcards with MySQL/PostgreSQL wildcards.
572 $keys = preg_replace('!\*+!', '%', $keys);
573 if (user_access('administer users')) {
574 // Administrators can also search in the otherwise private email field.
575 $result = pager_query("SELECT name, uid, mail FROM {users} WHERE LOWER(name) LIKE LOWER('%%%s%%') OR LOWER(mail) LIKE LOWER('%%%s%%')", 15, 0, NULL, $keys, $keys);
576 while ($account = db_fetch_object($result)) {
577 $find[] = array('title' => $account->name .' ('. $account->mail .')', 'link' => url('user/'. $account->uid, array('absolute' => TRUE)));
578 }
579 }
580 else {
581 $result = pager_query("SELECT name, uid FROM {users} WHERE LOWER(name) LIKE LOWER('%%%s%%')", 15, 0, NULL, $keys);
582 while ($account = db_fetch_object($result)) {
583 $find[] = array('title' => $account->name, 'link' => url('user/'. $account->uid, array('absolute' => TRUE)));
584 }
585 }
586 return $find;
587 }
588 }
589 }
590
591 /**
592 * Implementation of hook_elements().
593 */
594 function user_elements() {
595 return array(
596 'user_profile_category' => array(),
597 'user_profile_item' => array(),
598 );
599 }
600
601 /**
602 * Implementation of hook_user().
603 */
604 function user_user($type, &$edit, &$account, $category = NULL) {
605 if ($type == 'view') {
606 $account->content['user_picture'] = array(
607 '#value' => theme('user_picture', $account),
608 '#weight' => -10,
609 );
610 if (!isset($account->content['summary'])) {
611 $account->content['summary'] = array();
612 }
613 $account->content['summary'] += array(
614 '#type' => 'user_profile_category',
615 '#attributes' => array('class' => 'user-member'),
616 '#weight' => 5,
617 '#title' => t('History'),
618 );
619 $account->content['summary']['member_for'] = array(
620 '#type' => 'user_profile_item',
621 '#title' => t('Member for'),
622 '#value' => format_interval(time() - $account->created),
623 );
624 }
625 if ($type == 'form' && $category == 'account') {
626 $form_state = array();
627 return user_edit_form($form_state, arg(1), $edit);
628 }
629
630 if ($type == 'validate' && $category == 'account') {
631 return _user_edit_validate(arg(1), $edit);
632 }
633
634 if ($type == 'submit' && $category == 'account') {
635 return _user_edit_submit(arg(1), $edit);
636 }
637
638 if ($type == 'categories') {
639 return array(array('name' => 'account', 'title' => t('Account settings'), 'weight' => 1));
640 }
641 }
642
643 function user_login_block() {
644 $form = array(
645 '#action' => url($_GET['q'], array('query' => drupal_get_destination())),
646 '#id' => 'user-login-form',
647 '#validate' => user_login_default_validators(),
648 '#submit' => array('user_login_submit'),
649 );
650 $form['name'] = array('#type' => 'textfield',
651 '#title' => t('Username'),
652 '#maxlength' => USERNAME_MAX_LENGTH,
653 '#size' => 15,
654 '#required' => TRUE,
655 );
656 $form['pass'] = array('#type' => 'password',
657 '#title' => t('Password'),
658 '#maxlength' => 60,
659 '#size' => 15,
660 '#required' => TRUE,
661 );
662 $form['submit'] = array('#type' => 'submit',
663 '#value' => t('Log in'),
664 );
665 $items = array();
666 if (variable_get('user_register', 1)) {
667 $items[] = l(t('Create new account'), 'user/register', array('title' => t('Create a new user account.')));
668 }
669 $items[] = l(t('Request new password'), 'user/password', array('title' => t('Request new password via e-mail.')));
670 $form['links'] = array('#value' => theme('item_list', $items));
671 return $form;
672 }
673
674 /**
675 * Implementation of hook_block().
676 */
677 function user_block($op = 'list', $delta = 0, $edit = array()) {
678 global $user;
679
680 if ($op == 'list') {
681 $blocks[0]['info'] = t('User login');
682 // Not worth caching.
683 $blocks[0]['cache'] = BLOCK_NO_CACHE;
684
685 $blocks[1]['info'] = t('Navigation');
686 // Menu blocks can't be cached because each menu item can have
687 // a custom access callback. menu.inc manages its own caching.
688 $blocks[1]['cache'] = BLOCK_NO_CACHE;
689
690 $blocks[2]['info'] = t('Who\'s new');
691
692 // Too dynamic to cache.
693 $blocks[3]['info'] = t('Who\'s online');
694 $blocks[3]['cache'] = BLOCK_NO_CACHE;
695 return $blocks;
696 }
697 else if ($op == 'configure' && $delta == 2) {
698 $form['user_block_whois_new_count'] = array(
699 '#type' => 'select',
700 '#title' => t('Number of users to display'),
701 '#default_value' => variable_get('user_block_whois_new_count', 5),
702 '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
703 );
704 return $form;
705 }
706 else if ($op == 'configure' && $delta == 3) {
707 $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800, 2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval');
708 $form['user_block_seconds_online'] = array('#type' => 'select', '#title' => t('User activity'), '#default_value' => variable_get('user_block_seconds_online', 900), '#options' => $period, '#description' => t('A user is considered online for this long after they have last viewed a page.'));
709 $form['user_block_max_list_count'] = array('#type' => 'select', '#title' => t('User list length'), '#default_value' => variable_get('user_block_max_list_count', 10), '#options' => drupal_map_assoc(array(0, 5, 10, 15, 20, 25, 30, 40, 50, 75, 100)), '#description' => t('Maximum number of currently online users to display.'));
710
711 return $form;
712 }
713 else if ($op == 'save' && $delta == 2) {
714 variable_set('user_block_whois_new_count', $edit['user_block_whois_new_count']);
715 }
716 else if ($op == 'save' && $delta == 3) {
717 variable_set('user_block_seconds_online', $edit['user_block_seconds_online']);
718 variable_set('user_block_max_list_count', $edit['user_block_max_list_count']);
719 }
720 else if ($op == 'view') {
721 $block = array();
722
723 switch ($delta) {
724 case 0:
725 // For usability's sake, avoid showing two login forms on one page.
726 if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
727
728 $block['subject'] = t('User login');
729 $block['content'] = drupal_get_form('user_login_block');
730 }
731 return $block;
732
733 case 1:
734 if ($menu = menu_tree()) {
735 $block['subject'] = $user->uid ? check_plain($user->name) : t('Navigation');
736 $block['content'] = $menu;
737 }
738 return $block;
739
740 case 2:
741 if (user_access('access content')) {
742 // Retrieve a list of new users who have subsequently accessed the site successfully.
743 $result = db_query_range('SELECT uid, name FROM {users} WHERE status != 0 AND access != 0 ORDER BY created DESC', 0, variable_get('user_block_whois_new_count', 5));
744 while ($account = db_fetch_object($result)) {
745 $items[] = $account;
746 }
747 $output = theme('user_list', $items);
748
749 $block['subject'] = t('Who\'s new');
750 $block['content'] = $output;
751 }
752 return $block;
753
754 case 3:
755 if (user_access('access content')) {
756 // Count users active within the defined period.
757 $interval = time() - variable_get('user_block_seconds_online', 900);
758
759 // Perform database queries to gather online user lists. We use s.timestamp
760 // rather than u.access because it is much faster.
761 $anonymous_count = sess_count($interval);
762 $authenticated_users = db_query('SELECT DISTINCT u.uid, u.name, s.timestamp FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= %d AND s.uid > 0 ORDER BY s.timestamp DESC', $interval);
763 $authenticated_count = 0;
764 $max_users = variable_get('user_block_max_list_count', 10);
765 $items = array();
766 while ($account = db_fetch_object($authenticated_users)) {
767 if ($max_users > 0) {
768 $items[] = $account;
769 $max_users--;
770 }
771 $authenticated_count++;
772 }
773
774 // Format the output with proper grammar.
775 if ($anonymous_count == 1 && $authenticated_count == 1) {
776 $output = t('There is currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', '@count users'), '%visitors' => format_plural($anonymous_count, '1 guest', '@count guests')));
777 }
778 else {
779 $output = t('There are currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', '@count users'), '%visitors' => format_plural($anonymous_count, '1 guest', '@count guests')));
780 }
781
782 // Display a list of currently online users.
783 $max_users = variable_get('user_block_max_list_count', 10);
784 if ($authenticated_count && $max_users) {
785 $output .= theme('user_list', $items, t('Online users'));
786 }
787
788 $block['subject'] = t('Who\'s online');
789 $block['content'] = $output;
790 }
791 return $block;
792 }
793 }
794 }
795
796 /**
797 * Process variables for user-picture.tpl.php.
798 *
799 * The $variables array contains the following arguments:
800 * - $account
801 *
802 * @see user-picture.tpl.php
803 */
804 function template_preprocess_user_picture(&$variables) {
805 $variables['picture'] = '';
806 if (variable_get('user_pictures', 0)) {
807 $account = $variables['account'];
808 if (!empty($account->picture) && file_exists($account->picture)) {
809 $picture = file_create_url($account->picture);
810 }
811 else if (variable_get('user_picture_default', '')) {
812 $picture = variable_get('user_picture_default', '');
813 }
814
815 if (isset($picture)) {
816 $alt = t("@user's picture", array('@user' => $account->name ? $account->name : variable_get('anonymous', t('Anonymous'))));
817 $variables['picture'] = theme('image', $picture, $alt, $alt, '', FALSE);
818 if (!empty($account->uid) && user_access('access user profiles')) {
819 $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
820 $variables['picture'] = l($variables['picture'], "user/$account->uid", $attributes);
821 }
822 }
823 }
824 }
825
826 /**
827 * Make a list of users.
828 *
829 * @param $users
830 * An array with user objects. Should contain at least the name and uid.
831 * @param $title
832 * (optional) Title to pass on to theme_item_list().
833 *
834 * @ingroup themeable
835 */
836 function theme_user_list($users, $title = NULL) {
837 if (!empty($users)) {
838 foreach ($users as $user) {
839 $items[] = theme('username', $user);
840 }
841 }
842 return theme('item_list', $items, $title);
843 }
844
845 function user_is_anonymous() {
846 // Menu administrators can see items for anonymous when administering.
847 return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
848 }
849
850 function user_is_logged_in() {
851 return (bool)$GLOBALS['user']->uid;
852 }
853
854 function user_register_access() {
855 return user_is_anonymous() && variable_get('user_register', 1);
856 }
857
858 function user_view_access($account) {
859 return $account && $account->uid &&
860 (
861 // Always let users view their own profile.
862 ($GLOBALS['user']->uid == $account->uid) ||
863 // Administrators can view all accounts.
864 user_access('administer users') ||
865 // The user is not blocked and logged in at least once.
866 ($account->access && $account->status && user_access('access user profiles'))
867 );
868 }
869
870 function user_edit_access($account) {
871 return (($GLOBALS['user']->uid == $account->uid) || user_access('administer users')) && $account->uid > 0;
872 }
873
874 function user_load_self($arg) {
875 $arg[1] = user_load($GLOBALS['user']->uid);
876 return $arg;
877 }
878
879 /**
880 * Implementation of hook_menu().
881 */
882 function user_menu() {
883 $items['user/autocomplete'] = array(
884 'title' => 'User autocomplete',
885 'page callback' => 'user_autocomplete',
886 'access callback' => 'user_access',
887 'access arguments' => array('access user profiles'),
888 'type' => MENU_CALLBACK,
889 'file' => 'user.pages.inc',
890 );
891
892 // Registration and login pages.
893 $items['user'] = array(
894 'title' => 'User account',
895 'page callback' => 'user_page',
896 'access callback' => TRUE,
897 'type' => MENU_CALLBACK,
898 'file' => 'user.pages.inc',
899 );
900
901 $items['user/login'] = array(
902 'title' => 'Log in',
903 'access callback' => 'user_is_anonymous',
904 'type' => MENU_DEFAULT_LOCAL_TASK,
905 );
906
907 $items['user/register'] = array(
908 'title' => 'Create new account',
909 'page callback' => 'drupal_get_form',
910 'page arguments' => array('user_register'),
911 'access callback' => 'user_register_access',
912 'type' => MENU_LOCAL_TASK,
913 'file' => 'user.pages.inc',
914 );
915
916 $items['user/password'] = array(
917 'title' => 'Request new password',
918 'page callback' => 'drupal_get_form',
919 'page arguments' => array('user_pass'),
920 'access callback' => 'user_is_anonymous',
921 'type' => MENU_LOCAL_TASK,
922 'file' => 'user.pages.inc',
923 );
924 $items['user/reset/%/%/%'] = array(
925 'title' => 'Reset password',
926 'page callback' => 'drupal_get_form',
927 'page arguments' => array('user_pass_reset', 2, 3, 4),
928 'access callback' => TRUE,
929 'type' => MENU_CALLBACK,
930 'file' => 'user.pages.inc',
931 );
932
933 // Admin user pages.
934 $items['admin/user'] = array(
935 'title' => 'User management',
936 'description' => "Manage your site's users, groups and access to site features.",
937 'position' => 'left',
938 'page callback' => 'system_admin_menu_block_page',
939 'access arguments' => array('access administration pages'),
940 'file' => 'system.admin.inc',
941 'file path' => drupal_get_path('module', 'system'),
942 );
943 $items['admin/user/user'] = array(
944 'title' => 'Users',
945 'description' => 'List, add, and edit users.',
946 'page callback' => 'user_admin',
947 'page arguments' => array('list'),
948 'access arguments' => array('administer users'),
949 'file' => 'user.admin.inc',
950 );
951 $items['admin/user/user/list'] = array(
952 'title' => 'List',
953 'type' => MENU_DEFAULT_LOCAL_TASK,
954 'weight' => -10,
955 );
956 $items['admin/user/user/create'] = array(
957 'title' => 'Add user',
958 'page arguments' => array('create'),
959 'type' => MENU_LOCAL_TASK,
960 'file' => 'user.admin.inc',
961 );
962 $items['admin/user/settings'] = array(
963 'title' => 'User settings',
964 'description' => 'Configure default behavior of users, including registration requirements, e-mails, and user pictures.',
965 'page callback' => 'drupal_get_form',
966 'page arguments' => array('user_admin_settings'),
967 'access arguments' => array('administer users'),
968 'file' => 'user.admin.inc',
969 );
970
971 // Admin access pages.
972 $items['admin/user/permissions'] = array(
973 'title' => 'Permissions',
974 'description' => 'Determine access to features by selecting permissions for roles.',
975 'page callback' => 'drupal_get_form',
976 'page arguments' => array('user_admin_perm'),
977 'access arguments' => array('administer permissions'),
978 'file' => 'user.admin.inc',
979 );
980 $items['admin/user/roles'] = array(
981 'title' => 'Roles',
982 'description' => 'List, edit, or add user roles.',
983 'page callback' => 'drupal_get_form',
984 'page arguments' => array('user_admin_new_role'),
985 'access arguments' => array('administer permissions'),
986 'file' => 'user.admin.inc',
987 );
988 $items['admin/user/roles/edit'] = array(
989 'title' => 'Edit role',
990 'page arguments' => array('user_admin_role'),
991 'type' => MENU_CALLBACK,
992 'file' => 'user.admin.inc',
993 );
994 $items['admin/user/rules'] = array(
995 'title' => 'Access rules',
996 'description' => 'List and create rules to disallow usernames, e-mail addresses, and IP addresses.',
997 'page callback' => 'user_admin_access',
998 'access arguments' => array('administer permissions'),
999 'file' => 'user.admin.inc',
1000 );
1001 $items['admin/user/rules/list'] = array(
1002 'title' => 'List',
1003 'type' => MENU_DEFAULT_LOCAL_TASK,
1004 'weight' => -10,
1005 );
1006 $items['admin/user/rules/add'] = array(
1007 'title' => 'Add rule',
1008 'page callback' => 'user_admin_access_add',
1009 'type' => MENU_LOCAL_TASK,
1010 'file' => 'user.admin.inc',
1011 );
1012 $items['admin/user/rules/check'] = array(
1013 'title' => 'Check rules',
1014 'page callback' => 'user_admin_access_check',
1015 'type' => MENU_LOCAL_TASK,
1016 'file' => 'user.admin.inc',
1017 );
1018 $items['admin/user/rules/edit'] = array(
1019 'title' => 'Edit rule',
1020 'page callback' => 'user_admin_access_edit',
1021 'type' => MENU_CALLBACK,
1022 'file' => 'user.admin.inc',
1023 );
1024 $items['admin/user/rules/delete'] = array(
1025 'title' => 'Delete rule',
1026 'page callback' => 'drupal_get_form',
1027 'page arguments' => array('user_admin_access_delete_confirm'),
1028 'type' => MENU_CALLBACK,
1029 'file' => 'user.admin.inc',
1030 );
1031
1032 $items['logout'] = array(
1033 'title' => 'Log out',
1034 'access callback' => 'user_is_logged_in',
1035 'page callback' => 'user_logout',
1036 'weight' => 10,
1037 'file' => 'user.pages.inc',
1038 );
1039
1040 $items['user/%user_current'] = array(
1041 'title' => 'My account',
1042 'title callback' => 'user_page_title',
1043 'title arguments' => array(1),
1044 'page callback' => 'user_view',
1045 'page arguments' => array(1),
1046 'access callback' => 'user_view_access',
1047 'access arguments' => array(1),
1048 'parent' => '',
1049 'file' => 'user.pages.inc',
1050 );
1051
1052 $items['user/%user/view'] = array(
1053 'title' => 'View',
1054 'type' => MENU_DEFAULT_LOCAL_TASK,
1055 'weight' => -10,
1056 );
1057
1058 $items['user/%user/delete'] = array(
1059 'title' => 'Delete',
1060 'page callback' => 'drupal_get_form',
1061 'page arguments' => array('user_confirm_delete', 1),
1062 'access callback' => 'user_access',
1063 'access arguments' => array('administer users'),
1064 'type' => MENU_CALLBACK,
1065 'file' => 'user.pages.inc',
1066 );
1067
1068 $items['user/%user_category/edit'] = array(
1069 'title' => 'Edit',
1070 'page callback' => 'user_edit',
1071 'page arguments' => array(1),
1072 'access callback' => 'user_edit_access',
1073 'access arguments' => array(1),
1074 'type' => MENU_LOCAL_TASK,
1075 'load arguments' => array('%map', '%index'),
1076 'file' => 'user.pages.inc',
1077 );
1078
1079 $items['user/%user_category/edit/account'] = array(
1080 'title' => 'Account',
1081 'type' => MENU_DEFAULT_LOCAL_TASK,
1082 'load arguments' => array('%map', '%index'),
1083 );
1084
1085 $empty_account = new stdClass();
1086 if (($categories = _user_categories($empty_account)) && (count($categories) > 1)) {
1087 foreach ($categories as $key => $category) {
1088 // 'account' is already handled by the MENU_DEFAULT_LOCAL_TASK.
1089 if ($category['name'] != 'account') {
1090 $items['user/%user_category/edit/'. $category['name']] = array(
1091 'title callback' => 'check_plain',
1092 'title arguments' => array($category['title']),
1093 'page callback' => 'user_edit',
1094 'page arguments' => array(1, 3),
1095 'access callback' => isset($category['access callback']) ? $category['access callback'] : TRUE,
1096 'access arguments' => isset($category['access arguments']) ? $category['access arguments'] : array(),
1097 'type' => MENU_LOCAL_TASK,
1098 'weight' => $category['weight'],
1099 'load arguments' => array('%map', '%index'),
1100 'tab_parent' => 'user/%/edit',
1101 'file' => 'user.pages.inc',
1102 );
1103 }
1104 }
1105 }
1106 return $items;
1107 }
1108
1109 function user_init() {
1110 drupal_add_css(drupal_get_path('module', 'user') .'/user.css', 'module');
1111 }
1112
1113 function user_current_load($arg) {
1114 return user_load($arg ? $arg : $GLOBALS['user']->uid);
1115 }
1116
1117 /**
1118 * Return a user object after checking if any profile category in the path exists.
1119 */
1120 function user_category_load($uid, &$map, $index) {
1121 static $user_categories, $accounts;
1122
1123 // Cache $account - this load function will get called for each profile tab.
1124 if (!isset($accounts[$uid])) {
1125 $accounts[$uid] = user_load($uid);
1126 }
1127 $valid = TRUE;
1128 if ($account = $accounts[$uid]) {
1129 // Since the path is like user/%/edit/category_name, the category name will
1130 // be at a position 2 beyond the index corresponding to the % wildcard.
1131 $category_index = $index + 2;
1132 // Valid categories may contain slashes, and hence need to be imploded.
1133 $category_path = implode('/', array_slice($map, $category_index));
1134 if ($category_path) {
1135 // Check that the requested category exists.
1136 $valid = FALSE;
1137 if (!isset($user_categories)) {
1138 $empty_account = new stdClass();
1139 $user_categories = _user_categories($empty_account);
1140 }
1141 foreach ($user_categories as $category) {
1142 if ($category['name'] == $category_path) {
1143 $valid = TRUE;
1144 // Truncate the map array in case the category name had slashes.
1145 $map = array_slice($map, 0, $category_index);
1146 // Assign the imploded category name to the last map element.
1147 $map[$category_index] = $category_path;
1148 break;
1149 }
1150 }
1151 }
1152 }
1153 return $valid ? $account : FALSE;
1154 }
1155
1156 /**
1157 * Returns the user id of the currently logged in user.
1158 */
1159 function user_current_to_arg($arg) {
1160 // Give back the current user uid when called from eg. tracker, aka.
1161 // with an empty arg. Also use the current user uid when called from
1162 // the menu with a % for the current account link.
1163 return empty($arg) || $arg == '%' ? $GLOBALS['user']->uid : $arg;
1164 }
1165
1166 /**
1167 * Menu item title callback - use the user name if it's not the current user.
1168 */
1169 function user_page_title($account) {
1170 if ($account->uid == $GLOBALS['user']->uid) {
1171 return t('My account');
1172 }
1173 return $account->name;
1174 }
1175
1176 /**
1177 * Discover which external authentication module(s) authenticated a username.
1178 *
1179 * @param $authname
1180 * A username used by an external authentication module.
1181 * @return
1182 * An associative array with module as key and username as value.
1183 */
1184 function user_get_authmaps($authname = NULL) {
1185 $result = db_query("SELECT authname, module FROM {authmap} WHERE authname = '%s'", $authname);
1186 $authmaps = array();
1187 $has_rows = FALSE;
1188 while ($authmap = db_fetch_object($result)) {
1189 $authmaps[$authmap->module] = $authmap->authname;
1190 $has_rows = TRUE;
1191 }
1192 return $has_rows ? $authmaps : 0;
1193 }
1194
1195 /**
1196 * Save mappings of which external authentication module(s) authenticated
1197 * a user. Maps external usernames to user ids in the users table.
1198 *
1199 * @param $account
1200 * A user object.
1201 * @param $authmaps
1202 * An associative array with a compound key and the username as the value.
1203 * The key is made up of 'authname_' plus the name of the external authentication
1204 * module.
1205 * @see user_external_login_register()
1206 */
1207 function user_set_authmaps($account, $authmaps) {
1208 foreach ($authmaps as $key => $value) {
1209 $module = explode('_', $key, 2);
1210 if ($value) {
1211 db_query("UPDATE {authmap} SET authname = '%s' WHERE uid = %d AND module = '%s'", $value, $account->uid, $module[1]);
1212 if (!db_affected_rows()) {
1213 db_query("INSERT INTO {authmap} (authname, uid, module) VALUES ('%s', %d, '%s')", $value, $account->uid, $module[1]);
1214 }
1215 }
1216 else {
1217 db_query("DELETE FROM {authmap} WHERE uid = %d AND module = '%s'", $account->uid, $module[1]);
1218 }
1219 }
1220 }
1221
1222 /**
1223 * Form builder; the main user login form.
1224 *
1225 * @ingroup forms
1226 */
1227 function user_login(&$form_state, $msg = '') {
1228 global $user;
1229
1230 // If we are already logged on, go to the user page instead.
1231 if ($user->uid) {
1232 drupal_goto('user/'. $user->uid);
1233 }
1234
1235 // Display login form:
1236 if ($msg) {
1237 $form['message'] = array('#value' => '<p>'. check_plain($msg) .'</p>');
1238 }
1239 $form['name'] = array('#type' => 'textfield',
1240 '#title' => t('Username'),
1241 '#size' => 60,
1242 '#maxlength' => USERNAME_MAX_LENGTH,
1243 '#required' => TRUE,
1244 '#attributes' => array('tabindex' => '1'),
1245 );
1246
1247 $form['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal')));
1248 $form['pass'] = array('#type' => 'password',
1249 '#title' => t('Password'),
1250 '#description' => t('Enter the password that accompanies your username.'),
1251 '#required' => TRUE,
1252 '#attributes' => array('tabindex' => '2'),
1253 );
1254 $form['#validate'] = user_login_default_validators();
1255 $form['submit'] = array('#type' => 'submit', '#value' => t('Log in'), '#weight' => 2, '#attributes' => array('tabindex' => '3'));
1256
1257 return $form;
1258 }
1259
1260 /**
1261 * Set up a series for validators which check for blocked/denied users,
1262 * then authenticate against local database, then return an error if
1263 * authentication fails. Distributed authentication modules are welcome
1264 * to use hook_form_alter() to change this series in order to
1265 * authenticate against their user database instead of the local users
1266 * table.
1267 *
1268 * We use three validators instead of one since external authentication
1269 * modules usually only need to alter the second validator.
1270 *
1271 * @see user_login_name_validate()
1272 * @see user_login_authenticate_validate()
1273 * @see user_login_final_validate()
1274 * @return array
1275 * A simple list of validate functions.
1276 */
1277 function user_login_default_validators() {
1278 return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate');
1279 }
1280
1281 /**
1282 * A FAPI validate handler. Sets an error if supplied username has been blocked
1283 * or denied access.
1284 */
1285 function user_login_name_validate($form, &$form_state) {
1286 if (isset($form_state['values']['name'])) {
1287 if (user_is_blocked($form_state['values']['name'])) {
1288 // blocked in user administration
1289 form_set_error('name', t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name'])));
1290 }
1291 else if (drupal_is_denied('user', $form_state['values']['name'])) {
1292 // denied by access controls
1293 form_set_error('name', t('The name %name is a reserved username.', array('%name' => $form_state['values']['name'])));
1294 }
1295 }
1296 }
1297
1298 /**
1299 * A validate handler on the login form. Check supplied username/password
1300 * against local users table. If successful, sets the global $user object.
1301 */
1302 function user_login_authenticate_validate($form, &$form_state) {
1303 user_authenticate($form_state['values']);
1304 }
1305
1306 /**
1307 * A validate handler on the login form. Should be the last validator. Sets an
1308 * error if user has not been authenticated yet.
1309 */
1310 function user_login_final_validate($form, &$form_state) {
1311 global $user;
1312 if (!$user->uid) {
1313 form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password'))));
1314 watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name']));
1315 }
1316 }
1317
1318 /**
1319 * Try to log in the user locally.
1320 *
1321 * @param $form_values
1322 * Form values with at least 'name' and 'pass' keys, as well as anything else
1323 * which should be passed along to hook_user op 'login'.
1324 *
1325 * @return
1326 * A $user object, if successful.
1327 */
1328 function user_authenticate($form_values = array()) {
1329 global $user;
1330
1331 // Name and pass keys are required.
1332 if (!empty($form_values['name']) && !empty($form_values['pass']) &&
1333 $account = user_load(array('name' => $form_values['name'], 'pass' => trim($form_values['pass']), 'status' => 1))) {
1334 $user = $account;
1335 user_authenticate_finalize($form_values);
1336 return $user;
1337 }
1338 }
1339
1340 /**
1341 * Finalize the login process. Must be called when logging in a user.
1342 *
1343 * The function records a watchdog message about the new session, saves the
1344 * login timestamp, calls hook_user op 'login' and generates a new session.
1345 *
1346 * $param $edit
1347 * This array is passed to hook_user op login.
1348 */
1349 function user_authenticate_finalize(&$edit) {
1350 global $user;
1351 watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
1352 // Update the user table timestamp noting user has logged in.
1353 // This is also used to invalidate one-time login links.
1354 $user->login = time();
1355 db_query("UPDATE {users} SET login = %d WHERE uid = %d", $user->login, $user->uid);
1356 user_module_invoke('login', $edit, $user);
1357 sess_regenerate();
1358 }
1359
1360 /**
1361 * Submit handler for the login form. Redirects the user to a page.
1362 *
1363 * The user is redirected to the My Account page. Setting the destination in
1364 * the query string (as done by the user login block) overrides the redirect.
1365 */
1366 function user_login_submit($form, &$form_state) {
1367 global $user;
1368 if ($user->uid) {
1369 $form_state['redirect'] = 'user/'. $user->uid;
1370 return;
1371 }
1372 }
1373
1374 /**
1375 * Helper function for authentication modules. Either login in or registers
1376 * the current user, based on username. Either way, the global $user object is
1377 * populated based on $name.
1378 */
1379 function user_external_login_register($name, $module) {
1380 global $user;
1381
1382 $user = user_load(array('name' => $name));
1383 if (!isset($user->uid)) {
1384 // Register this new user.
1385 $userinfo = array(
1386 'name' => $name,
1387 'pass' => user_password(),
1388 'init' => $name,
1389 'status' => 1,
1390 "authname_$module" => $name,
1391 'access' => time()
1392 );
1393 $account = user_save('', $userinfo);
1394 // Terminate if an error occured during user_save().
1395 if (!$account) {
1396 drupal_set_message(t("Error saving user account."), 'error');
1397 return;
1398 }
1399 $user = $account;
1400 watchdog('user', 'New external user: %name using module %module.', array('%name' => $name, '%module' => $module), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $user->uid .'/edit'));
1401 }
1402 }
1403
1404 function user_pass_reset_url($account) {
1405 $timestamp = time();
1406 return url("user/reset/$account->uid/$timestamp/". user_pass_rehash($account->pass, $timestamp, $account->login), array('absolute' => TRUE));
1407 }
1408
1409 function user_pass_rehash($password, $timestamp, $login) {
1410 return md5($timestamp . $password . $login);
1411 }
1412
1413 function user_edit_form(&$form_state, $uid, $edit, $register = FALSE) {
1414 _user_password_dynamic_validation();
1415 $admin = user_access('administer users');
1416
1417 // Account information:
1418 $form['account'] = array('#type' => 'fieldset',
1419 '#title' => t('Account information'),
1420 '#weight' => -10,
1421 );
1422 if (user_access('change own username') || $admin || $register) {
1423 $form['account']['name'] = array('#type' => 'textfield',
1424 '#title' => t('Username'),
1425 '#default_value' => $edit['name'],
1426 '#maxlength' => USERNAME_MAX_LENGTH,
1427 '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, and underscores.'),
1428 '#required' => TRUE,
1429 );
1430 }
1431 $form['account']['mail'] = array('#type' => 'textfield',
1432 '#title' => t('E-mail address'),
1433 '#default_value' => $edit['mail'],
1434 '#maxlength' => EMAIL_MAX_LENGTH,
1435 '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
1436 '#required' => TRUE,
1437 );
1438 if (!$register) {
1439 $form['account']['pass'] = array('#type' => 'password_confirm',
1440 '#description' => t('To change the current user password, enter the new password in both fields.'),
1441 '#size' => 25,
1442 );
1443 }
1444 elseif (!variable_get('user_email_verification', TRUE) || $admin) {
1445 $form['account']['pass'] = array(
1446 '#type' => 'password_confirm',
1447 '#description' => t('Provide a password for the new account in both fields.'),
1448 '#required' => TRUE,
1449 '#size' => 25,
1450 );
1451 }
1452 if ($admin) {
1453 $form['account']['status'] = array(
1454 '#type' => 'radios',
1455 '#title' => t('Status'),
1456 '#default_value' => isset($edit['status']) ? $edit['status'] : 1,
1457 '#options' => array(t('Blocked'), t('Active'))
1458 );
1459 }
1460 if (user_access('administer permissions')) {
1461 $roles = user_roles(TRUE);
1462
1463 // The disabled checkbox subelement for the 'authenticated user' role
1464 // must be generated separately and added to the checkboxes element,
1465 // because of a limitation in D6 FormAPI not supporting a single disabled
1466 // checkbox within a set of checkboxes.
1467 // TODO: This should be solved more elegantly. See issue #119038.
1468 $checkbox_authenticated = array(
1469 '#type' => 'checkbox',
1470 '#title' => $roles[DRUPAL_AUTHENTICATED_RID],
1471 '#default_value' => TRUE,
1472 '#disabled' => TRUE,
1473 );
1474
1475 unset($roles[DRUPAL_AUTHENTICATED_RID]);
1476 if ($roles) {
1477 $default = empty($edit['roles']) ? array() : array_keys($edit['roles']);
1478 $form['account']['roles'] = array(
1479 '#type' => 'checkboxes',
1480 '#title' => t('Roles'),
1481 '#default_value' => $default,
1482 '#options' => $roles,
1483 DRUPAL_AUTHENTICATED_RID => $checkbox_authenticated,
1484 );
1485 }
1486 }
1487
1488 // Signature:
1489 if (variable_get('user_signatures', 0) && module_exists('comment') && !$register) {
1490 $form['signature_settings'] = array(
1491 '#type' => 'fieldset',
1492 '#title' => t('Signature settings'),
1493 '#weight' => 1,
1494 );
1495 $form['signature_settings']['signature'] = array(
1496 '#type' => 'textarea',
1497 '#title' => t('Signature'),
1498 '#default_value' => $edit['signature'],
1499 '#description' => t('Your signature will be publicly displayed at the end of your comments.'),
1500 );
1501 }
1502
1503 // Picture/avatar:
1504 if (variable_get('user_pictures', 0) && !$register) {
1505 $form['picture'] = array('#type' => 'fieldset', '#title' => t('Picture'), '#weight' => 1);
1506 $picture = theme('user_picture', (object)$edit);
1507 if ($edit['picture']) {
1508 $form['picture']['current_picture'] = array('#value' => $picture);
1509 $form['picture']['picture_delete'] = array('#type' => 'checkbox', '#title' => t('Delete picture'), '#description' => t('Check this box to delete your current picture.'));
1510 }
1511 else {
1512 $form['picture']['picture_delete'] = array('#type' => 'hidden');
1513 }
1514 $form['picture']['picture_upload'] = array('#type' => 'file', '#title' => t('Upload picture'), '#size' => 48, '#description' => t('Your virtual face or picture. Maximum dimensions are %dimensions and the maximum size is %size kB.', array('%dimensions' => variable_get('user_picture_dimensions', '85x85'), '%size' => variable_get('user_picture_file_size', '30'))) .' '. variable_get('user_picture_guidelines', ''));
1515 $form['#validate'][] = 'user_validate_picture';
1516 }
1517 $form['#uid'] = $uid;
1518
1519 return $form;
1520 }
1521
1522 function _user_edit_validate($uid, &$edit) {
1523 $user = user_load(array('uid' => $uid));
1524 // Validate the username:
1525 if (user_access('change own username') || user_access('administer users') || !$user->uid) {
1526 if ($error = user_validate_name($edit['name'])) {
1527 form_set_error('name', $error);
1528 }
1529 else if (db_result(db_query("SELECT COUNT(*) FROM {users} WHERE uid != %d AND LOWER(name) = LOWER('%s')", $uid, $edit['name'])) > 0) {
1530 form_set_error('name', t('The name %name is already taken.', array('%name' => $edit['name'])));
1531 }
1532 else if (drupal_is_denied('user', $edit['name'])) {
1533 form_set_error('name', t('The name %name has been denied access.', array('%name' => $edit['name'])));
1534 }
1535 }
1536
1537 // Validate the e-mail address:
1538 if ($error = user_validate_mail($edit['mail'])) {
1539 form_set_error('mail', $error);
1540 }
1541 else if (db_result(db_query("SELECT COUNT(*) FROM {users} WHERE uid != %d AND LOWER(mail) = LOWER('%s')", $uid, $edit['mail'])) > 0) {
1542 form_set_error('mail', t('The e-mail address %email is already registered. <a href="@password">Have you forgotten your password?</a>', array('%email' => $edit['mail'], '@password' => url('user/password'))));
1543 }
1544 else if (drupal_is_denied('mail', $edit['mail'])) {
1545 form_set_error('mail', t('The e-mail address %email has been denied access.', array('%email' => $edit['mail'])));
1546 }
1547 }
1548
1549 function _user_edit_submit($uid, &$edit) {
1550 $user = user_load(array('uid' => $uid));
1551 // Delete picture if requested, and if no replacement picture was given.
1552 if (!empty($edit['picture_delete'])) {
1553 if ($user->picture && file_exists($user->picture)) {
1554 file_delete($user->picture);
1555 }
1556 $edit['picture'] = '';
1557 }
1558 if (isset($edit['roles'])) {
1559 $edit['roles'] = array_filter($edit['roles']);
1560 }
1561 }
1562
1563 /**
1564 * Delete a user.
1565 *
1566 * @param $edit An array of submitted form values.
1567 * @param $uid The user ID of the user to delete.
1568 */
1569 function user_delete($edit, $uid) {
1570 $account = user_load(array('uid' => $uid));
1571 sess_destroy_uid($uid);
1572 _user_mail_notify('status_deleted', $account);
1573 db_query('DELETE FROM {users} WHERE uid = %d', $uid);
1574 db_query('DELETE FROM {users_roles} WHERE uid = %d', $uid);
1575 db_query('DELETE FROM {authmap} WHERE uid = %d', $uid);
1576 $variables = array('%name' => $account->name, '%email' => '<'. $account->mail .'>');
1577 watchdog('user', 'Deleted user: %name %email.', $variables, WATCHDOG_NOTICE);
1578 module_invoke_all('user', 'delete', $edit, $account);
1579 }
1580
1581 /**
1582 * Builds a structured array representing the profile content.
1583 *
1584 * @param $account
1585 * A user object.
1586 *
1587 * @return
1588 * A structured array containing the individual elements of the profile.
1589 */
1590 function user_build_content(&$account) {
1591 $edit = NULL;
1592 user_module_invoke('view', $edit, $account);
1593 // Allow modules to modify the fully-built profile.
1594 drupal_alter('profile', $account);
1595
1596 return $account->content;
1597 }
1598
1599 /**
1600 * Implementation of hook_mail().
1601 */
1602 function user_mail($key, &$message, $params) {
1603 $language = $message['language'];
1604 $variables = user_mail_tokens($params['account'], $language);
1605 $message['subject'] .= _user_mail_text($key .'_subject', $language, $variables);
1606 $message['body'][] = _user_mail_text($key .'_body', $language, $variables);
1607 }
1608
1609 /**
1610 * Returns a mail string for a variable name.
1611 *
1612 * Used by user_mail() and the settings forms to retrieve strings.
1613 */
1614 function _user_mail_text($key, $language = NULL, $variables = array()) {
1615 $langcode = isset($language) ? $language->language : NULL;
1616
1617 if ($admin_setting = variable_get('user_mail_'. $key, FALSE)) {
1618 // An admin setting overrides the default string.
1619 return strtr($admin_setting, $variables);
1620 }
1621 else {
1622 // No override, return default string.
1623 switch ($key) {
1624 case 'register_no_approval_required_subject':
1625 return t('Account details for !username at !site', $variables, $langcode);
1626 case 'register_no_approval_required_body':
1627 return t("!username,\n\nThank you for registering at !site. You may now log in to !login_uri using the following username and password:\n\nusername: !username\npassword: !password\n\nYou may also log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\n\n-- !site team", $variables, $langcode);
1628 case 'register_admin_created_subject':
1629 return t('An administrator created an account for you at !site', $variables, $langcode);
1630 case 'register_admin_created_body':
1631 return t("!username,\n\nA site administrator at !site has created an account for you. You may now log in to !login_uri using the following username and password:\n\nusername: !username\npassword: !password\n\nYou may also log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\n\n-- !site team", $variables, $langcode);
1632 case 'register_pending_approval_subject':
1633 case 'pending_approval_admin_subject':
1634 return t('Account details for !username at !site (pending admin approval)', $variables, $langcode);
1635 case 'register_pending_approval_body':
1636 return t("!username,\n\nThank you for registering at !site. Your application for an account is currently pending approval. Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details.\n\n\n-- !site team", $variables, $langcode);
1637 case 'register_pending_approval_admin_body':
1638 return t("!username has applied for an account.\n\n!edit_uri", $variables, $langcode);
1639 case 'password_reset_subject':
1640 return t('Replacement login information for !username at !site', $variables, $langcode);
1641 case 'password_reset_body':
1642 return t("!username,\n\nA request to reset the password for your account has been made at !site.\n\nYou may now log in to !uri_brief by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once. It expires after one day and nothing will happen if it's not used.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.", $variables, $langcode);
1643 case 'status_activated_subject':
1644 return t('Account details for !username at !site (approved)', $variables, $langcode);
1645 case 'status_activated_body':
1646 return t("!username,\n\nYour account at !site has been activated.\n\nYou may now log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\nOnce you have set your own password, you will be able to log in to !login_uri in the future using:\n\nusername: !username\n", $variables, $langcode);
1647 case 'status_blocked_subject':
1648 return t('Account details for !username at !site (blocked)', $variables, $langcode);
1649 case 'status_blocked_body':
1650 return t("!username,\n\nYour account on !site has been blocked.", $variables, $langcode);
1651 case 'status_deleted_subject':
1652 return t('Account details for !username at !site (deleted)', $variables, $langcode);
1653 case 'status_deleted_body':
1654 return t("!username,\n\nYour account on !site has been deleted.", $variables, $langcode);
1655 }
1656 }
1657 }
1658
1659 /*** Administrative features ***********************************************/
1660
1661 /**
1662 * Retrieve an array of roles matching specified conditions.
1663 *
1664 * @param $membersonly
1665 * Set this to TRUE to exclude the 'anonymous' role.
1666 * @param $permission
1667 * A string containing a permission. If set, only roles containing that
1668 * permission are returned.
1669 *
1670 * @return
1671 * An associative array with the role id as the key and the role name as
1672 * value.
1673 */
1674 function user_roles($membersonly = FALSE, $permission = NULL) {
1675 // System roles take the first two positions.
1676 $roles = array(
1677 DRUPAL_ANONYMOUS_RID => NULL,
1678 DRUPAL_AUTHENTICATED_RID => NULL,
1679 );
1680
1681 if (!empty($permission)) {
1682 $result = db_query("SELECT r.* FROM {role} r INNER JOIN {permission} p ON r.rid = p.rid WHERE p.perm LIKE '%%%s%%' ORDER BY r.name", $permission);
1683 }
1684 else {
1685 $result = db_query('SELECT * FROM {role} ORDER BY name');
1686 }
1687
1688 while ($role = db_fetch_object($result)) {
1689 switch ($role->rid) {
1690 // We only translate the built in role names
1691 case DRUPAL_ANONYMOUS_RID:
1692 if (!$membersonly) {
1693 $roles[$role->rid] = t($role->name);
1694 }
1695 break;
1696 case DRUPAL_AUTHENTICATED_RID:
1697 $roles[$role->rid] = t($role->name);
1698 break;
1699 default:
1700 $roles[$role->rid] = $role->name;
1701 }
1702 }
1703
1704 // Filter to remove unmatched system roles.
1705 return array_filter($roles);
1706 }
1707
1708 /**
1709 * Implementation of hook_user_operations().
1710 */
1711 function user_user_operations($form_state = array()) {
1712 $operations = array(
1713 'unblock' => array(
1714 'label' => t('Unblock the selected users'),
1715 'callback' => 'user_user_operations_unblock',
1716 ),
1717 'block' => array(
1718 'label' => t('Block the selected users'),
1719 'callback' => 'user_user_operations_block',
1720 ),
1721 'delete' => array(
1722 'label' => t('Delete the selected users'),
1723 ),
1724 );
1725
1726 if (user_access('administer permissions')) {
1727 $roles = user_roles(TRUE);
1728 unset($roles[DRUPAL_AUTHENTICATED_RID]); // Can't edit authenticated role.
1729
1730 $add_roles = array();
1731 foreach ($roles as $key => $value) {
1732 $add_roles['add_role-'. $key] = $value;
1733 }
1734
1735 $remove_roles = array();
1736 foreach ($roles as $key => $value) {
1737 $remove_roles['remove_role-'. $key] = $value;
1738 }
1739
1740 if (count($roles)) {
1741 $role_operations = array(
1742 t('Add a role to the selected users') => array(
1743 'label' => $add_roles,
1744 ),
1745 t('Remove a role from the selected users') => array(
1746 'label' => $remove_roles,
1747 ),
1748 );
1749
1750 $operations += $role_operations;
1751 }
1752 }
1753
1754 // If the form has been posted, we need to insert the proper data for
1755 // role editing if necessary.
1756 if (!empty($form_state['submitted'])) {
1757 $operation_rid = explode('-', $form_state['values']['operation']);
1758 $operation = $operation_rid[0];
1759 if ($operation == 'add_role' || $operation == 'remove_role') {
1760 $rid = $operation_rid[1];
1761 if (user_access('administer permissions')) {
1762 $operations[$form_state['values']['operation']] = array(
1763 'callback' => 'user_multiple_role_edit',
1764 'callback arguments' => array($operation, $rid),
1765 );
1766 }
1767 else {
1768 watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
1769 return;
1770 }
1771 }
1772 }
1773
1774 return $operations;
1775 }
1776
1777 /**
1778 * Callback function for admin mass unblocking users.
1779 */
1780 function user_user_operations_unblock($accounts) {
1781 foreach ($accounts as $uid) {
1782 $account = user_load(array('uid' => (int)$uid));
1783 // Skip unblocking user if they are already unblocked.
1784 if ($account !== FALSE && $account->status == 0) {
1785 user_save($account, array('status' => 1));
1786 }
1787 }
1788 }
1789
1790 /**
1791 * Callback function for admin mass blocking users.
1792 */
1793 function user_user_operations_block($accounts) {
1794 foreach ($accounts as $uid) {
1795 $account = user_load(array('uid' => (int)$uid));
1796 // Skip blocking user if they are already blocked.
1797 if ($account !== FALSE && $account->status == 1) {
1798 user_save($account, array('status' => 0));
1799 }
1800 }
1801 }
1802
1803 /**
1804 * Callback function for admin mass adding/deleting a user role.
1805 */
1806 function user_multiple_role_edit($accounts, $operation, $rid) {
1807 // The role name is not necessary as user_save() will reload the user
1808 // object, but some modules' hook_user() may look at this first.
1809 $role_name = db_result(db_query('SELECT name FROM {role} WHERE rid = %d', $rid));
1810
1811 switch ($operation) {
1812 case 'add_role':
1813 foreach ($accounts as $uid) {
1814 $account = user_load(array('uid' => (int)$uid));
1815 // Skip adding the role to the user if they already have it.
1816 if ($account !== FALSE && !isset($account->roles[$rid])) {
1817 $roles = $account->roles + array($rid => $role_name);
1818 user_save($account, array('roles' => $roles));
1819 }
1820 }
1821 break;
1822 case 'remove_role':
1823 foreach ($accounts as $uid) {
1824 $account = user_load(array('uid' => (int)$uid));
1825 // Skip removing the role from the user if they already don't have it.
1826 if ($account !== FALSE && isset($account->roles[$rid])) {
1827 $roles = array_diff($account->roles, array($rid => $role_name));
1828 user_save($account, array('roles' => $roles));
1829 }
1830 }
1831 break;
1832 }
1833 }
1834
1835 function user_multiple_delete_confirm(&$form_state) {
1836 $edit = $form_state['post'];
1837
1838 $form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
1839 // array_filter() returns only elements with TRUE values.
1840 foreach (array_filter($edit['accounts']) as $uid => $value) {
1841 $user = db_result(db_query('SELECT name FROM {users} WHERE uid = %d', $uid));
1842 $form['accounts'][$uid] = array('#type' => 'hidden', '#value' => $uid, '#prefix' => '<li>', '#suffix' => check_plain($user) ."</li>\n");
1843 }
1844 $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
1845
1846 return confirm_form($form,
1847 t('Are you sure you want to delete these users?'),
1848 'admin/user/user', t('This action cannot be undone.'),
1849 t('Delete all'), t('Cancel'));
1850 }
1851
1852 function user_multiple_delete_confirm_submit($form, &$form_state) {
1853 if ($form_state['values']['confirm']) {
1854 foreach ($form_state['values']['accounts'] as $uid => $value) {
1855 user_delete($form_state['values'], $uid);
1856 }
1857 drupal_set_message(t('The users have been deleted.'));
1858 }
1859 $form_state['redirect'] = 'admin/user/user';
1860 return;
1861 }
1862
1863 /**
1864 * Implementation of hook_help().
1865 */
1866 function user_help($path, $arg) {
1867 global $user;
1868
1869 switch ($path) {
1870 case 'admin/help#user':
1871 $output = '<p>'. t('The user module allows users to register, login, and log out. Users benefit from being able to sign on because it associates content they create with their account and allows various permissions to be set for their roles. The user module supports user roles which establish fine grained permissions allowing each role to do only what the administrator wants them to. Each user is assigned to one or more roles. By default there are two roles <em>anonymous</em> - a user who has not logged in, and <em>authenticated</em> a user who has signed up and who has been authorized.') .'</p>';
1872 $output .= '<p>'. t("Users can use their own name or handle and can specify personal configuration settings through their individual <em>My account</em> page. Users must authenticate by supplying a local username and password or through their OpenID, an optional and secure method for logging into many websites with a single username and password. In some configurations, users may authenticate using a username and password from another Drupal site, or through some other site-specific mechanism.") .'</p>';
1873 $output .= '<p>'. t('A visitor accessing your website is assigned a unique ID, or session ID, which is stored in a cookie. The cookie does not contain personal information, but acts as a key to retrieve information from your site. Users should have cookies enabled in their web browser when using your site.') .'</p>';
1874 $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@user">User module</a>.', array('@user' => 'http://drupal.org/handbook/modules/user/')) .'</p>';
1875 return $output;
1876 case 'admin/user/user':
1877 return '<p>'. t('Drupal allows users to register, login, log out, maintain user profiles, etc. Users of the site may not use their own names to post content until they have signed up for a user account.') .'</p>';
1878 case 'admin/user/user/create':
1879 case 'admin/user/user/account/create':
1880 return '<p>'. t("This web page allows administrators to register new users. Users' e-mail addresses and usernames must be unique.") .'</p>';
1881 case 'admin/user/rules':
1882 return '<p>'. t('Set up username and e-mail address access rules for new <em>and</em> existing accounts (currently logged in accounts will not be logged out). If a username or e-mail address for an account matches any deny rule, but not an allow rule, then the account will not be allowed to be created or to log in. A host rule is effective for every page view, not just registrations.') .'</p>';
1883 case 'admin/user/permissions':
1884 return '<p>'. t('Permissions let you control what users can do on your site. Each user role (defined on the <a href="@role">user roles page</a>) has its own set of permissions. For example, you could give users classified as "Administrators" permission to "administer nodes" but deny this power to ordinary, "authenticated" users. You can use permissions to reveal new features to privileged users (those with subscriptions, for example). Permissions also allow trusted users to share the administrative burden of running a busy site.', array('@role' => url('admin/user/roles'))) .'</p>';
1885 case 'admin/user/roles':
1886 return t('<p>Roles allow you to fine tune the security and administration of Drupal. A role defines a group of users that have certain privileges as defined in <a href="@permissions">user permissions</a>. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the <em>role names</em> of the various roles. To delete a role choose "edit".</p><p>By default, Drupal comes with two user roles:</p>
1887 <ul>
1888 <li>Anonymous user: this role is used for users that don\'t have a user account or that are not authenticated.</li>
1889 <li>Authenticated user: this role is automatically granted to all logged in users.</li>
1890 </ul>', array('@permissions' => url('admin/user/permissions')));
1891 case 'admin/user/search':
1892 return '<p>'. t('Enter a simple pattern ("*" may be used as a wildcard match) to search for a username or e-mail address. For example, one may search for "br" and Drupal might return "brian", "brad", and "brenda@example.com".') .'</p>';
1893 }
1894 }
1895
1896 /**
1897 * Retrieve a list of all user setting/information categories and sort them by weight.
1898 */
1899 function _user_categories($account) {
1900 $categories = array();
1901
1902 foreach (module_list() as $module) {
1903 if ($data = module_invoke($module, 'user', 'categories', NULL, $account, '')) {
1904 $categories = array_merge($data, $categories);
1905 }
1906 }
1907
1908 usort($categories, '_user_sort');
1909
1910 return $categories;
1911 }
1912
1913 function _user_sort($a, $b) {
1914 $a = (array)$a + array('weight' => 0, 'title' => '');
1915 $b = (array)$b + array('weight' => 0, 'title' => '');
1916 return $a['weight'] < $b['weight'] ? -1 : ($a['weight'] > $b['weight'] ? 1 : ($a['title'] < $b['title'] ? -1 : 1));
1917 }
1918
1919 /**
1920 * List user administration filters that can be applied.
1921 */
1922 function user_filters() {
1923 // Regular filters
1924 $filters = array();
1925 $roles = user_roles(TRUE);
1926 unset($roles[DRUPAL_AUTHENTICATED_RID]); // Don't list authorized role.
1927 if (count($roles)) {
1928 $filters['role'] = array(
1929 'title' => t('role'),
1930 'where' => "ur.rid = %d",
1931 'options' => $roles,
1932 'join' => '',
1933 );
1934 }
1935
1936 $options = array();
1937 foreach (module_list() as $module) {
1938 if ($permissions = module_invoke($module, 'perm')) {
1939 asort($permissions);
1940 foreach ($permissions as $permission) {
1941 $options[t('@module module', array('@module' => $module))][$permission] = t($permission);
1942 }
1943 }
1944 }
1945 ksort($options);
1946 $filters['permission'] = array(
1947 'title' => t('permission'),
1948 'join' => 'LEFT JOIN {permission} p ON ur.rid = p.rid',
1949 'where' => " ((p.perm IS NOT NULL AND p.perm LIKE '%%%s%%') OR u.uid = 1) ",
1950 'options' => $options,
1951 );
1952
1953 $filters['status'] = array(
1954 'title' => t('status'),
1955 'where' => 'u.status = %d',
1956 'join' => '',
1957 'options' => array(1 => t('active'), 0 => t('blocked')),
1958 );
1959 return $filters;
1960 }
1961
1962 /**
1963 * Build query for user administration filters based on session.
1964 */
1965 function user_build_filter_query() {
1966 $filters = user_filters();
1967
1968 // Build query
1969 $where = $args = $join = array();
1970 foreach ($_SESSION['user_overview_filter'] as $filter) {
1971 list($key, $value) = $filter;
1972 // This checks to see if this permission filter is an enabled permission for
1973 // the authenticated role. If so, then all users would be listed, and we can
1974 // skip adding it to the filter query.
1975 if ($key == 'permission') {
1976 $account = new stdClass();
1977 $account->uid = 'user_filter';
1978 $account->roles = array(DRUPAL_AUTHENTICATED_RID => 1);
1979 if (user_access($value, $account)) {
1980 continue;
1981 }
1982 }
1983 $where[] = $filters[$key]['where'];
1984 $args[] = $value;
1985 $join[] = $filters[$key]['join'];
1986 }
1987 $where = !empty($where) ? 'AND '. implode(' AND ', $where) : '';
1988 $join = !empty($join) ? ' '. implode(' ', array_unique($join)) : '';
1989
1990 return array('where' => $where,
1991 'join' => $join,
1992 'args' => $args,
1993 );
1994 }
1995
1996 /**
1997 * Implementation of hook_forms().
1998 */
1999 function user_forms() {
2000 $forms['user_admin_access_add_form']['callback'] = 'user_admin_access_form';
2001 $forms['user_admin_access_edit_form']['callback'] = 'user_admin_access_form';
2002 $forms['user_admin_new_role']['callback'] = 'user_admin_role';
2003 return $forms;
2004 }
2005
2006 /**
2007 * Implementation of hook_comment().
2008 */
2009 function user_comment(&$comment, $op) {
2010 // Validate signature.
2011 if ($op == 'view') {
2012 if (variable_get('user_signatures', 0) && !empty($comment->signature)) {
2013 $comment->signature = check_markup($comment->signature, $comment->format);
2014 }
2015 else {
2016 $comment->signature = '';
2017 }
2018 }
2019 }
2020
2021 /**
2022 * Theme output of user signature.
2023 *
2024 * @ingroup themeable
2025 */
2026 function theme_user_signature($signature) {
2027 $output = '';
2028 if ($signature) {
2029 $output .= '<div class="clear">';
2030 $output .= '<div>—</div>';
2031 $output .= $signature;
2032 $output .= '</div>';
2033 }
2034
2035 return $output;
2036 }
2037
2038 /**
2039 * Return an array of token to value mappings for user e-mail messages.
2040 *
2041 * @param $account
2042 * The user object of the account being notified. Must contain at
2043 * least the fields 'uid', 'name', and 'mail'.
2044 * @param $language
2045 * Language object to generate the tokens with.
2046 * @return
2047 * Array of mappings from token names to values (for use with strtr()).
2048 */
2049 function user_mail_tokens($account, $language) {
2050 global $base_url;
2051 $tokens = array(
2052 '!username' => $account->name,
2053 '!site' => variable_get('site_name', 'Drupal'),
2054 '!login_url' => user_pass_reset_url($account),
2055 '!uri' => $base_url,
2056 '!uri_brief' => substr($base_url, strlen('http://')),
2057 '!mailto' => $account->mail,
2058 '!date' => format_date(time(), 'medium', '', NULL, $language->language),
2059 '!login_uri' => url('user', array('absolute' => TRUE, 'language' => $language)),
2060 '!edit_uri' => url('user/'. $account->uid .'/edit', array('absolute' => TRUE, 'language' => $language)),
2061 );
2062 if (!empty($account->password)) {
2063 $tokens['!password'] = $account->password;
2064 }
2065 return $tokens;
2066 }
2067
2068 /**
2069 * Get the language object preferred by the user. This user preference can
2070 * be set on the user account editing page, and is only available if there
2071 * are more than one languages enabled on the site. If the user did not
2072 * choose a preferred language, or is the anonymous user, the $default
2073 * value, or if it is not set, the site default language will be returned.
2074 *
2075 * @param $account
2076 * User account to look up language for.
2077 * @param $default
2078 * Optional default language object to return if the account
2079 * has no valid language.
2080 */
2081 function user_preferred_language($account, $default = NULL) {
2082 $language_list = language_list();
2083 if ($account->language && isset($language_list[$account->language])) {
2084 return $language_list[$account->language];
2085 }
2086 else {
2087 return $default ? $default : language_default();
2088 }
2089 }
2090
2091 /**
2092 * Conditionally create and send a notification email when a certain
2093 * operation happens on the given user account.
2094 *
2095 * @see user_mail_tokens()
2096 * @see drupal_mail()
2097 *
2098 * @param $op
2099 * The operation being performed on the account. Possible values:
2100 * 'register_admin_created': Welcome message for user created by the admin
2101 * 'register_no_approval_required': Welcome message when user self-registers
2102 * 'register_pending_approval': Welcome message, user pending admin approval
2103 * 'password_reset': Password recovery request
2104 * 'status_activated': Account activated
2105 * 'status_blocked': Account blocked
2106 * 'status_deleted': Account deleted
2107 *
2108 * @param $account
2109 * The user object of the account being notified. Must contain at
2110 * least the fields 'uid', 'name', and 'mail'.
2111 * @param $language
2112 * Optional language to use for the notification, overriding account language.
2113 * @return
2114 * The return value from drupal_mail_send(), if ends up being called.
2115 */
2116 function _user_mail_notify($op, $account, $language = NULL) {
2117 // By default, we always notify except for deleted and blocked.
2118 $default_notify = ($op != 'status_deleted' && $op != 'status_blocked');
2119 $notify = variable_get('user_mail_'. $op .'_notify', $default_notify);
2120 if ($notify) {
2121 $params['account'] = $account;
2122 $language = $language ? $language : user_preferred_language($account);
2123 $mail = drupal_mail('user', $op, $account->mail, $language, $params);
2124 if ($op == 'register_pending_approval') {
2125 // If a user registered requiring admin approval, notify the admin, too.
2126 // We use the site default language for this.
2127 drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
2128 }
2129 }
2130 return empty($mail) ? NULL : $mail['result'];
2131 }
2132
2133 /**
2134 * Add javascript and string translations for dynamic password validation
2135 * (strength and confirmation checking).
2136 *
2137 * This is an internal function that makes it easier to manage the translation
2138 * strings that need to be passed to the javascript code.
2139 */
2140 function _user_password_dynamic_validation() {
2141 static $complete = FALSE;
2142 global $user;
2143 // Only need to do once per page.
2144 if (!$complete) {
2145 drupal_add_js(drupal_get_path('module', 'user') .'/user.js', 'module');
2146
2147 drupal_add_js(array(
2148 'password' => array(
2149 'strengthTitle' => t('Password strength:'),
2150 'lowStrength' => t('Low'),
2151 'mediumStrength' => t('Medium'),
2152 'highStrength' => t('High'),
2153 'tooShort' => t('It is recommended to choose a password that contains at least six characters. It should include numbers, punctuation, and both upper and lowercase letters.'),
2154 'needsMoreVariation' => t('The password does not include enough variation to be secure. Try:'),
2155 'addLetters' => t('Adding both upper and lowercase letters.'),
2156 'addNumbers' => t('Adding numbers.'),
2157 'addPunctuation' => t('Adding punctuation.'),
2158 'sameAsUsername' => t('It is recommended to choose a password different from the username.'),
2159 'confirmSuccess' => t('Yes'),
2160 'confirmFailure' => t('No'),
2161 'confirmTitle' => t('Passwords match:'),
2162 'username' => (isset($user->name) ? $user->name : ''))),
2163 'setting');
2164 $complete = TRUE;
2165 }
2166 }
2167
2168 /**
2169 * Implementation of hook_hook_info().
2170 */
2171 function user_hook_info() {
2172 return array(
2173 'user' => array(
2174 'user' => array(
2175 'insert' => array(
2176 'runs when' => t('After a user account has been created'),
2177 ),
2178 'update' => array(
2179 'runs when' => t("After a user's profile has been updated"),
2180 ),
2181 'delete' => array(
2182 'runs when' => t('After a user has been deleted')
2183 ),
2184 'login' => array(
2185 'runs when' => t('After a user has logged in')
2186 ),
2187 'logout' => array(
2188 'runs when' => t('After a user has logged out')
2189 ),
2190 'view' => array(
2191 'runs when' => t("When a user's profile is being viewed")
2192 ),
2193 ),
2194 ),
2195 );
2196 }
2197
2198 /**
2199 * Implementation of hook_action_info().
2200 */
2201 function user_action_info() {
2202 return array(
2203 'user_block_user_action' => array(
2204 'description' => t('Block current user'),
2205 'type' => 'user',
2206 'configurable' => FALSE,
2207 'hooks' => array(),
2208 ),
2209 'user_block_ip_action' => array(
2210 'description' => t('Ban IP address of current user'),
2211 'type' => 'user',
2212 'configurable' => FALSE,
2213 'hooks' => array(),
2214 ),
2215 );
2216 }
2217
2218 /**
2219 * Implementation of a Drupal action.
2220 * Blocks the current user.
2221 */
2222 function user_block_user_action(&$object, $context = array()) {
2223 if (isset($object->uid)) {
2224 $uid = $object->uid;
2225 }
2226 elseif (isset($context['uid'])) {
2227 $uid = $context['uid'];
2228 }
2229 else {
2230 global $user;
2231 $uid = $user->uid;
2232 }
2233 db_query("UPDATE {users} SET status = 0 WHERE uid = %d", $uid);
2234 sess_destroy_uid($uid);
2235 watchdog('action', 'Blocked user %name.', array('%name' => check_plain($user->name)));
2236 }
2237
2238 /**
2239 * Implementation of a Drupal action.
2240 * Adds an access rule that blocks the user's IP address.
2241 */
2242 function user_block_ip_action() {
2243 $ip = ip_address();
2244 db_query("INSERT INTO {access} (mask, type, status) VALUES ('%s', '%s', %d)", $ip, 'host', 0);
2245 watchdog('action', 'Banned IP address %ip', array('%ip' => $ip));
2246 }
2247
2248 /**
2249 * Submit handler for the user registration form.
2250 *
2251 * This function is shared by the installation form and the normal registration form,
2252 * which is why it can't be in the user.pages.inc file.
2253 */
2254 function user_register_submit($form, &$form_state) {
2255 global $base_url;
2256 $admin = user_access('administer users');
2257
2258 $mail = $form_state['values']['mail'];
2259 $name = $form_state['values']['name'];
2260 if (!variable_get('user_email_verification', TRUE) || $admin) {
2261 $pass = $form_state['values']['pass'];
2262 }
2263 else {
2264 $pass = user_password();
2265 };
2266 $notify = isset($form_state['values']['notify']) ? $form_state['values']['notify'] : NULL;
2267 $from = variable_get('site_mail', ini_get('sendmail_from'));
2268 if (isset($form_state['values']['roles'])) {
2269 // Remove unset roles.
2270 $roles = array_filter($form_state['values']['roles']);
2271 }
2272 else {
2273 $roles = array();
2274 }
2275
2276 if (!$admin && array_intersect(array_keys($form_state['values']), array('uid', 'roles', 'init', 'session', 'status'))) {
2277 watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
2278 $form_state['redirect'] = 'user/register';
2279 return;
2280 }
2281 // The unset below is needed to prevent these form values from being saved as
2282 // user data.
2283 unset($form_state['values']['form_token'], $form_state['values']['submit'], $form_state['values']['op'], $form_state['values']['notify'], $form_state['values']['form_id'], $form_state['values']['affiliates'], $form_state['values']['destination']);
2284
2285 $merge_data = array('pass' => $pass, 'init' => $mail, 'roles' => $roles);
2286 if (!$admin) {
2287 // Set the user's status because it was not displayed in the form.
2288 $merge_data['status'] = variable_get('user_register', 1) == 1;
2289 }
2290 $account = user_save('', array_merge($form_state['values'], $merge_data));
2291 // Terminate if an error occured during user_save().
2292 if (!$account) {
2293 drupal_set_message(t("Error saving user account."), 'error');
2294 $form_state['redirect'] = '';
2295 return;
2296 }
2297 $form_state['user'] = $account;
2298
2299 watchdog('user', 'New user: %name (%email).', array('%name' => $name, '%email' => $mail), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $account->uid .'/edit'));
2300
2301 // The first user may login immediately, and receives a customized welcome e-mail.
2302 if ($account->uid == 1) {
2303 drupal_set_message(t('Welcome to Drupal. You are now logged in as user #1, which gives you full control over your website.'));
2304 if (variable_get('user_email_verification', TRUE)) {
2305 drupal_set_message(t('</p><p> Your password is <strong>%pass</strong>. You may change your password below.</p>', array('%pass' => $pass)));
2306 }
2307
2308 user_authenticate(array_merge($form_state['values'], $merge_data));
2309
2310 $form_state['redirect'] = 'user/1/edit';
2311 return;
2312 }
2313 else {
2314 // Add plain text password into user account to generate mail tokens.
2315 $account->password = $pass;
2316 if ($admin && !$notify) {
2317 drupal_set_message(t('Created a new user account for <a href="@url">%name</a>. No e-mail has been sent.', array('@url' => url("user/$account->uid"), '%name' => $account->name)));
2318 }
2319 else if (!variable_get('user_email_verification', TRUE) && $account->status && !$admin) {
2320 // No e-mail verification is required, create new user account, and login
2321 // user immediately.
2322 _user_mail_notify('register_no_approval_required', $account);
2323 if (user_authenticate(array_merge($form_state['values'], $merge_data))) {
2324 drupal_set_message(t('Registration successful. You are now logged in.'));
2325 }
2326 $form_state['redirect'] = '';
2327 return;
2328 }
2329 else if ($account->status || $notify) {
2330 // Create new user account, no administrator approval required.
2331 $op = $notify ? 'register_admin_created' : 'register_no_approval_required';
2332 _user_mail_notify($op, $account);
2333 if ($notify) {
2334 drupal_set_message(t('Password and further instructions have been e-mailed to the new user <a href="@url">%name</a>.', array('@url' => url("user/$account->uid"), '%name' => $account->name)));
2335 }
2336 else {
2337 drupal_set_message(t('Your password and further instructions have been sent to your e-mail address.'));
2338 $form_state['redirect'] = '';
2339 return;
2340 }
2341 }
2342 else {
2343 // Create new user account, administrator approval required.
2344 _user_mail_notify('register_pending_approval', $account);
2345 drupal_set_message(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />In the meantime, a welcome message with further instructions has been sent to your e-mail address.'));
2346 $form_state['redirect'] = '';
2347 return;
2348
2349 }
2350 }
2351 }
2352
2353 /**
2354 * Form builder; The user registration form.
2355 *
2356 * @ingroup forms
2357 * @see user_register_validate()
2358 * @see user_register_submit()
2359 */
2360 function user_register() {
2361 global $user;
2362
2363 $admin = user_access('administer users');
2364
2365 // If we aren't admin but already logged on, go to the user page instead.
2366 if (!$admin && $user->uid) {
2367 drupal_goto('user/'. $user->uid);
2368 }
2369
2370 $form = array();
2371
2372 // Display the registration form.
2373 if (!$admin) {
2374 $form['user_registration_help'] = array('#value' => filter_xss_admin(variable_get('user_registration_help', '')));
2375 }
2376
2377 // Merge in the default user edit fields.
2378 $form = array_merge($form, user_edit_form($form_state, NULL, NULL, TRUE));
2379 if ($admin) {
2380 $form['account']['notify'] = array(
2381 '#type' => 'checkbox',
2382 '#title' => t('Notify user of new account')
2383 );
2384 // Redirect back to page which initiated the create request;
2385 // usually admin/user/user/create.
2386 $form['destination'] = array('#type' => 'hidden', '#value' => $_GET['q']);
2387 }
2388
2389 // Create a dummy variable for pass-by-reference parameters.
2390 $null = NULL;
2391 $extra = _user_forms($null, NULL, NULL, 'register');
2392
2393 // Remove form_group around default fields if there are no other groups.
2394 if (!$extra) {
2395 foreach (array('name', 'mail', 'pass', 'status', 'roles', 'notify') as $key) {
2396 if (isset($form['account'][$key])) {
2397 $form[$key] = $form['account'][$key];
2398 }
2399 }
2400 unset($form['account']);
2401 }
2402 else {
2403 $form = array_merge($form, $extra);
2404 }
2405
2406 if (variable_get('configurable_timezones', 1)) {
2407 // Override field ID, so we only change timezone on user registration,
2408 // and never touch it on user edit pages.
2409 $form['timezone'] = array(
2410 '#type' => 'hidden',
2411 '#default_value' => variable_get('date_default_timezone', NULL),
2412 '#id' => 'edit-user-register-timezone',
2413 );
2414
2415 // Add the JavaScript callback to automatically set the timezone.
2416 drupal_add_js('
2417 // Global Killswitch
2418 if (Drupal.jsEnabled) {
2419 $(document).ready(function() {
2420 Drupal.setDefaultTimezone();
2421 });
2422 }', 'inline');
2423 }
2424
2425 $form['submit'] = array('#type' => 'submit', '#value' => t('Create new account'), '#weight' => 30);
2426 $form['#validate'][] = 'user_register_validate';
2427
2428 return $form;
2429 }
2430
2431 function user_register_validate($form, &$form_state) {
2432 user_module_invoke('validate', $form_state['values'], $form_state['values'], 'account');
2433 }
2434
2435 /**
2436 * Retrieve a list of all form elements for the specified category.
2437 */
2438 function _user_forms(&$edit, $account, $category, $hook = 'form') {
2439 $groups = array();
2440 foreach (module_list() as $module) {
2441 if ($data = module_invoke($module, 'user', $hook, $edit, $account, $category)) {
2442 $groups = array_merge_recursive($data, $groups);
2443 }
2444 }
2445 uasort($groups, '_user_sort');
2446
2447 return empty($groups) ? FALSE : $groups;
2448 }