Code coverage for /20081101/modules/user/user.module

Line #Times calledCode
1
<?php
2
// $Id: user.module,v 1.930 2008/10/26 18:06:39 dries Exp $
3
4
/**
5
 * @file
6
 * Enables the user registration and login system.
7
 */
8
9
/**
10
 * Maximum length of username text field.
11
 */
122366
define('USERNAME_MAX_LENGTH', 60);
13
14
/**
15
 * Maximum length of user e-mail text field.
16
 */
172366
define('EMAIL_MAX_LENGTH', 64);
18
19
/**
20
 * Invokes hook_user() in every module.
21
 *
22
 * We cannot use module_invoke() for this, because the arguments need to
23
 * be passed by reference.
24
 */
252366
function user_module_invoke($type, &$array, &$user, $category = NULL) {
262047
  foreach (module_list() as $module) {
272047
    $function = $module . '_user_' . $type;
282047
    if (function_exists($function)) {
29328
      $function($array, $user, $category);
30328
    }
312047
  }
322047
}
33
34
/**
35
 * Implementation of hook_theme().
36
 */
372366
function user_theme() {
38
  return array(
39
    'user_picture' => array(
40178
      'arguments' => array('account' => NULL),
41178
      'template' => 'user-picture',
42178
    ),
43
    'user_profile' => array(
44178
      'arguments' => array('account' => NULL),
45178
      'template' => 'user-profile',
46178
      'file' => 'user.pages.inc',
47178
    ),
48
    'user_profile_category' => array(
49178
      'arguments' => array('element' => NULL),
50178
      'template' => 'user-profile-category',
51178
      'file' => 'user.pages.inc',
52178
    ),
53
    'user_profile_item' => array(
54178
      'arguments' => array('element' => NULL),
55178
      'template' => 'user-profile-item',
56178
      'file' => 'user.pages.inc',
57178
    ),
58
    'user_list' => array(
59178
      'arguments' => array('users' => NULL, 'title' => NULL),
60178
    ),
61
    'user_admin_perm' => array(
62178
      'arguments' => array('form' => NULL),
63178
      'file' => 'user.admin.inc',
64178
    ),
65
    'user_admin_new_role' => array(
66178
      'arguments' => array('form' => NULL),
67178
      'file' => 'user.admin.inc',
68178
    ),
69
    'user_admin_account' => array(
70178
      'arguments' => array('form' => NULL),
71178
      'file' => 'user.admin.inc',
72178
    ),
73
    'user_filter_form' => array(
74178
      'arguments' => array('form' => NULL),
75178
      'file' => 'user.admin.inc',
76178
    ),
77
    'user_filters' => array(
78178
      'arguments' => array('form' => NULL),
79178
      'file' => 'user.admin.inc',
80178
    ),
81
    'user_signature' => array(
82178
      'arguments' => array('signature' => NULL),
83178
    ),
84178
  );
850
}
86
872366
function user_external_load($authname) {
880
  $result = db_query("SELECT uid FROM {authmap} WHERE authname = '%s'",
$authname);
89
900
  if ($user = db_fetch_array($result)) {
910
    return user_load($user);
920
  }
93
  else {
940
    return FALSE;
95
  }
960
}
97
98
/**
99
 * Perform standard Drupal login operations for a user object.
100
 *
101
 * The user object must already be authenticated. This function verifies
102
 * that the user account is not blocked and then performs the login,
103
 * updates the login timestamp in the database, invokes hook_user('login'),
104
 * and regenerates the session.
105
 *
106
 * @param $account
107
 *    An authenticated user object to be set as the currently logged
108
 *    in user.
109
 * @param $edit
110
 *    The array of form values submitted by the user, if any.
111
 *    This array is passed to hook_user op login.
112
 * @return boolean
113
 *    TRUE if the login succeeds, FALSE otherwise.
114
 */
1152366
function user_external_login($account, $edit = array()) {
1160
  $form = drupal_get_form('user_login');
117
1180
  $state['values'] = $edit;
1190
  if (empty($state['values']['name'])) {
1200
    $state['values']['name'] = $account->name;
1210
  }
122
123
  // Check if user is blocked.
1240
  user_login_name_validate($form, $state, (array)$account);
1250
  if (form_get_errors()) {
126
    // Invalid login.
1270
    return FALSE;
1280
  }
129
130
  // Valid login.
1310
  global $user;
1320
  $user = $account;
1330
  user_authenticate_finalize($state['values']);
1340
  return TRUE;
1350
}
136
137
/**
138
 * Fetch a user object.
139
 *
140
 * @param $array
141
 *   An associative array of attributes to search for in selecting the
142
 *   user, such as user name or e-mail address.
143
 *
144
 * @return
145
 *   A fully-loaded $user object upon successful user load or FALSE if user
146
 *   cannot be loaded.
147
 */
1482366
function user_load($array = array()) {
149
  // Dynamically compose a SQL query:
1502047
  $query = array();
1512047
  $params = array();
152
1532047
  if (is_numeric($array)) {
1541769
    $array = array('uid' => $array);
1551769
  }
156310
  elseif (!is_array($array)) {
1577
    return FALSE;
1580
  }
159
1602047
  foreach ($array as $key => $value) {
1612047
    if ($key == 'uid' || $key == 'status') {
1622032
      $query[] = "$key = %d";
1632032
      $params[] = $value;
1642032
    }
16529
    elseif ($key == 'pass') {
1660
      $query[] = "pass = '%s'";
1670
      $params[] = $value;
1680
    }
169
    else {
17029
      $query[]= "LOWER($key) = LOWER('%s')";
17129
      $params[] = $value;
172
    }
1732047
  }
1742047
  $result = db_query('SELECT * FROM {users} u WHERE ' . implode(' AND ',
$query), $params);
175
1762047
  if ($user = db_fetch_object($result)) {
1772047
    $user = drupal_unpack($user);
178
1792047
    $user->roles = array();
1802047
    if ($user->uid) {
1811498
      $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
1821498
    }
183
    else {
184553
      $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
185
    }
1862047
    $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);
1872047
    while ($role = db_fetch_object($result)) {
1881482
      $user->roles[$role->rid] = $role->name;
1891482
    }
1902047
    user_module_invoke('load', $array, $user);
1912047
  }
192
  else {
1931
    $user = FALSE;
194
  }
195
1962047
  return $user;
1970
}
198
199
/**
200
 * Save changes to a user account or add a new user.
201
 *
202
 * @param $account
203
 *   The $user object for the user to modify or add. If $user->uid is
204
 *   omitted, a new user will be added.
205
 *
206
 * @param $edit
207
 *   An array of fields and values to save. For example array('name'
208
 *   => 'My name').  Keys that do not belong to columns in the user-related
209
 *   tables are added to the a serialized array in the 'data' column
210
 *   and will be loaded in the $user->data array by user_load().
211
 *   Setting a field to NULL deletes it from the data column.
212
 *
213
 * @param $category
214
 *   (optional) The category for storing profile information in.
215
 *
216
 * @return
217
 *   A fully-loaded $user object upon successful save or FALSE if the save
failed.
218
 */
2192366
function user_save($account, $edit = array(), $category = 'account') {
22093
  $table = drupal_get_schema('users');
22193
  $user_fields = $table['fields'];
222
22393
  if (!empty($edit['pass'])) {
224
    // Allow alternate password hashing schemes.
22580
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc',
'includes/password.inc');
22680
    $edit['pass'] = user_hash_password(trim($edit['pass']));
227
    // Abort if the hashing failed and returned FALSE.
22880
    if (!$edit['pass']) {
2290
      return FALSE;
2300
    }
23180
  }
232
  else {
233
    // Avoid overwriting an existing password with a blank password.
23413
    unset($edit['pass']);
235
  }
236
23793
  if (is_object($account) && $account->uid) {
23814
    user_module_invoke('update', $edit, $account, $category);
23914
    $data = unserialize(db_result(db_query('SELECT data FROM {users} WHERE
uid = %d', $account->uid)));
240
    // Consider users edited by an administrator as logged in, if they
haven't
241
    // already, so anonymous users can view the profile (if allowed).
24214
    if (empty($edit['access']) && empty($account->access) &&
user_access('administer users')) {
2430
      $edit['access'] = REQUEST_TIME;
2440
    }
24514
    foreach ($edit as $key => $value) {
246
      // Fields that don't pertain to the users or user_roles
247
      // automatically serialized into the users.data column.
24814
      if ($key != 'roles' && empty($user_fields[$key])) {
24913
        if ($value === NULL) {
25010
          unset($data[$key]);
25110
        }
252
        else {
25313
          $data[$key] = $value;
254
        }
25513
      }
25614
    }
257
25814
    $edit['data'] = $data;
25914
    $edit['uid'] = $account->uid;
260
    // Save changes to the users table.
26114
    $success = drupal_write_record('users', $edit, 'uid');
26214
    if (!$success) {
263
      // The query failed - better to abort the save than risk further data
loss.
2645
      return FALSE;
2650
    }
266
267
    // Reload user roles if provided.
2689
    if (isset($edit['roles']) && is_array($edit['roles'])) {
2690
      db_query('DELETE FROM {users_roles} WHERE uid = %d', $account->uid);
270
2710
      foreach (array_keys($edit['roles']) as $rid) {
2720
        if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID,
DRUPAL_AUTHENTICATED_RID))) {
2730
          db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)',
$account->uid, $rid);
2740
        }
2750
      }
2760
    }
277
278
    // Delete a blocked user's sessions to kick them if they are online.
2799
    if (isset($edit['status']) && $edit['status'] == 0) {
2801
      drupal_session_destroy_uid($account->uid);
2811
    }
282
283
    // If the password changed, delete all open sessions and recreate
284
    // the current one.
2859
    if (!empty($edit['pass'])) {
2861
      drupal_session_destroy_uid($account->uid);
2871
      drupal_session_regenerate();
2881
    }
289
290
    // Refresh user object.
2919
    $user = user_load(array('uid' => $account->uid));
292
293
    // Send emails after we have the new user object.
2949
    if (isset($edit['status']) && $edit['status'] != $account->status) {
295
      // The user's status is changing; conditionally send notification
email.
2961
      $op = $edit['status'] == 1 ? 'status_activated' : 'status_blocked';
2971
      _user_mail_notify($op, $user);
2981
    }
299
3009
    user_module_invoke('after_update', $edit, $user, $category);
3019
  }
302
  else {
303
    // Allow 'created' to be set by the caller.
30479
    if (!isset($edit['created'])) {
30579
      $edit['created'] = REQUEST_TIME;
30679
    }
307
    // Consider users created by an administrator as already logged in, so
308
    // anonymous users can view the profile (if allowed).
30979
    if (empty($edit['access']) && user_access('administer users')) {
31073
      $edit['access'] = REQUEST_TIME;
31173
    }
312
31379
    $success = drupal_write_record('users', $edit);
31479
    if (!$success) {
315
      // On a failed INSERT some other existing user's uid may be returned.
316
      // We must abort to avoid overwriting their account.
3170
      return FALSE;
3180
    }
319
320
    // Build the initial user object.
32179
    $user = user_load(array('uid' => $edit['uid']));
322
32379
    user_module_invoke('insert', $edit, $user, $category);
324
325
    // Note, we wait with saving the data column to prevent module-handled
326
    // fields from being saved there.
32779
    $data = array();
32879
    foreach ($edit as $key => $value) {
32979
      if (($key != 'roles') && (empty($user_fields[$key])) && ($value !==
NULL)) {
3305
        $data[$key] = $value;
3315
      }
33279
    }
33379
    if (!empty($data)) {
3345
      $data_array = array('uid' => $user->uid, 'data' => $data);
3355
      drupal_write_record('users', $data_array, 'uid');
3365
    }
337
338
    // Save user roles (delete just to be safe).
33979
    if (isset($edit['roles']) && is_array($edit['roles'])) {
34079
      db_query('DELETE FROM {users_roles} WHERE uid = %d', $edit['uid']);
34179
      foreach (array_keys($edit['roles']) as $rid) {
34276
        if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID,
DRUPAL_AUTHENTICATED_RID))) {
34376
          db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)',
$edit['uid'], $rid);
34476
        }
34576
      }
34679
    }
347
348
    // Build the finished user object.
34979
    $user = user_load(array('uid' => $edit['uid']));
350
  }
351
35288
  return $user;
3530
}
354
355
/**
356
 * Verify the syntax of the given name.
357
 */
3582366
function user_validate_name($name) {
3595
  if (!$name) {
3601
    return t('You must enter a username.');
3610
  }
3625
  if (substr($name, 0, 1) == ' ') {
3631
    return t('The username cannot begin with a space.');
3640
  }
3655
  if (substr($name, -1) == ' ') {
3661
    return t('The username cannot end with a space.');
3670
  }
3685
  if (strpos($name, '  ') !== FALSE) {
3691
    return t('The username cannot contain multiple spaces in a row.');
3700
  }
3715
  if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i', $name)) {
3721
    return t('The username contains an illegal character.');
3730
  }
3745
  if (preg_match('/[\x{80}-\x{A0}' .         // Non-printable ISO-8859-1 +
NBSP
3755
                   '\x{AD}' .                // Soft-hyphen
3765
                   '\x{2000}-\x{200F}' .     // Various space characters
3775
                   '\x{2028}-\x{202F}' .     // Bidirectional text
overrides
3785
                   '\x{205F}-\x{206F}' .     // Various text hinting
characters
3795
                   '\x{FEFF}' .              // Byte order mark
3805
                   '\x{FF01}-\x{FF60}' .     // Full-width latin
3815
                   '\x{FFF9}-\x{FFFD}' .     // Replacement characters
3825
                   '\x{0}-\x{1F}]/u',        // NULL byte and control
characters
3835
                   $name)) {
3840
    return t('The username contains an illegal character.');
3850
  }
3865
  if (drupal_strlen($name) > USERNAME_MAX_LENGTH) {
3871
    return t('The username %name is too long: it must be %max characters or
less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
3880
  }
3895
}
390
3912366
function user_validate_mail($mail) {
3926
  if (!$mail) {
3931
    return t('You must enter an e-mail address.');
3940
  }
3956
  if (!valid_email_address($mail)) {
3961
    return t('The e-mail address %mail is not valid.', array('%mail' =>
$mail));
3970
  }
3986
}
399
4002366
function user_validate_picture(&$form, &$form_state) {
401
  // If required, validate the uploaded picture.
402
  $validators = array(
4034
    'file_validate_is_image' => array(),
4044
    'file_validate_image_resolution' =>
array(variable_get('user_picture_dimensions', '85x85')),
4054
    'file_validate_size' => array(variable_get('user_picture_file_size',
'30') * 1024),
4064
  );
4074
  if ($file = file_save_upload('picture_upload', $validators)) {
408
    // Remove the old picture.
4092
    if (isset($form_state['values']['_account']->picture) &&
file_exists($form_state['values']['_account']->picture)) {
4100
      file_unmanaged_delete($form_state['values']['_account']->picture);
4110
    }
412
413
    // The image was saved using file_save_upload() and was added to the
414
    // files table as a temporary file. We'll make a copy and let the
garbage
415
    // collector delete the original upload.
4162
    $info = image_get_info($file->filepath);
4172
    $destination = file_create_path(variable_get('user_picture_path',
'pictures') . '/picture-' . $form['#uid'] . '.' . $info['extension']);
4182
    if ($filepath = file_unmanaged_copy($file->filepath, $destination,
FILE_EXISTS_REPLACE)) {
4192
      $form_state['values']['picture'] = $filepath;
4202
    }
421
    else {
4220
      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'))));
423
    }
4242
  }
4254
}
426
427
/**
428
 * Generate a random alphanumeric password.
429
 */
4302366
function user_password($length = 10) {
431
  // This variable contains the list of allowable characters for the
432
  // password. Note that the number 0 and the letter 'O' have been
433
  // removed to avoid confusion between the two. The same is true
434
  // of 'I', 1, and 'l'.
43579
  $allowable_characters =
'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
436
437
  // Zero-based count of characters in the allowable list:
43879
  $len = strlen($allowable_characters) - 1;
439
440
  // Declare the password as a blank string.
44179
  $pass = '';
442
443
  // Loop the number of times specified by $length.
44479
  for ($i = 0; $i < $length; $i++) {
445
446
    // Each iteration, pick a random character from the
447
    // allowable string and append it to the password:
44879
    $pass .= $allowable_characters[mt_rand(0, $len)];
44979
  }
450
45179
  return $pass;
4520
}
453
454
/**
455
 * Determine the permissions for one or more roles.
456
 *
457
 * @param $roles
458
 *   An array whose keys are the role IDs of interest, such as
$user->roles.
459
 * @param $reset
460
 *   Optional parameter - if TRUE data in the static variable is rebuilt.
461
 *
462
 * @return
463
 *   An array indexed by role ID. Each value is an array whose keys are the
464
 *   permission strings for the given role ID.
465
 */
4662366
function user_role_permissions($roles = array(), $reset = FALSE) {
4672078
  static $stored_permissions = array();
468
4692078
  if ($reset) {
470
    // Clear the data cached in the static variable.
4711
    $stored_permissions = array();
4721
  }
473
4742078
  $role_permissions = $fetch = array();
475
4762078
  if ($roles) {
4772078
    foreach ($roles as $rid => $name) {
4782078
      if (isset($stored_permissions[$rid])) {
47934
        $role_permissions[$rid] = $stored_permissions[$rid];
48034
      }
481
      else {
482
        // Add this rid to the list of those needing to be fetched.
4832078
        $fetch[] = $rid;
484
        // Prepare in case no permissions are returned.
4852078
        $stored_permissions[$rid] = array();
486
      }
4872078
    }
488
4892078
    if ($fetch) {
490
      // Get from the database permissions that were not in the static
variable.
491
      // Only role IDs with at least one permission assigned will return
rows.
4922078
      $result = db_query("SELECT r.rid, p.permission FROM {role} r INNER
JOIN {role_permission} p ON p.rid = r.rid WHERE r.rid IN (" .
db_placeholders($fetch) . ")", $fetch);
493
4942078
      while ($row = db_fetch_array($result)) {
4952078
        $stored_permissions[$row['rid']][$row['permission']] = TRUE;
4962078
      }
4972078
      foreach ($fetch as $rid) {
498
        // For every rid, we know we at least assigned an empty array.
4992078
        $role_permissions[$rid] = $stored_permissions[$rid];
5002078
      }
5012078
    }
5022078
  }
503
5042078
  return $role_permissions;
5050
}
506
507
/**
508
 * Determine whether the user has a given privilege.
509
 *
510
 * @param $string
511
 *   The permission, such as "administer nodes", being checked for.
512
 * @param $account
513
 *   (optional) The account to check, if not given use currently logged in
user.
514
 * @param $reset
515
 *   (optional) Resets the user's permissions cache, which will result in a
516
 *   recalculation of the user's permissions. This is necessary to support
517
 *   dynamically added user roles.
518
 *
519
 * @return
520
 *   Boolean TRUE if the current user has the requested permission.
521
 *
522
 * All permission checks in Drupal should go through this function. This
523
 * way, we guarantee consistent behavior, and ensure that the superuser
524
 * can perform all actions.
525
 */
5262366
function user_access($string, $account = NULL, $reset = FALSE) {
5272149
  global $user;
5282149
  static $perm = array();
529
5302149
  if ($reset) {
5311
    unset($perm);
5321
  }
533
5342149
  if (is_null($account)) {
5352133
    $account = $user;
5362133
  }
537
538
  // User #1 has all privileges:
5392149
  if ($account->uid == 1) {
54072
    return TRUE;
5410
  }
542
543
  // To reduce the number of SQL queries, we cache the user's permissions
544
  // in a static variable.
5452078
  if (!isset($perm[$account->uid])) {
5462078
    $role_permissions = user_role_permissions($account->roles, $reset);
547
5482078
    $perms = array();
5492078
    foreach ($role_permissions as $one_role) {
5502078
      $perms += $one_role;
5512078
    }
5522078
    $perm[$account->uid] = $perms;
5532078
  }
554
5552078
  return isset($perm[$account->uid][$string]);
5560
}
557
558
/**
559
 * Checks for usernames blocked by user administration.
560
 *
561
 * @return boolean TRUE for blocked users, FALSE for active.
562
 */
5632366
function user_is_blocked($name) {
564178
  $deny = db_fetch_object(db_query("SELECT name FROM {users} WHERE status =
0 AND name = LOWER('%s')", $name));
565
566178
  return $deny;
5670
}
568
569
/**
570
 * Implementation of hook_perm().
571
 */
5722366
function user_perm() {
573
   return array(
574
     'administer permissions' =>  array(
575172
       'title' => t('Administer permissions'),
576172
       'description' => t('Manage the permissions assigned to user roles.
%warning', array('%warning' => t('Warning: Give to trusted roles only; this
permission has security implications.'))),
577172
     ),
578
     'administer users' => array(
579172
       'title' => t('Administer users'),
580172
       'description' => t('Manage or block users, and manage their role
assignments.'),
581172
     ),
582
     'access user profiles' => array(
583172
       'title' => t('Access user profiles'),
584172
       'description' => t('View profiles of users on the site, which may
contain personal information.'),
585172
     ),
586
     'change own username' => array(
587172
       'title' => t('Change own username'),
588172
       'description' => t('Select a different username.'),
589172
     ),
590172
   );
5910
}
592
593
/**
594
 * Implementation of hook_file_download().
595
 *
596
 * Ensure that user pictures (avatars) are always downloadable.
597
 */
5982366
function user_file_download($file) {
5990
  if (strpos($file, variable_get('user_picture_path', 'pictures') .
'/picture-') === 0) {
6000
    $info = image_get_info(file_create_path($file));
6010
    return array('Content-type: ' . $info['mime_type']);
6020
  }
6030
}
604
605
/**
606
 * Implementation of hook_search().
607
 */
6082366
function user_search($op = 'search', $keys = NULL, $skip_access_check =
FALSE) {
609
  switch ($op) {
61011
    case 'name':
61111
      if ($skip_access_check || user_access('access user profiles')) {
6120
        return t('Users');
6130
      }
61411
    case 'search':
61511
      if (user_access('access user profiles')) {
6160
        $find = array();
617
        // Replace wildcards with MySQL/PostgreSQL wildcards.
6180
        $keys = preg_replace('!\*+!', '%', $keys);
6190
        if (user_access('administer users')) {
620
          // Administrators can also search in the otherwise private email
field.
6210
          $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);
6220
          while ($account = db_fetch_object($result)) {
6230
            $find[] = array('title' => $account->name . ' (' .
$account->mail . ')', 'link' => url('user/' . $account->uid,
array('absolute' => TRUE)));
6240
          }
6250
        }
626
        else {
6270
          $result = pager_query("SELECT name, uid FROM {users} WHERE
LOWER(name) LIKE LOWER('%%%s%%')", 15, 0, NULL, $keys);
6280
          while ($account = db_fetch_object($result)) {
6290
            $find[] = array('title' => $account->name, 'link' =>
url('user/' . $account->uid, array('absolute' => TRUE)));
6300
          }
631
        }
6320
        return $find;
6330
      }
63411
  }
63511
}
636
637
/**
638
 * Implementation of hook_elements().
639
 */
6402366
function user_elements() {
641
  return array(
6421837
    'user_profile_category' => array(),
6431837
    'user_profile_item' => array(),
6441837
  );
6450
}
646
647
/**
648
 * Implementation of hook_user_view().
649
 */
6502366
function user_user_view(&$edit, &$account, $category = NULL) {
651191
  $account->content['user_picture'] = array(
652191
    '#value' => theme('user_picture', $account),
653191
    '#weight' => -10,
654
  );
655191
  if (!isset($account->content['summary'])) {
656184
    $account->content['summary'] = array();
657184
  }
6580
  $account->content['summary'] += array(
659191
    '#type' => 'user_profile_category',
660191
    '#attributes' => array('class' => 'user-member'),
661191
    '#weight' => 5,
662191
    '#title' => t('History'),
663
  );
664191
  $account->content['summary']['member_for'] =  array(
665191
    '#type' => 'user_profile_item',
666191
    '#title' => t('Member for'),
667191
    '#markup' => format_interval(REQUEST_TIME - $account->created),
668
  );
669191
}
670
671
/**
672
 * Implementation of hook_user_form.
673
 */
6742366
function user_user_form(&$edit, &$account, $category = NULL) {
67558
  if ($category == 'account') {
67615
    $form_state = array();
67715
    return user_edit_form($form_state, arg(1), $edit);
6780
  }
67943
}
680
681
/**
682
 * Implementation of hook_user_validate.
683
 */
6842366
function user_user_validate(&$edit, &$account, $category = NULL) {
68515
  if ($category == 'account') {
6865
    return _user_edit_validate(arg(1), $edit);
6870
  }
68810
}
689
690
/**
691
 * Implementation of hook_user_submit.
692
 */
6932366
function user_user_submit(&$edit, &$account, $category = NULL) {
69413
  if ($category == 'account') {
6953
    return _user_edit_submit(arg(1), $edit);
6960
  }
69710
}
698
699
/**
700
 * Implementation of hook_user_categories.
701
 */
7022366
function user_user_categories(&$edit, &$account, $category = NULL) {
703204
    return array(array('name' => 'account', 'title' => t('Account
settings'), 'weight' => 1));
7040
}
705
7062366
function user_login_block() {
707
  $form = array(
708271
    '#action' => url($_GET['q'], array('query' =>
drupal_get_destination())),
709271
    '#id' => 'user-login-form',
710271
    '#validate' => user_login_default_validators(),
711271
    '#submit' => array('user_login_submit'),
712271
  );
713271
  $form['name'] = array('#type' => 'textfield',
714271
    '#title' => t('Username'),
715271
    '#maxlength' => USERNAME_MAX_LENGTH,
716271
    '#size' => 15,
717271
    '#required' => TRUE,
718
  );
719271
  $form['pass'] = array('#type' => 'password',
720271
    '#title' => t('Password'),
721271
    '#maxlength' => 60,
722271
    '#size' => 15,
723271
    '#required' => TRUE,
724
  );
725271
  $form['submit'] = array('#type' => 'submit',
726271
    '#value' => t('Log in'),
727
  );
728271
  $items = array();
729271
  if (variable_get('user_register', 1)) {
730271
    $items[] = l(t('Create new account'), 'user/register',
array('attributes' => array('title' => t('Create a new user account.'))));
731271
  }
732271
  $items[] = l(t('Request new password'), 'user/password',
array('attributes' => array('title' => t('Request new password via
e-mail.'))));
733271
  $form['links'] = array('#markup' => theme('item_list', $items));
734271
  return $form;
7350
}
736
737
/**
738
 * Implementation of hook_block().
739
 */
7402366
function user_block($op = 'list', $delta = '', $edit = array()) {
7411729
  global $user;
742
7431729
  if ($op == 'list') {
74433
    $blocks['login']['info'] = t('User login');
745
    // Not worth caching.
74633
    $blocks['login']['cache'] = BLOCK_NO_CACHE;
747
74833
    $blocks['navigation']['info'] = t('Navigation');
749
    // Menu blocks can't be cached because each menu item can have
750
    // a custom access callback. menu.inc manages its own caching.
75133
    $blocks['navigation']['cache'] = BLOCK_NO_CACHE;
752
75333
    $blocks['new']['info'] = t('Who\'s new');
754
755
    // Too dynamic to cache.
75633
    $blocks['online']['info'] = t('Who\'s online');
75733
    $blocks['online']['cache'] = BLOCK_NO_CACHE;
75833
    return $blocks;
7590
  }
7601721
  elseif ($op == 'configure' && $delta == 'new') {
7610
    $form['user_block_whois_new_count'] = array(
7620
      '#type' => 'select',
7630
      '#title' => t('Number of users to display'),
7640
      '#default_value' => variable_get('user_block_whois_new_count', 5),
7650
      '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
766
    );
7670
    return $form;
7680
  }
7691721
  elseif ($op == 'configure' && $delta == 'online') {
7700
    $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800,
2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval');
7710
    $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.'));
7720
    $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.'));
773
7740
    return $form;
7750
  }
7761721
  elseif ($op == 'save' && $delta == 'new') {
7770
    variable_set('user_block_whois_new_count',
$edit['user_block_whois_new_count']);
7780
  }
7791721
  elseif ($op == 'save' && $delta == 'online') {
7800
    variable_set('user_block_seconds_online',
$edit['user_block_seconds_online']);
7810
    variable_set('user_block_max_list_count',
$edit['user_block_max_list_count']);
7820
  }
7831721
  elseif ($op == 'view') {
7841719
    $block = array();
785
786
    switch ($delta) {
7871719
      case 'login':
788
        // For usability's sake, avoid showing two login forms on one page.
7891719
        if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
790
791271
          $block['subject'] = t('User login');
792271
          $block['content'] = drupal_get_form('user_login_block');
793271
        }
7941719
        return $block;
795
7961717
      case 'navigation':
7971717
        if ($menu = menu_tree()) {
7981205
          $block['subject'] = $user->uid ? check_plain($user->name) :
t('Navigation');
7991205
          $block['content'] = $menu;
8001205
        }
8011717
        return $block;
802
8030
      case 'new':
8040
        if (user_access('access content')) {
805
          // Retrieve a list of new users who have subsequently accessed
the site successfully.
8060
          $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));
8070
          while ($account = db_fetch_object($result)) {
8080
            $items[] = $account;
8090
          }
8100
          $output = theme('user_list', $items);
811
8120
          $block['subject'] = t('Who\'s new');
8130
          $block['content'] = $output;
8140
        }
8150
        return $block;
816
8170
      case 'online':
8180
        if (user_access('access content')) {
819
          // Count users active within the defined period.
8200
          $interval = REQUEST_TIME -
variable_get('user_block_seconds_online', 900);
821
822
          // Perform database queries to gather online user lists.  We use
s.timestamp
823
          // rather than u.access because it is much faster.
8240
          $anonymous_count = drupal_session_count($interval);
8250
          $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);
8260
          $authenticated_count = 0;
8270
          $max_users = variable_get('user_block_max_list_count', 10);
8280
          $items = array();
8290
          while ($account = db_fetch_object($authenticated_users)) {
8300
            if ($max_users > 0) {
8310
              $items[] = $account;
8320
              $max_users--;
8330
            }
8340
            $authenticated_count++;
8350
          }
836
837
          // Format the output with proper grammar.
8380
          if ($anonymous_count == 1 && $authenticated_count == 1) {
8390
            $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')));
8400
          }
841
          else {
8420
            $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')));
843
          }
844
845
          // Display a list of currently online users.
8460
          $max_users = variable_get('user_block_max_list_count', 10);
8470
          if ($authenticated_count && $max_users) {
8480
            $output .= theme('user_list', $items, t('Online users'));
8490
          }
850
8510
          $block['subject'] = t('Who\'s online');
8520
          $block['content'] = $output;
8530
        }
8540
        return $block;
8550
    }
8560
  }
8574
}
858
859
/**
860
 * Process variables for user-picture.tpl.php.
861
 *
862
 * The $variables array contains the following arguments:
863
 * - $account
864
 *
865
 * @see user-picture.tpl.php
866
 */
8672366
function template_preprocess_user_picture(&$variables) {
868201
  $variables['picture'] = '';
869201
  if (variable_get('user_pictures', 0)) {
87014
    $account = $variables['account'];
87114
    if (!empty($account->picture) && file_exists($account->picture)) {
8722
      $picture = file_create_url($account->picture);
8732
    }
87412
    elseif (variable_get('user_picture_default', '')) {
8750
      $picture = variable_get('user_picture_default', '');
8760
    }
877
87814
    if (isset($picture)) {
8792
      $alt = t("@user's picture", array('@user' => $account->name ?
$account->name : variable_get('anonymous', t('Anonymous'))));
8802
      $variables['picture'] = theme('image', $picture, $alt, $alt, '',
FALSE);
8812
      if (!empty($account->uid) && user_access('access user profiles')) {
8820
        $attributes = array('attributes' => array('title' => t('View user
profile.')), 'html' => TRUE);
8830
        $variables['picture'] = l($variables['picture'],
"user/$account->uid", $attributes);
8840
      }
8852
    }
88614
  }
887201
}
888
889
/**
890
 * Make a list of users.
891
 *
892
 * @param $users
893
 *   An array with user objects. Should contain at least the name and uid.
894
 * @param $title
895
 *  (optional) Title to pass on to theme_item_list().
896
 *
897
 * @ingroup themeable
898
 */
8992366
function theme_user_list($users, $title = NULL) {
9000
  if (!empty($users)) {
9010
    foreach ($users as $user) {
9020
      $items[] = theme('username', $user);
9030
    }
9040
  }
9050
  return theme('item_list', $items, $title);
9060
}
907
9082366
function user_is_anonymous() {
909
  // Menu administrators can see items for anonymous when administering.
910277
  return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
9110
}
912
9132366
function user_is_logged_in() {
9141844
  return (bool)$GLOBALS['user']->uid;
9150
}
916
9172366
function user_register_access() {
918277
  return user_is_anonymous() && variable_get('user_register', 1);
9190
}
920
9212366
function user_view_access($account) {
9221748
  return $account && $account->uid &&
923
    (
924
      // Always let users view their own profile.
9251198
      ($GLOBALS['user']->uid == $account->uid) ||
926
      // Administrators can view all accounts.
92742
      user_access('administer users') ||
928
      // The user is not blocked and logged in at least once.
9299
      ($account->access && $account->status && user_access('access user
profiles'))
9301748
    );
9310
}
932
933
/**
934
 * Access callback for user account editing.
935
 */
9362366
function user_edit_access($account) {
937245
  return (($GLOBALS['user']->uid == $account->uid) ||
user_access('administer users')) && $account->uid > 0;
9380
}
939
9402366
function user_load_self($arg) {
9410
  $arg[1] = user_load($GLOBALS['user']->uid);
9420
  return $arg;
9430
}
944
945
/**
946
 * Implementation of hook_menu().
947
 */
9482366
function user_menu() {
949161
  $items['user/autocomplete'] = array(
950161
    'title' => 'User autocomplete',
951161
    'page callback' => 'user_autocomplete',
952161
    'access callback' => 'user_access',
953161
    'access arguments' => array('access user profiles'),
954161
    'type' => MENU_CALLBACK,
955
  );
956
957
  // Registration and login pages.
958161
  $items['user'] = array(
959161
    'title' => 'User account',
960161
    'page callback' => 'user_page',
961161
    'access callback' => TRUE,
962161
    'type' => MENU_CALLBACK,
963
  );
964
965161
  $items['user/login'] = array(
966161
    'title' => 'Log in',
967161
    'access callback' => 'user_is_anonymous',
968161
    'type' => MENU_DEFAULT_LOCAL_TASK,
969
  );
970
971161
  $items['user/register'] = array(
972161
    'title' => 'Create new account',
973161
    'page callback' => 'drupal_get_form',
974161
    'page arguments' => array('user_register'),
975161
    'access callback' => 'user_register_access',
976161
    'type' => MENU_LOCAL_TASK,
977
  );
978
979161
  $items['user/password'] = array(
980161
    'title' => 'Request new password',
981161
    'page callback' => 'drupal_get_form',
982161
    'page arguments' => array('user_pass'),
983161
    'access callback' => 'user_is_anonymous',
984161
    'type' => MENU_LOCAL_TASK,
985
  );
986161
  $items['user/reset/%/%/%'] = array(
987161
    'title' => 'Reset password',
988161
    'page callback' => 'drupal_get_form',
989161
    'page arguments' => array('user_pass_reset', 2, 3, 4),
990161
    'access callback' => TRUE,
991161
    'type' => MENU_CALLBACK,
992
  );
993
994
  // User administration pages.
995161
  $items['admin/user'] = array(
996161
    'title' => 'User management',
997161
    'description' => "Manage your site's users, groups and access to site
features.",
998161
    'position' => 'left',
999161
    'page callback' => 'system_admin_menu_block_page',
1000161
    'access arguments' => array('access administration pages'),
1001
  );
1002161
  $items['admin/user/user'] = array(
1003161
    'title' => 'Users',
1004161
    'description' => 'List, add, and edit users.',
1005161
    'page callback' => 'user_admin',
1006161
    'page arguments' => array('list'),
1007161
    'access arguments' => array('administer users'),
1008
  );
1009161
  $items['admin/user/user/list'] = array(
1010161
    'title' => 'List',
1011161
    'type' => MENU_DEFAULT_LOCAL_TASK,
1012161
    'weight' => -10,
1013
  );
1014161
  $items['admin/user/user/create'] = array(
1015161
    'title' => 'Add user',
1016161
    'page arguments' => array('create'),
1017161
    'access arguments' => array('administer users'),
1018161
    'type' => MENU_LOCAL_TASK,
1019
  );
1020161
  $items['admin/user/settings'] = array(
1021161
    'title' => 'User settings',
1022161
    'description' => 'Configure default behavior of users, including
registration requirements, e-mails, and user pictures.',
1023161
    'page callback' => 'drupal_get_form',
1024161
    'page arguments' => array('user_admin_settings'),
1025161
    'access arguments' => array('administer users'),
1026
  );
1027
1028
  // Permission administration pages.
1029161
  $items['admin/user/permissions'] = array(
1030161
    'title' => 'Permissions',
1031161
    'description' => 'Determine access to features by selecting permissions
for roles.',
1032161
    'page callback' => 'drupal_get_form',
1033161
    'page arguments' => array('user_admin_perm'),
1034161
    'access arguments' => array('administer permissions'),
1035
  );
1036161
  $items['admin/user/roles'] = array(
1037161
    'title' => 'Roles',
1038161
    'description' => 'List, edit, or add user roles.',
1039161
    'page callback' => 'drupal_get_form',
1040161
    'page arguments' => array('user_admin_new_role'),
1041161
    'access arguments' => array('administer permissions'),
1042
  );
1043161
  $items['admin/user/roles/edit'] = array(
1044161
    'title' => 'Edit role',
1045161
    'page arguments' => array('user_admin_role'),
1046161
    'access arguments' => array('administer permissions'),
1047161
    'type' => MENU_CALLBACK,
1048
  );
1049
1050161
  $items['logout'] = array(
1051161
    'title' => 'Log out',
1052161
    'access callback' => 'user_is_logged_in',
1053161
    'page callback' => 'user_logout',
1054161
    'weight' => 10,
1055
  );
1056
1057161
  $items['user/%user_uid_optional'] = array(
1058161
    'title' => 'My account',
1059161
    'title callback' => 'user_page_title',
1060161
    'title arguments' => array(1),
1061161
    'page callback' => 'user_view',
1062161
    'page arguments' => array(1),
1063161
    'access callback' => 'user_view_access',
1064161
    'access arguments' => array(1),
1065161
    'parent' => '',
1066
  );
1067
1068161
  $items['user/%user/view'] = array(
1069161
    'title' => 'View',
1070161
    'type' => MENU_DEFAULT_LOCAL_TASK,
1071161
    'weight' => -10,
1072
  );
1073
1074161
  $items['user/%user/delete'] = array(
1075161
    'title' => 'Delete',
1076161
    'page callback' => 'drupal_get_form',
1077161
    'page arguments' => array('user_confirm_delete', 1),
1078161
    'access callback' => 'user_access',
1079161
    'access arguments' => array('administer users'),
1080161
    'type' => MENU_CALLBACK,
1081
  );
1082
1083161
  $items['user/%user/edit'] = array(
1084161
    'title' => 'Edit',
1085161
    'page callback' => 'user_edit',
1086161
    'page arguments' => array(1),
1087161
    'access callback' => 'user_edit_access',
1088161
    'access arguments' => array(1),
1089161
    'type' => MENU_LOCAL_TASK,
1090161
    'load arguments' => array('%map', '%index'),
1091
  );
1092
1093161
  $items['user/%user_category/edit/account'] = array(
1094161
    'title' => 'Account',
1095161
    'type' => MENU_DEFAULT_LOCAL_TASK,
1096161
    'load arguments' => array('%map', '%index'),
1097
  );
1098
1099161
  $empty_account = new stdClass();
1100161
  if (($categories = _user_categories($empty_account)) &&
(count($categories) > 1)) {
110110
    foreach ($categories as $key => $category) {
1102
      // 'account' is already handled by the MENU_DEFAULT_LOCAL_TASK.
110310
      if ($category['name'] != 'account') {
110410
        $items['user/%user_category/edit/' . $category['name']] = array(
110510
          'title callback' => 'check_plain',
110610
          'title arguments' => array($category['title']),
110710
          'page callback' => 'user_edit',
110810
          'page arguments' => array(1, 3),
110910
          'access callback' => isset($category['access callback']) ?
$category['access callback'] : 'user_edit_access',
111010
          'access arguments' => isset($category['access arguments']) ?
$category['access arguments'] : array(1),
111110
          'type' => MENU_LOCAL_TASK,
111210
          'weight' => $category['weight'],
111310
          'load arguments' => array('%map', '%index'),
111410
          'tab_parent' => 'user/%/edit',
1115
        );
111610
      }
111710
    }
111810
  }
1119161
  return $items;
11200
}
1121
11222366
function user_init() {
11232366
  drupal_add_css(drupal_get_path('module', 'user') . '/user.css');
11242366
}
1125
11262366
function user_uid_optional_load($arg) {
11271748
  return user_load(isset($arg) ? $arg : $GLOBALS['user']->uid);
11280
}
1129
1130
/**
1131
 * Return a user object after checking if any profile category in the path
exists.
1132
 */
11332366
function user_category_load($uid, &$map, $index) {
1134251
  static $user_categories, $accounts;
1135
1136
  // Cache $account - this load function will get called for each profile
tab.
1137251
  if (!isset($accounts[$uid])) {
1138251
    $accounts[$uid] = user_load($uid);
1139251
  }
1140251
  $valid = TRUE;
1141251
  if ($account = $accounts[$uid]) {
1142
    // Since the path is like user/%/edit/category_name, the category name
will
1143
    // be at a position 2 beyond the index corresponding to the % wildcard.
1144251
    $category_index = $index + 2;
1145
    // Valid categories may contain slashes, and hence need to be imploded.
1146251
    $category_path = implode('/', array_slice($map, $category_index));
1147251
    if ($category_path) {
1148
      // Check that the requested category exists.
114943
      $valid = FALSE;
115043
      if (!isset($user_categories)) {
115143
        $empty_account = new stdClass();
115243
        $user_categories = _user_categories($empty_account);
115343
      }
115443
      foreach ($user_categories as $category) {
115543
        if ($category['name'] == $category_path) {
115643
          $valid = TRUE;
1157
          // Truncate the map array in case the category name had slashes.
115843
          $map = array_slice($map, 0, $category_index);
1159
          // Assign the imploded category name to the last map element.
116043
          $map[$category_index] = $category_path;
116143
          break;
11620
        }
116343
      }
116443
    }
1165251
  }
1166251
  return $valid ? $account : FALSE;
11670
}
1168
1169
/**
1170
 * Returns the user id of the currently logged in user.
1171
 */
11722366
function user_uid_optional_to_arg($arg) {
1173
  // Give back the current user uid when called from eg. tracker, aka.
1174
  // with an empty arg. Also use the current user uid when called from
1175
  // the menu with a % for the current account link.
11761748
  return empty($arg) || $arg == '%' ? $GLOBALS['user']->uid : $arg;
11770
}
1178
1179
/**
1180
 * Menu item title callback - use the user name if it's not the current
user.
1181
 */
11822366
function user_page_title($account) {
11831198
  if ($account->uid == $GLOBALS['user']->uid) {
11841198
    return t('My account');
11850
  }
118633
  return $account->name;
11870
}
1188
1189
/**
1190
 * Discover which external authentication module(s) authenticated a
username.
1191
 *
1192
 * @param $authname
1193
 *   A username used by an external authentication module.
1194
 * @return
1195
 *   An associative array with module as key and username as value.
1196
 */
11972366
function user_get_authmaps($authname = NULL) {
11980
  $result = db_query("SELECT authname, module FROM {authmap} WHERE authname
= '%s'", $authname);
11990
  $authmaps = array();
12000
  $has_rows = FALSE;
12010
  while ($authmap = db_fetch_object($result)) {
12020
    $authmaps[$authmap->module] = $authmap->authname;
12030
    $has_rows = TRUE;
12040
  }
12050
  return $has_rows ? $authmaps : 0;
12060
}
1207
1208
/**
1209
 * Save mappings of which external authentication module(s) authenticated
1210
 * a user. Maps external usernames to user ids in the users table.
1211
 *
1212
 * @param $account
1213
 *   A user object.
1214
 * @param $authmaps
1215
 *   An associative array with a compound key and the username as the
value.
1216
 *   The key is made up of 'authname_' plus the name of the external
authentication
1217
 *   module.
1218
 * @see user_external_login_register()
1219
 */
12202366
function user_set_authmaps($account, $authmaps) {
12210
  foreach ($authmaps as $key => $value) {
12220
    $module = explode('_', $key, 2);
12230
    if ($value) {
12240
      db_merge('authmap')
12250
        ->key(array(
12260
        'uid' => $account->uid,
12270
        'module' => $module[1],
12280
        ))
12290
        ->fields(array(
12300
        'authname' => $value,
12310
        ))
12320
        ->execute();
12330
    }
1234
    else {
12350
      db_delete('authmap')->condition('uid',
$account->uid)->condition('module', $module[1])->execute();
1236
    }
12370
  }
12380
}
1239
1240
/**
1241
 * Form builder; the main user login form.
1242
 *
1243
 * @ingroup forms
1244
 */
12452366
function user_login(&$form_state) {
1246450
  global $user;
1247
1248
  // If we are already logged on, go to the user page instead.
1249450
  if ($user->uid) {
12500
    drupal_goto('user/' . $user->uid);
12510
  }
1252
1253
  // Display login form:
1254450
  $form['name'] = array('#type' => 'textfield',
1255450
    '#title' => t('Username'),
1256450
    '#size' => 60,
1257450
    '#maxlength' => USERNAME_MAX_LENGTH,
1258450
    '#required' => TRUE,
1259450
    '#attributes' => array('tabindex' => '1'),
1260
  );
1261
1262450
  $form['name']['#description'] = t('Enter your @s username.', array('@s'
=> variable_get('site_name', 'Drupal')));
1263450
  $form['pass'] = array('#type' => 'password',
1264450
    '#title' => t('Password'),
1265450
    '#description' => t('Enter the password that accompanies your
username.'),
1266450
    '#required' => TRUE,
1267450
    '#attributes' => array('tabindex' => '2'),
1268
  );
1269450
  $form['#validate'] = user_login_default_validators();
1270450
  $form['submit'] = array('#type' => 'submit', '#value' => t('Log in'),
'#weight' => 2, '#attributes' => array('tabindex' => '3'));
1271
1272450
  return $form;
12730
}
1274
1275
/**
1276
 * Set up a series for validators which check for blocked users,
1277
 * then authenticate against local database, then return an error if
1278
 * authentication fails. Distributed authentication modules are welcome
1279
 * to use hook_form_alter() to change this series in order to
1280
 * authenticate against their user database instead of the local users
1281
 * table.
1282
 *
1283
 * We use three validators instead of one since external authentication
1284
 * modules usually only need to alter the second validator.
1285
 *
1286
 * @see user_login_name_validate()
1287
 * @see user_login_authenticate_validate()
1288
 * @see user_login_final_validate()
1289
 * @return array
1290
 *   A simple list of validate functions.
1291
 */
12922366
function user_login_default_validators() {
1293721
  return array('user_login_name_validate',
'user_login_authenticate_validate', 'user_login_final_validate');
12940
}
1295
1296
/**
1297
 * A FAPI validate handler. Sets an error if supplied username has been
blocked.
1298
 */
12992366
function user_login_name_validate($form, &$form_state) {
1300178
  if (isset($form_state['values']['name']) &&
user_is_blocked($form_state['values']['name'])) {
1301
    // Blocked in user administration.
13020
    form_set_error('name', t('The username %name has not been activated or
is blocked.', array('%name' => $form_state['values']['name'])));
13030
  }
1304178
}
1305
1306
/**
1307
 * A validate handler on the login form. Check supplied username/password
1308
 * against local users table. If successful, sets the global $user object.
1309
 */
13102366
function user_login_authenticate_validate($form, &$form_state) {
1311178
  user_authenticate($form_state['values']);
1312178
}
1313
1314
/**
1315
 * A validate handler on the login form. Should be the last validator. Sets
an
1316
 * error if user has not been authenticated yet.
1317
 */
13182366
function user_login_final_validate($form, &$form_state) {
1319178
  global $user;
1320178
  if (!$user->uid) {
13211
    form_set_error('name', t('Sorry, unrecognized username or password. <a
href="@password">Have you forgotten your password?</a>', array('@password'
=> url('user/password'))));
13221
    watchdog('user', 'Login attempt failed for %user.', array('%user' =>
$form_state['values']['name']));
13231
  }
1324178
}
1325
1326
/**
1327
 * Try to log in the user locally.
1328
 *
1329
 * @param $form_values
1330
 *   Form values with at least 'name' and 'pass' keys, as well as anything
else
1331
 *   which should be passed along to hook_user op 'login'.
1332
 *
1333
 * @return
1334
 *  A $user object, if successful.
1335
 */
13362366
function user_authenticate($form_values = array()) {
1337186
  global $user;
1338
1339186
  $password = trim($form_values['pass']);
1340
  // Name and pass keys are required.
1341186
  if (!empty($form_values['name']) && !empty($password)) {
1342186
    $account = db_fetch_object(db_query("SELECT * FROM {users} WHERE name =
'%s' AND status = 1", $form_values['name']));
1343186
    if ($account) {
1344
      // Allow alternate password hashing schemes.
1345186
      require_once DRUPAL_ROOT . '/' . variable_get('password_inc',
'includes/password.inc');
1346186
      if (user_check_password($password, $account)) {
1347185
        if (user_needs_new_hash($account)) {
13480
           $new_hash = user_hash_password($password);
13490
           if ($new_hash) {
13500
             db_query("UPDATE {users} SET pass = '%s' WHERE uid = %d",
$new_hash, $account->uid);
13510
           }
13520
        }
1353185
        $account = user_load(array('uid' => $account->uid, 'status' => 1));
1354185
        $user = $account;
1355185
        user_authenticate_finalize($form_values);
1356185
        return $user;
13570
      }
13581
    }
13591
  }
13601
}
1361
1362
/**
1363
 * Finalize the login process. Must be called when logging in a user.
1364
 *
1365
 * The function records a watchdog message about the new session, saves the
1366
 * login timestamp, calls hook_user op 'login' and generates a new session.
1367
 *
1368
 * $param $edit
1369
 *   This array is passed to hook_user op login.
1370
 */
13712366
function user_authenticate_finalize(&$edit) {
1372186
  global $user;
1373186
  watchdog('user', 'Session opened for %name.', array('%name' =>
$user->name));
1374
  // Update the user table timestamp noting user has logged in.
1375
  // This is also used to invalidate one-time login links.
1376186
  $user->login = REQUEST_TIME;
1377186
  db_query("UPDATE {users} SET login = %d WHERE uid = %d", $user->login,
$user->uid);
1378186
  user_module_invoke('login', $edit, $user);
1379186
  drupal_session_regenerate();
1380186
}
1381
1382
/**
1383
 * Submit handler for the login form. Redirects the user to a page.
1384
 *
1385
 * The user is redirected to the My Account page. Setting the destination
in
1386
 * the query string (as done by the user login block) overrides the
redirect.
1387
 */
13882366
function user_login_submit($form, &$form_state) {
1389177
  global $user;
1390177
  if ($user->uid) {
1391177
    $form_state['redirect'] = 'user/' . $user->uid;
1392177
    return;
13930
  }
13940
}
1395
1396
/**
1397
 * Helper function for authentication modules. Either login in or registers
1398
 * the current user, based on username. Either way, the global $user object
is
1399
 * populated based on $name.
1400
 */
14012366
function user_external_login_register($name, $module) {
14020
  global $user;
1403
14040
  $existing_user = user_load(array('name' => $name));
14050
  if (isset($existing_user->uid)) {
14060
    $user = $existing_user;
14070
  }
1408
  else {
1409
    // Register this new user.
1410
    $userinfo = array(
14110
      'name' => $name,
14120
      'pass' => user_password(),
14130
      'init' => $name,
14140
      'status' => 1,
1415
      'access' => REQUEST_TIME
14160
    );
14170
    $account = user_save('', $userinfo);
1418
    // Terminate if an error occured during user_save().
14190
    if (!$account) {
14200
      drupal_set_message(t("Error saving user account."), 'error');
14210
      return;
14220
    }
14230
    user_set_authmaps($account, array("authname_$module" => $name));
14240
    $user = $account;
14250
    watchdog('user', 'New external user: %name using module %module.',
array('%name' => $name, '%module' => $module), WATCHDOG_NOTICE,
l(t('edit'), 'user/' . $user->uid . '/edit'));
1426
  }
14270
}
1428
14292366
function user_pass_reset_url($account) {
14303
  $timestamp = REQUEST_TIME;
14313
  return url("user/reset/$account->uid/$timestamp/" .
user_pass_rehash($account->pass, $timestamp, $account->login),
array('absolute' => TRUE));
14320
}
1433
14342366
function user_pass_rehash($password, $timestamp, $login) {
14355
  return md5($timestamp . $password . $login);
14360
}
1437
14382366
function user_edit_form(&$form_state, $uid, $edit, $register = FALSE) {
143922
  _user_password_dynamic_validation();
144022
  $admin = user_access('administer users');
1441
1442
  // Account information:
144322
  $form['account'] = array('#type' => 'fieldset',
144422
    '#title' => t('Account information'),
144522
    '#weight' => -10,
1446
  );
144722
  if (user_access('change own username') || $admin || $register) {
14489
    $form['account']['name'] = array('#type' => 'textfield',
14499
      '#title' => t('Username'),
14509
      '#default_value' => $edit['name'],
14519
      '#maxlength' => USERNAME_MAX_LENGTH,
14529
      '#description' => t('Spaces are allowed; punctuation is not allowed
except for periods, hyphens, apostrophes, and underscores.'),
14539
      '#required' => TRUE,
14549
      '#attributes' => array('class' => 'username'),
1455
    );
14569
  }
145722
  $form['account']['mail'] = array('#type' => 'textfield',
145822
    '#title' => t('E-mail address'),
145922
    '#default_value' => $edit['mail'],
146022
    '#maxlength' => EMAIL_MAX_LENGTH,
146122
    '#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.'),
146222
    '#required' => TRUE,
1463
  );
146422
  if (!$register) {
146515
    $form['account']['pass'] = array('#type' => 'password_confirm',
146615
      '#description' => t('To change the current user password, enter the
new password in both fields.'),
146715
      '#size' => 25,
1468
    );
146915
  }
14707
  elseif (!variable_get('user_email_verification', TRUE) || $admin) {
14713
    $form['account']['pass'] = array(
14723
      '#type' => 'password_confirm',
14733
      '#description' => t('Provide a password for the new account in both
fields.'),
14743
      '#required' => TRUE,
14753
      '#size' => 25,
1476
    );
14773
  }
147822
  if ($admin) {
14795
    $form['account']['status'] = array(
14805
      '#type' => 'radios',
14815
      '#title' => t('Status'),
14825
      '#default_value' => isset($edit['status']) ? $edit['status'] : 1,
14835
      '#options' => array(t('Blocked'), t('Active'))
14845
    );
14855
  }
148622
  if (user_access('administer permissions')) {
14870
    $roles = user_roles(TRUE);
1488
1489
    // The disabled checkbox subelement for the 'authenticated user' role
1490
    // must be generated separately and added to the checkboxes element,
1491
    // because of a limitation in D6 FormAPI not supporting a single
disabled
1492
    // checkbox within a set of checkboxes.
1493
    // TODO: This should be solved more elegantly. See issue #119038.
1494
    $checkbox_authenticated = array(
14950
      '#type' => 'checkbox',
14960
      '#title' => $roles[DRUPAL_AUTHENTICATED_RID],
14970
      '#default_value' => TRUE,
14980
      '#disabled' => TRUE,
14990
    );
1500
15010
    unset($roles[DRUPAL_AUTHENTICATED_RID]);
15020
    if ($roles) {
15030
      $default = empty($edit['roles']) ? array() :
array_keys($edit['roles']);
15040
      $form['account']['roles'] = array(
15050
        '#type' => 'checkboxes',
15060
        '#title' => t('Roles'),
15070
        '#default_value' => $default,
15080
        '#options' => $roles,
15090
        DRUPAL_AUTHENTICATED_RID => $checkbox_authenticated,
1510
      );
15110
    }
15120
  }
1513
1514
  // Signature:
151522
  if (variable_get('user_signatures', 0) && module_exists('comment') &&
!$register) {
15160
    $form['signature_settings'] = array(
15170
      '#type' => 'fieldset',
15180
      '#title' => t('Signature settings'),
15190
      '#weight' => 1,
1520
    );
15210
    $form['signature_settings']['signature'] = array(
15220
      '#type' => 'textarea',
15230
      '#title' => t('Signature'),
15240
      '#default_value' => $edit['signature'],
15250
      '#description' => t('Your signature will be publicly displayed at the
end of your comments.'),
1526
    );
15270
  }
1528
1529
  // Picture/avatar:
153022
  if (variable_get('user_pictures', 0) && !$register) {
153110
    $form['picture'] = array('#type' => 'fieldset', '#title' =>
t('Picture'), '#weight' => 1);
153210
    $picture = theme('user_picture', (object)$edit);
153310
    if ($edit['picture']) {
15342
      $form['picture']['current_picture'] = array('#markup' => $picture);
15352
      $form['picture']['picture_delete'] = array('#type' => 'checkbox',
'#title' => t('Delete picture'), '#description' => t('Check this box to
delete your current picture.'));
15362
    }
1537
    else {
15388
      $form['picture']['picture_delete'] = array('#type' => 'hidden');
1539
    }
154010
    $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', ''));
154110
    $form['#validate'][] = 'user_validate_picture';
154210
  }
154322
  $form['#uid'] = $uid;
1544
154522
  return $form;
15460
}
1547
15482366
function _user_edit_validate($uid, &$edit) {
15495
  $user = user_load(array('uid' => $uid));
1550
  // Validate the username:
15515
  if (user_access('change own username') || user_access('administer users')
|| !$user->uid) {
15524
    if ($error = user_validate_name($edit['name'])) {
15530
      form_set_error('name', $error);
15540
    }
15554
    elseif (db_result(db_query("SELECT COUNT(*) FROM {users} WHERE uid !=
%d AND LOWER(name) = LOWER('%s')", $uid, $edit['name'])) > 0) {
15560
      form_set_error('name', t('The name %name is already taken.',
array('%name' => $edit['name'])));
15570
    }
15584
  }
1559
1560
  // Validate the e-mail address:
15615
  if ($error = user_validate_mail($edit['mail'])) {
15620
    form_set_error('mail', $error);
15630
  }
15645
  elseif (db_result(db_query("SELECT COUNT(*) FROM {users} WHERE uid != %d
AND LOWER(mail) = LOWER('%s')", $uid, $edit['mail'])) > 0) {
15650
    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'))));
15660
  }
15675
}
1568
15692366
function _user_edit_submit($uid, &$edit) {
15703
  $user = user_load(array('uid' => $uid));
1571
  // Delete picture if requested, and if no replacement picture was given.
15723
  if (!empty($edit['picture_delete'])) {
15730
    if ($user->picture && file_exists($user->picture)) {
15740
      file_unmanaged_delete($user->picture);
15750
    }
15760
    $edit['picture'] = '';
15770
  }
15783
  if (isset($edit['roles'])) {
15790
    $edit['roles'] = array_filter($edit['roles']);
15800
  }
15813
}
1582
1583
/**
1584
 * Delete a user.
1585
 *
1586
 * @param $edit An array of submitted form values.
1587
 * @param $uid The user ID of the user to delete.
1588
 */
15892366
function user_delete($edit, $uid) {
15902
  $account = user_load(array('uid' => $uid));
15912
  drupal_session_destroy_uid($uid);
15922
  _user_mail_notify('status_deleted', $account);
15932
  module_invoke_all('user_delete', $edit, $account);
15942
  db_query('DELETE FROM {users} WHERE uid = %d', $uid);
15952
  db_query('DELETE FROM {users_roles} WHERE uid = %d', $uid);
15962
  db_query('DELETE FROM {authmap} WHERE uid = %d', $uid);
15972
  $variables = array('%name' => $account->name, '%email' => '<' .
$account->mail . '>');
15982
  watchdog('user', 'Deleted user: %name %email.', $variables,
WATCHDOG_NOTICE);
15992
}
1600
1601
/**
1602
 * Builds a structured array representing the profile content.
1603
 *
1604
 * @param $account
1605
 *   A user object.
1606
 *
1607
 * @return
1608
 *   A structured array containing the individual elements of the profile.
1609
 */
16102366
function user_build_content(&$account) {
1611191
  $edit = NULL;
1612191
  user_module_invoke('view', $edit, $account);
1613
  // Allow modules to modify the fully-built profile.
1614191
  drupal_alter('profile', $account);
1615
1616191
  return $account->content;
16170
}
1618
1619
/**
1620
 * Implementation of hook_mail().
1621
 */
16222366
function user_mail($key, &$message, $params) {
16232
  $language = $message['language'];
16242
  $variables = user_mail_tokens($params['account'], $language);
16252
  $message['subject'] .= _user_mail_text($key . '_subject', $language,
$variables);
16262
  $message['body'][] = _user_mail_text($key . '_body', $language,
$variables);
16272
}
1628
1629
/**
1630
 * Returns a mail string for a variable name.
1631
 *
1632
 * Used by user_mail() and the settings forms to retrieve strings.
1633
 */
16342366
function _user_mail_text($key, $language = NULL, $variables = array()) {
16352
  $langcode = isset($language) ? $language->language : NULL;
1636
16372
  if ($admin_setting = variable_get('user_mail_' . $key, FALSE)) {
1638
    // An admin setting overrides the default string.
16390
    return strtr($admin_setting, $variables);
16400
  }
1641
  else {
1642
    // No override, return default string.
1643
    switch ($key) {
16442
      case 'register_no_approval_required_subject':
16452
        return t('Account details for !username at !site', $variables,
$langcode);
16462
      case 'register_no_approval_required_body':
16472
        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);
16480
      case 'register_admin_created_subject':
16490
        return t('An administrator created an account for you at !site',
$variables, $langcode);
16500
      case 'register_admin_created_body':
16510
        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);
16520
      case 'register_pending_approval_subject':
16530
      case 'register_pending_approval_admin_subject':
16540
        return t('Account details for !username at !site (pending admin
approval)', $variables, $langcode);
16550
      case 'register_pending_approval_body':
16560
        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);
16570
      case 'register_pending_approval_admin_body':
16580
        return t("!username has applied for an account.\n\n!edit_uri",
$variables, $langcode);
16590
      case 'password_reset_subject':
16600
        return t('Replacement login information for !username at !site',
$variables, $langcode);
16610
      case 'password_reset_body':
16620
        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);
16630
      case 'status_activated_subject':
16640
        return t('Account details for !username at !site (approved)',
$variables, $langcode);
16650
      case 'status_activated_body':
16660
        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);
16670
      case 'status_blocked_subject':
16680
        return t('Account details for !username at !site (blocked)',
$variables, $langcode);
16690
      case 'status_blocked_body':
16700
        return t("!username,\n\nYour account on !site has been blocked.",
$variables, $langcode);
16710
      case 'status_deleted_subject':
16720
        return t('Account details for !username at !site (deleted)',
$variables, $langcode);
16730
      case 'status_deleted_body':
16740
        return t("!username,\n\nYour account on !site has been deleted.",
$variables, $langcode);
16750
    }
1676
  }
16770
}
1678
1679
/*** Administrative features
***********************************************/
1680
1681
/**
1682
 * Retrieve an array of roles matching specified conditions.
1683
 *
1684
 * @param $membersonly
1685
 *   Set this to TRUE to exclude the 'anonymous' role.
1686
 * @param $permission
1687
 *   A string containing a permission. If set, only roles containing that
1688
 *   permission are returned.
1689
 *
1690
 * @return
1691
 *   An associative array with the role id as the key and the role name as
1692
 *   value.
1693
 */
16942366
function user_roles($membersonly = FALSE, $permission = NULL) {
1695
  // System roles take the first two positions.
1696
  $roles = array(
169772
    DRUPAL_ANONYMOUS_RID => NULL,
169872
    DRUPAL_AUTHENTICATED_RID => NULL,
169972
  );
1700
170172
  if (!empty($permission)) {
170214
    $result = db_query("SELECT r.* FROM {role} r INNER JOIN
{role_permission} p ON r.rid = p.rid WHERE p.permission = '%s' ORDER BY
r.name", $permission);
170314
  }
1704
  else {
170558
    $result = db_query('SELECT * FROM {role} ORDER BY name');
1706
  }
1707
170872
  while ($role = db_fetch_object($result)) {
170972
    switch ($role->rid) {
1710
      // We only translate the built in role names
171172
      case DRUPAL_ANONYMOUS_RID:
171258
        if (!$membersonly) {
171350
          $roles[$role->rid] = t($role->name);
171450
        }
171558
        break;
171672
      case DRUPAL_AUTHENTICATED_RID:
171762
        $roles[$role->rid] = t($role->name);
171862
        break;
171970
      default:
172070
        $roles[$role->rid] = $role->name;
172170
    }
172272
  }
1723
1724
  // Filter to remove unmatched system roles.
172572
  return array_filter($roles);
17260
}
1727
1728
/**
1729
 * Implementation of hook_user_operations().
1730
 */
17312366
function user_user_operations($form_state = array()) {
1732
  $operations = array(
1733
    'unblock' => array(
17347
      'label' => t('Unblock the selected users'),
17357
      'callback' => 'user_user_operations_unblock',
17367
    ),
1737
    'block' => array(
17387
      'label' => t('Block the selected users'),
17397
      'callback' => 'user_user_operations_block',
17407
    ),
1741
    'delete' => array(
17427
      'label' => t('Delete the selected users'),
17437
    ),
17447
  );
1745
17467
  if (user_access('administer permissions')) {
17470
    $roles = user_roles(TRUE);
17480
    unset($roles[DRUPAL_AUTHENTICATED_RID]);  // Can't edit authenticated
role.
1749
17500
    $add_roles = array();
17510
    foreach ($roles as $key => $value) {
17520
      $add_roles['add_role-' . $key] = $value;
17530
    }
1754
17550
    $remove_roles = array();
17560
    foreach ($roles as $key => $value) {
17570
      $remove_roles['remove_role-' . $key] = $value;
17580
    }
1759
17600
    if (count($roles)) {
1761
      $role_operations = array(
17620
        t('Add a role to the selected users') => array(
17630
          'label' => $add_roles,
17640
        ),
17650
        t('Remove a role from the selected users') => array(
17660
          'label' => $remove_roles,
17670
        ),
17680
      );
1769
17700
      $operations += $role_operations;
17710
    }
17720
  }
1773
1774
  // If the form has been posted, we need to insert the proper data for
1775
  // role editing if necessary.
17767
  if (!empty($form_state['submitted'])) {
17771
    $operation_rid = explode('-', $form_state['values']['operation']);
17781
    $operation = $operation_rid[0];
17791
    if ($operation == 'add_role' || $operation == 'remove_role') {
17800
      $rid = $operation_rid[1];
17810
      if (user_access('administer permissions')) {
17820
        $operations[$form_state['values']['operation']] = array(
17830
          'callback' => 'user_multiple_role_edit',
17840
          'callback arguments' => array($operation, $rid),
1785
        );
17860
      }
1787
      else {
17880
        watchdog('security', 'Detected malicious attempt to alter protected
user fields.', array(), WATCHDOG_WARNING);
17890
        return;
1790
      }
17910
    }
17921
  }
1793
17947
  return $operations;
17950
}
1796
1797
/**
1798
 * Callback function for admin mass unblocking users.
1799
 */
18002366
function user_user_operations_unblock($accounts) {
18010
  foreach ($accounts as $uid) {
18020
    $account = user_load(array('uid' => (int)$uid));
1803
    // Skip unblocking user if they are already unblocked.
18040
    if ($account !== FALSE && $account->status == 0) {
18050
      user_save($account, array('status' => 1));
18060
    }
18070
  }
18080
}
1809
1810
/**
1811
 * Callback function for admin mass blocking users.
1812
 */
18132366
function user_user_operations_block($accounts) {
18141
  foreach ($accounts as $uid) {
18151
    $account = user_load(array('uid' => (int)$uid));
1816
    // Skip blocking user if they are already blocked.
18171
    if ($account !== FALSE && $account->status == 1) {
18181
      user_save($account, array('status' => 0));
18191
    }
18201
  }
18211
}
1822
1823
/**
1824
 * Callback function for admin mass adding/deleting a user role.
1825
 */
18262366
function user_multiple_role_edit($accounts, $operation, $rid) {
1827
  // The role name is not necessary as user_save() will reload the user
1828
  // object, but some modules' hook_user() may look at this first.
18290
  $role_name = db_result(db_query('SELECT name FROM {role} WHERE rid = %d',
$rid));
1830
1831
  switch ($operation) {
18320
    case 'add_role':
18330
      foreach ($accounts as $uid) {
18340
        $account = user_load(array('uid' => (int)$uid));
1835
        // Skip adding the role to the user if they already have it.
18360
        if ($account !== FALSE && !isset($account->roles[$rid])) {
18370
          $roles = $account->roles + array($rid => $role_name);
18380
          user_save($account, array('roles' => $roles));
18390
        }
18400
      }
18410
      break;
18420
    case 'remove_role':
18430
      foreach ($accounts as $uid) {
18440
        $account = user_load(array('uid' => (int)$uid));
1845
        // Skip removing the role from the user if they already don't have
it.
18460
        if ($account !== FALSE && isset($account->roles[$rid])) {
18470
          $roles = array_diff($account->roles, array($rid => $role_name));
18480
          user_save($account, array('roles' => $roles));
18490
        }
18500
      }
18510
      break;
18520
  }
18530
}
1854
18552366
function user_multiple_delete_confirm(&$form_state) {
18560
  $edit = $form_state['post'];
1857
18580
  $form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>',
'#tree' => TRUE);
1859
  // array_filter() returns only elements with TRUE values.
18600
  foreach (array_filter($edit['accounts']) as $uid => $value) {
18610
    $user = db_result(db_query('SELECT name FROM {users} WHERE uid = %d',
$uid));
18620
    $form['accounts'][$uid] = array('#type' => 'hidden', '#value' => $uid,
'#prefix' => '<li>', '#suffix' => check_plain($user) . "</li>\n");
18630
  }
18640
  $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
1865
18660
  return confirm_form($form,
18670
                      t('Are you sure you want to delete these users?'),
18680
                      'admin/user/user', t('This action cannot be
undone.'),
18690
                      t('Delete all'), t('Cancel'));
18700
}
1871
18722366
function user_multiple_delete_confirm_submit($form, &$form_state) {
18730
  if ($form_state['values']['confirm']) {
18740
    foreach ($form_state['values']['accounts'] as $uid => $value) {
18750
      user_delete($form_state['values'], $uid);
18760
    }
18770
    drupal_set_message(t('The users have been deleted.'));
18780
  }
18790
  $form_state['redirect'] = 'admin/user/user';
18800
  return;
18810
}
1882
1883
/**
1884
 * Implementation of hook_help().
1885
 */
18862366
function user_help($path, $arg) {
18871676
  global $user;
1888
1889
  switch ($path) {
18901676
    case 'admin/help#user':
189110
      $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>';
189210
      $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>';
189310
      $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>';
189410
      $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>';
189510
      return $output;
18961676
    case 'admin/user/user':
18976
      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>';
18981670
    case 'admin/user/user/create':
18991670
    case 'admin/user/user/account/create':
19002
      return '<p>' . t("This web page allows administrators to register new
users. Users' e-mail addresses and usernames must be unique.") . '</p>';
19011668
    case 'admin/user/permissions':
190220
      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>';
19031668
    case 'admin/user/roles':
19040
      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>
1905
      <ul>
1906
      <li>Anonymous user: this role is used for users that don\'t have a
user account or that are not authenticated.</li>
1907
      <li>Authenticated user: this role is automatically granted to all
logged in users.</li>
19080
      </ul>', array('@permissions' => url('admin/user/permissions')));
19091668
    case 'admin/user/search':
19100
      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>';
19110
  }
19121668
}
1913
1914
/**
1915
 * Retrieve a list of all user setting/information categories and sort them
by weight.
1916
 */
19172366
function _user_categories($account) {
1918204
  $categories = array();
1919
1920204
  foreach (module_list() as $module) {
1921204
    if ($data = module_invoke($module, 'user_categories', NULL, $account,
'')) {
1922204
      $categories = array_merge($data, $categories);
1923204
    }
1924204
  }
1925
1926204
  usort($categories, '_user_sort');
1927
1928204
  return $categories;
19290
}
1930
19312366
function _user_sort($a, $b) {
193268
  $a = (array)$a + array('weight' => 0, 'title' => '');
193368
  $b = (array)$b + array('weight' => 0, 'title' => '');
193468
  return $a['weight'] < $b['weight'] ? -1 : ($a['weight'] > $b['weight'] ?
1 : ($a['title'] < $b['title'] ? -1 : 1));
19350
}
1936
1937
/**
1938
 * List user administration filters that can be applied.
1939
 */
19402366
function user_filters() {
1941
  // Regular filters
19428
  $filters = array();
19438
  $roles = user_roles(TRUE);
19448
  unset($roles[DRUPAL_AUTHENTICATED_RID]); // Don't list authorized role.
19458
  if (count($roles)) {
19468
    $filters['role'] = array(
19478
      'title' => t('role'),
19488
      'where' => "ur.rid = %d",
19498
      'options' => $roles,
19508
      'join' => '',
1951
    );
19528
  }
1953
19548
  $options = array();
19558
  foreach (module_list() as $module) {
19568
    if ($permissions = module_invoke($module, 'perm')) {
19578
      asort($permissions);
19588
      foreach ($permissions as $permission => $description) {
19598
        $options[t('@module module', array('@module' =>
$module))][$permission] = t($permission);
19608
      }
19618
    }
19628
  }
19638
  ksort($options);
19648
  $filters['permission'] = array(
19658
    'title' => t('permission'),
19668
    'join' => 'LEFT JOIN {role_permission} p ON ur.rid = p.rid',
19678
    'where' => " (p.permission = '%s' OR u.uid = 1) ",
19688
    'options' => $options,
1969
  );
1970
19718
  $filters['status'] = array(
19728
    'title' => t('status'),
19738
    'where' => 'u.status = %d',
19748
    'join' => '',
19758
    'options' => array(1 => t('active'), 0 => t('blocked')),
1976
  );
19778
  return $filters;
19780
}
1979
1980
/**
1981
 * Build query for user administration filters based on session.
1982
 */
19832366
function user_build_filter_query() {
19847
  $filters = user_filters();
1985
1986
  // Build query
19877
  $where = $args = $join = array();
19887
  foreach ($_SESSION['user_overview_filter'] as $filter) {
19894
    list($key, $value) = $filter;
1990
    // This checks to see if this permission filter is an enabled
permission for
1991
    // the authenticated role. If so, then all users would be listed, and
we can
1992
    // skip adding it to the filter query.
19934
    if ($key == 'permission') {
19944
      $account = new stdClass();
19954
      $account->uid = 'user_filter';
19964
      $account->roles = array(DRUPAL_AUTHENTICATED_RID => 1);
19974
      if (user_access($value, $account)) {
19980
        continue;
19990
      }
20004
    }
20014
    $where[] = $filters[$key]['where'];
20024
    $args[] = $value;
20034
    $join[] = $filters[$key]['join'];
20044
  }
20057
  $where = !empty($where) ? 'AND ' . implode(' AND ', $where) : '';
20067
  $join = !empty($join) ? ' ' . implode(' ', array_unique($join)) : '';
2007
20087
  return array('where' => $where,
20097
           'join' => $join,
20107
           'args' => $args,
20117
         );
20120
}
2013
2014
/**
2015
 * Implementation of hook_forms().
2016
 */
20172366
function user_forms() {
2018150
  $forms['user_admin_access_add_form']['callback'] =
'user_admin_access_form';
2019150
  $forms['user_admin_access_edit_form']['callback'] =
'user_admin_access_form';
2020150
  $forms['user_admin_new_role']['callback'] = 'user_admin_role';
2021150
  return $forms;
20220
}
2023
2024
/**
2025
 * Implementation of hook_comment().
2026
 */
20272366
function user_comment(&$comment, $op) {
2028
  // Validate signature.
202958
  if ($op == 'view') {
203038
    if (variable_get('user_signatures', 0) && !empty($comment->signature))
{
20310
      $comment->signature = check_markup($comment->signature,
$comment->format);
20320
    }
2033
    else {
203438
      $comment->signature = '';
2035
    }
203638
  }
203758
}
2038
2039
/**
2040
 * Theme output of user signature.
2041
 *
2042
 * @ingroup themeable
2043
 */
20442366
function theme_user_signature($signature) {
20450
  $output = '';
20460
  if ($signature) {
20470
    $output .= '<div class="clear">';
20480
    $output .= '<div>—</div>';
20490
    $output .= $signature;
20500
    $output .= '</div>';
20510
  }
2052
20530
  return $output;
20540
}
2055
2056
/**
2057
 * Return an array of token to value mappings for user e-mail messages.
2058
 *
2059
 * @param $account
2060
 *  The user object of the account being notified.  Must contain at
2061
 *  least the fields 'uid', 'name', and 'mail'.
2062
 * @param $language
2063
 *  Language object to generate the tokens with.
2064
 * @return
2065
 *  Array of mappings from token names to values (for use with strtr()).
2066
 */
20672366
function user_mail_tokens($account, $language) {
20682
  global $base_url;
2069
  $tokens = array(
20702
    '!username' => $account->name,
20712
    '!site' => variable_get('site_name', 'Drupal'),
20722
    '!login_url' => user_pass_reset_url($account),
20732
    '!uri' => $base_url,
20742
    '!uri_brief' => preg_replace('!^https?://!', '', $base_url),
20752
    '!mailto' => $account->mail,
20762
    '!date' => format_date(REQUEST_TIME, 'medium', '', NULL,
$language->language),
20772
    '!login_uri' => url('user', array('absolute' => TRUE, 'language' =>
$language)),
20782
    '!edit_uri' => url('user/' . $account->uid . '/edit', array('absolute'
=> TRUE, 'language' => $language)),
20792
  );
20802
  if (!empty($account->password)) {
20812
    $tokens['!password'] = $account->password;
20822
  }
20832
  return $tokens;
20840
}
2085
2086
/**
2087
 * Get the language object preferred by the user. This user preference can
2088
 * be set on the user account editing page, and is only available if there
2089
 * are more than one languages enabled on the site. If the user did not
2090
 * choose a preferred language, or is the anonymous user, the $default
2091
 * value, or if it is not set, the site default language will be returned.
2092
 *
2093
 * @param $account
2094
 *   User account to look up language for.
2095
 * @param $default
2096
 *   Optional default language object to return if the account
2097
 *   has no valid language.
2098
 */
20992366
function user_preferred_language($account, $default = NULL) {
21006
  $language_list = language_list();
21016
  if ($account->language && isset($language_list[$account->language])) {
21020
    return $language_list[$account->language];
21030
  }
2104
  else {
21056
    return $default ? $default : language_default();
2106
  }
21070
}
2108
2109
/**
2110
 * Conditionally create and send a notification email when a certain
2111
 * operation happens on the given user account.
2112
 *
2113
 * @see user_mail_tokens()
2114
 * @see drupal_mail()
2115
 *
2116
 * @param $op
2117
 *  The operation being performed on the account.  Possible values:
2118
 *  'register_admin_created': Welcome message for user created by the admin
2119
 *  'register_no_approval_required': Welcome message when user
self-registers
2120
 *  'register_pending_approval': Welcome message, user pending admin
approval
2121
 *  'password_reset': Password recovery request
2122
 *  'status_activated': Account activated
2123
 *  'status_blocked': Account blocked
2124
 *  'status_deleted': Account deleted
2125
 *
2126
 * @param $account
2127
 *  The user object of the account being notified.  Must contain at
2128
 *  least the fields 'uid', 'name', and 'mail'.
2129
 * @param $language
2130
 *  Optional language to use for the notification, overriding account
language.
2131
 * @return
2132
 *  The return value from drupal_mail_send(), if ends up being called.
2133
 */
21342366
function _user_mail_notify($op, $account, $language = NULL) {
2135
  // By default, we always notify except for deleted and blocked.
21365
  $default_notify = ($op != 'status_deleted' && $op != 'status_blocked');
21375
  $notify = variable_get('user_mail_' . $op . '_notify', $default_notify);
21385
  if ($notify) {
21392
    $params['account'] = $account;
21402
    $language = $language ? $language : user_preferred_language($account);
21412
    $mail = drupal_mail('user', $op, $account->mail, $language, $params);
21422
    if ($op == 'register_pending_approval') {
2143
      // If a user registered requiring admin approval, notify the admin,
too.
2144
      // We use the site default language for this.
21450
      drupal_mail('user', 'register_pending_approval_admin',
variable_get('site_mail', ini_get('sendmail_from')), language_default(),
$params);
21460
    }
21472
  }
21485
  return empty($mail) ? NULL : $mail['result'];
21490
}
2150
2151
/**
2152
 * Add javascript and string translations for dynamic password validation
2153
 * (strength and confirmation checking).
2154
 *
2155
 * This is an internal function that makes it easier to manage the
translation
2156
 * strings that need to be passed to the javascript code.
2157
 */
21582366
function _user_password_dynamic_validation() {
215922
  static $complete = FALSE;
216022
  global $user;
2161
  // Only need to do once per page.
216222
  if (!$complete) {
216322
    drupal_add_js(drupal_get_path('module', 'user') . '/user.js',
'module');
2164
216522
    drupal_add_js(array(
2166
      'password' => array(
216722
        'strengthTitle' => t('Password strength:'),
216822
        'hasWeaknesses' => t('To make your password stronger:'),
216922
        'tooShort' => t('Make it at least 6 characters'),
217022
        'addLowerCase' => t('Add lowercase letters'),
217122
        'addUpperCase' => t('Add uppercase letters'),
217222
        'addNumbers' => t('Add numbers'),
217322
        'addPunctuation' => t('Add punctuation'),
217422
        'sameAsUsername' => t('Make it different from your username'),
217522
        'confirmSuccess' => t('yes'),
217622
        'confirmFailure' => t('no'),
217722
        'confirmTitle' => t('Passwords match:'),
217822
        'username' => (isset($user->name) ? $user->name : ''))),
217922
      'setting');
218022
    $complete = TRUE;
218122
  }
218222
}
2183
2184
/**
2185
 * Implementation of hook_hook_info().
2186
 */
21872366
function user_hook_info() {
2188
  return array(
2189
    'user' => array(
2190
      'user' => array(
2191
        'insert' => array(
219255
          'runs when' => t('After a user account has been created'),
219355
        ),
2194
        'update' => array(
219555
          'runs when' => t("After a user's profile has been updated"),
219655
        ),
2197
        'delete' => array(
219855
          'runs when' => t('After a user has been deleted')
219955
        ),
2200
        'login' => array(
220155
          'runs when' => t('After a user has logged in')
220255
        ),
2203
        'logout' => array(
220455
          'runs when' => t('After a user has logged out')
220555
        ),
2206
        'view' => array(
220755
          'runs when' => t("When a user's profile is being viewed")
220855
        ),
220955
      ),
221055
    ),
221155
  );
22120
}
2213
2214
/**
2215
 * Implementation of hook_action_info().
2216
 */
22172366
function user_action_info() {
2218
  return array(
2219
    'user_block_user_action' => array(
2220215
      'description' => t('Block current user'),
2221215
      'type' => 'user',
2222215
      'configurable' => FALSE,
2223215
      'hooks' => array(),
2224215
    ),
2225215
  );
22260
}
2227
2228
/**
2229
 * Implementation of a Drupal action.
2230
 * Blocks the current user.
2231
 */
22322366
function user_block_user_action(&$object, $context = array()) {
22330
  if (isset($object->uid)) {
22340
    $uid = $object->uid;
22350
  }
22360
  elseif (isset($context['uid'])) {
22370
    $uid = $context['uid'];
22380
  }
2239
  else {
22400
    global $user;
22410
    $uid = $user->uid;
2242
  }
22430
  db_query("UPDATE {users} SET status = 0 WHERE uid = %d", $uid);
22440
  drupal_session_destroy_uid($uid);
22450
  watchdog('action', 'Blocked user %name.', array('%name' =>
check_plain($user->name)));
22460
}
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
 */
22542366
function user_register_submit($form, &$form_state) {
22553
  global $base_url;
22563
  $admin = user_access('administer users');
2257
22583
  $mail = $form_state['values']['mail'];
22593
  $name = $form_state['values']['name'];
22603
  if (!variable_get('user_email_verification', TRUE) || $admin) {
22611
    $pass = $form_state['values']['pass'];
22621
  }
2263
  else {
22642
    $pass = user_password();
2265
  };
22663
  $notify = isset($form_state['values']['notify']) ?
$form_state['values']['notify'] : NULL;
22673
  $from = variable_get('site_mail', ini_get('sendmail_from'));
22683
  if (isset($form_state['values']['roles'])) {
2269
    // Remove unset roles.
22700
    $roles = array_filter($form_state['values']['roles']);
22710
  }
2272
  else {
22733
    $roles = array();
2274
  }
2275
22763
  if (!$admin && array_intersect(array_keys($form_state['values']),
array('uid', 'roles', 'init', 'session', 'status'))) {
22770
    watchdog('security', 'Detected malicious attempt to alter protected
user fields.', array(), WATCHDOG_WARNING);
22780
    $form_state['redirect'] = 'user/register';
22790
    return;
22800
  }
2281
  // The unset below is needed to prevent these form values from being
saved as
2282
  // user data.
22833
  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'],
$form_state['values']['form_build_id']);
2284
22853
  $merge_data = array('pass' => $pass, 'init' => $mail, 'roles' => $roles);
22863
  if (!$admin) {
2287
    // Set the user's status because it was not displayed in the form.
22882
    $merge_data['status'] = variable_get('user_register', 1) == 1;
22892
  }
22903
  $account = user_save('', array_merge($form_state['values'],
$merge_data));
2291
  // Terminate if an error occured during user_save().
22923
  if (!$account) {
22930
    drupal_set_message(t("Error saving user account."), 'error');
22940
    $form_state['redirect'] = '';
22950
    return;
22960
  }
22973
  $form_state['user'] = $account;
2298
22993
  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.
23023
  if ($account->uid == 1) {
23030
    drupal_set_message(t('Welcome to Drupal. You are now logged in as user
#1, which gives you full control over your website.'));
23040
    if (variable_get('user_email_verification', TRUE)) {
23050
      drupal_set_message(t('</p><p> Your password is
<strong>%pass</strong>. You may change your password below.</p>',
array('%pass' => $pass)));
23060
    }
2307
23080
    user_authenticate(array_merge($form_state['values'], $merge_data));
2309
23100
    $form_state['redirect'] = 'user/1/edit';
23110
    return;
23120
  }
2313
  else {
2314
    // Add plain text password into user account to generate mail tokens.
23153
    $account->password = $pass;
23163
    if ($admin && !$notify) {
23171
      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)));
23181
    }
23192
    elseif (!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.
23220
      _user_mail_notify('register_no_approval_required', $account);
23230
      if (user_authenticate(array_merge($form_state['values'],
$merge_data))) {
23240
        drupal_set_message(t('Registration successful. You are now logged
in.'));
23250
      }
23260
      $form_state['redirect'] = '';
23270
      return;
23280
    }
23292
    elseif ($account->status || $notify) {
2330
      // Create new user account, no administrator approval required.
23312
      $op = $notify ? 'register_admin_created' :
'register_no_approval_required';
23322
      _user_mail_notify($op, $account);
23332
      if ($notify) {
23340
        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)));
23350
      }
2336
      else {
23372
        drupal_set_message(t('Your password and further instructions have
been sent to your e-mail address.'));
23382
        $form_state['redirect'] = '';
23392
        return;
2340
      }
23410
    }
2342
    else {
2343
      // Create new user account, administrator approval required.
23440
      _user_mail_notify('register_pending_approval', $account);
23450
      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.'));
23460
      $form_state['redirect'] = '';
23470
      return;
2348
2349
    }
2350
  }
23511
}
2352
2353
/**
2354
 * Form builder; The user registration form.
2355
 *
2356
 * @ingroup forms
2357
 * @see user_register_validate()
2358
 * @see user_register_submit()
2359
 */
23602366
function user_register() {
23617
  global $user;
2362
23637
  $admin = user_access('administer users');
2364
2365
  // If we aren't admin but already logged on, go to the user page instead.
23667
  if (!$admin && $user->uid) {
23670
    drupal_goto('user/' . $user->uid);
23680
  }
2369
23707
  $form = array();
2371
2372
  // Display the registration form.
23737
  if (!$admin) {
23744
    $form['user_registration_help'] = array('#markup' =>
filter_xss_admin(variable_get('user_registration_help', '')));
23754
  }
2376
2377
  // Merge in the default user edit fields.
23787
  $form = array_merge($form, user_edit_form($form_state, NULL, NULL,
TRUE));
23797
  if ($admin) {
23803
    $form['account']['notify'] = array(
23813
     '#type' => 'checkbox',
23823
     '#title' => t('Notify user of new account')
23833
    );
2384
    // Redirect back to page which initiated the create request;
2385
    // usually admin/user/user/create.
23863
    $form['destination'] = array('#type' => 'hidden', '#value' =>
$_GET['q']);
23873
  }
2388
2389
  // Create a dummy variable for pass-by-reference parameters.
23907
  $null = NULL;
23917
  $extra = _user_forms($null, NULL, NULL, 'register');
2392
2393
  // Remove form_group around default fields if there are no other groups.
23947
  if (!$extra) {
23957
    foreach (array('name', 'mail', 'pass', 'status', 'roles', 'notify') as
$key) {
23967
      if (isset($form['account'][$key])) {
23977
        $form[$key] = $form['account'][$key];
23987
      }
23997
    }
24007
    unset($form['account']);
24017
  }
2402
  else {
24030
    $form = array_merge($form, $extra);
2404
  }
2405
24067
  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.
24097
    $form['timezone'] = array(
24107
      '#type' => 'hidden',
24117
      '#default_value' => variable_get('date_default_timezone', NULL),
24127
      '#id' => 'edit-user-register-timezone',
2413
    );
2414
2415
    // Add the JavaScript callback to automatically set the timezone.
24167
    drupal_add_js('
2417
// Global Killswitch
2418
if (Drupal.jsEnabled) {
2419
  $(document).ready(function() {
2420
    Drupal.setDefaultTimezone();
2421
  });
24227
}', 'inline');
24237
  }
2424
24257
  $form['submit'] = array('#type' => 'submit', '#value' => t('Create new
account'), '#weight' => 30);
24267
  $form['#validate'][] = 'user_register_validate';
2427
24287
  return $form;
24290
}
2430
24312366
function user_register_validate($form, &$form_state) {
24323
  user_module_invoke('validate', $form_state['values'],
$form_state['values'], 'account');
24333
}
2434
2435
/**
2436
 * Retrieve a list of all form elements for the specified category.
2437
 */
24382366
function _user_forms(&$edit, $account, $category, $hook = 'form') {
243965
  $groups = array();
244065
  foreach (module_list() as $module) {
244165
    if ($data = module_invoke($module, 'user_' . $hook, $edit, $account,
$category)) {
244258
      $groups = array_merge_recursive($data, $groups);
244358
    }
244465
  }
244565
  uasort($groups, '_user_sort');
2446
244765
  return empty($groups) ? FALSE : $groups;
24480
}
2449
24502366