user.module 108 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
/**
 * Maximum length of username text field.
 */
12
define('USERNAME_MAX_LENGTH', 60);
13 14 15 16

/**
 * Maximum length of user e-mail text field.
 */
17 18
define('EMAIL_MAX_LENGTH', 64);

19

Dries's avatar
Dries committed
20 21 22
/**
 * Invokes hook_user() in every module.
 *
23
 * We cannot use module_invoke() for this, because the arguments need to
Dries's avatar
Dries committed
24 25
 * be passed by reference.
 */
26
function user_module_invoke($type, &$edit, $account, $category = NULL) {
27
  foreach (module_implements('user_' . $type) as $module) {
28
    $function = $module . '_user_' . $type;
29
    $function($edit, $account, $category);
Dries's avatar
 
Dries committed
30 31 32
  }
}

33
/**
34
 * Implement hook_theme().
35 36 37 38 39
 */
function user_theme() {
  return array(
    'user_picture' => array(
      'arguments' => array('account' => NULL),
40
      'template' => 'user-picture',
41 42
    ),
    'user_profile' => array(
43
      'arguments' => array('elements' => NULL),
44
      'template' => 'user-profile',
45
      'file' => 'user.pages.inc',
46 47 48
    ),
    'user_profile_category' => array(
      'arguments' => array('element' => NULL),
49
      'template' => 'user-profile-category',
50
      'file' => 'user.pages.inc',
51 52 53
    ),
    'user_profile_item' => array(
      'arguments' => array('element' => NULL),
54
      'template' => 'user-profile-item',
55
      'file' => 'user.pages.inc',
56 57 58 59
    ),
    'user_list' => array(
      'arguments' => array('users' => NULL, 'title' => NULL),
    ),
60
    'user_admin_permissions' => array(
61
      'arguments' => array('form' => NULL),
62
      'file' => 'user.admin.inc',
63 64 65
    ),
    'user_admin_new_role' => array(
      'arguments' => array('form' => NULL),
66
      'file' => 'user.admin.inc',
67 68 69
    ),
    'user_admin_account' => array(
      'arguments' => array('form' => NULL),
70
      'file' => 'user.admin.inc',
71 72 73
    ),
    'user_filter_form' => array(
      'arguments' => array('form' => NULL),
74
      'file' => 'user.admin.inc',
75 76 77
    ),
    'user_filters' => array(
      'arguments' => array('form' => NULL),
78
      'file' => 'user.admin.inc',
79
    ),
80 81 82
    'user_signature' => array(
      'arguments' => array('signature' => NULL),
    ),
83 84 85
  );
}

Dries's avatar
 
Dries committed
86
/**
87
 * Implement hook_entity_info().
Dries's avatar
 
Dries committed
88
 */
89
function user_entity_info() {
Dries's avatar
 
Dries committed
90 91
  $return = array(
    'user' => array(
92
      'label' => t('User'),
93 94 95
      'controller class' => 'UserController',
      'base table' => 'users',
      'fieldable' => TRUE,
96 97 98 99 100 101 102
      'object keys' => array(
        'id' => 'uid',
      ),
      'bundles' => array(
        'user' => array(
          'label' => t('User'),
          'admin' => array(
103
            'path' => 'admin/config/people/accounts',
104 105 106 107
            'access arguments' => array('administer users'),
          ),
        ),
      ),
Dries's avatar
 
Dries committed
108 109 110 111 112 113
    ),
  );
  return $return;
}

/**
114
 * Implement hook_field_build_modes().
Dries's avatar
 
Dries committed
115 116 117 118 119 120 121 122 123 124 125
 */
function user_field_build_modes($obj_type) {
  $modes = array();
  if ($obj_type == 'user') {
    $modes = array(
      'full' => t('User account'),
    );
  }
  return $modes;
}

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
/**
 * Implement hook_field_extra_fields().
 */
function user_field_extra_fields($bundle) {
  $extra = array();

  if ($bundle == 'user') {
    $extra['account'] = array(
      'label' => 'User name and password',
      'description' => t('User module account form elements'),
      'weight' => -10,
    );
    $extra['timezone'] = array(
      'label' => 'Timezone',
      'description' => t('User module timezone form element.'),
      'weight' => 6,
    );
    $extra['summary'] = array(
      'label' => 'History',
      'description' => t('User module history view element.'),
      'weight' => 5,
    );
  }

  return $extra;
}

Dries's avatar
 
Dries committed
153
function user_external_load($authname) {
154
  $uid = db_query("SELECT uid FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchField();
Dries's avatar
 
Dries committed
155

156 157
  if ($uid) {
    return user_load($uid);
Dries's avatar
 
Dries committed
158 159
  }
  else {
160
    return FALSE;
Dries's avatar
 
Dries committed
161 162 163
  }
}

Dries's avatar
Dries committed
164
/**
165
 * Load multiple users based on certain conditions.
Dries's avatar
Dries committed
166
 *
167 168 169
 * This function should be used whenever you need to load more than one user
 * from the database. Users are loaded into memory and will not require
 * database access if loaded again during the same page request.
Dries's avatar
Dries committed
170
 *
171 172 173 174 175 176 177 178
 * @param $uids
 *   An array of user IDs.
 * @param $conditions
 *   An array of conditions to match against the {users} table. These
 *   should be supplied in the form array('field_name' => 'field_value').
 * @param $reset
 *   A boolean indicating that the internal cache should be reset. Use this if
 *   loading a user object which has been altered during the page request.
179
 * @return
180 181
 *   An array of user objects, indexed by uid.
 *
182
 * @see entity_load()
183 184 185
 * @see user_load()
 * @see user_load_by_mail()
 * @see user_load_by_name()
Dries's avatar
Dries committed
186
 */
187
function user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) {
188 189
  return entity_load('user', $uids, $conditions, $reset);
}
190

191 192 193 194 195 196 197 198
/**
 * Controller class for users.
 *
 * This extends the DrupalDefaultEntityController class, adding required
 * special handling for user objects.
 */
class UserController extends DrupalDefaultEntityController {
  function attachLoad(&$queried_users) {
199 200
    // Build an array of user picture IDs so that these can be fetched later.
    $picture_fids = array();
201
    foreach ($queried_users as $key => $record) {
202
      $picture_fids[] = $record->picture;
203 204
      $queried_users[$key] = drupal_unpack($record);
      $queried_users[$key]->roles = array();
205 206 207 208 209 210
      if ($record->uid) {
        $queried_users[$record->uid]->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
      }
      else {
        $queried_users[$record->uid]->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
      }
211
    }
212

213 214 215 216 217
    // Add any additional roles from the database.
    $result = db_query('SELECT r.rid, r.name, ur.uid FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid IN (:uids)', array(':uids' => array_keys($queried_users)));
    foreach ($result as $record) {
      $queried_users[$record->uid]->roles[$record->rid] = $record->name;
    }
Dries's avatar
 
Dries committed
218

219 220 221 222 223 224 225 226 227
    // Add the full file objects for user pictures if enabled.
    if (!empty($picture_fids) && variable_get('user_pictures', 1) == 1) {
      $pictures = file_load_multiple($picture_fids);
      foreach ($queried_users as $account) {
        if (!empty($account->picture) && isset($pictures[$account->picture])) {
          $account->picture = $pictures[$account->picture];
        }
        else {
          $account->picture = NULL;
228 229 230
        }
      }
    }
231 232 233
    // Call the default attachLoad() method. This will add fields and call
    // hook_user_load().
    parent::attachLoad($queried_users);
Dries's avatar
 
Dries committed
234
  }
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
}

/**
 * Fetch a user object.
 *
 * @param $uid
 *   Integer specifying the user id.
 * @param $reset
 *   A boolean indicating that the internal cache should be reset.
 * @return
 *   A fully-loaded $user object upon successful user load or FALSE if user
 *   cannot be loaded.
 *
 * @see user_load_multiple()
 */
function user_load($uid, $reset = FALSE) {
  $users = user_load_multiple(array($uid), array(), $reset);
  return reset($users);
}

/**
 * Fetch a user object by email address.
 *
 * @param $mail
 *   String with the account's e-mail address.
 * @return
 *   A fully-loaded $user object upon successful user load or FALSE if user
 *   cannot be loaded.
 *
 * @see user_load_multiple()
 */
function user_load_by_mail($mail) {
  $users = user_load_multiple(array(), array('mail' => $mail));
  return reset($users);
}

/**
 * Fetch a user object by account name.
 *
 * @param $name
 *   String with the account's user name.
 * @return
 *   A fully-loaded $user object upon successful user load or FALSE if user
 *   cannot be loaded.
 *
 * @see user_load_multiple()
 */
function user_load_by_name($name) {
  $users = user_load_multiple(array(), array('name' => $name));
  return reset($users);
Dries's avatar
 
Dries committed
285 286
}

287
/**
288
 * Save changes to a user account or add a new user.
289 290
 *
 * @param $account
291
 *   (optional) The user object to modify or add. If you want to modify
292 293
 *   an existing user account, you will need to ensure that (a) $account
 *   is an object, and (b) you have set $account->uid to the numeric
294 295
 *   user ID of the user account you wish to modify. If you
 *   want to create a new user account, you can set $account->is_new to
296
 *   TRUE or omit the $account->uid field.
297
 * @param $edit
298
 *   An array of fields and values to save. For example array('name'
299
 *   => 'My name'). Keys that do not belong to columns in the user-related
300 301
 *   tables are added to the a serialized array in the 'data' column
 *   and will be loaded in the $user->data array by user_load().
302 303
 *   Setting a field to NULL deletes it from the data column, if you are
 *   modifying an existing user account.
304 305
 * @param $category
 *   (optional) The category for storing profile information in.
306 307
 *
 * @return
308
 *   A fully-loaded $user object upon successful save or FALSE if the save failed.
309
 */
310
function user_save($account, $edit = array(), $category = 'account') {
311
  $table = drupal_get_schema('users');
312 313
  $user_fields = $table['fields'];

314
  if (!empty($edit['pass'])) {
315
    // Allow alternate password hashing schemes.
316
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
317
    $edit['pass'] = user_hash_password(trim($edit['pass']));
318
    // Abort if the hashing failed and returned FALSE.
319
    if (!$edit['pass']) {
320 321
      return FALSE;
    }
322 323 324
  }
  else {
    // Avoid overwriting an existing password with a blank password.
325
    unset($edit['pass']);
326 327
  }

Dries's avatar
 
Dries committed
328 329 330 331 332 333 334 335 336 337 338 339
  // Get the fields form so we can recognize the fields in the $edit
  // form that should not go into the serialized data array.
  $field_form = array();
  $field_form_state = array();
  $edit = (object) $edit;
  field_attach_form('user', $edit, $field_form, $field_form_state);

  // Presave fields.
  field_attach_presave('user', $edit);

  $edit = (array) $edit;

340
  if (!isset($account->is_new)) {
341
    $account->is_new = empty($account->uid);
342 343
  }
  if (is_object($account) && !$account->is_new) {
344
    user_module_invoke('update', $edit, $account, $category);
345
    $data = unserialize(db_query('SELECT data FROM {users} WHERE uid = :uid', array(':uid' => $account->uid))->fetchField());
346 347
    // Consider users edited by an administrator as logged in, if they haven't
    // already, so anonymous users can view the profile (if allowed).
348
    if (empty($edit['access']) && empty($account->access) && user_access('administer users')) {
349
      $edit['access'] = REQUEST_TIME;
350
    }
351
    foreach ($edit as $key => $value) {
Dries's avatar
 
Dries committed
352
      // Form fields that don't pertain to the users, user_roles, or
353
      // Field API are automatically serialized into the users.data
Dries's avatar
 
Dries committed
354
      // column.
355
      if (!in_array($key, array('roles', 'is_new')) && empty($user_fields[$key]) && empty($field_form[$key])) {
356 357
        if ($value === NULL) {
          unset($data[$key]);
Dries's avatar
 
Dries committed
358
        }
359 360
        else {
          $data[$key] = $value;
Dries's avatar
 
Dries committed
361
        }
Dries's avatar
 
Dries committed
362 363 364
      }
    }

365 366 367 368 369 370
    // Process picture uploads.
    if (!empty($edit['picture']->fid)) {
      $picture = $edit['picture'];
      // If the picture is a temporary file move it to its final location and
      // make it permanent.
      if (($picture->status & FILE_STATUS_PERMANENT) == 0) {
371 372
        $info = image_get_info($picture->uri);
        $picture_directory =  variable_get('file_default_scheme', 'public') . '://' . variable_get('user_picture_path', 'pictures');
373

374 375 376 377
        // Prepare the pictures directory.
        file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY);
        $destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '.' . $info['extension']);

378 379 380 381 382 383 384 385
        if ($picture = file_move($picture, $destination, FILE_EXISTS_REPLACE)) {
          $picture->status |= FILE_STATUS_PERMANENT;
          $edit['picture'] = file_save($picture);
        }
      }
    }
    $edit['picture'] = empty($edit['picture']->fid) ? 0 : $edit['picture']->fid;

386
    $edit['data'] = $data;
387
    // Do not allow 'uid' to be changed.
388
    $edit['uid'] = $account->uid;
389
    // Save changes to the user table.
390
    $success = drupal_write_record('users', $edit, 'uid');
391
    if (!$success) {
Dries's avatar
 
Dries committed
392 393 394 395
      // The query failed - better to abort the save than risk further
      // data loss.

      // TODO: Fields change: I think this is a bug.  If no columns in
396
      // the user table are changed, drupal_write_record returns
Dries's avatar
 
Dries committed
397
      // FALSE because rowCount() (rows changed) is 0.  However,
398
      // non-users data may have been changed, e.g. fields.
Dries's avatar
 
Dries committed
399
      // return FALSE;
400
    }
Dries's avatar
 
Dries committed
401

402
    // If the picture changed or was unset, remove the old one. This step needs
403
    // to occur after updating the {users} record so that user_file_references()
404 405 406 407 408
    // doesn't report it in use and block the deletion.
    if (!empty($account->picture->fid) && ($edit['picture'] != $account->picture->fid)) {
      file_delete($account->picture);
    }

409
    // Reload user roles if provided.
410
    if (isset($edit['roles']) && is_array($edit['roles'])) {
411 412 413
      db_delete('users_roles')
        ->condition('uid', $account->uid)
        ->execute();
Dries's avatar
 
Dries committed
414

415
      $query = db_insert('users_roles')->fields(array('uid', 'rid'));
416
      foreach (array_keys($edit['roles']) as $rid) {
417
        if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
418 419 420 421
          $query->values(array(
            'uid' => $account->uid,
            'rid' => $rid,
          ));
422
        }
423
      }
424
      $query->execute();
Dries's avatar
 
Dries committed
425 426
    }

427
    // Delete a blocked user's sessions to kick them if they are online.
428
    if (isset($edit['status']) && $edit['status'] == 0) {
429
      drupal_session_destroy_uid($account->uid);
430 431
    }

432 433
    // If the password changed, delete all open sessions and recreate
    // the current one.
434
    if (!empty($edit['pass'])) {
435
      drupal_session_destroy_uid($account->uid);
436 437 438
      if ($account->uid == $GLOBALS['user']->uid) {
        drupal_session_regenerate();
      }
439 440
    }

Dries's avatar
 
Dries committed
441
    // Save Field data.
442 443
    $object = (object) $edit;
    field_attach_update('user', $object);
Dries's avatar
 
Dries committed
444

445
    // Refresh user object.
446
    $user = user_load($account->uid, TRUE);
447 448

    // Send emails after we have the new user object.
449
    if (isset($edit['status']) && $edit['status'] != $account->status) {
450
      // The user's status is changing; conditionally send notification email.
451
      $op = $edit['status'] == 1 ? 'status_activated' : 'status_blocked';
452 453 454
      _user_mail_notify($op, $user);
    }

455
    user_module_invoke('after_update', $edit, $user, $category);
Dries's avatar
 
Dries committed
456 457
  }
  else {
458
    // Allow 'created' to be set by the caller.
459
    if (!isset($edit['created'])) {
460
      $edit['created'] = REQUEST_TIME;
461
    }
462 463
    // Consider users created by an administrator as already logged in, so
    // anonymous users can view the profile (if allowed).
464
    if (empty($edit['access']) && user_access('administer users')) {
465
      $edit['access'] = REQUEST_TIME;
466
    }
467

468
    $edit['mail'] = trim($edit['mail']);
469
    $success = drupal_write_record('users', $edit);
470 471 472 473 474
    if (!$success) {
      // On a failed INSERT some other existing user's uid may be returned.
      // We must abort to avoid overwriting their account.
      return FALSE;
    }
475

476
    // Build the initial user object.
477
    $user = user_load($edit['uid'], TRUE);
Dries's avatar
 
Dries committed
478

479 480
    $object = (object) $edit;
    field_attach_insert('user', $object);
Dries's avatar
 
Dries committed
481

482
    user_module_invoke('insert', $edit, $user, $category);
483

484 485
    // Note, we wait with saving the data column to prevent module-handled
    // fields from being saved there.
486
    $data = array();
487
    foreach ($edit as $key => $value) {
488
      // Form fields that don't pertain to the users, user_roles, or
489
      // Field API are automatically serialized into the user.data
Dries's avatar
 
Dries committed
490
      // column.
491
      if ((!in_array($key, array('roles', 'is_new'))) && (empty($user_fields[$key]) && empty($field_form[$key])) && ($value !== NULL)) {
492 493 494
        $data[$key] = $value;
      }
    }
495 496
    if (!empty($data)) {
      $data_array = array('uid' => $user->uid, 'data' => $data);
497
      drupal_write_record('users', $data_array, 'uid');
498
    }
499

500
    // Save user roles (delete just to be safe).
501
    if (isset($edit['roles']) && is_array($edit['roles'])) {
502 503 504 505
      db_delete('users_roles')
        ->condition('uid', $edit['uid'])
        ->execute();
      $query = db_insert('users_roles')->fields(array('uid', 'rid'));
506
      foreach (array_keys($edit['roles']) as $rid) {
507
        if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
508 509 510 511
          $query->values(array(
            'uid' => $edit['uid'],
            'rid' => $rid,
          ));
512
        }
513
      }
514
      $query->execute();
515 516
    }

517
    // Build the finished user object.
518
    $user = user_load($edit['uid'], TRUE);
Dries's avatar
 
Dries committed
519 520 521 522 523
  }

  return $user;
}

Dries's avatar
Dries committed
524 525 526
/**
 * Verify the syntax of the given name.
 */
Dries's avatar
 
Dries committed
527
function user_validate_name($name) {
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
  if (!$name) {
    return t('You must enter a username.');
  }
  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 (strpos($name, '  ') !== FALSE) {
    return t('The username cannot contain multiple spaces in a row.');
  }
  if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i', $name)) {
    return t('The username contains an illegal character.');
  }
543
  if (preg_match('/[\x{80}-\x{A0}' .         // Non-printable ISO-8859-1 + NBSP
544 545 546 547 548 549 550 551 552
                  '\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
                  '\x{FFF9}-\x{FFFD}' .     // Replacement characters
                  '\x{0}-\x{1F}]/u',        // NULL byte and control characters
                  $name)) {
553 554
    return t('The username contains an illegal character.');
  }
555 556 557
  if (drupal_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
558 559 560
}

function user_validate_mail($mail) {
561
  $mail = trim($mail);
562 563 564
  if (!$mail) {
    return t('You must enter an e-mail address.');
  }
565
  if (!valid_email_address($mail)) {
566
    return t('The e-mail address %mail is not valid.', array('%mail' => $mail));
Dries's avatar
 
Dries committed
567 568 569
  }
}

570
function user_validate_picture(&$form, &$form_state) {
571
  // If required, validate the uploaded picture.
572 573 574 575 576
  $validators = array(
    'file_validate_is_image' => array(),
    'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
    'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
  );
577

578 579 580 581 582 583 584
  // Save the file as a temporary file.
  $file = file_save_upload('picture_upload', $validators);
  if ($file === FALSE) {
    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'))));
  }
  elseif ($file !== NULL) {
    $form_state['values']['picture_upload'] = $file;
Dries's avatar
 
Dries committed
585 586 587
  }
}

Dries's avatar
Dries committed
588 589 590
/**
 * Generate a random alphanumeric password.
 */
Dries's avatar
 
Dries committed
591 592
function user_password($length = 10) {
  // This variable contains the list of allowable characters for the
593 594
  // password. Note that the number 0 and the letter 'O' have been
  // removed to avoid confusion between the two. The same is true
595
  // of 'I', 1, and 'l'.
596
  $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
Dries's avatar
Dries committed
597

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

Dries's avatar
Dries committed
601 602
  // Declare the password as a blank string.
  $pass = '';
Dries's avatar
 
Dries committed
603

Dries's avatar
Dries committed
604
  // Loop the number of times specified by $length.
Dries's avatar
 
Dries committed
605 606 607 608
  for ($i = 0; $i < $length; $i++) {

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

  return $pass;
Dries's avatar
 
Dries committed
613 614
}

615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
/**
 * Determine the permissions for one or more roles.
 *
 * @param $roles
 *   An array whose keys are the role IDs of interest, such as $user->roles.
 * @param $reset
 *   Optional parameter - if TRUE data in the static variable is rebuilt.
 *
 * @return
 *   An array indexed by role ID. Each value is an array whose keys are the
 *   permission strings for the given role ID.
 */
function user_role_permissions($roles = array(), $reset = FALSE) {
  static $stored_permissions = array();

  if ($reset) {
    // Clear the data cached in the static variable.
    $stored_permissions = array();
  }

  $role_permissions = $fetch = array();

  if ($roles) {
    foreach ($roles as $rid => $name) {
      if (isset($stored_permissions[$rid])) {
        $role_permissions[$rid] = $stored_permissions[$rid];
      }
      else {
        // Add this rid to the list of those needing to be fetched.
        $fetch[] = $rid;
        // Prepare in case no permissions are returned.
        $stored_permissions[$rid] = array();
      }
    }

    if ($fetch) {
      // Get from the database permissions that were not in the static variable.
      // Only role IDs with at least one permission assigned will return rows.
653
      $result = db_query("SELECT rid, permission FROM {role_permission} WHERE rid IN (:fetch)", array(':fetch' => $fetch));
654

655 656
      foreach ($result as $row) {
        $stored_permissions[$row->rid][$row->permission] = TRUE;
657 658 659 660 661 662 663 664 665 666 667
      }
      foreach ($fetch as $rid) {
        // For every rid, we know we at least assigned an empty array.
        $role_permissions[$rid] = $stored_permissions[$rid];
      }
    }
  }

  return $role_permissions;
}

Dries's avatar
Dries committed
668 669 670 671 672
/**
 * Determine whether the user has a given privilege.
 *
 * @param $string
 *   The permission, such as "administer nodes", being checked for.
Dries's avatar
 
Dries committed
673 674
 * @param $account
 *   (optional) The account to check, if not given use currently logged in user.
675 676 677 678
 * @param $reset
 *   (optional) Resets the user's permissions cache, which will result in a
 *   recalculation of the user's permissions. This is necessary to support
 *   dynamically added user roles.
Dries's avatar
Dries committed
679 680
 *
 * @return
681
 *   Boolean TRUE if the current user has the requested permission.
Dries's avatar
Dries committed
682 683 684 685 686
 *
 * 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.
 */
687
function user_access($string, $account = NULL, $reset = FALSE) {
Dries's avatar
 
Dries committed
688
  global $user;
Dries's avatar
 
Dries committed
689
  static $perm = array();
Dries's avatar
 
Dries committed
690

691
  if ($reset) {
692
    $perm = array();
693 694
  }

695
  if (!isset($account)) {
696 697 698
    $account = $user;
  }

699
  // User #1 has all privileges:
700
  if ($account->uid == 1) {
701
    return TRUE;
Dries's avatar
 
Dries committed
702 703
  }

Dries's avatar
Dries committed
704 705
  // To reduce the number of SQL queries, we cache the user's permissions
  // in a static variable.
706
  if (!isset($perm[$account->uid])) {
707
    $role_permissions = user_role_permissions($account->roles, $reset);
Dries's avatar
 
Dries committed
708

709
    $perms = array();
710 711
    foreach ($role_permissions as $one_role) {
      $perms += $one_role;
Dries's avatar
 
Dries committed
712
    }
713
    $perm[$account->uid] = $perms;
Dries's avatar
 
Dries committed
714
  }
715

716
  return isset($perm[$account->uid][$string]);
Dries's avatar
 
Dries committed
717 718
}

719
/**
720
 * Checks for usernames blocked by user administration.
721
 *
722
 * @return boolean TRUE for blocked users, FALSE for active.
723 724
 */
function user_is_blocked($name) {
725
  $deny = db_query("SELECT name FROM {users} WHERE status = 0 AND name = LOWER(:name)", array(':name' => $name))->fetchObject();
726

727
  return $deny;
728 729
}

Dries's avatar
Dries committed
730
/**
731
 * Implement hook_permission().
Dries's avatar
Dries committed
732
 */
733
function user_permission() {
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
  return array(
    'administer permissions' =>  array(
      'title' => t('Administer permissions'),
      'description' => t('Manage the permissions assigned to user roles. %warning', array('%warning' => t('Warning: Give to trusted roles only; this permission has security implications.'))),
    ),
    'administer users' => array(
      'title' => t('Administer users'),
      'description' => t('Manage or block users, and manage their role assignments.'),
    ),
    'access user profiles' => array(
      'title' => t('Access user profiles'),
      'description' => t('View profiles of users on the site, which may contain personal information.'),
    ),
    'change own username' => array(
      'title' => t('Change own username'),
      'description' => t('Select a different username.'),
    ),
    'cancel account' => array(
      'title' => t('Cancel account'),
753
      'description' => t('Remove or disable own user account and unpublish, anonymize, or remove own submissions depending on the configured <a href="@user-settings-url">user settings</a>.', array('@user-settings-url' => url('admin/config/people/accounts'))),
754 755 756 757 758 759
    ),
    'select account cancellation method' => array(
      'title' => t('Select method for cancelling own account'),
      'description' => t('Select the method for cancelling own user account. %warning', array('%warning' => t('Warning: Give to trusted roles only; this permission has security implications.'))),
    ),
  );
Dries's avatar
 
Dries committed
760 761
}

Dries's avatar
Dries committed
762
/**
763
 * Implement hook_file_download().
Dries's avatar
Dries committed
764 765 766
 *
 * Ensure that user pictures (avatars) are always downloadable.
 */
767
function user_file_download($filepath) {
768 769
  if (strpos(file_uri_target($filepath), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) {
    $info = image_get_info($filepath);
770
    return array('Content-Type' => $info['mime_type']);
Dries's avatar
 
Dries committed
771 772 773
  }
}

774
/**
775
 * Implement hook_file_references().
776 777 778
 */
function user_file_references($file) {
  // Determine if the file is used by this module.
779 780
  $file_used = (bool) db_query_range('SELECT 1 FROM {users} WHERE picture = :fid', array(':fid' => $file->fid), 0, 1)->fetchField();
  if ($file_used) {
781 782 783 784 785 786
    // Return the name of the module and how many references it has to the file.
    return array('user' => $count);
  }
}

/**
787
 * Implement hook_file_delete().
788 789 790
 */
function user_file_delete($file) {
  // Remove any references to the file.
791
  db_update('users')
792 793 794 795 796
    ->fields(array('picture' => 0))
    ->condition('picture', $file->fid)
    ->execute();
}

Dries's avatar
Dries committed
797
/**
798
 * Implement hook_search().
Dries's avatar
Dries committed
799
 */
800
function user_search($op = 'search', $keys = NULL, $skip_access_check = FALSE) {
801 802
  switch ($op) {
    case 'name':
803
      if ($skip_access_check || user_access('access user profiles')) {
804
        return t('Users');
805
      }
806
    case 'search':
807 808 809 810
      if (user_access('access user profiles')) {
        $find = array();
        // Replace wildcards with MySQL/PostgreSQL wildcards.
        $keys = preg_replace('!\*+!', '%', $keys);
811
        $query = db_select('users')->extend('PagerDefault');
812
        $query->fields('users', array('name', 'uid', 'mail'));
813 814
        if (user_access('administer users')) {
          // Administrators can also search in the otherwise private email field.
815
          $query->condition(db_or()->
816 817
            where('LOWER(name) LIKE LOWER(:name)', array(':name' => "%$keys%"))->
            where('LOWER(mail) LIKE LOWER(:mail)', array(':mail' => "%$keys%")));
818 819
        }
        else {
820 821
          $query->where('LOWER(name) LIKE LOWER(:name)', array(':name' => "%$keys%"));
        }
822 823 824
        $result = $query
          ->limit(15)
          ->execute();
825 826
        foreach ($result as $account) {
          $find[] = array('title' => $account->name . ' (' . $account->mail . ')', 'link' => url('user/' . $account->uid, array('absolute' => TRUE)));
827 828
        }
        return $find;
829
      }
Dries's avatar
 
Dries committed
830 831 832
  }
}

Dries's avatar
Dries committed
833
/**
834
 * Implement hook_elements().
Dries's avatar
Dries committed
835 836 837
 */
function user_elements() {
  return array(
838
    'user_profile_category' => array(
839
      '#theme_wrappers' => array('user_profile_category')
840 841 842 843
    ),
    'user_profile_item' => array(
      '#theme' => 'user_profile_item'
    ),
Dries's avatar
Dries committed
844 845 846
  );
}

Dries's avatar
Dries committed
847
/**
848
 * Implement hook_user_view().
Dries's avatar
Dries committed
849
 */
850
function user_user_view($account) {
851
  $account->content['user_picture'] = array(
852
    '#markup' => theme('user_picture', $account),
853 854 855 856 857 858 859
    '#weight' => -10,
  );
  if (!isset($account->content['summary'])) {
    $account->content['summary'] = array();
  }
  $account->content['summary'] += array(
    '#type' => 'user_profile_category',
860
    '#attributes' => array('class' => array('user-member')),
861 862 863
    '#weight' => 5,
    '#title' => t('History'),
  );
864
  $account->content['summary']['member_for'] = array(
865 866 867 868 869 870 871
    '#type' => 'user_profile_item',
    '#title' => t('Member for'),
    '#markup' => format_interval(REQUEST_TIME - $account->created),
  );
}

/**
872
 * Implement hook_user_form.
873
 */
874
function user_user_form(&$edit, $account, $category) {
875
  if ($category == 'account') {
876
    $form_state = array();
877
    return user_edit_form($form_state, (isset($account->uid) ? $account->uid : FALSE), $edit);
878
  }
879
}
880

881
/**
882
 * Implement hook_user_validate().
883
 */
884
function user_user_validate(&$edit, $account, $category) {
885
  if ($category == 'account') {
886 887 888 889 890 891
    $uid = isset($account->uid) ? $account->uid : FALSE;
    // Validate the username when: new user account; or user is editing own account and can change username; or an admin user.
    if (!$uid || ($GLOBALS['user']->uid == $uid && user_access('change own username')) || user_access('administer users')) {
      if ($error = user_validate_name($edit['name'])) {
        form_set_error('name', $error);
      }
892
      elseif ((bool) db_query_range("SELECT 1 FROM {users} WHERE uid <> :uid AND LOWER(name) = LOWER(:name)", array(':uid' => $uid, ':name' => $edit['name']), 0, 1)->fetchField()) {
893 894 895 896
        form_set_error('name', t('The name %name is already taken.', array('%name' => $edit['name'])));
      }
    }

897
    // Validate the e-mail address, and check if it is taken by an existing user.
898 899 900
    if ($error = user_validate_mail($edit['mail'])) {
      form_set_error('mail', $error);
    }
901
    elseif ((bool) db_query_range("SELECT 1 FROM {users} WHERE uid <> :uid AND LOWER(mail) = LOWER(:mail)", array(':uid' => $uid, ':mail' => $edit['mail']), 0, 1)->fetchField()) {
902 903 904 905 906 907 908
      // Format error message dependent on whether the user is logged in or not.
      if ($GLOBALS['user']->uid) {
        form_set_error('mail', t('The e-mail address %email is already taken.', array('%email' => $edit['mail'])));
      }
      else {
        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'))));
      }
909
    }
910 911 912 913 914 915 916 917 918

    // Make sure the signature isn't longer than the size of the database field.
    // Signatures are disabled by default, so make sure it exists first.
    if (isset($edit['signature'])) {
      $user_schema = drupal_get_schema('users');
      if (strlen($edit['signature']) > $user_schema['fields']['signature']['length']) {
        form_set_error('signature', t('The signature is too long: it must be %max characters or less.', array('%max' => $user_schema['fields']['signature']['length'])));
      }
    }
919
  }
920
}
921

922
/**
923
 * Implement hook_user_submit().
924
 */
925
function user_user_submit(&$edit, $account, $category) {
926
  if ($category == 'account') {
927 928 929
    if (!empty($edit['picture_upload'])) {
      $edit['picture'] = $edit['picture_upload'];
    }
930
    // Delete picture if requested, and if no replacement picture was given.
931 932
    elseif (!empty($edit['picture_delete'])) {
      $edit['picture'] = NULL;
933
    }