user.module 111 KB
Newer Older
Dries's avatar
 
Dries committed
1 2 3
<?php
// $Id$

Dries's avatar
 
Dries committed
4 5 6 7 8
/**
 * @file
 * Enables the user registration and login system.
 */

9 10 11
define('USERNAME_MAX_LENGTH', 60);
define('EMAIL_MAX_LENGTH', 64);

Dries's avatar
Dries committed
12 13 14
/**
 * Invokes hook_user() in every module.
 *
15
 * We cannot use module_invoke() for this, because the arguments need to
Dries's avatar
Dries committed
16 17
 * be passed by reference.
 */
18
function user_module_invoke($type, &$array, &$user, $category = NULL) {
Dries's avatar
 
Dries committed
19 20
  foreach (module_list() as $module) {
    $function = $module .'_user';
21 22 23
    if (function_exists($function)) {
      $function($type, $array, $user, $category);
    }
Dries's avatar
 
Dries committed
24 25 26
  }
}

Dries's avatar
 
Dries committed
27
function user_external_load($authname) {
Dries's avatar
 
Dries committed
28
  $result = db_query("SELECT uid FROM {authmap} WHERE authname = '%s'", $authname);
Dries's avatar
 
Dries committed
29

30
  if ($user = db_fetch_array($result)) {
Dries's avatar
 
Dries committed
31
    return user_load($user);
Dries's avatar
 
Dries committed
32 33 34 35 36 37
  }
  else {
    return 0;
  }
}

Dries's avatar
Dries committed
38 39 40 41 42
/**
 * Fetch a user object.
 *
 * @param $array
 *   An associative array of attributes to search for in selecting the
43
 *   user, such as user name or e-mail address.
Dries's avatar
Dries committed
44 45
 *
 * @return
46
 *   A fully-loaded $user object upon successful user load or FALSE if user cannot be loaded.
Dries's avatar
Dries committed
47
 */
Dries's avatar
 
Dries committed
48
function user_load($array = array()) {
Dries's avatar
Dries committed
49
  // Dynamically compose a SQL query:
50
  $query = array();
51
  $params = array();
52

Dries's avatar
 
Dries committed
53
  foreach ($array as $key => $value) {
54 55
    if ($key == 'uid' || $key == 'status') {
      $query[] = "$key = %d";
56
      $params[] = $value;
57
    }
58 59 60 61
    else if ($key == 'pass') {
      $query[] = "pass = '%s'";
      $params[] = md5($value);
    }
Dries's avatar
 
Dries committed
62
    else {
63
      $query[]= "LOWER($key) = LOWER('%s')";
64
      $params[] = $value;
Dries's avatar
 
Dries committed
65 66
    }
  }
67
  $result = db_query('SELECT * FROM {users} u WHERE ' . implode(' AND ', $query), $params);
Dries's avatar
 
Dries committed
68

69 70 71
  if (db_num_rows($result)) {
    $user = db_fetch_object($result);
    $user = drupal_unpack($user);
Dries's avatar
 
Dries committed
72

73
    $user->roles = array();
74 75 76 77 78 79
    if ($user->uid) {
      $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
    }
    else {
      $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
    }
80 81 82 83
    $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);
    while ($role = db_fetch_object($result)) {
      $user->roles[$role->rid] = $role->name;
    }
84
    user_module_invoke('load', $array, $user);
85 86
  }
  else {
87
    $user = FALSE;
Dries's avatar
 
Dries committed
88
  }
Dries's avatar
 
Dries committed
89 90 91 92

  return $user;
}

93
/**
94
 * Save changes to a user account or add a new user.
95 96
 *
 * @param $account
97 98
 *   The $user object for the user to modify or add. If $user->uid is
 *   omitted, a new user will be added.
99 100 101
 *
 * @param $array
 *   An array of fields and values to save. For example array('name' => 'My name');
102
 *   Setting a field to NULL deletes it from the data column.
103 104 105 106
 *
 * @param $category
 *   (optional) The category for storing profile information in.
 */
107
function user_save($account, $array = array(), $category = 'account') {
Dries's avatar
Dries committed
108
  // Dynamically compose a SQL query:
Kjartan's avatar
Kjartan committed
109
  $user_fields = user_fields();
Dries's avatar
 
Dries committed
110
  if ($account->uid) {
111
    user_module_invoke('update', $array, $account, $category);
Dries's avatar
 
Dries committed
112

Dries's avatar
Dries committed
113
    $data = unserialize(db_result(db_query('SELECT data FROM {users} WHERE uid = %d', $account->uid)));
Dries's avatar
 
Dries committed
114
    foreach ($array as $key => $value) {
115
      if ($key == 'pass' && !empty($value)) {
Dries's avatar
 
Dries committed
116 117
        $query .= "$key = '%s', ";
        $v[] = md5($value);
Dries's avatar
 
Dries committed
118
      }
119
      else if ((substr($key, 0, 4) !== 'auth') && ($key != 'pass')) {
Kjartan's avatar
Kjartan committed
120
        if (in_array($key, $user_fields)) {
121
          // Save standard fields
Dries's avatar
 
Dries committed
122 123
          $query .= "$key = '%s', ";
          $v[] = $value;
Dries's avatar
 
Dries committed
124
        }
Dries's avatar
 
Dries committed
125
        else if ($key != 'roles') {
126
          // Roles is a special case: it used below.
127
          if ($value === NULL) {
128 129 130 131 132
            unset($data[$key]);
          }
          else {
            $data[$key] = $value;
          }
Dries's avatar
 
Dries committed
133
        }
Dries's avatar
 
Dries committed
134 135
      }
    }
136
    $query .= "data = '%s' ";
Dries's avatar
 
Dries committed
137
    $v[] = serialize($data);
Dries's avatar
 
Dries committed
138

139
    db_query("UPDATE {users} SET $query WHERE uid = %d", array_merge($v, array($account->uid)));
Dries's avatar
 
Dries committed
140

141
    // Reload user roles if provided
142
    if (is_array($array['roles'])) {
Dries's avatar
Dries committed
143
      db_query('DELETE FROM {users_roles} WHERE uid = %d', $account->uid);
Dries's avatar
 
Dries committed
144

145
      foreach (array_keys($array['roles']) as $rid) {
146 147 148
        if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
          db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $account->uid, $rid);
        }
149
      }
Dries's avatar
 
Dries committed
150 151
    }

152
    // Delete a blocked user's sessions to kick them if they are online.
153
    if (isset($array['status']) && $array['status'] == 0) {
154
      sess_destroy_uid($account->uid);
155 156
    }

157
    // Refresh user object
Dries's avatar
 
Dries committed
158
    $user = user_load(array('uid' => $account->uid));
159
    user_module_invoke('after_update', $array, $user, $category);
Dries's avatar
 
Dries committed
160 161
  }
  else {
Dries's avatar
Dries committed
162
    $array['uid'] = db_next_id('{users}_uid');
Dries's avatar
 
Dries committed
163

164 165 166 167
    if (!isset($array['created'])) {    // Allow 'created' to be set by hook_auth
      $array['created'] = time();
    }

168 169 170
    // Note, we wait with saving the data column to prevent module-handled
    // fields from being saved there. We cannot invoke hook_user('insert') here
    // because we don't have a fully initialized user object yet.
Dries's avatar
 
Dries committed
171
    foreach ($array as $key => $value) {
172 173 174 175
      switch($key) {
        case 'pass':
          $fields[] = $key;
          $values[] = md5($value);
Dries's avatar
 
Dries committed
176
          $s[] = "'%s'";
Dries's avatar
Dries committed
177
          break;
178 179 180 181 182 183 184 185 186 187 188 189 190 191
        case 'uid':        case 'mode':     case 'sort':
        case 'threshold':  case 'created':  case 'access':
        case 'login':      case 'status':
          $fields[] = $key;
          $values[] = $value;
          $s[] = "%d";
          break;
        default:
          if (substr($key, 0, 4) !== 'auth' && in_array($key, $user_fields)) {
            $fields[] = $key;
            $values[] = $value;
            $s[] = "'%s'";
          }
          break;
Dries's avatar
 
Dries committed
192 193
      }
    }
Dries's avatar
Dries committed
194
    db_query('INSERT INTO {users} ('. implode(', ', $fields) .') VALUES ('. implode(', ', $s) .')', $values);
Dries's avatar
 
Dries committed
195

196 197
    // Build the initial user object.
    $user = user_load(array('uid' => $array['uid']));
Dries's avatar
 
Dries committed
198

199 200 201 202 203
    user_module_invoke('insert', $array, $user, $category);

    // Build and save the serialized data field now
    $data = array();
    foreach ($array as $key => $value) {
204
      if ((substr($key, 0, 4) !== 'auth') && ($key != 'roles') && (!in_array($key, $user_fields)) && ($value !== NULL)) {
205 206 207 208 209
        $data[$key] = $value;
      }
    }
    db_query("UPDATE {users} SET data = '%s' WHERE uid = %d", serialize($data), $user->uid);

210
    // Save user roles (delete just to be safe).
211 212 213 214 215 216
    if (is_array($array['roles'])) {
      db_query('DELETE FROM {users_roles} WHERE uid = %d', $array['uid']);
      foreach (array_keys($array['roles']) as $rid) {
        if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
          db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $array['uid'], $rid);
        }
217 218 219
      }
    }

220 221
    // Build the finished user object.
    $user = user_load(array('uid' => $array['uid']));
Dries's avatar
 
Dries committed
222 223
  }

224
  // Save distributed authentication mappings
225
  $authmaps = array();
Dries's avatar
 
Dries committed
226
  foreach ($array as $key => $value) {
Dries's avatar
 
Dries committed
227
    if (substr($key, 0, 4) == 'auth') {
Dries's avatar
 
Dries committed
228 229 230
      $authmaps[$key] = $value;
    }
  }
231
  if (sizeof($authmaps) > 0) {
Dries's avatar
 
Dries committed
232
    user_set_authmaps($user, $authmaps);
Dries's avatar
 
Dries committed
233 234 235 236 237
  }

  return $user;
}

Dries's avatar
Dries committed
238 239 240
/**
 * Verify the syntax of the given name.
 */
Dries's avatar
 
Dries committed
241
function user_validate_name($name) {
242
  if (!strlen($name)) return t('You must enter a username.');
Dries's avatar
Dries committed
243 244 245
  if (substr($name, 0, 1) == ' ') return t('The username cannot begin with a space.');
  if (substr($name, -1) == ' ') return t('The username cannot end with a space.');
  if (ereg('  ', $name)) return t('The username cannot contain multiple spaces in a row.');
246
  if (ereg("[^\x80-\xF7 [:alnum:]@_.-]", $name)) return t('The username contains an illegal character.');
247 248 249 250 251 252 253
  if (preg_match('/[\x{80}-\x{A0}'.          // Non-printable ISO-8859-1 + NBSP
                   '\x{AD}'.                 // Soft-hyphen
                   '\x{2000}-\x{200F}'.      // Various space characters
                   '\x{2028}-\x{202F}'.      // Bidirectional text overrides
                   '\x{205F}-\x{206F}'.      // Various text hinting characters
                   '\x{FEFF}'.               // Byte order mark
                   '\x{FF01}-\x{FF60}'.      // Full-width latin
254 255
                   '\x{FFF9}-\x{FFFD}'.      // Replacement characters
                   '\x{0}]/u',               // NULL byte
256 257 258
                   $name)) {
    return t('The username contains an illegal character.');
  }
Dries's avatar
Dries committed
259
  if (ereg('@', $name) && !eregi('@([0-9a-z](-?[0-9a-z])*.)+[a-z]{2}([zmuvtg]|fo|me)?$', $name)) return t('The username is not a valid authentication ID.');
260
  if (strlen($name) > USERNAME_MAX_LENGTH) return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
Dries's avatar
 
Dries committed
261 262 263
}

function user_validate_mail($mail) {
Dries's avatar
Dries committed
264
  if (!$mail) return t('You must enter an e-mail address.');
265
  if (!valid_email_address($mail)) {
266
    return t('The e-mail address %mail is not valid.', array('%mail' => $mail));
Dries's avatar
 
Dries committed
267 268 269
  }
}

Dries's avatar
 
Dries committed
270
function user_validate_picture($file, &$edit, $user) {
271
  global $form_values;
Dries's avatar
Dries committed
272
  // Initialize the picture:
273
  $form_values['picture'] = $user->picture;
Dries's avatar
 
Dries committed
274

Dries's avatar
Dries committed
275 276
  // Check that uploaded file is an image, with a maximum file size
  // and maximum height/width.
277
  $info = image_get_info($file->filepath);
Dries's avatar
Dries committed
278
  list($maxwidth, $maxheight) = explode('x', variable_get('user_picture_dimensions', '85x85'));
Dries's avatar
 
Dries committed
279

280
  if (!$info || !$info['extension']) {
281
    form_set_error('picture_upload', t('The uploaded file was not an image.'));
Dries's avatar
 
Dries committed
282
  }
283 284
  else if (image_get_toolkit()) {
    image_scale($file->filepath, $file->filepath, $maxwidth, $maxheight);
Dries's avatar
 
Dries committed
285
  }
286
  else if (filesize($file->filepath) > (variable_get('user_picture_file_size', '30') * 1000)) {
287
    form_set_error('picture_upload', t('The uploaded image is too large; the maximum file size is %size kB.', array('%size' => variable_get('user_picture_file_size', '30'))));
288
  }
289
  else if ($info['width'] > $maxwidth || $info['height'] > $maxheight) {
290
    form_set_error('picture_upload', t('The uploaded image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => variable_get('user_picture_dimensions', '85x85'))));
Dries's avatar
 
Dries committed
291
  }
292 293

  if (!form_get_errors()) {
294
    if ($file = file_save_upload('picture_upload', variable_get('user_picture_path', 'pictures') .'/picture-'. $user->uid .'.'. $info['extension'], 1)) {
295
      $form_values['picture'] = $file->filepath;
296 297
    }
    else {
298
      form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist.", array('%directory' => variable_get('user_picture_path', 'pictures'))));
299
    }
Dries's avatar
 
Dries committed
300 301 302
  }
}

Dries's avatar
Dries committed
303 304 305
/**
 * Generate a random alphanumeric password.
 */
Dries's avatar
 
Dries committed
306 307
function user_password($length = 10) {
  // This variable contains the list of allowable characters for the
308 309
  // password. Note that the number 0 and the letter 'O' have been
  // removed to avoid confusion between the two. The same is true
310 311
  // of 'I', 1, and l.
  $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
Dries's avatar
Dries committed
312

313 314
  // Zero-based count of characters in the allowable list:
  $len = strlen($allowable_characters) - 1;
Dries's avatar
 
Dries committed
315

Dries's avatar
Dries committed
316 317
  // Declare the password as a blank string.
  $pass = '';
Dries's avatar
 
Dries committed
318

Dries's avatar
Dries committed
319
  // Loop the number of times specified by $length.
Dries's avatar
 
Dries committed
320 321 322 323
  for ($i = 0; $i < $length; $i++) {

    // Each iteration, pick a random character from the
    // allowable string and append it to the password:
324
    $pass .= $allowable_characters[mt_rand(0, $len)];
Dries's avatar
 
Dries committed
325 326 327
  }

  return $pass;
Dries's avatar
 
Dries committed
328 329
}

Dries's avatar
Dries committed
330 331 332 333 334
/**
 * Determine whether the user has a given privilege.
 *
 * @param $string
 *   The permission, such as "administer nodes", being checked for.
Dries's avatar
 
Dries committed
335 336
 * @param $account
 *   (optional) The account to check, if not given use currently logged in user.
Dries's avatar
Dries committed
337 338
 *
 * @return
339
 *   boolean TRUE if the current user has the requested permission.
Dries's avatar
Dries committed
340 341 342 343 344
 *
 * All permission checks in Drupal should go through this function. This
 * way, we guarantee consistent behavior, and ensure that the superuser
 * can perform all actions.
 */
Dries's avatar
 
Dries committed
345
function user_access($string, $account = NULL) {
Dries's avatar
 
Dries committed
346
  global $user;
Dries's avatar
 
Dries committed
347
  static $perm = array();
Dries's avatar
 
Dries committed
348

349 350 351 352
  if (is_null($account)) {
    $account = $user;
  }

353
  // User #1 has all privileges:
354
  if ($account->uid == 1) {
355
    return TRUE;
Dries's avatar
 
Dries committed
356 357
  }

Dries's avatar
Dries committed
358 359
  // To reduce the number of SQL queries, we cache the user's permissions
  // in a static variable.
360
  if (!isset($perm[$account->uid])) {
361
    $result = db_query("SELECT DISTINCT(p.perm) FROM {role} r INNER JOIN {permission} p ON p.rid = r.rid WHERE r.rid IN (%s)", implode(',', array_keys($account->roles)));
Dries's avatar
 
Dries committed
362

Steven Wittens's avatar
Steven Wittens committed
363
    $perm[$account->uid] = '';
Dries's avatar
 
Dries committed
364
    while ($row = db_fetch_object($result)) {
365
      $perm[$account->uid] .= "$row->perm, ";
Dries's avatar
 
Dries committed
366
    }
Dries's avatar
 
Dries committed
367
  }
368

369
  if (isset($perm[$account->uid])) {
370
    return strpos($perm[$account->uid], "$string, ") !== FALSE;
371
  }
372

373
  return FALSE;
Dries's avatar
 
Dries committed
374 375
}

376 377 378
/**
 * Checks for usernames blocked by user administration
 *
379
 * @return boolean TRUE for blocked users, FALSE for active
380 381
 */
function user_is_blocked($name) {
382
  $deny  = db_fetch_object(db_query("SELECT name FROM {users} WHERE status = 0 AND name = LOWER('%s')", $name));
383

384
  return $deny;
385 386
}

Dries's avatar
 
Dries committed
387 388
function user_fields() {
  static $fields;
Dries's avatar
 
Dries committed
389

Dries's avatar
 
Dries committed
390
  if (!$fields) {
Dries's avatar
Dries committed
391
    $result = db_query('SELECT * FROM {users} WHERE uid = 1');
Kjartan's avatar
Kjartan committed
392 393 394
    if (db_num_rows($result)) {
      $fields = array_keys(db_fetch_array($result));
    }
Dries's avatar
 
Dries committed
395 396
    else {
      // Make sure we return the default fields at least
397
      $fields = array('uid', 'name', 'pass', 'mail', 'picture', 'mode', 'sort', 'threshold', 'theme', 'signature', 'created', 'access', 'login', 'status', 'timezone', 'language', 'init', 'data');
Dries's avatar
 
Dries committed
398
    }
Dries's avatar
 
Dries committed
399
  }
Dries's avatar
 
Dries committed
400

Dries's avatar
 
Dries committed
401
  return $fields;
Dries's avatar
 
Dries committed
402 403
}

Dries's avatar
Dries committed
404 405 406
/**
 * Implementation of hook_perm().
 */
Dries's avatar
 
Dries committed
407
function user_perm() {
408
  return array('administer access control', 'administer users', 'access user profiles', 'change own username');
Dries's avatar
 
Dries committed
409 410
}

Dries's avatar
Dries committed
411 412 413 414 415
/**
 * Implementation of hook_file_download().
 *
 * Ensure that user pictures (avatars) are always downloadable.
 */
Dries's avatar
 
Dries committed
416
function user_file_download($file) {
Steven Wittens's avatar
Steven Wittens committed
417
  if (strpos($file, variable_get('user_picture_path', 'pictures') .'/picture-') === 0) {
418 419
    $info = image_get_info(file_create_path($file));
    return array('Content-type: '. $info['mime_type']);
Dries's avatar
 
Dries committed
420 421 422
  }
}

Dries's avatar
Dries committed
423 424 425
/**
 * Implementation of hook_search().
 */
426
function user_search($op = 'search', $keys = NULL) {
427 428
  switch ($op) {
    case 'name':
429
      if (user_access('access user profiles')) {
430
        return t('Users');
431
      }
432
    case 'search':
433 434 435 436 437 438
      if (user_access('access user profiles')) {
        $find = array();
        // Replace wildcards with MySQL/PostgreSQL wildcards.
        $keys = preg_replace('!\*+!', '%', $keys);
        $result = pager_query("SELECT * FROM {users} WHERE LOWER(name) LIKE LOWER('%%%s%%')", 15, 0, NULL, $keys);
        while ($account = db_fetch_object($result)) {
439
          $find[] = array('title' => $account->name, 'link' => url('user/'. $account->uid, NULL, NULL, TRUE));
440 441
        }
        return $find;
442
      }
Dries's avatar
 
Dries committed
443 444 445
  }
}

Dries's avatar
Dries committed
446 447 448
/**
 * Implementation of hook_user().
 */
449
function user_user($type, &$edit, &$user, $category = NULL) {
Dries's avatar
Dries committed
450
  if ($type == 'view') {
451
    $items['history'] = array('title' => t('Member for'),
452 453 454 455 456
      'value' => format_interval(time() - $user->created),
      'class' => 'member',
    );

    return array(t('History') => $items);
Dries's avatar
Dries committed
457
  }
458 459 460 461 462
  if ($type == 'form' && $category == 'account') {
    return user_edit_form(arg(1), $edit);
  }

  if ($type == 'validate' && $category == 'account') {
463
    return _user_edit_validate(arg(1), $edit);
464 465
  }

466 467 468 469
  if ($type == 'submit' && $category == 'account') {
    return _user_edit_submit(arg(1), $edit);
  }

470
  if ($type == 'categories') {
471
    return array(array('name' => 'account', 'title' => t('Account settings'), 'weight' => 1));
472
  }
Dries's avatar
Dries committed
473 474
}

475 476 477 478 479 480 481 482
function user_login_block() {
  $form = array(
    '#action' => url($_GET['q'], drupal_get_destination()),
    '#id' => 'user-login-form',
    '#base' => 'user_login',
  );
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Username'),
483
    '#maxlength' => USERNAME_MAX_LENGTH,
484 485 486 487 488
    '#size' => 15,
    '#required' => TRUE,
  );
  $form['pass'] = array('#type' => 'password',
    '#title' => t('Password'),
489
    '#maxlength' => 60,
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    '#size' => 15,
    '#required' => TRUE,
  );
  $form['submit'] = array('#type' => 'submit',
    '#value' => t('Log in'),
  );
  $items = array();
  if (variable_get('user_register', 1)) {
    $items[] = l(t('Create new account'), 'user/register', array('title' => t('Create a new user account.')));
  }
  $items[] = l(t('Request new password'), 'user/password', array('title' => t('Request new password via e-mail.')));
  $form['links'] = array('#value' => theme('item_list', $items));
  return $form;
}

Dries's avatar
Dries committed
505 506 507
/**
 * Implementation of hook_block().
 */
508
function user_block($op = 'list', $delta = 0, $edit = array()) {
Dries's avatar
 
Dries committed
509 510
  global $user;

Dries's avatar
Dries committed
511 512 513 514 515
  if ($op == 'list') {
     $blocks[0]['info'] = t('User login');
     $blocks[1]['info'] = t('Navigation');
     $blocks[2]['info'] = t('Who\'s new');
     $blocks[3]['info'] = t('Who\'s online');
516

517
     return $blocks;
518
  }
519 520 521 522 523 524 525 526 527
  else if ($op == 'configure' && $delta == 2) {
    $form['user_block_whois_new_count'] = array(
      '#type' => 'select',
      '#title' => t('Number of users to display'),
      '#default_value' => variable_get('user_block_whois_new_count', 5),
      '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
    );
    return $form;
  }
528 529
  else if ($op == 'configure' && $delta == 3) {
    $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800, 2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval');
530 531
    $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.'));
    $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.'));
532

533
    return $form;
534
  }
535 536 537
  else if ($op == 'save' && $delta == 2) {
    variable_set('user_block_whois_new_count', $edit['user_block_whois_new_count']);
  }
538 539 540 541 542
  else if ($op == 'save' && $delta == 3) {
    variable_set('user_block_seconds_online', $edit['user_block_seconds_online']);
    variable_set('user_block_max_list_count', $edit['user_block_max_list_count']);
  }
  else if ($op == 'view') {
Dries's avatar
 
Dries committed
543 544
    $block = array();

Dries's avatar
 
Dries committed
545 546
    switch ($delta) {
      case 0:
Dries's avatar
Dries committed
547 548
        // For usability's sake, avoid showing two login forms on one page.
        if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
Dries's avatar
 
Dries committed
549

Dries's avatar
Dries committed
550
          $block['subject'] = t('User login');
551
          $block['content'] = drupal_get_form('user_login_block');
Dries's avatar
 
Dries committed
552
        }
Dries's avatar
Dries committed
553
        return $block;
Dries's avatar
Dries committed
554

555
      case 1:
Dries's avatar
 
Dries committed
556
        if ($menu = theme('menu_tree')) {
Dries's avatar
Dries committed
557
           $block['subject'] = $user->uid ? check_plain($user->name) : t('Navigation');
558
           $block['content'] = $menu;
Dries's avatar
 
Dries committed
559
        }
560
        return $block;
Dries's avatar
Dries committed
561

Dries's avatar
 
Dries committed
562
      case 2:
563
        if (user_access('access content')) {
Steven Wittens's avatar
Steven Wittens committed
564
          // Retrieve a list of new users who have subsequently accessed the site successfully.
565
          $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));
566
          while ($account = db_fetch_object($result)) {
567
            $items[] = $account;
568
          }
Dries's avatar
Dries committed
569
          $output = theme('user_list', $items);
Dries's avatar
 
Dries committed
570

Dries's avatar
Dries committed
571 572
          $block['subject'] = t('Who\'s new');
          $block['content'] = $output;
573
        }
Dries's avatar
Dries committed
574 575
        return $block;

Dries's avatar
 
Dries committed
576
      case 3:
577
        if (user_access('access content')) {
Dries's avatar
Dries committed
578
          // Count users with activity in the past defined period.
579
          $interval = time() - variable_get('user_block_seconds_online', 900);
580

581 582 583 584 585
          // Perform database queries to gather online user lists.  We use s.timestamp
          // rather than u.access because it is much faster is much faster..
          $anonymous_count = sess_count($interval);
          $authenticated_users = db_query('SELECT u.uid, u.name 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);
          $authenticated_count = db_num_rows($authenticated_users);
Dries's avatar
 
Dries committed
586

Dries's avatar
Dries committed
587
          // Format the output with proper grammar.
588 589
          if ($anonymous_count == 1 && $authenticated_count == 1) {
            $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')));
Dries's avatar
 
Dries committed
590 591
          }
          else {
592
            $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')));
Dries's avatar
 
Dries committed
593 594
          }

595 596
          // Display a list of currently online users.
          $max_users = variable_get('user_block_max_list_count', 10);
597
          if ($authenticated_count && $max_users) {
598
            $items = array();
599

600
            while ($max_users-- && $account = db_fetch_object($authenticated_users)) {
601 602
              $items[] = $account;
            }
603

604 605
            $output .= theme('user_list', $items, t('Online users'));
          }
606

Dries's avatar
Dries committed
607 608
          $block['subject'] = t('Who\'s online');
          $block['content'] = $output;
Dries's avatar
 
Dries committed
609
        }
Dries's avatar
 
Dries committed
610
        return $block;
Dries's avatar
 
Dries committed
611 612
    }
  }
613 614
}

Dries's avatar
 
Dries committed
615 616 617 618 619 620 621 622 623
function theme_user_picture($account) {
  if (variable_get('user_pictures', 0)) {
    if ($account->picture && file_exists($account->picture)) {
      $picture = file_create_url($account->picture);
    }
    else if (variable_get('user_picture_default', '')) {
      $picture = variable_get('user_picture_default', '');
    }

624
    if (isset($picture)) {
625
      $alt = t("@user's picture", array('@user' => $account->name ? $account->name : variable_get('anonymous', t('Anonymous'))));
626
      $picture = theme('image', $picture, $alt, $alt, '', FALSE);
627
      if (!empty($account->uid) && user_access('access user profiles')) {
628
        $picture = l($picture, "user/$account->uid", array('title' => t('View user profile.')), NULL, NULL, FALSE, TRUE);
Dries's avatar
 
Dries committed
629 630 631 632 633 634 635
      }

      return "<div class=\"picture\">$picture</div>";
    }
  }
}

636 637 638
/**
 * Theme a user page
 * @param $account the user object
639 640 641 642 643
 * @param $fields a multidimensional array for the fields, in the form of array (
 *   'category1' => array(item_array1, item_array2), 'category2' => array(item_array3,
 *    .. etc.). Item arrays are formatted as array(array('title' => 'item title',
 * 'value' => 'item value', 'class' => 'class-name'), ... etc.). Module names are incorporated
 * into the CSS class.
644 645 646
 *
 * @ingroup themeable
 */
Dries's avatar
Dries committed
647
function theme_user_profile($account, $fields) {
648
  $output = '<div class="profile">';
Dries's avatar
 
Dries committed
649
  $output .= theme('user_picture', $account);
650
  foreach ($fields as $category => $items) {
651
    if (strlen($category) > 0) {
652
      $output .= '<h2 class="title">'. $category .'</h2>';
653
    }
654 655
    $output .= '<dl>';
    foreach ($items as $item) {
656
      if (isset($item['title'])) {
657
        $output .= '<dt class="'. $item['class'] .'">'. $item['title'] .'</dt>';
658 659
      }
      $output .= '<dd class="'. $item['class'] .'">'. $item['value'] .'</dd>';
660 661
    }
    $output .= '</dl>';
Dries's avatar
Dries committed
662
  }
663
  $output .= '</div>';
Dries's avatar
 
Dries committed
664 665 666 667

  return $output;
}

668 669 670 671 672 673 674
/**
 * Make a list of users.
 * @param $items an array with user objects. Should contain at least the name and uid
 *
 * @ingroup themeable
 */
function theme_user_list($users, $title = NULL) {
675 676 677 678
  if (!empty($users)) {
    foreach ($users as $user) {
      $items[] = theme('username', $user);
    }
679
  }
Dries's avatar
Dries committed
680
  return theme('item_list', $items, $title);
Dries's avatar
 
Dries committed
681 682
}

Dries's avatar
 
Dries committed
683
/**
Dries's avatar
 
Dries committed
684
 * Implementation of hook_menu().
Dries's avatar
 
Dries committed
685
 */
Dries's avatar
 
Dries committed
686
function user_menu($may_cache) {
Dries's avatar
 
Dries committed
687
  global $user;
Dries's avatar
 
Dries committed
688

Dries's avatar
 
Dries committed
689
  $items = array();
Dries's avatar
 
Dries committed
690

691
  $admin_access = user_access('administer users');
692
  $access_access = user_access('administer access control');
693
  $view_access = user_access('access user profiles');
Dries's avatar
 
Dries committed
694

Dries's avatar
 
Dries committed
695
  if ($may_cache) {
696
    $items[] = array('path' => 'user', 'title' => t('User account'),
697 698
      'callback' => 'drupal_get_form', 'callback arguments' => array('user_login'),
      'access' => !$user->uid, 'type' => MENU_CALLBACK);
699

700
    $items[] = array('path' => 'user/autocomplete', 'title' => t('User autocomplete'),
701
      'callback' => 'user_autocomplete', 'access' => $view_access, 'type' => MENU_CALLBACK);
Steven Wittens's avatar
Steven Wittens committed
702

Steven Wittens's avatar
Steven Wittens committed
703
    // Registration and login pages.
704
    $items[] = array('path' => 'user/login', 'title' => t('Log in'),
705 706
      'callback' => 'drupal_get_form', 'callback arguments' => array('user_login'),
      'access' => !$user->uid, 'type' => MENU_DEFAULT_LOCAL_TASK);
707
    $items[] = array('path' => 'user/register', 'title' => t('Create new account'),
708
      'callback' => 'drupal_get_form', 'callback arguments' => array('user_register'), 'access' => !$user->uid && variable_get('user_register', 1), 'type' => MENU_LOCAL_TASK);
709
    $items[] = array('path' => 'user/password', 'title' => t('Request new password'),
710
      'callback' => 'drupal_get_form', 'callback arguments' => array('user_pass'), 'access' => !$user->uid, 'type' => MENU_LOCAL_TASK);
711
    $items[] = array('path' => 'user/reset', 'title' => t('Reset password'),
712
      'callback' => 'drupal_get_form', 'callback arguments' => array('user_pass_reset'), 'access' => TRUE, 'type' => MENU_CALLBACK);
713
    $items[] = array('path' => 'user/help', 'title' => t('Help'),
Dries's avatar
 
Dries committed
714
      'callback' => 'user_help_page', 'type' => MENU_CALLBACK);
Dries's avatar
 
Dries committed
715

Steven Wittens's avatar
Steven Wittens committed
716
    // Admin user pages
717
    $items[] = array('path' => 'admin/user',
718
      'title' => t('User management'),
719 720 721
      'description' => t('Manage your site\'s users, groups and access to site features.'),
      'position' => 'left',
      'callback' => 'system_admin_menu_block_page',
722
      'access' => user_access('administer site configuration'),
723
    );
724
    $items[] = array('path' => 'admin/user/user', 'title' => t('Users'),
725
      'description' => t('List, add, and edit users.'),
726
      'callback' => 'user_admin', 'callback arguments' => array('list'), 'access' => $admin_access);
727
    $items[] = array('path' => 'admin/user/user/list', 'title' => t('List'),
Dries's avatar
 
Dries committed
728
      'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
729
    $items[] = array('path' => 'admin/user/user/create', 'title' => t('Add user'),
730
      'callback' => 'user_admin', 'callback arguments' => array('create'), 'access' => $admin_access,
Dries's avatar
 
Dries committed
731
      'type' => MENU_LOCAL_TASK);
732
    $items[] = array('path' => 'admin/user/settings', 'title' => t('User settings'),
733
      'description' => t('Configure default behavior of users, including registration requirements, e-mails, and user pictures.'),
734
      'callback' => 'drupal_get_form', 'callback arguments' => array('user_admin_settings'));
735

Steven Wittens's avatar
Steven Wittens committed
736
    // Admin access pages
737
    $items[] = array('path' => 'admin/user/access', 'title' => t('Access control'),
738
      'description' => t('Determine access to features by selecting permissions for roles.'),
739
      'callback' => 'drupal_get_form', 'callback arguments' => array('user_admin_perm'), 'access' => $access_access);
740
    $items[] = array('path' => 'admin/user/roles', 'title' => t('Roles'),
741
      'description' => t('List, edit, or add user roles.'),
742
      'callback' => 'drupal_get_form', 'callback arguments' => array('user_admin_new_role'), 'access' => $access_access,
743
      'type' => MENU_NORMAL_ITEM);
744
    $items[] = array('path' => 'admin/user/roles/edit', 'title' => t('Edit role'),
745
       'callback' => 'drupal_get_form', 'callback arguments' => array('user_admin_role'), 'access' => $access_access,
746
      'type' => MENU_CALLBACK);
747
    $items[] = array('path' => 'admin/user/rules', 'title' => t('Access rules'),
748 749
      'description' => t('List and create rules to disallow usernames, e-mail addresses, and IP addresses.'),
      'callback' => 'user_admin_access', 'access' => $access_access);
750
    $items[] = array('path' => 'admin/user/rules/list', 'title' => t('List'),
751
      'access' => $access_access, 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
752
    $items[] = array('path' => 'admin/user/rules/add', 'title' => t('Add rule'),
753
      'callback' => 'user_admin_access_add', 'access' => $access_access,
Dries's avatar
 
Dries committed
754
      'type' => MENU_LOCAL_TASK);
755
    $items[] = array('path' => 'admin/user/rules/check', 'title' => t('Check rules'),
756
      'callback' => 'user_admin_access_check', 'access' => $access_access,
Dries's avatar
 
Dries committed
757
      'type' => MENU_LOCAL_TASK);
758
    $items[] = array('path' => 'admin/user/rules/edit', 'title' => t('Edit rule'),
759
      'callback' => 'user_admin_access_edit', 'access' => $access_access,
760
      'type' => MENU_CALLBACK);
761
    $items[] = array('path' => 'admin/user/rules/delete', 'title' => t('Delete rule'),
762 763
      'callback' => 'drupal_get_form', 'callback arguments' => array('user_admin_access_delete_confirm'),
      'access' => $access_access, 'type' => MENU_CALLBACK);
764

765
    if (module_exists('search')) {
766
      $items[] = array('path' => 'admin/user/search', 'title' => t('Search users'),
767
        'description' => t('Search users by name.'),
768
        'callback' => 'user_admin', 'callback arguments' => array('search'), 'access' => $admin_access,
769
        'type' => MENU_NORMAL_ITEM);
770
    }
Dries's avatar
 
Dries committed
771

Steven Wittens's avatar
Steven Wittens committed
772