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

Line #Times calledCode
1
<?php
2
// $Id: user.module,v 1.914 2008/08/08 19:48:43 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
 */
122027
define('USERNAME_MAX_LENGTH', 60);
13
14
/**
15
 * Maximum length of user e-mail text field.
16
 */
172027
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
 */
252027
function user_module_invoke($type, &$array, &$user, $category = NULL) {
261745
  foreach (module_list() as $module) {
271745
    $function = $module . '_user';
281745
    if (function_exists($function)) {
291745
      $function($type, $array, $user, $category);
301745
    }
311745
  }
321745
}
33
34
/**
35
 * Implementation of hook_theme().
36
 */
372027
function user_theme() {
38
  return array(
39
    'user_picture' => array(
4091
      'arguments' => array('account' => NULL),
4191
      'template' => 'user-picture',
4291
    ),
43
    'user_profile' => array(
4491
      'arguments' => array('account' => NULL),
4591
      'template' => 'user-profile',
4691
      'file' => 'user.pages.inc',
4791
    ),
48
    'user_profile_category' => array(
4991
      'arguments' => array('element' => NULL),
5091
      'template' => 'user-profile-category',
5191
      'file' => 'user.pages.inc',
5291
    ),
53
    'user_profile_item' => array(
5491
      'arguments' => array('element' => NULL),
5591
      'template' => 'user-profile-item',
5691
      'file' => 'user.pages.inc',
5791
    ),
58
    'user_list' => array(
5991
      'arguments' => array('users' => NULL, 'title' => NULL),
6091
    ),
61
    'user_admin_perm' => array(
6291
      'arguments' => array('form' => NULL),
6391
      'file' => 'user.admin.inc',
6491
    ),
65
    'user_admin_new_role' => array(
6691
      'arguments' => array('form' => NULL),
6791
      'file' => 'user.admin.inc',
6891
    ),
69
    'user_admin_account' => array(
7091
      'arguments' => array('form' => NULL),
7191
      'file' => 'user.admin.inc',
7291
    ),
73
    'user_filter_form' => array(
7491
      'arguments' => array('form' => NULL),
7591
      'file' => 'user.admin.inc',
7691
    ),
77
    'user_filters' => array(
7891
      'arguments' => array('form' => NULL),
7991
      'file' => 'user.admin.inc',
8091
    ),
81
    'user_signature' => array(
8291
      'arguments' => array('signature' => NULL),
8391
    ),
8491
  );
850
}
86
872027
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
 */
1152027
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
 */
1482027
function user_load($array = array()) {
149
  // Dynamically compose a SQL query:
1501745
  $query = array();
1511745
  $params = array();
152
1531745
  if (is_numeric($array)) {
1541516
    $array = array('uid' => $array);
1551516
  }
156261
  elseif (!is_array($array)) {
1577
    return FALSE;
1580
  }
159
1601745
  foreach ($array as $key => $value) {
1611745
    if ($key == 'uid' || $key == 'status') {
1621731
      $query[] = "$key = %d";
1631731
      $params[] = $value;
1641731
    }
16525
    else if ($key == 'pass') {
1660
      $query[] = "pass = '%s'";
1670
      $params[] = $value;
1680
    }
169
    else {
17025
      $query[]= "LOWER($key) = LOWER('%s')";
17125
      $params[] = $value;
172
    }
1731745
  }
1741745
  $result = db_query('SELECT * FROM {users} u WHERE ' . implode(' AND ',
$query), $params);
175
1761745
  if ($user = db_fetch_object($result)) {
1771745
    $user = drupal_unpack($user);
178
1791745
    $user->roles = array();
1801745
    if ($user->uid) {
1811305
      $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
1821305
    }
183
    else {
184444
      $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
185
    }
1861745
    $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);
1871745
    while ($role = db_fetch_object($result)) {
1881289
      $user->roles[$role->rid] = $role->name;
1891289
    }
1901745
    user_module_invoke('load', $array, $user);
1911745
  }
192
  else {
1931
    $user = FALSE;
194
  }
195
1961745
  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 $array
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
 */
2192027
function user_save($account, $array = array(), $category = 'account') {
22069
  $table = drupal_get_schema('users');
22169
  $user_fields = $table['fields'];
222
22369
  if (!empty($array['pass'])) {
224
    // Allow alternate password hashing schemes.
22557
    require_once variable_get('password_inc', './includes/password.inc');
22657
    $array['pass'] = user_hash_password(trim($array['pass']));
227
    // Abort if the hashing failed and returned FALSE.
22857
    if (!$array['pass']) {
2290
      return FALSE;
2300
    }
23157
  }
232
  else {
233
    // Avoid overwriting an existing password with a blank password.
23412
    unset($array['pass']);
235
  }
236
23769
  if (is_object($account) && $account->uid) {
23813
    user_module_invoke('update', $array, $account, $category);
23913
    $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).
24213
    if (empty($array['access']) && empty($account->access) &&
user_access('administer users')) {
2430
      $array['access'] = time();
2440
    }
24513
    foreach ($array as $key => $value) {
246
      // Fields that don't pertain to the users or user_roles
247
      // automatically serialized into the users.data column.
24813
      if ($key != 'roles' && empty($user_fields[$key])) {
24912
        if ($value === NULL) {
2509
          unset($data[$key]);
2519
        }
252
        else {
2533
          $data[$key] = $value;
254
        }
25512
      }
25613
    }
257
25813
    $array['data'] = $data;
25913
    $array['uid'] = $account->uid;
260
    // Save changes to the users table.
26113
    $success = drupal_write_record('users', $array, 'uid');
26213
    if (!$success) {
263
      // The query failed - better to abort the save than risk further data
loss.
2640
      return FALSE;
2650
    }
266
267
    // Reload user roles if provided.
26813
    if (isset($array['roles']) && is_array($array['roles'])) {
2690
      db_query('DELETE FROM {users_roles} WHERE uid = %d', $account->uid);
270
2710
      foreach (array_keys($array['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.
27913
    if (isset($array['status']) && $array['status'] == 0) {
2800
      sess_destroy_uid($account->uid);
2810
    }
282
283
    // If the password changed, delete all open sessions and recreate
284
    // the current one.
28513
    if (!empty($array['pass'])) {
2861
      sess_destroy_uid($account->uid);
2871
      sess_regenerate();
2881
    }
289
290
    // Refresh user object.
29113
    $user = user_load(array('uid' => $account->uid));
292
293
    // Send emails after we have the new user object.
29413
    if (isset($array['status']) && $array['status'] != $account->status) {
295
      // The user's status is changing; conditionally send notification
email.
2960
      $op = $array['status'] == 1 ? 'status_activated' : 'status_blocked';
2970
      _user_mail_notify($op, $user);
2980
    }
299
30013
    user_module_invoke('after_update', $array, $user, $category);
30113
  }
302
  else {
303
    // Allow 'created' to be set by the caller.
30456
    if (!isset($array['created'])) {
30556
      $array['created'] = time();
30656
    }
307
    // Consider users created by an administrator as already logged in, so
308
    // anonymous users can view the profile (if allowed).
30956
    if (empty($array['access']) && user_access('administer users')) {
31052
      $array['access'] = time();
31152
    }
312
31356
    $success = drupal_write_record('users', $array);
31456
    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.
32156
    $user = user_load(array('uid' => $array['uid']));
322
32356
    user_module_invoke('insert', $array, $user, $category);
324
325
    // Note, we wait with saving the data column to prevent module-handled
326
    // fields from being saved there.
32756
    $data = array();
32856
    foreach ($array as $key => $value) {
32956
      if (($key != 'roles') && (empty($user_fields[$key])) && ($value !==
NULL)) {
3302
        $data[$key] = $value;
3312
      }
33256
    }
33356
    if (!empty($data)) {
3342
      $data_array = array('uid' => $user->uid, 'data' => $data);
3352
      drupal_write_record('users', $data_array, 'uid');
3362
    }
337
338
    // Save user roles (delete just to be safe).
33956
    if (isset($array['roles']) && is_array($array['roles'])) {
34056
      db_query('DELETE FROM {users_roles} WHERE uid = %d', $array['uid']);
34156
      foreach (array_keys($array['roles']) as $rid) {
34253
        if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID,
DRUPAL_AUTHENTICATED_RID))) {
34353
          db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)',
$array['uid'], $rid);
34453
        }
34553
      }
34656
    }
347
348
    // Build the finished user object.
34956
    $user = user_load(array('uid' => $array['uid']));
350
  }
351
35269
  return $user;
3530
}
354
355
/**
356
 * Verify the syntax of the given name.
357
 */
3582027
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
3912027
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
4002027
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.
4093
    if (isset($form_state['values']['_account']->picture) &&
file_exists($form_state['values']['_account']->picture)) {
4100
      file_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.
4163
    $info = image_get_info($file->filepath);
4173
    $destination = variable_get('user_picture_path', 'pictures') .
'/picture-' . $form['#uid'] . '.' . $info['extension'];
4183
    if (file_copy($file, $destination, FILE_EXISTS_REPLACE)) {
4193
      $form_state['values']['picture'] = $file->filepath;
4203
    }
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
    }
4243
  }
4254
}
426
427
/**
428
 * Generate a random alphanumeric password.
429
 */
4302027
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'.
43556
  $allowable_characters =
'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
436
437
  // Zero-based count of characters in the allowable list:
43856
  $len = strlen($allowable_characters) - 1;
439
440
  // Declare the password as a blank string.
44156
  $pass = '';
442
443
  // Loop the number of times specified by $length.
44456
  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:
44856
    $pass .= $allowable_characters[mt_rand(0, $len)];
44956
  }
450
45156
  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
 */
4662027
function user_role_permissions($roles = array(), $reset = FALSE) {
4671785
  static $stored_permissions = array();
468
4691785
  if ($reset) {
470
    // Clear the data cached in the static variable.
4711
    $stored_permissions = array();
4721
  }
473
4741785
  $role_permissions = $fetch = array();
475
4761785
  if ($roles) {
4771785
    foreach ($roles as $rid => $name) {
4781785
      if (isset($stored_permissions[$rid])) {
47924
        $role_permissions[$rid] = $stored_permissions[$rid];
48024
      }
481
      else {
482
        // Add this rid to the list of those needing to be fetched.
4831785
        $fetch[] = $rid;
484
        // Prepare in case no permissions are returned.
4851785
        $stored_permissions[$rid] = array();
486
      }
4871785
    }
488
4891785
    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.
4921785
      $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
4941785
      while ($row = db_fetch_array($result)) {
4951785
        $stored_permissions[$row['rid']][$row['permission']] = TRUE;
4961785
      }
4971785
      foreach ($fetch as $rid) {
498
        // For every rid, we know we at least assigned an empty array.
4991785
        $role_permissions[$rid] = $stored_permissions[$rid];
5001785
      }
5011785
    }
5021785
  }
503
5041785
  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
 */
5262027
function user_access($string, $account = NULL, $reset = FALSE) {
5271835
  global $user;
5281835
  static $perm = array();
529
5301835
  if ($reset) {
5311
    unset($perm);
5321
  }
533
5341835
  if (is_null($account)) {
5351819
    $account = $user;
5361819
  }
537
538
  // User #1 has all privileges:
5391835
  if ($account->uid == 1) {
54051
    return TRUE;
5410
  }
542
543
  // To reduce the number of SQL queries, we cache the user's permissions
544
  // in a static variable.
5451785
  if (!isset($perm[$account->uid])) {
5461785
    $role_permissions = user_role_permissions($account->roles, $reset);
547
5481785
    $perms = array();
5491785
    foreach ($role_permissions as $one_role) {
5501785
      $perms += $one_role;
5511785
    }
5521785
    $perm[$account->uid] = $perms;
5531785
  }
554
5551785
  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
 */
5632027
function user_is_blocked($name) {
564151
  $deny = db_fetch_object(db_query("SELECT name FROM {users} WHERE status =
0 AND name = LOWER('%s')", $name));
565
566151
  return $deny;
5670
}
568
569
/**
570
 * Implementation of hook_perm().
571
 */
5722027
function user_perm() {
573
   return array(
57487
     'administer permissions' => t('Manage the permissions assigned to user
roles. %warning', array('%warning' => t('Warning: Give to trusted roles
only; this permission has security implications.'))),
57587
     'administer users' => t('Manage or block users, and manage their role
assignments.'),
57687
     'access user profiles' => t('View profiles of users on the site, which
may contain personal information.'),
57787
     'change own username' => t('Select a different username.'),
57887
   );
5790
}
580
581
/**
582
 * Implementation of hook_file_download().
583
 *
584
 * Ensure that user pictures (avatars) are always downloadable.
585
 */
5862027
function user_file_download($file) {
5870
  if (strpos($file, variable_get('user_picture_path', 'pictures') .
'/picture-') === 0) {
5880
    $info = image_get_info(file_create_path($file));
5890
    return array('Content-type: ' . $info['mime_type']);
5900
  }
5910
}
592
593
/**
594
 * Implementation of hook_search().
595
 */
5962027
function user_search($op = 'search', $keys = NULL, $skip_access_check =
FALSE) {
597
  switch ($op) {
5983
    case 'name':
5993
      if ($skip_access_check || user_access('access user profiles')) {
6000
        return t('Users');
6010
      }
6023
    case 'search':
6033
      if (user_access('access user profiles')) {
6040
        $find = array();
605
        // Replace wildcards with MySQL/PostgreSQL wildcards.
6060
        $keys = preg_replace('!\*+!', '%', $keys);
6070
        if (user_access('administer users')) {
608
          // Administrators can also search in the otherwise private email
field.
6090
          $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);
6100
          while ($account = db_fetch_object($result)) {
6110
            $find[] = array('title' => $account->name . ' (' .
$account->mail . ')', 'link' => url('user/' . $account->uid,
array('absolute' => TRUE)));
6120
          }
6130
        }
614
        else {
6150
          $result = pager_query("SELECT name, uid FROM {users} WHERE
LOWER(name) LIKE LOWER('%%%s%%')", 15, 0, NULL, $keys);
6160
          while ($account = db_fetch_object($result)) {
6170
            $find[] = array('title' => $account->name, 'link' =>
url('user/' . $account->uid, array('absolute' => TRUE)));
6180
          }
619
        }
6200
        return $find;
6210
      }
6223
  }
6233
}
624
625
/**
626
 * Implementation of hook_elements().
627
 */
6282027
function user_elements() {
629
  return array(
6301570
    'user_profile_category' => array(),
6311570
    'user_profile_item' => array(),
6321570
  );
6330
}
634
635
/**
636
 * Implementation of hook_user().
637
 */
6382027
function user_user($type, &$edit, &$account, $category = NULL) {
6391848
  if ($type == 'view') {
640163
    $account->content['user_picture'] = array(
641163
      '#value' => theme('user_picture', $account),
642163
      '#weight' => -10,
643
    );
644163
    if (!isset($account->content['summary'])) {
645156
      $account->content['summary'] = array();
646156
    }
6470
    $account->content['summary'] += array(
648163
      '#type' => 'user_profile_category',
649163
      '#attributes' => array('class' => 'user-member'),
650163
      '#weight' => 5,
651163
      '#title' => t('History'),
652
    );
653163
    $account->content['summary']['member_for'] =  array(
654163
      '#type' => 'user_profile_item',
655163
      '#title' => t('Member for'),
656163
      '#markup' => format_interval(time() - $account->created),
657
    );
658163
  }
6591848
  if ($type == 'form' && $category == 'account') {
66016
    $form_state = array();
66116
    return user_edit_form($form_state, arg(1), $edit);
6620
  }
663
6641848
  if ($type == 'validate' && $category == 'account') {
6655
    return _user_edit_validate(arg(1), $edit);
6660
  }
667
6681848
  if ($type == 'submit' && $category == 'account') {
6694
    return _user_edit_submit(arg(1), $edit);
6700
  }
671
6721848
  if ($type == 'categories') {
673122
    return array(array('name' => 'account', 'title' => t('Account
settings'), 'weight' => 1));
6740
  }
6751828
}
676
6772027
function user_login_block() {
678
  $form = array(
679204
    '#action' => url($_GET['q'], array('query' =>
drupal_get_destination())),
680204
    '#id' => 'user-login-form',
681204
    '#validate' => user_login_default_validators(),
682204
    '#submit' => array('user_login_submit'),
683204
  );
684204
  $form['name'] = array('#type' => 'textfield',
685204
    '#title' => t('Username'),
686204
    '#maxlength' => USERNAME_MAX_LENGTH,
687204
    '#size' => 15,
688204
    '#required' => TRUE,
689
  );
690204
  $form['pass'] = array('#type' => 'password',
691204
    '#title' => t('Password'),
692204
    '#maxlength' => 60,
693204
    '#size' => 15,
694204
    '#required' => TRUE,
695
  );
696204
  $form['submit'] = array('#type' => 'submit',
697204
    '#value' => t('Log in'),
698
  );
699204
  $items = array();
700204
  if (variable_get('user_register', 1)) {
701204
    $items[] = l(t('Create new account'), 'user/register',
array('attributes' => array('title' => t('Create a new user account.'))));
702204
  }
703204
  $items[] = l(t('Request new password'), 'user/password',
array('attributes' => array('title' => t('Request new password via
e-mail.'))));
704204
  $form['links'] = array('#markup' => theme('item_list', $items));
705204
  return $form;
7060
}
707
708
/**
709
 * Implementation of hook_block().
710
 */
7112027
function user_block($op = 'list', $delta = '', $edit = array()) {
7121488
  global $user;
713
7141488
  if ($op == 'list') {
71532
    $blocks['login']['info'] = t('User login');
716
    // Not worth caching.
71732
    $blocks['login']['cache'] = BLOCK_NO_CACHE;
718
71932
    $blocks['navigation']['info'] = t('Navigation');
720
    // Menu blocks can't be cached because each menu item can have
721
    // a custom access callback. menu.inc manages its own caching.
72232
    $blocks['navigation']['cache'] = BLOCK_NO_CACHE;
723
72432
    $blocks['new']['info'] = t('Who\'s new');
725
726
    // Too dynamic to cache.
72732
    $blocks['online']['info'] = t('Who\'s online');
72832
    $blocks['online']['cache'] = BLOCK_NO_CACHE;
72932
    return $blocks;
7300
  }
7311480
  else if ($op == 'configure' && $delta == 'new') {
7320
    $form['user_block_whois_new_count'] = array(
7330
      '#type' => 'select',
7340
      '#title' => t('Number of users to display'),
7350
      '#default_value' => variable_get('user_block_whois_new_count', 5),
7360
      '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9,
10)),
737
    );
7380
    return $form;
7390
  }
7401480
  else if ($op == 'configure' && $delta == 'online') {
7410
    $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800,
2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval');
7420
    $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.'));
7430
    $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.'));
744
7450
    return $form;
7460
  }
7471480
  else if ($op == 'save' && $delta == 'new') {
7480
    variable_set('user_block_whois_new_count',
$edit['user_block_whois_new_count']);
7490
  }
7501480
  else if ($op == 'save' && $delta == 'online') {
7510
    variable_set('user_block_seconds_online',
$edit['user_block_seconds_online']);
7520
    variable_set('user_block_max_list_count',
$edit['user_block_max_list_count']);
7530
  }
7541480
  else if ($op == 'view') {
7551478
    $block = array();
756
757
    switch ($delta) {
7581478
      case 'login':
759
        // For usability's sake, avoid showing two login forms on one
page.
7601478
        if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
761
762204
          $block['subject'] = t('User login');
763204
          $block['content'] = drupal_get_form('user_login_block');
764204
        }
7651478
        return $block;
766
7671476
      case 'navigation':
7681476
        if ($menu = menu_tree()) {
7691070
          $block['subject'] = $user->uid ? check_plain($user->name) :
t('Navigation');
7701070
          $block['content'] = $menu;
7711070
        }
7721476
        return $block;
773
7740
      case 'new':
7750
        if (user_access('access content')) {
776
          // Retrieve a list of new users who have subsequently accessed
the site successfully.
7770
          $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));
7780
          while ($account = db_fetch_object($result)) {
7790
            $items[] = $account;
7800
          }
7810
          $output = theme('user_list', $items);
782
7830
          $block['subject'] = t('Who\'s new');
7840
          $block['content'] = $output;
7850
        }
7860
        return $block;
787
7880
      case 'online':
7890
        if (user_access('access content')) {
790
          // Count users active within the defined period.
7910
          $interval = time() - variable_get('user_block_seconds_online',
900);
792
793
          // Perform database queries to gather online user lists.  We use
s.timestamp
794
          // rather than u.access because it is much faster.
7950
          $anonymous_count = sess_count($interval);
7960
          $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);
7970
          $authenticated_count = 0;
7980
          $max_users = variable_get('user_block_max_list_count', 10);
7990
          $items = array();
8000
          while ($account = db_fetch_object($authenticated_users)) {
8010
            if ($max_users > 0) {
8020
              $items[] = $account;
8030
              $max_users--;
8040
            }
8050
            $authenticated_count++;
8060
          }
807
808
          // Format the output with proper grammar.
8090
          if ($anonymous_count == 1 && $authenticated_count == 1) {
8100
            $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')));
8110
          }
812
          else {
8130
            $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')));
814
          }
815
816
          // Display a list of currently online users.
8170
          $max_users = variable_get('user_block_max_list_count', 10);
8180
          if ($authenticated_count && $max_users) {
8190
            $output .= theme('user_list', $items, t('Online users'));
8200
          }
821
8220
          $block['subject'] = t('Who\'s online');
8230
          $block['content'] = $output;
8240
        }
8250
        return $block;
8260
    }
8270
  }
8284
}
829
830
/**
831
 * Process variables for user-picture.tpl.php.
832
 *
833
 * The $variables array contains the following arguments:
834
 * - $account
835
 *
836
 * @see user-picture.tpl.php
837
 */
8382027
function template_preprocess_user_picture(&$variables) {
839174
  $variables['picture'] = '';
840174
  if (variable_get('user_pictures', 0)) {
84115
    $account = $variables['account'];
84215
    if (!empty($account->picture) && file_exists($account->picture)) {
8433
      $picture = file_create_url($account->picture);
8443
    }
84512
    else if (variable_get('user_picture_default', '')) {
8460
      $picture = variable_get('user_picture_default', '');
8470
    }
848
84915
    if (isset($picture)) {
8503
      $alt = t("@user's picture", array('@user' => $account->name ?
$account->name : variable_get('anonymous', t('Anonymous'))));
8513
      $variables['picture'] = theme('image', $picture, $alt, $alt, '',
FALSE);
8523
      if (!empty($account->uid) && user_access('access user profiles')) {
8530
        $attributes = array('attributes' => array('title' => t('View user
profile.')), 'html' => TRUE);
8540
        $variables['picture'] = l($variables['picture'],
"user/$account->uid", $attributes);
8550
      }
8563
    }
85715
  }
858174
}
859
860
/**
861
 * Make a list of users.
862
 *
863
 * @param $users
864
 *   An array with user objects. Should contain at least the name and uid.
865
 * @param $title
866
 *  (optional) Title to pass on to theme_item_list().
867
 *
868
 * @ingroup themeable
869
 */
8702027
function theme_user_list($users, $title = NULL) {
8710
  if (!empty($users)) {
8720
    foreach ($users as $user) {
8730
      $items[] = theme('username', $user);
8740
    }
8750
  }
8760
  return theme('item_list', $items, $title);
8770
}
878
8792027
function user_is_anonymous() {
880
  // Menu administrators can see items for anonymous when administering.
881238
  return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
8820
}
883
8842027
function user_is_logged_in() {
8851583
  return (bool)$GLOBALS['user']->uid;
8860
}
887
8882027
function user_register_access() {
889238
  return user_is_anonymous() && variable_get('user_register', 1);
8900
}
891
8922027
function user_view_access($account) {
8931498
  return $account && $account->uid &&
894
    (
895
      // Always let users view their own profile.
8961057
      ($GLOBALS['user']->uid == $account->uid) ||
897
      // Administrators can view all accounts.
89832
      user_access('administer users') ||
899
      // The user is not blocked and logged in at least once.
9002
      ($account->access && $account->status && user_access('access user
profiles'))
9011498
    );
9020
}
903
904
/**
905
 * Access callback for user account editing.
906
 */
9072027
function user_edit_access($account) {
908209
  return (($GLOBALS['user']->uid == $account->uid) ||
user_access('administer users')) && $account->uid > 0;
9090
}
910
9112027
function user_load_self($arg) {
9120
  $arg[1] = user_load($GLOBALS['user']->uid);
9130
  return $arg;
9140
}
915
916
/**
917
 * Implementation of hook_menu().
918
 */
9192027
function user_menu() {
92085
  $items['user/autocomplete'] = array(
92185
    'title' => 'User autocomplete',
92285
    'page callback' => 'user_autocomplete',
92385
    'access callback' => 'user_access',
92485
    'access arguments' => array('access user profiles'),
92585
    'type' => MENU_CALLBACK,
926
  );
927
928
  // Registration and login pages.
92985
  $items['user'] = array(
93085
    'title' => 'User account',
93185
    'page callback' => 'user_page',
93285
    'access callback' => TRUE,
93385
    'type' => MENU_CALLBACK,
934
  );
935
93685
  $items['user/login'] = array(
93785
    'title' => 'Log in',
93885
    'access callback' => 'user_is_anonymous',
93985
    'type' => MENU_DEFAULT_LOCAL_TASK,
940
  );
941
94285
  $items['user/register'] = array(
94385
    'title' => 'Create new account',
94485
    'page callback' => 'drupal_get_form',
94585
    'page arguments' => array('user_register'),
94685
    'access callback' => 'user_register_access',
94785
    'type' => MENU_LOCAL_TASK,
948
  );
949
95085
  $items['user/password'] = array(
95185
    'title' => 'Request new password',
95285
    'page callback' => 'drupal_get_form',
95385
    'page arguments' => array('user_pass'),
95485
    'access callback' => 'user_is_anonymous',
95585
    'type' => MENU_LOCAL_TASK,
956
  );
95785
  $items['user/reset/%/%/%'] = array(
95885
    'title' => 'Reset password',
95985
    'page callback' => 'drupal_get_form',
96085
    'page arguments' => array('user_pass_reset', 2, 3, 4),
96185
    'access callback' => TRUE,
96285
    'type' => MENU_CALLBACK,
963
  );
964
965
  // User administration pages.
96685
  $items['admin/user'] = array(
96785
    'title' => 'User management',
96885
    'description' => "Manage your site's users, groups and access to site
features.",
96985
    'position' => 'left',
97085
    'page callback' => 'system_admin_menu_block_page',
97185
    'access arguments' => array('access administration pages'),
972
  );
97385
  $items['admin/user/user'] = array(
97485
    'title' => 'Users',
97585
    'description' => 'List, add, and edit users.',
97685
    'page callback' => 'user_admin',
97785
    'page arguments' => array('list'),
97885
    'access arguments' => array('administer users'),
979
  );
98085
  $items['admin/user/user/list'] = array(
98185
    'title' => 'List',
98285
    'type' => MENU_DEFAULT_LOCAL_TASK,
98385
    'weight' => -10,
984
  );
98585
  $items['admin/user/user/create'] = array(
98685
    'title' => 'Add user',
98785
    'page arguments' => array('create'),
98885
    'access arguments' => array('administer users'),
98985
    'type' => MENU_LOCAL_TASK,
990
  );
99185
  $items['admin/user/settings'] = array(
99285
    'title' => 'User settings',
99385
    'description' => 'Configure default behavior of users, including
registration requirements, e-mails, and user pictures.',
99485
    'page callback' => 'drupal_get_form',
99585
    'page arguments' => array('user_admin_settings'),
99685
    'access arguments' => array('administer users'),
997
  );
998
999
  // Permission administration pages.
100085
  $items['admin/user/permissions'] = array(
100185
    'title' => 'Permissions',
100285
    'description' => 'Determine access to features by selecting permissions
for roles.',
100385
    'page callback' => 'drupal_get_form',
100485
    'page arguments' => array('user_admin_perm'),
100585
    'access arguments' => array('administer permissions'),
1006
  );
100785
  $items['admin/user/roles'] = array(
100885
    'title' => 'Roles',
100985
    'description' => 'List, edit, or add user roles.',
101085
    'page callback' => 'drupal_get_form',
101185
    'page arguments' => array('user_admin_new_role'),
101285
    'access arguments' => array('administer permissions'),
1013
  );
101485
  $items['admin/user/roles/edit'] = array(
101585
    'title' => 'Edit role',
101685
    'page arguments' => array('user_admin_role'),
101785
    'access arguments' => array('administer permissions'),
101885
    'type' => MENU_CALLBACK,
1019
  );
1020
102185
  $items['logout'] = array(
102285
    'title' => 'Log out',
102385
    'access callback' => 'user_is_logged_in',
102485
    'page callback' => 'user_logout',
102585
    'weight' => 10,
1026
  );
1027
102885
  $items['user/%user_uid_optional'] = array(
102985
    'title' => 'My account',
103085
    'title callback' => 'user_page_title',
103185
    'title arguments' => array(1),
103285
    'page callback' => 'user_view',
103385
    'page arguments' => array(1),
103485
    'access callback' => 'user_view_access',
103585
    'access arguments' => array(1),
103685
    'parent' => '',
1037
  );
1038
103985
  $items['user/%user/view'] = array(
104085
    'title' => 'View',
104185
    'type' => MENU_DEFAULT_LOCAL_TASK,
104285
    'weight' => -10,
1043
  );
1044
104585
  $items['user/%user/delete'] = array(
104685
    'title' => 'Delete',
104785
    'page callback' => 'drupal_get_form',
104885
    'page arguments' => array('user_confirm_delete', 1),
104985
    'access callback' => 'user_access',
105085
    'access arguments' => array('administer users'),
105185
    'type' => MENU_CALLBACK,
1052
  );
1053
105485
  $items['user/%user_category/edit'] = array(
105585
    'title' => 'Edit',
105685
    'page callback' => 'user_edit',
105785
    'page arguments' => array(1),
105885
    'access callback' => 'user_edit_access',
105985
    'access arguments' => array(1),
106085
    'type' => MENU_LOCAL_TASK,
106185
    'load arguments' => array('%map', '%index'),
1062
  );
1063
106485
  $items['user/%user_category/edit/account'] = array(
106585
    'title' => 'Account',
106685
    'type' => MENU_DEFAULT_LOCAL_TASK,
106785
    'load arguments' => array('%map', '%index'),
1068
  );
1069
107085
  $empty_account = new stdClass();
107185
  if (($categories = _user_categories($empty_account)) &&
(count($categories) > 1)) {
10729
    foreach ($categories as $key => $category) {
1073
      // 'account' is already handled by the MENU_DEFAULT_LOCAL_TASK.
10749
      if ($category['name'] != 'account') {
10759
        $items['user/%user_category/edit/' . $category['name']] = array(
10769
          'title callback' => 'check_plain',
10779
          'title arguments' => array($category['title']),
10789
          'page callback' => 'user_edit',
10799
          'page arguments' => array(1, 3),
10809
          'access callback' => isset($category['access callback']) ?
$category['access callback'] : 'user_edit_access',
10819
          'access arguments' => isset($category['access arguments']) ?
$category['access arguments'] : array(1),
10829
          'type' => MENU_LOCAL_TASK,
10839
          'weight' => $category['weight'],
10849
          'load arguments' => array('%map', '%index'),
10859
          'tab_parent' => 'user/%/edit',
1086
        );
10879
      }
10889
    }
10899
  }
109085
  return $items;
10910
}
1092
10932027
function user_init() {
10942027
  drupal_add_css(drupal_get_path('module', 'user') . '/user.css',
'module');
10952027
}
1096
10972027
function user_uid_optional_load($arg) {
10981498
  return user_load(isset($arg) ? $arg : $GLOBALS['user']->uid);
10990
}
1100
1101
/**
1102
 * Return a user object after checking if any profile category in the path
exists.
1103
 */
11042027
function user_category_load($uid, &$map, $index) {
1105218
  static $user_categories, $accounts;
1106
1107
  // Cache $account - this load function will get called for each profile
tab.
1108218
  if (!isset($accounts[$uid])) {
1109218
    $accounts[$uid] = user_load($uid);
1110218
  }
1111218
  $valid = TRUE;
1112218
  if ($account = $accounts[$uid]) {
1113
    // Since the path is like user/%/edit/category_name, the category name
will
1114
    // be at a position 2 beyond the index corresponding to the %
wildcard.
1115218
    $category_index = $index + 2;
1116
    // Valid categories may contain slashes, and hence need to be
imploded.
1117218
    $category_path = implode('/', array_slice($map, $category_index));
1118218
    if ($category_path) {
1119
      // Check that the requested category exists.
112037
      $valid = FALSE;
112137
      if (!isset($user_categories)) {
112237
        $empty_account = new stdClass();
112337
        $user_categories = _user_categories($empty_account);
112437
      }
112537
      foreach ($user_categories as $category) {
112637
        if ($category['name'] == $category_path) {
112737
          $valid = TRUE;
1128
          // Truncate the map array in case the category name had slashes.
112937
          $map = array_slice($map, 0, $category_index);
1130
          // Assign the imploded category name to the last map element.
113137
          $map[$category_index] = $category_path;
113237
          break;
11330
        }
113437
      }
113537
    }
1136218
  }
1137218
  return $valid ? $account : FALSE;
11380
}
1139
1140
/**
1141
 * Returns the user id of the currently logged in user.
1142
 */
11432027
function user_uid_optional_to_arg($arg) {
1144
  // Give back the current user uid when called from eg. tracker, aka.
1145
  // with an empty arg. Also use the current user uid when called from
1146
  // the menu with a % for the current account link.
11471498
  return empty($arg) || $arg == '%' ? $GLOBALS['user']->uid : $arg;
11480
}
1149
1150
/**
1151
 * Menu item title callback - use the user name if it's not the current
user.
1152
 */
11532027
function user_page_title($account) {
11541057
  if ($account->uid == $GLOBALS['user']->uid) {
11551057
    return t('My account');
11560
  }
115730
  return $account->name;
11580
}
1159
1160
/**
1161
 * Discover which external authentication module(s) authenticated a
username.
1162
 *
1163
 * @param $authname
1164
 *   A username used by an external authentication module.
1165
 * @return
1166
 *   An associative array with module as key and username as value.
1167
 */
11682027
function user_get_authmaps($authname = NULL) {
11690
  $result = db_query("SELECT authname, module FROM {authmap} WHERE authname
= '%s'", $authname);
11700
  $authmaps = array();
11710
  $has_rows = FALSE;
11720
  while ($authmap = db_fetch_object($result)) {
11730
    $authmaps[$authmap->module] = $authmap->authname;
11740
    $has_rows = TRUE;
11750
  }
11760
  return $has_rows ? $authmaps : 0;
11770
}
1178
1179
/**
1180
 * Save mappings of which external authentication module(s) authenticated
1181
 * a user. Maps external usernames to user ids in the users table.
1182
 *
1183
 * @param $account
1184
 *   A user object.
1185
 * @param $authmaps
1186
 *   An associative array with a compound key and the username as the
value.
1187
 *   The key is made up of 'authname_' plus the name of the external
authentication
1188
 *   module.
1189
 * @see user_external_login_register()
1190
 */
11912027
function user_set_authmaps($account, $authmaps) {
11920
  foreach ($authmaps as $key => $value) {
11930
    $module = explode('_', $key, 2);
11940
    if ($value) {
11950
      db_query("UPDATE {authmap} SET authname = '%s' WHERE uid = %d AND
module = '%s'", $value, $account->uid, $module[1]);
11960
      if (!db_affected_rows()) {
11970
        db_query("INSERT INTO {authmap} (authname, uid, module) VALUES
('%s', %d, '%s')", $value, $account->uid, $module[1]);
11980
      }
11990
    }
1200
    else {
12010
      db_query("DELETE FROM {authmap} WHERE uid = %d AND module = '%s'",
$account->uid, $module[1]);
1202
    }
12030
  }
12040
}
1205
1206
/**
1207
 * Form builder; the main user login form.
1208
 *
1209
 * @ingroup forms
1210
 */
12112027
function user_login(&$form_state) {
1212384
  global $user;
1213
1214
  // If we are already logged on, go to the user page instead.
1215384
  if ($user->uid) {
12160
    drupal_goto('user/' . $user->uid);
12170
  }
1218
1219
  // Display login form:
1220384
  $form['name'] = array('#type' => 'textfield',
1221384
    '#title' => t('Username'),
1222384
    '#size' => 60,
1223384
    '#maxlength' => USERNAME_MAX_LENGTH,
1224384
    '#required' => TRUE,
1225384
    '#attributes' => array('tabindex' => '1'),
1226
  );
1227
1228384
  $form['name']['#description'] = t('Enter your @s username.', array('@s'
=> variable_get('site_name', 'Drupal')));
1229384
  $form['pass'] = array('#type' => 'password',
1230384
    '#title' => t('Password'),
1231384
    '#description' => t('Enter the password that accompanies your
username.'),
1232384
    '#required' => TRUE,
1233384
    '#attributes' => array('tabindex' => '2'),
1234
  );
1235384
  $form['#validate'] = user_login_default_validators();
1236384
  $form['submit'] = array('#type' => 'submit', '#value' => t('Log in'),
'#weight' => 2, '#attributes' => array('tabindex' => '3'));
1237
1238384
  return $form;
12390
}
1240
1241
/**
1242
 * Set up a series for validators which check for blocked users,
1243
 * then authenticate against local database, then return an error if
1244
 * authentication fails. Distributed authentication modules are welcome
1245
 * to use hook_form_alter() to change this series in order to
1246
 * authenticate against their user database instead of the local users
1247
 * table.
1248
 *
1249
 * We use three validators instead of one since external authentication
1250
 * modules usually only need to alter the second validator.
1251
 *
1252
 * @see user_login_name_validate()
1253
 * @see user_login_authenticate_validate()
1254
 * @see user_login_final_validate()
1255
 * @return array
1256
 *   A simple list of validate functions.
1257
 */
12582027
function user_login_default_validators() {
1259588
  return array('user_login_name_validate',
'user_login_authenticate_validate', 'user_login_final_validate');
12600
}
1261
1262
/**
1263
 * A FAPI validate handler. Sets an error if supplied username has been
blocked.
1264
 */
12652027
function user_login_name_validate($form, &$form_state) {
1266151
  if (isset($form_state['values']['name']) &&
user_is_blocked($form_state['values']['name'])) {
1267
    // Blocked in user administration.
12680
    form_set_error('name', t('The username %name has not been activated or
is blocked.', array('%name' => $form_state['values']['name'])));
12690
  }
1270151
}
1271
1272
/**
1273
 * A validate handler on the login form. Check supplied username/password
1274
 * against local users table. If successful, sets the global $user object.
1275
 */
12762027
function user_login_authenticate_validate($form, &$form_state) {
1277151
  user_authenticate($form_state['values']);
1278151
}
1279
1280
/**
1281
 * A validate handler on the login form. Should be the last validator. Sets
an
1282
 * error if user has not been authenticated yet.
1283
 */
12842027
function user_login_final_validate($form, &$form_state) {
1285151
  global $user;
1286151
  if (!$user->uid) {
12871
    form_set_error('name', t('Sorry, unrecognized username or password. <a
href="@password">Have you forgotten your password?</a>', array('@password'
=> url('user/password'))));
12881
    watchdog('user', 'Login attempt failed for %user.', array('%user' =>
$form_state['values']['name']));
12891
  }
1290151
}
1291
1292
/**
1293
 * Try to log in the user locally.
1294
 *
1295
 * @param $form_values
1296
 *   Form values with at least 'name' and 'pass' keys, as well as anything
else
1297
 *   which should be passed along to hook_user op 'login'.
1298
 *
1299
 * @return
1300
 *  A $user object, if successful.
1301
 */
13022027
function user_authenticate($form_values = array()) {
1303159
  global $user;
1304
1305159
  $password = trim($form_values['pass']);
1306
  // Name and pass keys are required.
1307159
  if (!empty($form_values['name']) && !empty($password)) {
1308159
    $account = db_fetch_object(db_query("SELECT * FROM {users} WHERE name =
'%s' AND status = 1", $form_values['name']));
1309159
    if ($account) {
1310
      // Allow alternate password hashing schemes.
1311159
      require_once variable_get('password_inc',
'./includes/password.inc');
1312159
      if (user_check_password($password, $account)) {
1313158
        if (user_needs_new_hash($account)) {
13140
           $new_hash = user_hash_password($password);
13150
           if ($new_hash) {
13160
             db_query("UPDATE {users} SET pass = '%s' WHERE uid = %d",
$new_hash, $account->uid);
13170
           }
13180
        }
1319158
        $account = user_load(array('uid' => $account->uid, 'status' =>
1));
1320158
        $user = $account;
1321158
        user_authenticate_finalize($form_values);
1322158
        return $user;
13230
      }
13241
    }
13251
  }
13261
}
1327
1328
/**
1329
 * Finalize the login process. Must be called when logging in a user.
1330
 *
1331
 * The function records a watchdog message about the new session, saves
the
1332
 * login timestamp, calls hook_user op 'login' and generates a new
session.
1333
 *
1334
 * $param $edit
1335
 *   This array is passed to hook_user op login.
1336
 */
13372027
function user_authenticate_finalize(&$edit) {
1338159
  global $user;
1339159
  watchdog('user', 'Session opened for %name.', array('%name' =>
$user->name));
1340
  // Update the user table timestamp noting user has logged in.
1341
  // This is also used to invalidate one-time login links.
1342159
  $user->login = time();
1343159
  db_query("UPDATE {users} SET login = %d WHERE uid = %d", $user->login,
$user->uid);
1344159
  user_module_invoke('login', $edit, $user);
1345159
  sess_regenerate();
1346159
}
1347
1348
/**
1349
 * Submit handler for the login form. Redirects the user to a page.
1350
 *
1351
 * The user is redirected to the My Account page. Setting the destination
in
1352
 * the query string (as done by the user login block) overrides the
redirect.
1353
 */
13542027
function user_login_submit($form, &$form_state) {
1355150
  global $user;
1356150
  if ($user->uid) {
1357150
    $form_state['redirect'] = 'user/' . $user->uid;
1358150
    return;
13590
  }
13600
}
1361
1362
/**
1363
 * Helper function for authentication modules. Either login in or
registers
1364
 * the current user, based on username. Either way, the global $user object
is
1365
 * populated based on $name.
1366
 */
13672027
function user_external_login_register($name, $module) {
13680
  global $user;
1369
13700
  $existing_user = user_load(array('name' => $name));
13710
  if (isset($existing_user->uid)) {
13720
    $user = $existing_user;
13730
  }
1374
  else {
1375
    // Register this new user.
1376
    $userinfo = array(
13770
      'name' => $name,
13780
      'pass' => user_password(),
13790
      'init' => $name,
13800
      'status' => 1,
13810
      'access' => time()
13820
    );
13830
    $account = user_save('', $userinfo);
1384
    // Terminate if an error occured during user_save().
13850
    if (!$account) {
13860
      drupal_set_message(t("Error saving user account."), 'error');
13870
      return;
13880
    }
13890
    user_set_authmaps($account, array("authname_$module" => $name));
13900
    $user = $account;
13910
    watchdog('user', 'New external user: %name using module %module.',
array('%name' => $name, '%module' => $module), WATCHDOG_NOTICE,
l(t('edit'), 'user/' . $user->uid . '/edit'));
1392
  }
13930
}
1394
13952027
function user_pass_reset_url($account) {
13963
  $timestamp = time();
13973
  return url("user/reset/$account->uid/$timestamp/" .
user_pass_rehash($account->pass, $timestamp, $account->login),
array('absolute' => TRUE));
13980
}
1399
14002027
function user_pass_rehash($password, $timestamp, $login) {
14015
  return md5($timestamp . $password . $login);
14020
}
1403
14042027
function user_edit_form(&$form_state, $uid, $edit, $register = FALSE) {
140523
  _user_password_dynamic_validation();
140623
  $admin = user_access('administer users');
1407
1408
  // Account information:
140923
  $form['account'] = array('#type' => 'fieldset',
141023
    '#title' => t('Account information'),
141123
    '#weight' => -10,
1412
  );
141323
  if (user_access('change own username') || $admin || $register) {
14149
    $form['account']['name'] = array('#type' => 'textfield',
14159
      '#title' => t('Username'),
14169
      '#default_value' => $edit['name'],
14179
      '#maxlength' => USERNAME_MAX_LENGTH,
14189
      '#description' => t('Spaces are allowed; punctuation is not allowed
except for periods, hyphens, apostrophes, and underscores.'),
14199
      '#required' => TRUE,
1420
    );
14219
  }
142223
  $form['account']['mail'] = array('#type' => 'textfield',
142323
    '#title' => t('E-mail address'),
142423
    '#default_value' => $edit['mail'],
142523
    '#maxlength' => EMAIL_MAX_LENGTH,
142623
    '#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.'),
142723
    '#required' => TRUE,
1428
  );
142923
  if (!$register) {
143016
    $form['account']['pass'] = array('#type' => 'password_confirm',
143116
      '#description' => t('To change the current user password, enter the
new password in both fields.'),
143216
      '#size' => 25,
1433
    );
143416
  }
14357
  elseif (!variable_get('user_email_verification', TRUE) || $admin) {
14363
    $form['account']['pass'] = array(
14373
      '#type' => 'password_confirm',
14383
      '#description' => t('Provide a password for the new account in both
fields.'),
14393
      '#required' => TRUE,
14403
      '#size' => 25,
1441
    );
14423
  }
144323
  if ($admin) {
14445
    $form['account']['status'] = array(
14455
      '#type' => 'radios',
14465
      '#title' => t('Status'),
14475
      '#default_value' => isset($edit['status']) ? $edit['status'] : 1,
14485
      '#options' => array(t('Blocked'), t('Active'))
14495
    );
14505
  }
145123
  if (user_access('administer permissions')) {
14520
    $roles = user_roles(TRUE);
1453
1454
    // The disabled checkbox subelement for the 'authenticated user' role
1455
    // must be generated separately and added to the checkboxes element,
1456
    // because of a limitation in D6 FormAPI not supporting a single
disabled
1457
    // checkbox within a set of checkboxes.
1458
    // TODO: This should be solved more elegantly. See issue #119038.
1459
    $checkbox_authenticated = array(
14600
      '#type' => 'checkbox',
14610
      '#title' => $roles[DRUPAL_AUTHENTICATED_RID],
14620
      '#default_value' => TRUE,
14630
      '#disabled' => TRUE,
14640
    );
1465
14660
    unset($roles[DRUPAL_AUTHENTICATED_RID]);
14670
    if ($roles) {
14680
      $default = empty($edit['roles']) ? array() :
array_keys($edit['roles']);
14690
      $form['account']['roles'] = array(
14700
        '#type' => 'checkboxes',
14710
        '#title' => t('Roles'),
14720
        '#default_value' => $default,
14730
        '#options' => $roles,
14740
        DRUPAL_AUTHENTICATED_RID => $checkbox_authenticated,
1475
      );
14760
    }
14770
  }
1478
1479
  // Signature:
148023
  if (variable_get('user_signatures', 0) && module_exists('comment') &&
!$register) {
14810
    $form['signature_settings'] = array(
14820
      '#type' => 'fieldset',
14830
      '#title' => t('Signature settings'),
14840
      '#weight' => 1,
1485
    );
14860
    $form['signature_settings']['signature'] = array(
14870
      '#type' => 'textarea',
14880
      '#title' => t('Signature'),
14890
      '#default_value' => $edit['signature'],
14900
      '#description' => t('Your signature will be publicly displayed at the
end of your comments.'),
1491
    );
14920
  }
1493
1494
  // Picture/avatar:
149523
  if (variable_get('user_pictures', 0) && !$register) {
149611
    $form['picture'] = array('#type' => 'fieldset', '#title' =>
t('Picture'), '#weight' => 1);
149711
    $picture = theme('user_picture', (object)$edit);
149811
    if ($edit['picture']) {
14993
      $form['picture']['current_picture'] = array('#markup' => $picture);
15003
      $form['picture']['picture_delete'] = array('#type' => 'checkbox',
'#title' => t('Delete picture'), '#description' => t('Check this box to
delete your current picture.'));
15013
    }
1502
    else {
15038
      $form['picture']['picture_delete'] = array('#type' => 'hidden');
1504
    }
150511
    $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', ''));
150611
    $form['#validate'][] = 'user_validate_picture';
150711
  }
150823
  $form['#uid'] = $uid;
1509
151023
  return $form;
15110
}
1512
15132027
function _user_edit_validate($uid, &$edit) {
15145
  $user = user_load(array('uid' => $uid));
1515
  // Validate the username:
15165
  if (user_access('change own username') || user_access('administer users')
|| !$user->uid) {
15174
    if ($error = user_validate_name($edit['name'])) {
15180
      form_set_error('name', $error);
15190
    }
15204
    else if (db_result(db_query("SELECT COUNT(*) FROM {users} WHERE uid !=
%d AND LOWER(name) = LOWER('%s')", $uid, $edit['name'])) > 0) {
15210
      form_set_error('name', t('The name %name is already taken.',
array('%name' => $edit['name'])));
15220
    }
15234
  }
1524
1525
  // Validate the e-mail address:
15265
  if ($error = user_validate_mail($edit['mail'])) {
15270
    form_set_error('mail', $error);
15280
  }
15295
  else if (db_result(db_query("SELECT COUNT(*) FROM {users} WHERE uid != %d
AND LOWER(mail) = LOWER('%s')", $uid, $edit['mail'])) > 0) {
15300
    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'))));
15310
  }
15325
}
1533
15342027
function _user_edit_submit($uid, &$edit) {
15354
  $user = user_load(array('uid' => $uid));
1536
  // Delete picture if requested, and if no replacement picture was given.
15374
  if (!empty($edit['picture_delete'])) {
15380
    if ($user->picture && file_exists($user->picture)) {
15390
      file_delete($user->picture);
15400
    }
15410
    $edit['picture'] = '';
15420
  }
15434
  if (isset($edit['roles'])) {
15440
    $edit['roles'] = array_filter($edit['roles']);
15450
  }
15464
}
1547
1548
/**
1549
 * Delete a user.
1550
 *
1551
 * @param $edit An array of submitted form values.
1552
 * @param $uid The user ID of the user to delete.
1553
 */
15542027
function user_delete($edit, $uid) {
15552
  $account = user_load(array('uid' => $uid));
15562
  sess_destroy_uid($uid);
15572
  _user_mail_notify('status_deleted', $account);
15582
  module_invoke_all('user', 'delete', $edit, $account);
15592
  db_query('DELETE FROM {users} WHERE uid = %d', $uid);
15602
  db_query('DELETE FROM {users_roles} WHERE uid = %d', $uid);
15612
  db_query('DELETE FROM {authmap} WHERE uid = %d', $uid);
15622
  $variables = array('%name' => $account->name, '%email' => '<' .
$account->mail . '>');
15632
  watchdog('user', 'Deleted user: %name %email.', $variables,
WATCHDOG_NOTICE);
15642
}
1565
1566
/**
1567
 * Builds a structured array representing the profile content.
1568
 *
1569
 * @param $account
1570
 *   A user object.
1571
 *
1572
 * @return
1573
 *   A structured array containing the individual elements of the profile.
1574
 */
15752027
function user_build_content(&$account) {
1576163
  $edit = NULL;
1577163
  user_module_invoke('view', $edit, $account);
1578
  // Allow modules to modify the fully-built profile.
1579163
  drupal_alter('profile', $account);
1580
1581163
  return $account->content;
15820
}
1583
1584
/**
1585
 * Implementation of hook_mail().
1586
 */
15872027
function user_mail($key, &$message, $params) {
15882
  $language = $message['language'];
15892
  $variables = user_mail_tokens($params['account'], $language);
15902
  $message['subject'] .= _user_mail_text($key . '_subject', $language,
$variables);
15912
  $message['body'][] = _user_mail_text($key . '_body', $language,
$variables);
15922
}
1593
1594
/**
1595
 * Returns a mail string for a variable name.
1596
 *
1597
 * Used by user_mail() and the settings forms to retrieve strings.
1598
 */
15992027
function _user_mail_text($key, $language = NULL, $variables = array()) {
16002
  $langcode = isset($language) ? $language->language : NULL;
1601
16022
  if ($admin_setting = variable_get('user_mail_' . $key, FALSE)) {
1603
    // An admin setting overrides the default string.
16040
    return strtr($admin_setting, $variables);
16050
  }
1606
  else {
1607
    // No override, return default string.
1608
    switch ($key) {
16092
      case 'register_no_approval_required_subject':
16102
        return t('Account details for !username at !site', $variables,
$langcode);
16112
      case 'register_no_approval_required_body':
16122
        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);
16130
      case 'register_admin_created_subject':
16140
        return t('An administrator created an account for you at !site',
$variables, $langcode);
16150
      case 'register_admin_created_body':
16160
        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);
16170
      case 'register_pending_approval_subject':
16180
      case 'register_pending_approval_admin_subject':
16190
        return t('Account details for !username at !site (pending admin
approval)', $variables, $langcode);
16200
      case 'register_pending_approval_body':
16210
        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);
16220
      case 'register_pending_approval_admin_body':
16230
        return t("!username has applied for an account.\n\n!edit_uri",
$variables, $langcode);
16240
      case 'password_reset_subject':
16250
        return t('Replacement login information for !username at !site',
$variables, $langcode);
16260
      case 'password_reset_body':
16270
        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);
16280
      case 'status_activated_subject':
16290
        return t('Account details for !username at !site (approved)',
$variables, $langcode);
16300
      case 'status_activated_body':
16310
        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);
16320
      case 'status_blocked_subject':
16330
        return t('Account details for !username at !site (blocked)',
$variables, $langcode);
16340
      case 'status_blocked_body':
16350
        return t("!username,\n\nYour account on !site has been blocked.",
$variables, $langcode);
16360
      case 'status_deleted_subject':
16370
        return t('Account details for !username at !site (deleted)',
$variables, $langcode);
16380
      case 'status_deleted_body':
16390
        return t("!username,\n\nYour account on !site has been deleted.",
$variables, $langcode);
16400
    }
1641
  }
16420
}
1643
1644
/*** Administrative features
***********************************************/
1645
1646
/**
1647
 * Retrieve an array of roles matching specified conditions.
1648
 *
1649
 * @param $membersonly
1650
 *   Set this to TRUE to exclude the 'anonymous' role.
1651
 * @param $permission
1652
 *   A string containing a permission. If set, only roles containing that
1653
 *   permission are returned.
1654
 *
1655
 * @return
1656
 *   An associative array with the role id as the key and the role name as
1657
 *   value.
1658
 */
16592027
function user_roles($membersonly = FALSE, $permission = NULL) {
1660
  // System roles take the first two positions.
1661
  $roles = array(
166258
    DRUPAL_ANONYMOUS_RID => NULL,
166358
    DRUPAL_AUTHENTICATED_RID => NULL,
166458
  );
1665
166658
  if (!empty($permission)) {
16679
    $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);
16689
  }
1669
  else {
167049
    $result = db_query('SELECT * FROM {role} ORDER BY name');
1671
  }
1672
167358
  while ($role = db_fetch_object($result)) {
167458
    switch ($role->rid) {
1675
      // We only translate the built in role names
167658
      case DRUPAL_ANONYMOUS_RID:
167749
        if (!$membersonly) {
167848
          $roles[$role->rid] = t($role->name);
167948
        }
168049
        break;
168158
      case DRUPAL_AUTHENTICATED_RID:
168249
        $roles[$role->rid] = t($role->name);
168349
        break;
168458
      default:
168558
        $roles[$role->rid] = $role->name;
168658
    }
168758
  }
1688
1689
  // Filter to remove unmatched system roles.
169058
  return array_filter($roles);
16910
}
1692
1693
/**
1694
 * Implementation of hook_user_operations().
1695
 */
16962027
function user_user_operations($form_state = array()) {
1697
  $operations = array(
1698
    'unblock' => array(
16991
      'label' => t('Unblock the selected users'),
17001
      'callback' => 'user_user_operations_unblock',
17011
    ),
1702
    'block' => array(
17031
      'label' => t('Block the selected users'),
17041
      'callback' => 'user_user_operations_block',
17051
    ),
1706
    'delete' => array(
17071
      'label' => t('Delete the selected users'),
17081
    ),
17091
  );
1710
17111
  if (user_access('administer permissions')) {
17120
    $roles = user_roles(TRUE);
17130
    unset($roles[DRUPAL_AUTHENTICATED_RID]);  // Can't edit authenticated
role.
1714
17150
    $add_roles = array();
17160
    foreach ($roles as $key => $value) {
17170
      $add_roles['add_role-' . $key] = $value;
17180
    }
1719
17200
    $remove_roles = array();
17210
    foreach ($roles as $key => $value) {
17220
      $remove_roles['remove_role-' . $key] = $value;
17230
    }
1724
17250
    if (count($roles)) {
1726
      $role_operations = array(
17270
        t('Add a role to the selected users') => array(
17280
          'label' => $add_roles,
17290
        ),
17300
        t('Remove a role from the selected users') => array(
17310
          'label' => $remove_roles,
17320
        ),
17330
      );
1734
17350
      $operations += $role_operations;
17360
    }
17370
  }
1738
1739
  // If the form has been posted, we need to insert the proper data for
1740
  // role editing if necessary.
17411
  if (!empty($form_state['submitted'])) {
17420
    $operation_rid = explode('-', $form_state['values']['operation']);
17430
    $operation = $operation_rid[0];
17440
    if ($operation == 'add_role' || $operation == 'remove_role') {
17450
      $rid = $operation_rid[1];
17460
      if (user_access('administer permissions')) {
17470
        $operations[$form_state['values']['operation']] = array(
17480
          'callback' => 'user_multiple_role_edit',
17490
          'callback arguments' => array($operation, $rid),
1750
        );
17510
      }
1752
      else {
17530
        watchdog('security', 'Detected malicious attempt to alter protected
user fields.', array(), WATCHDOG_WARNING);
17540
        return;
1755
      }
17560
    }
17570
  }
1758
17591
  return $operations;
17600
}
1761
1762
/**
1763
 * Callback function for admin mass unblocking users.
1764
 */
17652027
function user_user_operations_unblock($accounts) {
17660
  foreach ($accounts as $uid) {
17670
    $account = user_load(array('uid' => (int)$uid));
1768
    // Skip unblocking user if they are already unblocked.
17690
    if ($account !== FALSE && $account->status == 0) {
17700
      user_save($account, array('status' => 1));
17710
    }
17720
  }
17730
}
1774
1775
/**
1776
 * Callback function for admin mass blocking users.
1777
 */
17782027
function user_user_operations_block($accounts) {
17790
  foreach ($accounts as $uid) {
17800
    $account = user_load(array('uid' => (int)$uid));
1781
    // Skip blocking user if they are already blocked.
17820
    if ($account !== FALSE && $account->status == 1) {
17830
      user_save($account, array('status' => 0));
17840
    }
17850
  }
17860
}
1787
1788
/**
1789
 * Callback function for admin mass adding/deleting a user role.
1790
 */
17912027
function user_multiple_role_edit($accounts, $operation, $rid) {
1792
  // The role name is not necessary as user_save() will reload the user
1793
  // object, but some modules' hook_user() may look at this first.
17940
  $role_name = db_result(db_query('SELECT name FROM {role} WHERE rid = %d',
$rid));
1795
1796
  switch ($operation) {
17970
    case 'add_role':
17980
      foreach ($accounts as $uid) {
17990
        $account = user_load(array('uid' => (int)$uid));
1800
        // Skip adding the role to the user if they already have it.
18010
        if ($account !== FALSE && !isset($account->roles[$rid])) {
18020
          $roles = $account->roles + array($rid => $role_name);
18030
          user_save($account, array('roles' => $roles));
18040
        }
18050
      }
18060
      break;
18070
    case 'remove_role':
18080
      foreach ($accounts as $uid) {
18090
        $account = user_load(array('uid' => (int)$uid));
1810
        // Skip removing the role from the user if they already don't have
it.
18110
        if ($account !== FALSE && isset($account->roles[$rid])) {
18120
          $roles = array_diff($account->roles, array($rid => $role_name));
18130
          user_save($account, array('roles' => $roles));
18140
        }
18150
      }
18160
      break;
18170
  }
18180
}
1819
18202027
function user_multiple_delete_confirm(&$form_state) {
18210
  $edit = $form_state['post'];
1822
18230
  $form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>',
'#tree' => TRUE);
1824
  // array_filter() returns only elements with TRUE values.
18250
  foreach (array_filter($edit['accounts']) as $uid => $value) {
18260
    $user = db_result(db_query('SELECT name FROM {users} WHERE uid = %d',
$uid));
18270
    $form['accounts'][$uid] = array('#type' => 'hidden', '#value' => $uid,
'#prefix' => '<li>', '#suffix' => check_plain($user) . "</li>\n");
18280
  }
18290
  $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
1830
18310
  return confirm_form($form,
18320
                      t('Are you sure you want to delete these users?'),
18330
                      'admin/user/user', t('This action cannot be
undone.'),
18340
                      t('Delete all'), t('Cancel'));
18350
}
1836
18372027
function user_multiple_delete_confirm_submit($form, &$form_state) {
18380
  if ($form_state['values']['confirm']) {
18390
    foreach ($form_state['values']['accounts'] as $uid => $value) {
18400
      user_delete($form_state['values'], $uid);
18410
    }
18420
    drupal_set_message(t('The users have been deleted.'));
18430
  }
18440
  $form_state['redirect'] = 'admin/user/user';
18450
  return;
18460
}
1847
1848
/**
1849
 * Implementation of hook_help().
1850
 */
18512027
function user_help($path, $arg) {
18521491
  global $user;
1853
1854
  switch ($path) {
18551491
    case 'admin/help#user':
185615
      $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>';
185715
      $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>';
185815
      $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>';
185915
      $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>';
186015
      return $output;
18611489
    case 'admin/user/user':
18621
      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>';
18631488
    case 'admin/user/user/create':
18641488
    case 'admin/user/user/account/create':
18652
      return '<p>' . t("This web page allows administrators to register new
users. Users' e-mail addresses and usernames must be unique.") . '</p>';
18661486
    case 'admin/user/permissions':
186716
      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>';
18681486
    case 'admin/user/roles':
18690
      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>
1870
      <ul>
1871
      <li>Anonymous user: this role is used for users that don\'t have a
user account or that are not authenticated.</li>
1872
      <li>Authenticated user: this role is automatically granted to all
logged in users.</li>
18730
      </ul>', array('@permissions' => url('admin/user/permissions')));
18741486
    case 'admin/user/search':
18750
      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>';
18760
  }
18771486
}
1878
1879
/**
1880
 * Retrieve a list of all user setting/information categories and sort them
by weight.
1881
 */
18822027
function _user_categories($account) {
1883122
  $categories = array();
1884
1885122
  foreach (module_list() as $module) {
1886122
    if ($data = module_invoke($module, 'user', 'categories', NULL,
$account, '')) {
1887122
      $categories = array_merge($data, $categories);
1888122
    }
1889122
  }
1890
1891122
  usort($categories, '_user_sort');
1892
1893122
  return $categories;
18940
}
1895
18962027
function _user_sort($a, $b) {
189762
  $a = (array)$a + array('weight' => 0, 'title' => '');
189862
  $b = (array)$b + array('weight' => 0, 'title' => '');
189962
  return $a['weight'] < $b['weight'] ? -1 : ($a['weight'] > $b['weight'] ?
1 : ($a['title'] < $b['title'] ? -1 : 1));
19000
}
1901
1902
/**
1903
 * List user administration filters that can be applied.
1904
 */
19052027
function user_filters() {
1906
  // Regular filters
19071
  $filters = array();
19081
  $roles = user_roles(TRUE);
19091
  unset($roles[DRUPAL_AUTHENTICATED_RID]); // Don't list authorized role.
19101
  if (count($roles)) {
19111
    $filters['role'] = array(
19121
      'title' => t('role'),
19131
      'where' => "ur.rid = %d",
19141
      'options' => $roles,
19151
      'join' => '',
1916
    );
19171
  }
1918
19191
  $options = array();
19201
  foreach (module_list() as $module) {
19211
    if ($permissions = module_invoke($module, 'perm')) {
19221
      asort($permissions);
19231
      foreach ($permissions as $permission => $description) {
19241
        $options[t('@module module', array('@module' =>
$module))][$permission] = t($permission);
19251
      }
19261
    }
19271
  }
19281
  ksort($options);
19291
  $filters['permission'] = array(
19301
    'title' => t('permission'),
19311
    'join' => 'LEFT JOIN {role_permission} p ON ur.rid = p.rid',
19321
    'where' => " (p.permission = '%s' OR u.uid = 1) ",
19331
    'options' => $options,
1934
  );
1935
19361
  $filters['status'] = array(
19371
    'title' => t('status'),
19381
    'where' => 'u.status = %d',
19391
    'join' => '',
19401
    'options' => array(1 => t('active'), 0 => t('blocked')),
1941
  );
19421
  return $filters;
19430
}
1944
1945
/**
1946
 * Build query for user administration filters based on session.
1947
 */
19482027
function user_build_filter_query() {
19491
  $filters = user_filters();
1950
1951
  // Build query
19521
  $where = $args = $join = array();
19531
  foreach ($_SESSION['user_overview_filter'] as $filter) {
19540
    list($key, $value) = $filter;
1955
    // This checks to see if this permission filter is an enabled
permission for
1956
    // the authenticated role. If so, then all users would be listed, and
we can
1957
    // skip adding it to the filter query.
19580
    if ($key == 'permission') {
19590
      $account = new stdClass();
19600
      $account->uid = 'user_filter';
19610
      $account->roles = array(DRUPAL_AUTHENTICATED_RID => 1);
19620
      if (user_access($value, $account)) {
19630
        continue;
19640
      }
19650
    }
19660
    $where[] = $filters[$key]['where'];
19670
    $args[] = $value;
19680
    $join[] = $filters[$key]['join'];
19690
  }
19701
  $where = !empty($where) ? 'AND ' . implode(' AND ', $where) : '';
19711
  $join = !empty($join) ? ' ' . implode(' ', array_unique($join)) : '';
1972
19731
  return array('where' => $where,
19741
           'join' => $join,
19751
           'args' => $args,
19761
         );
19770
}
1978
1979
/**
1980
 * Implementation of hook_forms().
1981
 */
19822027
function user_forms() {
1983135
  $forms['user_admin_access_add_form']['callback'] =
'user_admin_access_form';
1984135
  $forms['user_admin_access_edit_form']['callback'] =
'user_admin_access_form';
1985135
  $forms['user_admin_new_role']['callback'] = 'user_admin_role';
1986135
  return $forms;
19870
}
1988
1989
/**
1990
 * Implementation of hook_comment().
1991
 */
19922027
function user_comment(&$comment, $op) {
1993
  // Validate signature.
199452
  if ($op == 'view') {
199532
    if (variable_get('user_signatures', 0) && !empty($comment->signature))
{
19960
      $comment->signature = check_markup($comment->signature,
$comment->format);
19970
    }
1998
    else {
199932
      $comment->signature = '';
2000
    }
200132
  }
200252
}
2003
2004
/**
2005
 * Theme output of user signature.
2006
 *
2007
 * @ingroup themeable
2008
 */
20092027
function theme_user_signature($signature) {
20100
  $output = '';
20110
  if ($signature) {
20120
    $output .= '<div class="clear">';
20130
    $output .= '<div>—</div>';
20140
    $output .= $signature;
20150
    $output .= '</div>';
20160
  }
2017
20180
  return $output;
20190
}
2020
2021
/**
2022
 * Return an array of token to value mappings for user e-mail messages.
2023
 *
2024
 * @param $account
2025
 *  The user object of the account being notified.  Must contain at
2026
 *  least the fields 'uid', 'name', and 'mail'.
2027
 * @param $language
2028
 *  Language object to generate the tokens with.
2029
 * @return
2030
 *  Array of mappings from token names to values (for use with strtr()).
2031
 */
20322027
function user_mail_tokens($account, $language) {
20332
  global $base_url;
2034
  $tokens = array(
20352
    '!username' => $account->name,
20362
    '!site' => variable_get('site_name', 'Drupal'),
20372
    '!login_url' => user_pass_reset_url($account),
20382
    '!uri' => $base_url,
20392
    '!uri_brief' => substr($base_url, strlen('http://')),
20402
    '!mailto' => $account->mail,
20412
    '!date' => format_date(time(), 'medium', '', NULL,
$language->language),
20422
    '!login_uri' => url('user', array('absolute' => TRUE, 'language' =>
$language)),
20432
    '!edit_uri' => url('user/' . $account->uid . '/edit', array('absolute'
=> TRUE, 'language' => $language)),
20442
  );
20452
  if (!empty($account->password)) {
20462
    $tokens['!password'] = $account->password;
20472
  }
20482
  return $tokens;
20490
}
2050
2051
/**
2052
 * Get the language object preferred by the user. This user preference can
2053
 * be set on the user account editing page, and is only available if there
2054
 * are more than one languages enabled on the site. If the user did not
2055
 * choose a preferred language, or is the anonymous user, the $default
2056
 * value, or if it is not set, the site default language will be returned.
2057
 *
2058
 * @param $account
2059
 *   User account to look up language for.
2060
 * @param $default
2061
 *   Optional default language object to return if the account
2062
 *   has no valid language.
2063
 */
20642027
function user_preferred_language($account, $default = NULL) {
20653
  $language_list = language_list();
20663
  if ($account->language && isset($language_list[$account->language])) {
20670
    return $language_list[$account->language];
20680
  }
2069
  else {
20703
    return $default ? $default : language_default();
2071
  }
20720
}
2073
2074
/**
2075
 * Conditionally create and send a notification email when a certain
2076
 * operation happens on the given user account.
2077
 *
2078
 * @see user_mail_tokens()
2079
 * @see drupal_mail()
2080
 *
2081
 * @param $op
2082
 *  The operation being performed on the account.  Possible values:
2083
 *  'register_admin_created': Welcome message for user created by the
admin
2084
 *  'register_no_approval_required': Welcome message when user
self-registers
2085
 *  'register_pending_approval': Welcome message, user pending admin
approval
2086
 *  'password_reset': Password recovery request
2087
 *  'status_activated': Account activated
2088
 *  'status_blocked': Account blocked
2089
 *  'status_deleted': Account deleted
2090
 *
2091
 * @param $account
2092
 *  The user object of the account being notified.  Must contain at
2093
 *  least the fields 'uid', 'name', and 'mail'.
2094
 * @param $language
2095
 *  Optional language to use for the notification, overriding account
language.
2096
 * @return
2097
 *  The return value from drupal_mail_send(), if ends up being called.
2098
 */
20992027
function _user_mail_notify($op, $account, $language = NULL) {
2100
  // By default, we always notify except for deleted and blocked.
21014
  $default_notify = ($op != 'status_deleted' && $op != 'status_blocked');
21024
  $notify = variable_get('user_mail_' . $op . '_notify', $default_notify);
21034
  if ($notify) {
21042
    $params['account'] = $account;
21052
    $language = $language ? $language : user_preferred_language($account);
21062
    $mail = drupal_mail('user', $op, $account->mail, $language, $params);
21072
    if ($op == 'register_pending_approval') {
2108
      // If a user registered requiring admin approval, notify the admin,
too.
2109
      // We use the site default language for this.
21100
      drupal_mail('user', 'register_pending_approval_admin',
variable_get('site_mail', ini_get('sendmail_from')), language_default(),
$params);
21110
    }
21122
  }
21134
  return empty($mail) ? NULL : $mail['result'];
21140
}
2115
2116
/**
2117
 * Add javascript and string translations for dynamic password validation
2118
 * (strength and confirmation checking).
2119
 *
2120
 * This is an internal function that makes it easier to manage the
translation
2121
 * strings that need to be passed to the javascript code.
2122
 */
21232027
function _user_password_dynamic_validation() {
212423
  static $complete = FALSE;
212523
  global $user;
2126
  // Only need to do once per page.
212723
  if (!$complete) {
212823
    drupal_add_js(drupal_get_path('module', 'user') . '/user.js',
'module');
2129
213023
    drupal_add_js(array(
2131
      'password' => array(
213223
        'strengthTitle' => t('Password strength:'),
213323
        'lowStrength' => t('Low'),
213423
        'mediumStrength' => t('Medium'),
213523
        'highStrength' => t('High'),
213623
        'tooShort' => t('It is recommended to choose a password that
contains at least six characters. It should include numbers, punctuation,
and both upper and lowercase letters.'),
213723
        'needsMoreVariation' => t('The password does not include enough
variation to be secure. Try:'),
213823
        'addLetters' => t('Adding both upper and lowercase letters.'),
213923
        'addNumbers' => t('Adding numbers.'),
214023
        'addPunctuation' => t('Adding punctuation.'),
214123
        'sameAsUsername' => t('It is recommended to choose a password
different from the username.'),
214223
        'confirmSuccess' => t('Yes'),
214323
        'confirmFailure' => t('No'),
214423
        'confirmTitle' => t('Passwords match:'),
214523
        'username' => (isset($user->name) ? $user->name : ''))),
214623
      'setting');
214723
    $complete = TRUE;
214823
  }
214923
}
2150
2151
/**
2152
 * Implementation of hook_hook_info().
2153
 */
21542027
function user_hook_info() {
2155
  return array(
2156
    'user' => array(
2157
      'user' => array(
2158
        'insert' => array(
215955
          'runs when' => t('After a user account has been created'),
216055
        ),
2161
        'update' => array(
216255
          'runs when' => t("After a user's profile has been updated"),
216355
        ),
2164
        'delete' => array(
216555
          'runs when' => t('After a user has been deleted')
216655
        ),
2167
        'login' => array(
216855
          'runs when' => t('After a user has logged in')
216955
        ),
2170
        'logout' => array(
217155
          'runs when' => t('After a user has logged out')
217255
        ),
2173
        'view' => array(
217455
          'runs when' => t("When a user's profile is being viewed")
217555
        ),
217655
      ),
217755
    ),
217855
  );
21790
}
2180
2181
/**
2182
 * Implementation of hook_action_info().
2183
 */
21842027
function user_action_info() {
2185
  return array(
2186
    'user_block_user_action' => array(
2187131
      'description' => t('Block current user'),
2188131
      'type' => 'user',
2189131
      'configurable' => FALSE,
2190131
      'hooks' => array(),
2191131
    ),
2192131
  );
21930
}
2194
2195
/**
2196
 * Implementation of a Drupal action.
2197
 * Blocks the current user.
2198
 */
21992027
function user_block_user_action(&$object, $context = array()) {
22000
  if (isset($object->uid)) {
22010
    $uid = $object->uid;
22020
  }
22030
  elseif (isset($context['uid'])) {
22040
    $uid = $context['uid'];
22050
  }
2206
  else {
22070
    global $user;
22080
    $uid = $user->uid;
2209
  }
22100
  db_query("UPDATE {users} SET status = 0 WHERE uid = %d", $uid);
22110
  sess_destroy_uid($uid);
22120
  watchdog('action', 'Blocked user %name.', array('%name' =>
check_plain($user->name)));
22130
}
2214
2215
/**
2216
 * Submit handler for the user registration form.
2217
 *
2218
 * This function is shared by the installation form and the normal
registration form,
2219
 * which is why it can't be in the user.pages.inc file.
2220
 */
22212027
function user_register_submit($form, &$form_state) {
22223
  global $base_url;
22233
  $admin = user_access('administer users');
2224
22253
  $mail = $form_state['values']['mail'];
22263
  $name = $form_state['values']['name'];
22273
  if (!variable_get('user_email_verification', TRUE) || $admin) {
22281
    $pass = $form_state['values']['pass'];
22291
  }
2230
  else {
22312
    $pass = user_password();
2232
  };
22333
  $notify = isset($form_state['values']['notify']) ?
$form_state['values']['notify'] : NULL;
22343
  $from = variable_get('site_mail', ini_get('sendmail_from'));
22353
  if (isset($form_state['values']['roles'])) {
2236
    // Remove unset roles.
22370
    $roles = array_filter($form_state['values']['roles']);
22380
  }
2239
  else {
22403
    $roles = array();
2241
  }
2242
22433
  if (!$admin && array_intersect(array_keys($form_state['values']),
array('uid', 'roles', 'init', 'session', 'status'))) {
22440
    watchdog('security', 'Detected malicious attempt to alter protected
user fields.', array(), WATCHDOG_WARNING);
22450
    $form_state['redirect'] = 'user/register';
22460
    return;
22470
  }
2248
  // The unset below is needed to prevent these form values from being
saved as
2249
  // user data.
22503
  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']);
2251
22523
  $merge_data = array('pass' => $pass, 'init' => $mail, 'roles' =>
$roles);
22533
  if (!$admin) {
2254
    // Set the user's status because it was not displayed in the form.
22552
    $merge_data['status'] = variable_get('user_register', 1) == 1;
22562
  }
22573
  $account = user_save('', array_merge($form_state['values'],
$merge_data));
2258
  // Terminate if an error occured during user_save().
22593
  if (!$account) {
22600
    drupal_set_message(t("Error saving user account."), 'error');
22610
    $form_state['redirect'] = '';
22620
    return;
22630
  }
22643
  $form_state['user'] = $account;
2265
22663
  watchdog('user', 'New user: %name (%email).', array('%name' => $name,
'%email' => $mail), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $account->uid .
'/edit'));
2267
2268
  // The first user may login immediately, and receives a customized
welcome e-mail.
22693
  if ($account->uid == 1) {
22700
    drupal_set_message(t('Welcome to Drupal. You are now logged in as user
#1, which gives you full control over your website.'));
22710
    if (variable_get('user_email_verification', TRUE)) {
22720
      drupal_set_message(t('</p><p> Your password is
<strong>%pass</strong>. You may change your password below.</p>',
array('%pass' => $pass)));
22730
    }
2274
22750
    user_authenticate(array_merge($form_state['values'], $merge_data));
2276
22770
    $form_state['redirect'] = 'user/1/edit';
22780
    return;
22790
  }
2280
  else {
2281
    // Add plain text password into user account to generate mail tokens.
22823
    $account->password = $pass;
22833
    if ($admin && !$notify) {
22841
      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)));
22851
    }
22862
    else if (!variable_get('user_email_verification', TRUE) &&
$account->status && !$admin) {
2287
      // No e-mail verification is required, create new user account, and
login
2288
      // user immediately.
22890
      _user_mail_notify('register_no_approval_required', $account);
22900
      if (user_authenticate(array_merge($form_state['values'],
$merge_data))) {
22910
        drupal_set_message(t('Registration successful. You are now logged
in.'));
22920
      }
22930
      $form_state['redirect'] = '';
22940
      return;
22950
    }
22962
    else if ($account->status || $notify) {
2297
      // Create new user account, no administrator approval required.
22982
      $op = $notify ? 'register_admin_created' :
'register_no_approval_required';
22992
      _user_mail_notify($op, $account);
23002
      if ($notify) {
23010
        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)));
23020
      }
2303
      else {
23042
        drupal_set_message(t('Your password and further instructions have
been sent to your e-mail address.'));
23052
        $form_state['redirect'] = '';
23062
        return;
2307
      }
23080
    }
2309
    else {
2310
      // Create new user account, administrator approval required.
23110
      _user_mail_notify('register_pending_approval', $account);
23120
      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.'));
23130
      $form_state['redirect'] = '';
23140
      return;
2315
2316
    }
2317
  }
23181
}
2319
2320
/**
2321
 * Form builder; The user registration form.
2322
 *
2323
 * @ingroup forms
2324
 * @see user_register_validate()
2325
 * @see user_register_submit()
2326
 */
23272027
function user_register() {
23287
  global $user;
2329
23307
  $admin = user_access('administer users');
2331
2332
  // If we aren't admin but already logged on, go to the user page
instead.
23337
  if (!$admin && $user->uid) {
23340
    drupal_goto('user/' . $user->uid);
23350
  }
2336
23377
  $form = array();
2338
2339
  // Display the registration form.
23407
  if (!$admin) {
23414
    $form['user_registration_help'] = array('#markup' =>
filter_xss_admin(variable_get('user_registration_help', '')));
23424
  }
2343
2344
  // Merge in the default user edit fields.
23457
  $form = array_merge($form, user_edit_form($form_state, NULL, NULL,
TRUE));
23467
  if ($admin) {
23473
    $form['account']['notify'] = array(
23483
     '#type' => 'checkbox',
23493
     '#title' => t('Notify user of new account')
23503
    );
2351
    // Redirect back to page which initiated the create request;
2352
    // usually admin/user/user/create.
23533
    $form['destination'] = array('#type' => 'hidden', '#value' =>
$_GET['q']);
23543
  }
2355
2356
  // Create a dummy variable for pass-by-reference parameters.
23577
  $null = NULL;
23587
  $extra = _user_forms($null, NULL, NULL, 'register');
2359
2360
  // Remove form_group around default fields if there are no other groups.
23617
  if (!$extra) {
23627
    foreach (array('name', 'mail', 'pass', 'status', 'roles', 'notify') as
$key) {
23637
      if (isset($form['account'][$key])) {
23647
        $form[$key] = $form['account'][$key];
23657
      }
23667
    }
23677
    unset($form['account']);
23687
  }
2369
  else {
23700
    $form = array_merge($form, $extra);
2371
  }
2372
23737
  if (variable_get('configurable_timezones', 1)) {
2374
    // Override field ID, so we only change timezone on user registration,
2375
    // and never touch it on user edit pages.
23767
    $form['timezone'] = array(
23777
      '#type' => 'hidden',
23787
      '#default_value' => variable_get('date_default_timezone', NULL),
23797
      '#id' => 'edit-user-register-timezone',
2380
    );
2381
2382
    // Add the JavaScript callback to automatically set the timezone.
23837
    drupal_add_js('
2384
// Global Killswitch
2385
if (Drupal.jsEnabled) {
2386
  $(document).ready(function() {
2387
    Drupal.setDefaultTimezone();
2388
  });
23897
}', 'inline');
23907
  }
2391
23927
  $form['submit'] = array('#type' => 'submit', '#value' => t('Create new
account'), '#weight' => 30);
23937
  $form['#validate'][] = 'user_register_validate';
2394
23957
  return $form;
23960
}
2397
23982027
function user_register_validate($form, &$form_state) {
23993
  user_module_invoke('validate', $form_state['values'],
$form_state['values'], 'account');
24003
}
2401
2402
/**
2403
 * Retrieve a list of all form elements for the specified category.
2404
 */
24052027
function _user_forms(&$edit, $account, $category, $hook = 'form') {
240660
  $groups = array();
240760
  foreach (module_list() as $module) {
240860
    if ($data = module_invoke($module, 'user', $hook, $edit, $account,
$category)) {
240953
      $groups = array_merge_recursive($data, $groups);
241053
    }
241160
  }
241260
  uasort($groups, '_user_sort');
2413
241460
  return empty($groups) ? FALSE : $groups;
24150
}
24162027