Projet

Général

Profil

Paste
Télécharger (141 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / user / user.module @ 30d5b9c5

1
<?php
2

    
3
/**
4
 * @file
5
 * Enables the user registration and login system.
6
 */
7

    
8
/**
9
 * Maximum length of username text field.
10
 */
11
define('USERNAME_MAX_LENGTH', 60);
12

    
13
/**
14
 * Maximum length of user e-mail text field.
15
 */
16
define('EMAIL_MAX_LENGTH', 254);
17

    
18
/**
19
 * Only administrators can create user accounts.
20
 */
21
define('USER_REGISTER_ADMINISTRATORS_ONLY', 0);
22

    
23
/**
24
 * Visitors can create their own accounts.
25
 */
26
define('USER_REGISTER_VISITORS', 1);
27

    
28
/**
29
 * Visitors can create accounts, but they don't become active without
30
 * administrative approval.
31
 */
32
define('USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL', 2);
33

    
34
/**
35
 * Implements hook_help().
36
 */
37
function user_help($path, $arg) {
38
  global $user;
39

    
40
  switch ($path) {
41
    case 'admin/help#user':
42
      $output = '';
43
      $output .= '<h3>' . t('About') . '</h3>';
44
      $output .= '<p>' . t('The User module allows users to register, log in, and log out. It also allows users with proper permissions to manage user roles (used to classify users) and permissions associated with those roles. For more information, see the online handbook entry for <a href="@user">User module</a>.', array('@user' => 'http://drupal.org/documentation/modules/user')) . '</p>';
45
      $output .= '<h3>' . t('Uses') . '</h3>';
46
      $output .= '<dl>';
47
      $output .= '<dt>' . t('Creating and managing users') . '</dt>';
48
      $output .= '<dd>' . t('The User module allows users with the appropriate <a href="@permissions">permissions</a> to create user accounts through the <a href="@people">People administration page</a>, where they can also assign users to one or more roles, and block or delete user accounts. If allowed, users without accounts (anonymous users) can create their own accounts on the <a href="@register">Create new account</a> page.', array('@permissions' => url('admin/people/permissions', array('fragment' => 'module-user')), '@people' => url('admin/people'), '@register' => url('user/register'))) . '</dd>';
49
      $output .= '<dt>' . t('User roles and permissions') . '</dt>';
50
      $output .= '<dd>' . t('<em>Roles</em> are used to group and classify users; each user can be assigned one or more roles. By default there are two roles: <em>anonymous user</em> (users that are not logged in) and <em>authenticated user</em> (users that are registered and logged in). Depending on choices you made when you installed Drupal, the installation process may have defined more roles, and you can create additional custom roles on the <a href="@roles">Roles page</a>. After creating roles, you can set permissions for each role on the <a href="@permissions_user">Permissions page</a>. Granting a permission allows users who have been assigned a particular role to perform an action on the site, such as viewing a particular type of content, editing or creating content, administering settings for a particular module, or using a particular function of the site (such as search).', array('@permissions_user' => url('admin/people/permissions'), '@roles' => url('admin/people/permissions/roles'))) . '</dd>';
51
      $output .= '<dt>' . t('Account settings') . '</dt>';
52
      $output .= '<dd>' . t('The <a href="@accounts">Account settings page</a> allows you to manage settings for the displayed name of the anonymous user role, personal contact forms, user registration, and account cancellation. On this page you can also manage settings for account personalization (including signatures and user pictures), and adapt the text for the e-mail messages that are sent automatically during the user registration process.', array('@accounts'  => url('admin/config/people/accounts'))) . '</dd>';
53
      $output .= '</dl>';
54
      return $output;
55
    case 'admin/people/create':
56
      return '<p>' . t("This web page allows administrators to register new users. Users' e-mail addresses and usernames must be unique.") . '</p>';
57
    case 'admin/people/permissions':
58
      return '<p>' . t('Permissions let you control what users can do and see on your site. You can define a specific set of permissions for each role. (See the <a href="@role">Roles</a> page to create a role). Two important roles to consider are Authenticated Users and Administrators. Any permissions granted to the Authenticated Users role will be given to any user who can log into your site. You can make any role the Administrator role for the site, meaning this will be granted all new permissions automatically. You can do this on the <a href="@settings">User Settings</a> page. You should be careful to ensure that only trusted users are given this access and level of control of your site.', array('@role' => url('admin/people/permissions/roles'), '@settings' => url('admin/config/people/accounts'))) . '</p>';
59
    case 'admin/people/permissions/roles':
60
      $output = '<p>' . t('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 on the <a href="@permissions">permissions page</a>. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the names and order of the roles on your site. It is recommended to order your roles from least permissive (anonymous user) to most permissive (administrator). To delete a role choose "edit role".', array('@permissions' => url('admin/people/permissions'))) . '</p>';
61
      $output .= '<p>' . t('By default, Drupal comes with two user roles:') . '</p>';
62
      $output .= '<ul>';
63
      $output .= '<li>' . t("Anonymous user: this role is used for users that don't have a user account or that are not authenticated.") . '</li>';
64
      $output .= '<li>' . t('Authenticated user: this role is automatically granted to all logged in users.') . '</li>';
65
      $output .= '</ul>';
66
      return $output;
67
    case 'admin/config/people/accounts/fields':
68
      return '<p>' . t('This form lets administrators add, edit, and arrange fields for storing user data.') . '</p>';
69
    case 'admin/config/people/accounts/display':
70
      return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
71
    case 'admin/people/search':
72
      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>';
73
  }
74
}
75

    
76
/**
77
 * Invokes a user hook in every module.
78
 *
79
 * We cannot use module_invoke() for this, because the arguments need to
80
 * be passed by reference.
81
 *
82
 * @param $type
83
 *   A text string that controls which user hook to invoke.  Valid choices are:
84
 *   - cancel: Invokes hook_user_cancel().
85
 *   - insert: Invokes hook_user_insert().
86
 *   - login: Invokes hook_user_login().
87
 *   - presave: Invokes hook_user_presave().
88
 *   - update: Invokes hook_user_update().
89
 * @param $edit
90
 *   An associative array variable containing form values to be passed
91
 *   as the first parameter of the hook function.
92
 * @param $account
93
 *   The user account object to be passed as the second parameter of the hook
94
 *   function.
95
 * @param $category
96
 *   The category of user information being acted upon.
97
 */
98
function user_module_invoke($type, &$edit, $account, $category = NULL) {
99
  foreach (module_implements('user_' . $type) as $module) {
100
    $function = $module . '_user_' . $type;
101
    $function($edit, $account, $category);
102
  }
103
}
104

    
105
/**
106
 * Implements hook_theme().
107
 */
108
function user_theme() {
109
  return array(
110
    'user_picture' => array(
111
      'variables' => array('account' => NULL),
112
      'template' => 'user-picture',
113
    ),
114
    'user_profile' => array(
115
      'render element' => 'elements',
116
      'template' => 'user-profile',
117
      'file' => 'user.pages.inc',
118
    ),
119
    'user_profile_category' => array(
120
      'render element' => 'element',
121
      'template' => 'user-profile-category',
122
      'file' => 'user.pages.inc',
123
    ),
124
    'user_profile_item' => array(
125
      'render element' => 'element',
126
      'template' => 'user-profile-item',
127
      'file' => 'user.pages.inc',
128
    ),
129
    'user_list' => array(
130
      'variables' => array('users' => NULL, 'title' => NULL),
131
    ),
132
    'user_admin_permissions' => array(
133
      'render element' => 'form',
134
      'file' => 'user.admin.inc',
135
    ),
136
    'user_admin_roles' => array(
137
      'render element' => 'form',
138
      'file' => 'user.admin.inc',
139
    ),
140
    'user_permission_description' => array(
141
      'variables' => array('permission_item' => NULL, 'hide' => NULL),
142
      'file' => 'user.admin.inc',
143
    ),
144
    'user_signature' => array(
145
      'variables' => array('signature' => NULL),
146
    ),
147
  );
148
}
149

    
150
/**
151
 * Implements hook_entity_info().
152
 */
153
function user_entity_info() {
154
  $return = array(
155
    'user' => array(
156
      'label' => t('User'),
157
      'controller class' => 'UserController',
158
      'base table' => 'users',
159
      'uri callback' => 'user_uri',
160
      'label callback' => 'format_username',
161
      'fieldable' => TRUE,
162
      // $user->language is only the preferred user language for the user
163
      // interface textual elements. As it is not necessarily related to the
164
      // language assigned to fields, we do not define it as the entity language
165
      // key.
166
      'entity keys' => array(
167
        'id' => 'uid',
168
      ),
169
      'bundles' => array(
170
        'user' => array(
171
          'label' => t('User'),
172
          'admin' => array(
173
            'path' => 'admin/config/people/accounts',
174
            'access arguments' => array('administer users'),
175
          ),
176
        ),
177
      ),
178
      'view modes' => array(
179
        'full' => array(
180
          'label' => t('User account'),
181
          'custom settings' => FALSE,
182
        ),
183
      ),
184
    ),
185
  );
186
  return $return;
187
}
188

    
189
/**
190
 * Implements callback_entity_info_uri().
191
 */
192
function user_uri($user) {
193
  return array(
194
    'path' => 'user/' . $user->uid,
195
  );
196
}
197

    
198
/**
199
 * Implements hook_field_info_alter().
200
 */
201
function user_field_info_alter(&$info) {
202
  // Add the 'user_register_form' instance setting to all field types.
203
  foreach ($info as $field_type => &$field_type_info) {
204
    $field_type_info += array('instance_settings' => array());
205
    $field_type_info['instance_settings'] += array(
206
      'user_register_form' => FALSE,
207
    );
208
  }
209
}
210

    
211
/**
212
 * Implements hook_field_extra_fields().
213
 */
214
function user_field_extra_fields() {
215
  $return['user']['user'] = array(
216
    'form' => array(
217
      'account' => array(
218
        'label' => t('User name and password'),
219
        'description' => t('User module account form elements.'),
220
        'weight' => -10,
221
      ),
222
      'timezone' => array(
223
        'label' => t('Timezone'),
224
        'description' => t('User module timezone form element.'),
225
        'weight' => 6,
226
      ),
227
    ),
228
    'display' => array(
229
      'summary' => array(
230
        'label' => t('History'),
231
        'description' => t('User module history view element.'),
232
        'weight' => 5,
233
      ),
234
    ),
235
  );
236

    
237
  return $return;
238
}
239

    
240
/**
241
 * Fetches a user object based on an external authentication source.
242
 *
243
 * @param string $authname
244
 *   The external authentication username.
245
 *
246
 * @return
247
 *   A fully-loaded user object if the user is found or FALSE if not found.
248
 */
249
function user_external_load($authname) {
250
  $uid = db_query("SELECT uid FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchField();
251

    
252
  if ($uid) {
253
    return user_load($uid);
254
  }
255
  else {
256
    return FALSE;
257
  }
258
}
259

    
260
/**
261
 * Load multiple users based on certain conditions.
262
 *
263
 * This function should be used whenever you need to load more than one user
264
 * from the database. Users are loaded into memory and will not require
265
 * database access if loaded again during the same page request.
266
 *
267
 * @param $uids
268
 *   An array of user IDs.
269
 * @param $conditions
270
 *   (deprecated) An associative array of conditions on the {users}
271
 *   table, where the keys are the database fields and the values are the
272
 *   values those fields must have. Instead, it is preferable to use
273
 *   EntityFieldQuery to retrieve a list of entity IDs loadable by
274
 *   this function.
275
 * @param $reset
276
 *   A boolean indicating that the internal cache should be reset. Use this if
277
 *   loading a user object which has been altered during the page request.
278
 *
279
 * @return
280
 *   An array of user objects, indexed by uid.
281
 *
282
 * @see entity_load()
283
 * @see user_load()
284
 * @see user_load_by_mail()
285
 * @see user_load_by_name()
286
 * @see EntityFieldQuery
287
 *
288
 * @todo Remove $conditions in Drupal 8.
289
 */
290
function user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) {
291
  return entity_load('user', $uids, $conditions, $reset);
292
}
293

    
294
/**
295
 * Controller class for users.
296
 *
297
 * This extends the DrupalDefaultEntityController class, adding required
298
 * special handling for user objects.
299
 */
300
class UserController extends DrupalDefaultEntityController {
301

    
302
  function attachLoad(&$queried_users, $revision_id = FALSE) {
303
    // Build an array of user picture IDs so that these can be fetched later.
304
    $picture_fids = array();
305
    foreach ($queried_users as $key => $record) {
306
      $picture_fids[] = $record->picture;
307
      $queried_users[$key]->data = unserialize($record->data);
308
      $queried_users[$key]->roles = array();
309
      if ($record->uid) {
310
        $queried_users[$record->uid]->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
311
      }
312
      else {
313
        $queried_users[$record->uid]->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
314
      }
315
    }
316

    
317
    // Add any additional roles from the database.
318
    $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)));
319
    foreach ($result as $record) {
320
      $queried_users[$record->uid]->roles[$record->rid] = $record->name;
321
    }
322

    
323
    // Add the full file objects for user pictures if enabled.
324
    if (!empty($picture_fids) && variable_get('user_pictures', 0)) {
325
      $pictures = file_load_multiple($picture_fids);
326
      foreach ($queried_users as $account) {
327
        if (!empty($account->picture) && isset($pictures[$account->picture])) {
328
          $account->picture = $pictures[$account->picture];
329
        }
330
        else {
331
          $account->picture = NULL;
332
        }
333
      }
334
    }
335
    // Call the default attachLoad() method. This will add fields and call
336
    // hook_user_load().
337
    parent::attachLoad($queried_users, $revision_id);
338
  }
339
}
340

    
341
/**
342
 * Loads a user object.
343
 *
344
 * Drupal has a global $user object, which represents the currently-logged-in
345
 * user. So to avoid confusion and to avoid clobbering the global $user object,
346
 * it is a good idea to assign the result of this function to a different local
347
 * variable, generally $account. If you actually do want to act as the user you
348
 * are loading, it is essential to call drupal_save_session(FALSE); first.
349
 * See
350
 * @link http://drupal.org/node/218104 Safely impersonating another user @endlink
351
 * for more information.
352
 *
353
 * @param $uid
354
 *   Integer specifying the user ID to load.
355
 * @param $reset
356
 *   TRUE to reset the internal cache and load from the database; FALSE
357
 *   (default) to load from the internal cache, if set.
358
 *
359
 * @return
360
 *   A fully-loaded user object upon successful user load, or FALSE if the user
361
 *   cannot be loaded.
362
 *
363
 * @see user_load_multiple()
364
 */
365
function user_load($uid, $reset = FALSE) {
366
  $users = user_load_multiple(array($uid), array(), $reset);
367
  return reset($users);
368
}
369

    
370
/**
371
 * Fetch a user object by email address.
372
 *
373
 * @param $mail
374
 *   String with the account's e-mail address.
375
 * @return
376
 *   A fully-loaded $user object upon successful user load or FALSE if user
377
 *   cannot be loaded.
378
 *
379
 * @see user_load_multiple()
380
 */
381
function user_load_by_mail($mail) {
382
  $users = user_load_multiple(array(), array('mail' => $mail));
383
  return reset($users);
384
}
385

    
386
/**
387
 * Fetch a user object by account name.
388
 *
389
 * @param $name
390
 *   String with the account's user name.
391
 * @return
392
 *   A fully-loaded $user object upon successful user load or FALSE if user
393
 *   cannot be loaded.
394
 *
395
 * @see user_load_multiple()
396
 */
397
function user_load_by_name($name) {
398
  $users = user_load_multiple(array(), array('name' => $name));
399
  return reset($users);
400
}
401

    
402
/**
403
 * Save changes to a user account or add a new user.
404
 *
405
 * @param $account
406
 *   (optional) The user object to modify or add. If you want to modify
407
 *   an existing user account, you will need to ensure that (a) $account
408
 *   is an object, and (b) you have set $account->uid to the numeric
409
 *   user ID of the user account you wish to modify. If you
410
 *   want to create a new user account, you can set $account->is_new to
411
 *   TRUE or omit the $account->uid field.
412
 * @param $edit
413
 *   An array of fields and values to save. For example array('name'
414
 *   => 'My name'). Key / value pairs added to the $edit['data'] will be
415
 *   serialized and saved in the {users.data} column.
416
 * @param $category
417
 *   (optional) The category for storing profile information in.
418
 *
419
 * @return
420
 *   A fully-loaded $user object upon successful save or FALSE if the save failed.
421
 *
422
 * @todo D8: Drop $edit and fix user_save() to be consistent with others.
423
 */
424
function user_save($account, $edit = array(), $category = 'account') {
425
  $transaction = db_transaction();
426
  try {
427
    if (!empty($edit['pass'])) {
428
      // Allow alternate password hashing schemes.
429
      require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
430
      $edit['pass'] = user_hash_password(trim($edit['pass']));
431
      // Abort if the hashing failed and returned FALSE.
432
      if (!$edit['pass']) {
433
        return FALSE;
434
      }
435
    }
436
    else {
437
      // Avoid overwriting an existing password with a blank password.
438
      unset($edit['pass']);
439
    }
440
    if (isset($edit['mail'])) {
441
      $edit['mail'] = trim($edit['mail']);
442
    }
443

    
444
    // Load the stored entity, if any.
445
    if (!empty($account->uid) && !isset($account->original)) {
446
      $account->original = entity_load_unchanged('user', $account->uid);
447
    }
448

    
449
    if (empty($account)) {
450
      $account = new stdClass();
451
    }
452
    if (!isset($account->is_new)) {
453
      $account->is_new = empty($account->uid);
454
    }
455
    // Prepopulate $edit['data'] with the current value of $account->data.
456
    // Modules can add to or remove from this array in hook_user_presave().
457
    if (!empty($account->data)) {
458
      $edit['data'] = !empty($edit['data']) ? array_merge($account->data, $edit['data']) : $account->data;
459
    }
460

    
461
    // Invoke hook_user_presave() for all modules.
462
    user_module_invoke('presave', $edit, $account, $category);
463

    
464
    // Invoke presave operations of Field Attach API and Entity API. Those APIs
465
    // require a fully-fledged and updated entity object. Therefore, we need to
466
    // copy any new property values of $edit into it.
467
    foreach ($edit as $key => $value) {
468
      $account->$key = $value;
469
    }
470
    field_attach_presave('user', $account);
471
    module_invoke_all('entity_presave', $account, 'user');
472

    
473
    if (is_object($account) && !$account->is_new) {
474
      // Process picture uploads.
475
      if (!empty($account->picture->fid) && (!isset($account->original->picture->fid) || $account->picture->fid != $account->original->picture->fid)) {
476
        $picture = $account->picture;
477
        // If the picture is a temporary file move it to its final location and
478
        // make it permanent.
479
        if (!$picture->status) {
480
          $info = image_get_info($picture->uri);
481
          $picture_directory =  file_default_scheme() . '://' . variable_get('user_picture_path', 'pictures');
482

    
483
          // Prepare the pictures directory.
484
          file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY);
485
          $destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '-' . REQUEST_TIME . '.' . $info['extension']);
486

    
487
          // Move the temporary file into the final location.
488
          if ($picture = file_move($picture, $destination, FILE_EXISTS_RENAME)) {
489
            $picture->status = FILE_STATUS_PERMANENT;
490
            $account->picture = file_save($picture);
491
            file_usage_add($picture, 'user', 'user', $account->uid);
492
          }
493
        }
494
        // Delete the previous picture if it was deleted or replaced.
495
        if (!empty($account->original->picture->fid)) {
496
          file_usage_delete($account->original->picture, 'user', 'user', $account->uid);
497
          file_delete($account->original->picture);
498
        }
499
      }
500
      elseif (isset($edit['picture_delete']) && $edit['picture_delete']) {
501
        file_usage_delete($account->original->picture, 'user', 'user', $account->uid);
502
        file_delete($account->original->picture);
503
      }
504
      // Save the picture object, if it is set. drupal_write_record() expects
505
      // $account->picture to be a FID.
506
      $picture = empty($account->picture) ? NULL : $account->picture;
507
      $account->picture = empty($account->picture->fid) ? 0 : $account->picture->fid;
508

    
509
      // Do not allow 'uid' to be changed.
510
      $account->uid = $account->original->uid;
511
      // Save changes to the user table.
512
      $success = drupal_write_record('users', $account, 'uid');
513
      // Restore the picture object.
514
      $account->picture = $picture;
515
      if ($success === FALSE) {
516
        // The query failed - better to abort the save than risk further
517
        // data loss.
518
        return FALSE;
519
      }
520

    
521
      // Reload user roles if provided.
522
      if ($account->roles != $account->original->roles) {
523
        db_delete('users_roles')
524
          ->condition('uid', $account->uid)
525
          ->execute();
526

    
527
        $query = db_insert('users_roles')->fields(array('uid', 'rid'));
528
        foreach (array_keys($account->roles) as $rid) {
529
          if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
530
            $query->values(array(
531
              'uid' => $account->uid,
532
              'rid' => $rid,
533
            ));
534
          }
535
        }
536
        $query->execute();
537
      }
538

    
539
      // Delete a blocked user's sessions to kick them if they are online.
540
      if ($account->original->status != $account->status && $account->status == 0) {
541
        drupal_session_destroy_uid($account->uid);
542
      }
543

    
544
      // If the password changed, delete all open sessions and recreate
545
      // the current one.
546
      if ($account->pass != $account->original->pass) {
547
        drupal_session_destroy_uid($account->uid);
548
        if ($account->uid == $GLOBALS['user']->uid) {
549
          drupal_session_regenerate();
550
        }
551
      }
552

    
553
      // Save Field data.
554
      field_attach_update('user', $account);
555

    
556
      // Send emails after we have the new user object.
557
      if ($account->status != $account->original->status) {
558
        // The user's status is changing; conditionally send notification email.
559
        $op = $account->status == 1 ? 'status_activated' : 'status_blocked';
560
        _user_mail_notify($op, $account);
561
      }
562

    
563
      // Update $edit with any interim changes to $account.
564
      foreach ($account as $key => $value) {
565
        if (!property_exists($account->original, $key) || $value !== $account->original->$key) {
566
          $edit[$key] = $value;
567
        }
568
      }
569
      user_module_invoke('update', $edit, $account, $category);
570
      module_invoke_all('entity_update', $account, 'user');
571
    }
572
    else {
573
      // Allow 'uid' to be set by the caller. There is no danger of writing an
574
      // existing user as drupal_write_record will do an INSERT.
575
      if (empty($account->uid)) {
576
        $account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
577
      }
578
      // Allow 'created' to be set by the caller.
579
      if (!isset($account->created)) {
580
        $account->created = REQUEST_TIME;
581
      }
582
      $success = drupal_write_record('users', $account);
583
      if ($success === FALSE) {
584
        // On a failed INSERT some other existing user's uid may be returned.
585
        // We must abort to avoid overwriting their account.
586
        return FALSE;
587
      }
588

    
589
      // Make sure $account is properly initialized.
590
      $account->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
591

    
592
      field_attach_insert('user', $account);
593
      $edit = (array) $account;
594
      user_module_invoke('insert', $edit, $account, $category);
595
      module_invoke_all('entity_insert', $account, 'user');
596

    
597
      // Save user roles. Skip built-in roles, and ones that were already saved
598
      // to the database during hook calls.
599
      $rids_to_skip = array_merge(array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID), db_query('SELECT rid FROM {users_roles} WHERE uid = :uid', array(':uid' => $account->uid))->fetchCol());
600
      if ($rids_to_save = array_diff(array_keys($account->roles), $rids_to_skip)) {
601
        $query = db_insert('users_roles')->fields(array('uid', 'rid'));
602
        foreach ($rids_to_save as $rid) {
603
          $query->values(array(
604
            'uid' => $account->uid,
605
            'rid' => $rid,
606
          ));
607
        }
608
        $query->execute();
609
      }
610
    }
611
    // Clear internal properties.
612
    unset($account->is_new);
613
    unset($account->original);
614
    // Clear the static loading cache.
615
    entity_get_controller('user')->resetCache(array($account->uid));
616

    
617
    return $account;
618
  }
619
  catch (Exception $e) {
620
    $transaction->rollback();
621
    watchdog_exception('user', $e);
622
    throw $e;
623
  }
624
}
625

    
626
/**
627
 * Verify the syntax of the given name.
628
 */
629
function user_validate_name($name) {
630
  if (!$name) {
631
    return t('You must enter a username.');
632
  }
633
  if (substr($name, 0, 1) == ' ') {
634
    return t('The username cannot begin with a space.');
635
  }
636
  if (substr($name, -1) == ' ') {
637
    return t('The username cannot end with a space.');
638
  }
639
  if (strpos($name, '  ') !== FALSE) {
640
    return t('The username cannot contain multiple spaces in a row.');
641
  }
642
  if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i', $name)) {
643
    return t('The username contains an illegal character.');
644
  }
645
  if (preg_match('/[\x{80}-\x{A0}' .         // Non-printable ISO-8859-1 + NBSP
646
                  '\x{AD}' .                // Soft-hyphen
647
                  '\x{2000}-\x{200F}' .     // Various space characters
648
                  '\x{2028}-\x{202F}' .     // Bidirectional text overrides
649
                  '\x{205F}-\x{206F}' .     // Various text hinting characters
650
                  '\x{FEFF}' .              // Byte order mark
651
                  '\x{FF01}-\x{FF60}' .     // Full-width latin
652
                  '\x{FFF9}-\x{FFFD}' .     // Replacement characters
653
                  '\x{0}-\x{1F}]/u',        // NULL byte and control characters
654
                  $name)) {
655
    return t('The username contains an illegal character.');
656
  }
657
  if (drupal_strlen($name) > USERNAME_MAX_LENGTH) {
658
    return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
659
  }
660
}
661

    
662
/**
663
 * Validates a user's email address.
664
 *
665
 * Checks that a user's email address exists and follows all standard
666
 * validation rules. Returns error messages when the address is invalid.
667
 *
668
 * @param $mail
669
 *   A user's email address.
670
 *
671
 * @return
672
 *   If the address is invalid, a human-readable error message is returned.
673
 *   If the address is valid, nothing is returned.
674
 */
675
function user_validate_mail($mail) {
676
  if (!$mail) {
677
    return t('You must enter an e-mail address.');
678
  }
679
  if (!valid_email_address($mail)) {
680
    return t('The e-mail address %mail is not valid.', array('%mail' => $mail));
681
  }
682
}
683

    
684
/**
685
 * Validates an image uploaded by a user.
686
 *
687
 * @see user_account_form()
688
 */
689
function user_validate_picture(&$form, &$form_state) {
690
  // If required, validate the uploaded picture.
691
  $validators = array(
692
    'file_validate_is_image' => array(),
693
    'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
694
    'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
695
  );
696

    
697
  // Save the file as a temporary file.
698
  $file = file_save_upload('picture_upload', $validators);
699
  if ($file === FALSE) {
700
    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'))));
701
  }
702
  elseif ($file !== NULL) {
703
    $form_state['values']['picture_upload'] = $file;
704
  }
705
}
706

    
707
/**
708
 * Generate a random alphanumeric password.
709
 */
710
function user_password($length = 10) {
711
  // This variable contains the list of allowable characters for the
712
  // password. Note that the number 0 and the letter 'O' have been
713
  // removed to avoid confusion between the two. The same is true
714
  // of 'I', 1, and 'l'.
715
  $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
716

    
717
  // Zero-based count of characters in the allowable list:
718
  $len = strlen($allowable_characters) - 1;
719

    
720
  // Declare the password as a blank string.
721
  $pass = '';
722

    
723
  // Loop the number of times specified by $length.
724
  for ($i = 0; $i < $length; $i++) {
725
    do {
726
      // Find a secure random number within the range needed.
727
      $index = ord(drupal_random_bytes(1));
728
    } while ($index > $len);
729

    
730
    // Each iteration, pick a random character from the
731
    // allowable string and append it to the password:
732
    $pass .= $allowable_characters[$index];
733
  }
734

    
735
  return $pass;
736
}
737

    
738
/**
739
 * Determine the permissions for one or more roles.
740
 *
741
 * @param $roles
742
 *   An array whose keys are the role IDs of interest, such as $user->roles.
743
 *
744
 * @return
745
 *   If $roles is a non-empty array, an array indexed by role ID is returned.
746
 *   Each value is an array whose keys are the permission strings for the given
747
 *   role ID. If $roles is empty nothing is returned.
748
 */
749
function user_role_permissions($roles = array()) {
750
  $cache = &drupal_static(__FUNCTION__, array());
751

    
752
  $role_permissions = $fetch = array();
753

    
754
  if ($roles) {
755
    foreach ($roles as $rid => $name) {
756
      if (isset($cache[$rid])) {
757
        $role_permissions[$rid] = $cache[$rid];
758
      }
759
      else {
760
        // Add this rid to the list of those needing to be fetched.
761
        $fetch[] = $rid;
762
        // Prepare in case no permissions are returned.
763
        $cache[$rid] = array();
764
      }
765
    }
766

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

    
772
      foreach ($result as $row) {
773
        $cache[$row->rid][$row->permission] = TRUE;
774
      }
775
      foreach ($fetch as $rid) {
776
        // For every rid, we know we at least assigned an empty array.
777
        $role_permissions[$rid] = $cache[$rid];
778
      }
779
    }
780
  }
781

    
782
  return $role_permissions;
783
}
784

    
785
/**
786
 * Determine whether the user has a given privilege.
787
 *
788
 * @param $string
789
 *   The permission, such as "administer nodes", being checked for.
790
 * @param $account
791
 *   (optional) The account to check, if not given use currently logged in user.
792
 *
793
 * @return
794
 *   Boolean TRUE if the current user has the requested permission.
795
 *
796
 * All permission checks in Drupal should go through this function. This
797
 * way, we guarantee consistent behavior, and ensure that the superuser
798
 * can perform all actions.
799
 */
800
function user_access($string, $account = NULL) {
801
  global $user;
802

    
803
  if (!isset($account)) {
804
    $account = $user;
805
  }
806

    
807
  // User #1 has all privileges:
808
  if ($account->uid == 1) {
809
    return TRUE;
810
  }
811

    
812
  // To reduce the number of SQL queries, we cache the user's permissions
813
  // in a static variable.
814
  // Use the advanced drupal_static() pattern, since this is called very often.
815
  static $drupal_static_fast;
816
  if (!isset($drupal_static_fast)) {
817
    $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
818
  }
819
  $perm = &$drupal_static_fast['perm'];
820
  if (!isset($perm[$account->uid])) {
821
    $role_permissions = user_role_permissions($account->roles);
822

    
823
    $perms = array();
824
    foreach ($role_permissions as $one_role) {
825
      $perms += $one_role;
826
    }
827
    $perm[$account->uid] = $perms;
828
  }
829

    
830
  return isset($perm[$account->uid][$string]);
831
}
832

    
833
/**
834
 * Checks for usernames blocked by user administration.
835
 *
836
 * @param $name
837
 *   A string containing a name of the user.
838
 *
839
 * @return
840
 *   Object with property 'name' (the user name), if the user is blocked;
841
 *   FALSE if the user is not blocked.
842
 */
843
function user_is_blocked($name) {
844
  return db_select('users')
845
    ->fields('users', array('name'))
846
    ->condition('name', db_like($name), 'LIKE')
847
    ->condition('status', 0)
848
    ->execute()->fetchObject();
849
}
850

    
851
/**
852
 * Checks if a user has a role.
853
 *
854
 * @param int $rid
855
 *   A role ID.
856
 *
857
 * @param object|null $account
858
 *   (optional) A user account. Defaults to the current user.
859
 *
860
 * @return bool
861
 *   TRUE if the user has the role, or FALSE if not.
862
 */
863
function user_has_role($rid, $account = NULL) {
864
  if (!$account) {
865
    $account = $GLOBALS['user'];
866
  }
867

    
868
  return isset($account->roles[$rid]);
869
}
870

    
871
/**
872
 * Implements hook_permission().
873
 */
874
function user_permission() {
875
  return array(
876
    'administer permissions' =>  array(
877
      'title' => t('Administer permissions'),
878
      'restrict access' => TRUE,
879
    ),
880
    'administer users' => array(
881
      'title' => t('Administer users'),
882
      'restrict access' => TRUE,
883
    ),
884
    'access user profiles' => array(
885
      'title' => t('View user profiles'),
886
    ),
887
    'change own username' => array(
888
      'title' => t('Change own username'),
889
    ),
890
    'cancel account' => array(
891
      'title' => t('Cancel own user account'),
892
      'description' => t('Note: content may be kept, unpublished, deleted or transferred to the %anonymous-name user depending on the configured <a href="@user-settings-url">user settings</a>.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')), '@user-settings-url' => url('admin/config/people/accounts'))),
893
    ),
894
    'select account cancellation method' => array(
895
      'title' => t('Select method for cancelling own account'),
896
      'restrict access' => TRUE,
897
    ),
898
  );
899
}
900

    
901
/**
902
 * Implements hook_file_download().
903
 *
904
 * Ensure that user pictures (avatars) are always downloadable.
905
 */
906
function user_file_download($uri) {
907
  if (strpos(file_uri_target($uri), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) {
908
    $info = image_get_info($uri);
909
    return array('Content-Type' => $info['mime_type']);
910
  }
911
}
912

    
913
/**
914
 * Implements hook_file_move().
915
 */
916
function user_file_move($file, $source) {
917
  // If a user's picture is replaced with a new one, update the record in
918
  // the users table.
919
  if (isset($file->fid) && isset($source->fid) && $file->fid != $source->fid) {
920
    db_update('users')
921
      ->fields(array(
922
        'picture' => $file->fid,
923
      ))
924
      ->condition('picture', $source->fid)
925
      ->execute();
926
  }
927
}
928

    
929
/**
930
 * Implements hook_file_delete().
931
 */
932
function user_file_delete($file) {
933
  // Remove any references to the file.
934
  db_update('users')
935
    ->fields(array('picture' => 0))
936
    ->condition('picture', $file->fid)
937
    ->execute();
938
}
939

    
940
/**
941
 * Implements hook_search_info().
942
 */
943
function user_search_info() {
944
  return array(
945
    'title' => 'Users',
946
  );
947
}
948

    
949
/**
950
 * Implements hook_search_access().
951
 */
952
function user_search_access() {
953
  return user_access('access user profiles');
954
}
955

    
956
/**
957
 * Implements hook_search_execute().
958
 */
959
function user_search_execute($keys = NULL, $conditions = NULL) {
960
  $find = array();
961
  // Escape for LIKE matching.
962
  $keys = db_like($keys);
963
  // Replace wildcards with MySQL/PostgreSQL wildcards.
964
  $keys = preg_replace('!\*+!', '%', $keys);
965
  $query = db_select('users')->extend('PagerDefault');
966
  $query->fields('users', array('uid'));
967
  if (user_access('administer users')) {
968
    // Administrators can also search in the otherwise private email field,
969
    // and they don't need to be restricted to only active users.
970
    $query->fields('users', array('mail'));
971
    $query->condition(db_or()->
972
      condition('name', '%' . $keys . '%', 'LIKE')->
973
      condition('mail', '%' . $keys . '%', 'LIKE'));
974
  }
975
  else {
976
    // Regular users can only search via usernames, and we do not show them
977
    // blocked accounts.
978
    $query->condition('name', '%' . $keys . '%', 'LIKE')
979
      ->condition('status', 1);
980
  }
981
  $uids = $query
982
    ->limit(15)
983
    ->execute()
984
    ->fetchCol();
985
  $accounts = user_load_multiple($uids);
986

    
987
  $results = array();
988
  foreach ($accounts as $account) {
989
    $result = array(
990
      'title' => format_username($account),
991
      'link' => url('user/' . $account->uid, array('absolute' => TRUE)),
992
    );
993
    if (user_access('administer users')) {
994
      $result['title'] .= ' (' . $account->mail . ')';
995
    }
996
    $results[] = $result;
997
  }
998

    
999
  return $results;
1000
}
1001

    
1002
/**
1003
 * Implements hook_element_info().
1004
 */
1005
function user_element_info() {
1006
  $types['user_profile_category'] = array(
1007
    '#theme_wrappers' => array('user_profile_category'),
1008
  );
1009
  $types['user_profile_item'] = array(
1010
    '#theme' => 'user_profile_item',
1011
  );
1012
  return $types;
1013
}
1014

    
1015
/**
1016
 * Implements hook_user_view().
1017
 */
1018
function user_user_view($account) {
1019
  $account->content['user_picture'] = array(
1020
    '#markup' => theme('user_picture', array('account' => $account)),
1021
    '#weight' => -10,
1022
  );
1023
  if (!isset($account->content['summary'])) {
1024
    $account->content['summary'] = array();
1025
  }
1026
  $account->content['summary'] += array(
1027
    '#type' => 'user_profile_category',
1028
    '#attributes' => array('class' => array('user-member')),
1029
    '#weight' => 5,
1030
    '#title' => t('History'),
1031
  );
1032
  $account->content['summary']['member_for'] = array(
1033
    '#type' => 'user_profile_item',
1034
    '#title' => t('Member for'),
1035
    '#markup' => format_interval(REQUEST_TIME - $account->created),
1036
  );
1037
}
1038

    
1039
/**
1040
 * Helper function to add default user account fields to user registration and edit form.
1041
 *
1042
 * @see user_account_form_validate()
1043
 * @see user_validate_current_pass()
1044
 * @see user_validate_picture()
1045
 * @see user_validate_mail()
1046
 */
1047
function user_account_form(&$form, &$form_state) {
1048
  global $user;
1049

    
1050
  $account = $form['#user'];
1051
  $register = ($form['#user']->uid > 0 ? FALSE : TRUE);
1052

    
1053
  $admin = user_access('administer users');
1054

    
1055
  $form['#validate'][] = 'user_account_form_validate';
1056

    
1057
  // Account information.
1058
  $form['account'] = array(
1059
    '#type'   => 'container',
1060
    '#weight' => -10,
1061
  );
1062
  // Only show name field on registration form or user can change own username.
1063
  $form['account']['name'] = array(
1064
    '#type' => 'textfield',
1065
    '#title' => t('Username'),
1066
    '#maxlength' => USERNAME_MAX_LENGTH,
1067
    '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
1068
    '#required' => TRUE,
1069
    '#attributes' => array('class' => array('username')),
1070
    '#default_value' => (!$register ? $account->name : ''),
1071
    '#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin),
1072
    '#weight' => -10,
1073
  );
1074

    
1075
  $form['account']['mail'] = array(
1076
    '#type' => 'textfield',
1077
    '#title' => t('E-mail address'),
1078
    '#maxlength' => EMAIL_MAX_LENGTH,
1079
    '#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.'),
1080
    '#required' => TRUE,
1081
    '#default_value' => (!$register ? $account->mail : ''),
1082
  );
1083

    
1084
  // Display password field only for existing users or when user is allowed to
1085
  // assign a password during registration.
1086
  if (!$register) {
1087
    $form['account']['pass'] = array(
1088
      '#type' => 'password_confirm',
1089
      '#size' => 25,
1090
      '#description' => t('To change the current user password, enter the new password in both fields.'),
1091
    );
1092
    // To skip the current password field, the user must have logged in via a
1093
    // one-time link and have the token in the URL.
1094
    $pass_reset = isset($_SESSION['pass_reset_' . $account->uid]) && isset($_GET['pass-reset-token']) && ($_GET['pass-reset-token'] == $_SESSION['pass_reset_' . $account->uid]);
1095
    $protected_values = array();
1096
    $current_pass_description = '';
1097
    // The user may only change their own password without their current
1098
    // password if they logged in via a one-time login link.
1099
    if (!$pass_reset) {
1100
      $protected_values['mail'] = $form['account']['mail']['#title'];
1101
      $protected_values['pass'] = t('Password');
1102
      $request_new = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
1103
      $current_pass_description = t('Enter your current password to change the %mail or %pass. !request_new.', array('%mail' => $protected_values['mail'], '%pass' => $protected_values['pass'], '!request_new' => $request_new));
1104
    }
1105
    // The user must enter their current password to change to a new one.
1106
    if ($user->uid == $account->uid) {
1107
      $form['account']['current_pass_required_values'] = array(
1108
        '#type' => 'value',
1109
        '#value' => $protected_values,
1110
      );
1111
      $form['account']['current_pass'] = array(
1112
        '#type' => 'password',
1113
        '#title' => t('Current password'),
1114
        '#size' => 25,
1115
        '#access' => !empty($protected_values),
1116
        '#description' => $current_pass_description,
1117
        '#weight' => -5,
1118
        // Do not let web browsers remember this password, since we are trying
1119
        // to confirm that the person submitting the form actually knows the
1120
        // current one.
1121
        '#attributes' => array('autocomplete' => 'off'),
1122
      );
1123
      $form['#validate'][] = 'user_validate_current_pass';
1124
    }
1125
  }
1126
  elseif (!variable_get('user_email_verification', TRUE) || $admin) {
1127
    $form['account']['pass'] = array(
1128
      '#type' => 'password_confirm',
1129
      '#size' => 25,
1130
      '#description' => t('Provide a password for the new account in both fields.'),
1131
      '#required' => TRUE,
1132
    );
1133
  }
1134

    
1135
  if ($admin) {
1136
    $status = isset($account->status) ? $account->status : 1;
1137
  }
1138
  else {
1139
    $status = $register ? variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS : $account->status;
1140
  }
1141
  $form['account']['status'] = array(
1142
    '#type' => 'radios',
1143
    '#title' => t('Status'),
1144
    '#default_value' => $status,
1145
    '#options' => array(t('Blocked'), t('Active')),
1146
    '#access' => $admin,
1147
  );
1148

    
1149
  $roles = array_map('check_plain', user_roles(TRUE));
1150
  // The disabled checkbox subelement for the 'authenticated user' role
1151
  // must be generated separately and added to the checkboxes element,
1152
  // because of a limitation in Form API not supporting a single disabled
1153
  // checkbox within a set of checkboxes.
1154
  // @todo This should be solved more elegantly. See issue #119038.
1155
  $checkbox_authenticated = array(
1156
    '#type' => 'checkbox',
1157
    '#title' => $roles[DRUPAL_AUTHENTICATED_RID],
1158
    '#default_value' => TRUE,
1159
    '#disabled' => TRUE,
1160
  );
1161
  unset($roles[DRUPAL_AUTHENTICATED_RID]);
1162
  $form['account']['roles'] = array(
1163
    '#type' => 'checkboxes',
1164
    '#title' => t('Roles'),
1165
    '#default_value' => (!$register && isset($account->roles) ? array_keys($account->roles) : array()),
1166
    '#options' => $roles,
1167
    '#access' => $roles && user_access('administer permissions'),
1168
    DRUPAL_AUTHENTICATED_RID => $checkbox_authenticated,
1169
  );
1170

    
1171
  $form['account']['notify'] = array(
1172
    '#type' => 'checkbox',
1173
    '#title' => t('Notify user of new account'),
1174
    '#access' => $register && $admin,
1175
  );
1176

    
1177
  // Signature.
1178
  $form['signature_settings'] = array(
1179
    '#type' => 'fieldset',
1180
    '#title' => t('Signature settings'),
1181
    '#weight' => 1,
1182
    '#access' => (!$register && variable_get('user_signatures', 0)),
1183
  );
1184

    
1185
  $form['signature_settings']['signature'] = array(
1186
    '#type' => 'text_format',
1187
    '#title' => t('Signature'),
1188
    '#default_value' => isset($account->signature) ? $account->signature : '',
1189
    '#description' => t('Your signature will be publicly displayed at the end of your comments.'),
1190
    '#format' => isset($account->signature_format) ? $account->signature_format : NULL,
1191
  );
1192

    
1193
  // Picture/avatar.
1194
  $form['picture'] = array(
1195
    '#type' => 'fieldset',
1196
    '#title' => t('Picture'),
1197
    '#weight' => 1,
1198
    '#access' => (!$register && variable_get('user_pictures', 0)),
1199
  );
1200
  $form['picture']['picture'] = array(
1201
    '#type' => 'value',
1202
    '#value' => isset($account->picture) ? $account->picture : NULL,
1203
  );
1204
  $form['picture']['picture_current'] = array(
1205
    '#markup' => theme('user_picture', array('account' => $account)),
1206
  );
1207
  $form['picture']['picture_delete'] = array(
1208
    '#type' => 'checkbox',
1209
    '#title' => t('Delete picture'),
1210
    '#access' => !empty($account->picture->fid),
1211
    '#description' => t('Check this box to delete your current picture.'),
1212
  );
1213
  $form['picture']['picture_upload'] = array(
1214
    '#type' => 'file',
1215
    '#title' => t('Upload picture'),
1216
    '#size' => 48,
1217
    '#description' => t('Your virtual face or picture. Pictures larger than @dimensions pixels will be scaled down.', array('@dimensions' => variable_get('user_picture_dimensions', '85x85'))) . ' ' . filter_xss_admin(variable_get('user_picture_guidelines', '')),
1218
  );
1219
  $form['#validate'][] = 'user_validate_picture';
1220
}
1221

    
1222
/**
1223
 * Form validation handler for the current password on the user_account_form().
1224
 *
1225
 * @see user_account_form()
1226
 */
1227
function user_validate_current_pass(&$form, &$form_state) {
1228
  $account = $form['#user'];
1229
  foreach ($form_state['values']['current_pass_required_values'] as $key => $name) {
1230
    // This validation only works for required textfields (like mail) or
1231
    // form values like password_confirm that have their own validation
1232
    // that prevent them from being empty if they are changed.
1233
    if ((strlen(trim($form_state['values'][$key])) > 0) && ($form_state['values'][$key] != $account->$key)) {
1234
      require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
1235
      $current_pass_failed = empty($form_state['values']['current_pass']) || !user_check_password($form_state['values']['current_pass'], $account);
1236
      if ($current_pass_failed) {
1237
        form_set_error('current_pass', t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => $name)));
1238
        form_set_error($key);
1239
      }
1240
      // We only need to check the password once.
1241
      break;
1242
    }
1243
  }
1244
}
1245

    
1246
/**
1247
 * Form validation handler for user_account_form().
1248
 *
1249
 * @see user_account_form()
1250
 */
1251
function user_account_form_validate($form, &$form_state) {
1252
  if ($form['#user_category'] == 'account' || $form['#user_category'] == 'register') {
1253
    $account = $form['#user'];
1254
    // Validate new or changing username.
1255
    if (isset($form_state['values']['name'])) {
1256
      if ($error = user_validate_name($form_state['values']['name'])) {
1257
        form_set_error('name', $error);
1258
      }
1259
      elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('name', db_like($form_state['values']['name']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
1260
        form_set_error('name', t('The name %name is already taken.', array('%name' => $form_state['values']['name'])));
1261
      }
1262
    }
1263

    
1264
    // Trim whitespace from mail, to prevent confusing 'e-mail not valid'
1265
    // warnings often caused by cutting and pasting.
1266
    $mail = trim($form_state['values']['mail']);
1267
    form_set_value($form['account']['mail'], $mail, $form_state);
1268

    
1269
    // Validate the e-mail address, and check if it is taken by an existing user.
1270
    if ($error = user_validate_mail($form_state['values']['mail'])) {
1271
      form_set_error('mail', $error);
1272
    }
1273
    elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('mail', db_like($form_state['values']['mail']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
1274
      // Format error message dependent on whether the user is logged in or not.
1275
      if ($GLOBALS['user']->uid) {
1276
        form_set_error('mail', t('The e-mail address %email is already taken.', array('%email' => $form_state['values']['mail'])));
1277
      }
1278
      else {
1279
        form_set_error('mail', t('The e-mail address %email is already registered. <a href="@password">Have you forgotten your password?</a>', array('%email' => $form_state['values']['mail'], '@password' => url('user/password'))));
1280
      }
1281
    }
1282

    
1283
    // Make sure the signature isn't longer than the size of the database field.
1284
    // Signatures are disabled by default, so make sure it exists first.
1285
    if (isset($form_state['values']['signature'])) {
1286
      // Move text format for user signature into 'signature_format'.
1287
      $form_state['values']['signature_format'] = $form_state['values']['signature']['format'];
1288
      // Move text value for user signature into 'signature'.
1289
      $form_state['values']['signature'] = $form_state['values']['signature']['value'];
1290

    
1291
      $user_schema = drupal_get_schema('users');
1292
      if (drupal_strlen($form_state['values']['signature']) > $user_schema['fields']['signature']['length']) {
1293
        form_set_error('signature', t('The signature is too long: it must be %max characters or less.', array('%max' => $user_schema['fields']['signature']['length'])));
1294
      }
1295
    }
1296
  }
1297
}
1298

    
1299
/**
1300
 * Implements hook_user_presave().
1301
 */
1302
function user_user_presave(&$edit, $account, $category) {
1303
  if ($category == 'account' || $category == 'register') {
1304
    if (!empty($edit['picture_upload'])) {
1305
      $edit['picture'] = $edit['picture_upload'];
1306
    }
1307
    // Delete picture if requested, and if no replacement picture was given.
1308
    elseif (!empty($edit['picture_delete'])) {
1309
      $edit['picture'] = NULL;
1310
    }
1311
    // Prepare user roles.
1312
    if (isset($edit['roles'])) {
1313
      $edit['roles'] = array_filter($edit['roles']);
1314
    }
1315
  }
1316

    
1317
  // Move account cancellation information into $user->data.
1318
  foreach (array('user_cancel_method', 'user_cancel_notify') as $key) {
1319
    if (isset($edit[$key])) {
1320
      $edit['data'][$key] = $edit[$key];
1321
    }
1322
  }
1323
}
1324

    
1325
/**
1326
 * Implements hook_user_categories().
1327
 */
1328
function user_user_categories() {
1329
  return array(array(
1330
    'name' => 'account',
1331
    'title' => t('Account settings'),
1332
    'weight' => 1,
1333
  ));
1334
}
1335

    
1336
function user_login_block($form) {
1337
  $form['#action'] = url(current_path(), array('query' => drupal_get_destination(), 'external' => FALSE));
1338
  $form['#id'] = 'user-login-form';
1339
  $form['#validate'] = user_login_default_validators();
1340
  $form['#submit'][] = 'user_login_submit';
1341
  $form['name'] = array('#type' => 'textfield',
1342
    '#title' => t('Username'),
1343
    '#maxlength' => USERNAME_MAX_LENGTH,
1344
    '#size' => 15,
1345
    '#required' => TRUE,
1346
  );
1347
  $form['pass'] = array('#type' => 'password',
1348
    '#title' => t('Password'),
1349
    '#size' => 15,
1350
    '#required' => TRUE,
1351
  );
1352
  $form['actions'] = array('#type' => 'actions');
1353
  $form['actions']['submit'] = array('#type' => 'submit',
1354
    '#value' => t('Log in'),
1355
  );
1356
  $items = array();
1357
  if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
1358
    $items[] = l(t('Create new account'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'))));
1359
  }
1360
  $items[] = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
1361
  $form['links'] = array('#markup' => theme('item_list', array('items' => $items)));
1362
  return $form;
1363
}
1364

    
1365
/**
1366
 * Implements hook_block_info().
1367
 */
1368
function user_block_info() {
1369
  global $user;
1370

    
1371
  $blocks['login']['info'] = t('User login');
1372
  // Not worth caching.
1373
  $blocks['login']['cache'] = DRUPAL_NO_CACHE;
1374

    
1375
  $blocks['new']['info'] = t('Who\'s new');
1376
  $blocks['new']['properties']['administrative'] = TRUE;
1377

    
1378
  // Too dynamic to cache.
1379
  $blocks['online']['info'] = t('Who\'s online');
1380
  $blocks['online']['cache'] = DRUPAL_NO_CACHE;
1381
  $blocks['online']['properties']['administrative'] = TRUE;
1382

    
1383
  return $blocks;
1384
}
1385

    
1386
/**
1387
 * Implements hook_block_configure().
1388
 */
1389
function user_block_configure($delta = '') {
1390
  global $user;
1391

    
1392
  switch ($delta) {
1393
    case 'new':
1394
      $form['user_block_whois_new_count'] = array(
1395
        '#type' => 'select',
1396
        '#title' => t('Number of users to display'),
1397
        '#default_value' => variable_get('user_block_whois_new_count', 5),
1398
        '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
1399
      );
1400
      return $form;
1401

    
1402
    case 'online':
1403
      $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800, 2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval');
1404
      $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.'));
1405
      $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.'));
1406
      return $form;
1407
  }
1408
}
1409

    
1410
/**
1411
 * Implements hook_block_save().
1412
 */
1413
function user_block_save($delta = '', $edit = array()) {
1414
  global $user;
1415

    
1416
  switch ($delta) {
1417
    case 'new':
1418
      variable_set('user_block_whois_new_count', $edit['user_block_whois_new_count']);
1419
      break;
1420

    
1421
    case 'online':
1422
      variable_set('user_block_seconds_online', $edit['user_block_seconds_online']);
1423
      variable_set('user_block_max_list_count', $edit['user_block_max_list_count']);
1424
      break;
1425
  }
1426
}
1427

    
1428
/**
1429
 * Implements hook_block_view().
1430
 */
1431
function user_block_view($delta = '') {
1432
  global $user;
1433

    
1434
  $block = array();
1435

    
1436
  switch ($delta) {
1437
    case 'login':
1438
      // For usability's sake, avoid showing two login forms on one page.
1439
      if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
1440

    
1441
        $block['subject'] = t('User login');
1442
        $block['content'] = drupal_get_form('user_login_block');
1443
      }
1444
      return $block;
1445

    
1446
    case 'new':
1447
      if (user_access('access content')) {
1448
        // Retrieve a list of new users who have subsequently accessed the site successfully.
1449
        $items = 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))->fetchAll();
1450
        $output = theme('user_list', array('users' => $items));
1451

    
1452
        $block['subject'] = t('Who\'s new');
1453
        $block['content'] = $output;
1454
      }
1455
      return $block;
1456

    
1457
    case 'online':
1458
      if (user_access('access content')) {
1459
        // Count users active within the defined period.
1460
        $interval = REQUEST_TIME - variable_get('user_block_seconds_online', 900);
1461

    
1462
        // Perform database queries to gather online user lists. We use s.timestamp
1463
        // rather than u.access because it is much faster.
1464
        $authenticated_count = db_query("SELECT COUNT(DISTINCT s.uid) FROM {sessions} s WHERE s.timestamp >= :timestamp AND s.uid > 0", array(':timestamp' => $interval))->fetchField();
1465

    
1466
        $output = '<p>' . format_plural($authenticated_count, 'There is currently 1 user online.', 'There are currently @count users online.') . '</p>';
1467

    
1468
        // Display a list of currently online users.
1469
        $max_users = variable_get('user_block_max_list_count', 10);
1470
        if ($authenticated_count && $max_users) {
1471
          $items = db_query_range('SELECT u.uid, u.name, MAX(s.timestamp) AS max_timestamp FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= :interval AND s.uid > 0 GROUP BY u.uid, u.name ORDER BY max_timestamp DESC', 0, $max_users, array(':interval' => $interval))->fetchAll();
1472
          $output .= theme('user_list', array('users' => $items));
1473
        }
1474

    
1475
        $block['subject'] = t('Who\'s online');
1476
        $block['content'] = $output;
1477
      }
1478
      return $block;
1479
  }
1480
}
1481

    
1482
/**
1483
 * Process variables for user-picture.tpl.php.
1484
 *
1485
 * The $variables array contains the following arguments:
1486
 * - $account: A user, node or comment object with 'name', 'uid' and 'picture'
1487
 *   fields.
1488
 *
1489
 * @see user-picture.tpl.php
1490
 */
1491
function template_preprocess_user_picture(&$variables) {
1492
  $variables['user_picture'] = '';
1493
  if (variable_get('user_pictures', 0)) {
1494
    $account = $variables['account'];
1495
    if (!empty($account->picture)) {
1496
      // @TODO: Ideally this function would only be passed file objects, but
1497
      // since there's a lot of legacy code that JOINs the {users} table to
1498
      // {node} or {comments} and passes the results into this function if we
1499
      // a numeric value in the picture field we'll assume it's a file id
1500
      // and load it for them. Once we've got user_load_multiple() and
1501
      // comment_load_multiple() functions the user module will be able to load
1502
      // the picture files in mass during the object's load process.
1503
      if (is_numeric($account->picture)) {
1504
        $account->picture = file_load($account->picture);
1505
      }
1506
      if (!empty($account->picture->uri)) {
1507
        $filepath = $account->picture->uri;
1508
      }
1509
    }
1510
    elseif (variable_get('user_picture_default', '')) {
1511
      $filepath = variable_get('user_picture_default', '');
1512
    }
1513
    if (isset($filepath)) {
1514
      $alt = t("@user's picture", array('@user' => format_username($account)));
1515
      // If the image does not have a valid Drupal scheme (for eg. HTTP),
1516
      // don't load image styles.
1517
      if (module_exists('image') && file_valid_uri($filepath) && $style = variable_get('user_picture_style', '')) {
1518
        $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
1519
      }
1520
      else {
1521
        $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt));
1522
      }
1523
      if (!empty($account->uid) && user_access('access user profiles')) {
1524
        $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
1525
        $variables['user_picture'] = l($variables['user_picture'], "user/$account->uid", $attributes);
1526
      }
1527
    }
1528
  }
1529
}
1530

    
1531
/**
1532
 * Returns HTML for a list of users.
1533
 *
1534
 * @param $variables
1535
 *   An associative array containing:
1536
 *   - users: An array with user objects. Should contain at least the name and
1537
 *     uid.
1538
 *   - title: (optional) Title to pass on to theme_item_list().
1539
 *
1540
 * @ingroup themeable
1541
 */
1542
function theme_user_list($variables) {
1543
  $users = $variables['users'];
1544
  $title = $variables['title'];
1545
  $items = array();
1546

    
1547
  if (!empty($users)) {
1548
    foreach ($users as $user) {
1549
      $items[] = theme('username', array('account' => $user));
1550
    }
1551
  }
1552
  return theme('item_list', array('items' => $items, 'title' => $title));
1553
}
1554

    
1555
/**
1556
 * Determines if the current user is anonymous.
1557
 *
1558
 * @return bool
1559
 *   TRUE if the user is anonymous, FALSE if the user is authenticated.
1560
 */
1561
function user_is_anonymous() {
1562
  // Menu administrators can see items for anonymous when administering.
1563
  return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
1564
}
1565

    
1566
/**
1567
 * Determines if the current user is logged in.
1568
 *
1569
 * @return bool
1570
 *   TRUE if the user is logged in, FALSE if the user is anonymous.
1571
 */
1572
function user_is_logged_in() {
1573
  return (bool) $GLOBALS['user']->uid;
1574
}
1575

    
1576
/**
1577
 * Determines if the current user has access to the user registration page.
1578
 *
1579
 * @return bool
1580
 *   TRUE if the user is not already logged in and can register for an account.
1581
 */
1582
function user_register_access() {
1583
  return user_is_anonymous() && variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL);
1584
}
1585

    
1586
/**
1587
 * User view access callback.
1588
 *
1589
 * @param $account
1590
 *   Can either be a full user object or a $uid.
1591
 */
1592
function user_view_access($account) {
1593
  $uid = is_object($account) ? $account->uid : (int) $account;
1594

    
1595
  // Never allow access to view the anonymous user account.
1596
  if ($uid) {
1597
    // Admins can view all, users can view own profiles at all times.
1598
    if ($GLOBALS['user']->uid == $uid || user_access('administer users')) {
1599
      return TRUE;
1600
    }
1601
    elseif (user_access('access user profiles')) {
1602
      // At this point, load the complete account object.
1603
      if (!is_object($account)) {
1604
        $account = user_load($uid);
1605
      }
1606
      return (is_object($account) && $account->status);
1607
    }
1608
  }
1609
  return FALSE;
1610
}
1611

    
1612
/**
1613
 * Access callback for user account editing.
1614
 */
1615
function user_edit_access($account) {
1616
  return (($GLOBALS['user']->uid == $account->uid) || user_access('administer users')) && $account->uid > 0;
1617
}
1618

    
1619
/**
1620
 * Menu access callback; limit access to account cancellation pages.
1621
 *
1622
 * Limit access to users with the 'cancel account' permission or administrative
1623
 * users, and prevent the anonymous user from cancelling the account.
1624
 */
1625
function user_cancel_access($account) {
1626
  return ((($GLOBALS['user']->uid == $account->uid) && user_access('cancel account')) || user_access('administer users')) && $account->uid > 0;
1627
}
1628

    
1629
/**
1630
 * Implements hook_menu().
1631
 */
1632
function user_menu() {
1633
  $items['user/autocomplete'] = array(
1634
    'title' => 'User autocomplete',
1635
    'page callback' => 'user_autocomplete',
1636
    'access callback' => 'user_access',
1637
    'access arguments' => array('access user profiles'),
1638
    'type' => MENU_CALLBACK,
1639
    'file' => 'user.pages.inc',
1640
  );
1641

    
1642
  // Registration and login pages.
1643
  $items['user'] = array(
1644
    'title' => 'User account',
1645
    'title callback' => 'user_menu_title',
1646
    'page callback' => 'user_page',
1647
    'access callback' => TRUE,
1648
    'file' => 'user.pages.inc',
1649
    'weight' => -10,
1650
    'menu_name' => 'user-menu',
1651
  );
1652

    
1653
  $items['user/login'] = array(
1654
    'title' => 'Log in',
1655
    'access callback' => 'user_is_anonymous',
1656
    'type' => MENU_DEFAULT_LOCAL_TASK,
1657
  );
1658

    
1659
  $items['user/register'] = array(
1660
    'title' => 'Create new account',
1661
    'page callback' => 'drupal_get_form',
1662
    'page arguments' => array('user_register_form'),
1663
    'access callback' => 'user_register_access',
1664
    'type' => MENU_LOCAL_TASK,
1665
  );
1666

    
1667
  $items['user/password'] = array(
1668
    'title' => 'Request new password',
1669
    'page callback' => 'drupal_get_form',
1670
    'page arguments' => array('user_pass'),
1671
    'access callback' => TRUE,
1672
    'type' => MENU_LOCAL_TASK,
1673
    'file' => 'user.pages.inc',
1674
  );
1675
  $items['user/reset/%/%/%'] = array(
1676
    'title' => 'Reset password',
1677
    'page callback' => 'drupal_get_form',
1678
    'page arguments' => array('user_pass_reset', 2, 3, 4),
1679
    'access callback' => TRUE,
1680
    'type' => MENU_CALLBACK,
1681
    'file' => 'user.pages.inc',
1682
  );
1683

    
1684
  $items['user/logout'] = array(
1685
    'title' => 'Log out',
1686
    'access callback' => 'user_is_logged_in',
1687
    'page callback' => 'user_logout',
1688
    'weight' => 10,
1689
    'menu_name' => 'user-menu',
1690
    'file' => 'user.pages.inc',
1691
  );
1692

    
1693
  // User listing pages.
1694
  $items['admin/people'] = array(
1695
    'title' => 'People',
1696
    'description' => 'Manage user accounts, roles, and permissions.',
1697
    'page callback' => 'user_admin',
1698
    'page arguments' => array('list'),
1699
    'access arguments' => array('administer users'),
1700
    'position' => 'left',
1701
    'weight' => -4,
1702
    'file' => 'user.admin.inc',
1703
  );
1704
  $items['admin/people/people'] = array(
1705
    'title' => 'List',
1706
    'description' => 'Find and manage people interacting with your site.',
1707
    'access arguments' => array('administer users'),
1708
    'type' => MENU_DEFAULT_LOCAL_TASK,
1709
    'weight' => -10,
1710
    'file' => 'user.admin.inc',
1711
  );
1712

    
1713
  // Permissions and role forms.
1714
  $items['admin/people/permissions'] = array(
1715
    'title' => 'Permissions',
1716
    'description' => 'Determine access to features by selecting permissions for roles.',
1717
    'page callback' => 'drupal_get_form',
1718
    'page arguments' => array('user_admin_permissions'),
1719
    'access arguments' => array('administer permissions'),
1720
    'file' => 'user.admin.inc',
1721
    'type' => MENU_LOCAL_TASK,
1722
  );
1723
  $items['admin/people/permissions/list'] = array(
1724
    'title' => 'Permissions',
1725
    'description' => 'Determine access to features by selecting permissions for roles.',
1726
    'type' => MENU_DEFAULT_LOCAL_TASK,
1727
    'weight' => -8,
1728
  );
1729
  $items['admin/people/permissions/roles'] = array(
1730
    'title' => 'Roles',
1731
    'description' => 'List, edit, or add user roles.',
1732
    'page callback' => 'drupal_get_form',
1733
    'page arguments' => array('user_admin_roles'),
1734
    'access arguments' => array('administer permissions'),
1735
    'file' => 'user.admin.inc',
1736
    'type' => MENU_LOCAL_TASK,
1737
    'weight' => -5,
1738
  );
1739
  $items['admin/people/permissions/roles/edit/%user_role'] = array(
1740
    'title' => 'Edit role',
1741
    'page arguments' => array('user_admin_role', 5),
1742
    'access callback' => 'user_role_edit_access',
1743
    'access arguments' => array(5),
1744
  );
1745
  $items['admin/people/permissions/roles/delete/%user_role'] = array(
1746
    'title' => 'Delete role',
1747
    'page callback' => 'drupal_get_form',
1748
    'page arguments' => array('user_admin_role_delete_confirm', 5),
1749
    'access callback' => 'user_role_edit_access',
1750
    'access arguments' => array(5),
1751
    'file' => 'user.admin.inc',
1752
  );
1753

    
1754
  $items['admin/people/create'] = array(
1755
    'title' => 'Add user',
1756
    'page arguments' => array('create'),
1757
    'access arguments' => array('administer users'),
1758
    'type' => MENU_LOCAL_ACTION,
1759
  );
1760

    
1761
  // Administration pages.
1762
  $items['admin/config/people'] = array(
1763
    'title' => 'People',
1764
    'description' => 'Configure user accounts.',
1765
    'position' => 'left',
1766
    'weight' => -20,
1767
    'page callback' => 'system_admin_menu_block_page',
1768
    'access arguments' => array('access administration pages'),
1769
    'file' => 'system.admin.inc',
1770
    'file path' => drupal_get_path('module', 'system'),
1771
  );
1772
  $items['admin/config/people/accounts'] = array(
1773
    'title' => 'Account settings',
1774
    'description' => 'Configure default behavior of users, including registration requirements, e-mails, fields, and user pictures.',
1775
    'page callback' => 'drupal_get_form',
1776
    'page arguments' => array('user_admin_settings'),
1777
    'access arguments' => array('administer users'),
1778
    'file' => 'user.admin.inc',
1779
    'weight' => -10,
1780
  );
1781
  $items['admin/config/people/accounts/settings'] = array(
1782
    'title' => 'Settings',
1783
    'type' => MENU_DEFAULT_LOCAL_TASK,
1784
    'weight' => -10,
1785
  );
1786

    
1787
  $items['user/%user'] = array(
1788
    'title' => 'My account',
1789
    'title callback' => 'user_page_title',
1790
    'title arguments' => array(1),
1791
    'page callback' => 'user_view_page',
1792
    'page arguments' => array(1),
1793
    'access callback' => 'user_view_access',
1794
    'access arguments' => array(1),
1795
    // By assigning a different menu name, this item (and all registered child
1796
    // paths) are no longer considered as children of 'user'. When accessing the
1797
    // user account pages, the preferred menu link that is used to build the
1798
    // active trail (breadcrumb) will be found in this menu (unless there is
1799
    // more specific link), so the link to 'user' will not be in the breadcrumb.
1800
    'menu_name' => 'navigation',
1801
  );
1802

    
1803
  $items['user/%user/view'] = array(
1804
    'title' => 'View',
1805
    'type' => MENU_DEFAULT_LOCAL_TASK,
1806
    'weight' => -10,
1807
  );
1808

    
1809
  $items['user/%user/cancel'] = array(
1810
    'title' => 'Cancel account',
1811
    'page callback' => 'drupal_get_form',
1812
    'page arguments' => array('user_cancel_confirm_form', 1),
1813
    'access callback' => 'user_cancel_access',
1814
    'access arguments' => array(1),
1815
    'file' => 'user.pages.inc',
1816
  );
1817

    
1818
  $items['user/%user/cancel/confirm/%/%'] = array(
1819
    'title' => 'Confirm account cancellation',
1820
    'page callback' => 'user_cancel_confirm',
1821
    'page arguments' => array(1, 4, 5),
1822
    'access callback' => 'user_cancel_access',
1823
    'access arguments' => array(1),
1824
    'file' => 'user.pages.inc',
1825
  );
1826

    
1827
  $items['user/%user/edit'] = array(
1828
    'title' => 'Edit',
1829
    'page callback' => 'drupal_get_form',
1830
    'page arguments' => array('user_profile_form', 1),
1831
    'access callback' => 'user_edit_access',
1832
    'access arguments' => array(1),
1833
    'type' => MENU_LOCAL_TASK,
1834
    'file' => 'user.pages.inc',
1835
  );
1836

    
1837
  $items['user/%user_category/edit/account'] = array(
1838
    'title' => 'Account',
1839
    'type' => MENU_DEFAULT_LOCAL_TASK,
1840
    'load arguments' => array('%map', '%index'),
1841
  );
1842

    
1843
  if (($categories = _user_categories()) && (count($categories) > 1)) {
1844
    foreach ($categories as $key => $category) {
1845
      // 'account' is already handled by the MENU_DEFAULT_LOCAL_TASK.
1846
      if ($category['name'] != 'account') {
1847
        $items['user/%user_category/edit/' . $category['name']] = array(
1848
          'title callback' => 'check_plain',
1849
          'title arguments' => array($category['title']),
1850
          'page callback' => 'drupal_get_form',
1851
          'page arguments' => array('user_profile_form', 1, 3),
1852
          'access callback' => isset($category['access callback']) ? $category['access callback'] : 'user_edit_access',
1853
          'access arguments' => isset($category['access arguments']) ? $category['access arguments'] : array(1),
1854
          'type' => MENU_LOCAL_TASK,
1855
          'weight' => $category['weight'],
1856
          'load arguments' => array('%map', '%index'),
1857
          'tab_parent' => 'user/%/edit',
1858
          'file' => 'user.pages.inc',
1859
        );
1860
      }
1861
    }
1862
  }
1863
  return $items;
1864
}
1865

    
1866
/**
1867
 * Implements hook_menu_site_status_alter().
1868
 */
1869
function user_menu_site_status_alter(&$menu_site_status, $path) {
1870
  if ($menu_site_status == MENU_SITE_OFFLINE) {
1871
    // If the site is offline, log out unprivileged users.
1872
    if (user_is_logged_in() && !user_access('access site in maintenance mode')) {
1873
      module_load_include('pages.inc', 'user', 'user');
1874
      user_logout();
1875
    }
1876

    
1877
    if (user_is_anonymous()) {
1878
      switch ($path) {
1879
        case 'user':
1880
          // Forward anonymous user to login page.
1881
          drupal_goto('user/login');
1882
        case 'user/login':
1883
        case 'user/password':
1884
          // Disable offline mode.
1885
          $menu_site_status = MENU_SITE_ONLINE;
1886
          break;
1887
        default:
1888
          if (strpos($path, 'user/reset/') === 0) {
1889
            // Disable offline mode.
1890
            $menu_site_status = MENU_SITE_ONLINE;
1891
          }
1892
          break;
1893
      }
1894
    }
1895
  }
1896
  if (user_is_logged_in()) {
1897
    if ($path == 'user/login') {
1898
      // If user is logged in, redirect to 'user' instead of giving 403.
1899
      drupal_goto('user');
1900
    }
1901
    if ($path == 'user/register') {
1902
      // Authenticated user should be redirected to user edit page.
1903
      drupal_goto('user/' . $GLOBALS['user']->uid . '/edit');
1904
    }
1905
  }
1906
}
1907

    
1908
/**
1909
 * Implements hook_menu_link_alter().
1910
 */
1911
function user_menu_link_alter(&$link) {
1912
  // The path 'user' must be accessible for anonymous users, but only visible
1913
  // for authenticated users. Authenticated users should see "My account", but
1914
  // anonymous users should not see it at all. Therefore, invoke
1915
  // user_translated_menu_link_alter() to conditionally hide the link.
1916
  if ($link['link_path'] == 'user' && isset($link['module']) && $link['module'] == 'system') {
1917
    $link['options']['alter'] = TRUE;
1918
  }
1919

    
1920
  // Force the Logout link to appear on the top-level of 'user-menu' menu by
1921
  // default (i.e., unless it has been customized).
1922
  if ($link['link_path'] == 'user/logout' && isset($link['module']) && $link['module'] == 'system' && empty($link['customized'])) {
1923
    $link['plid'] = 0;
1924
  }
1925
}
1926

    
1927
/**
1928
 * Implements hook_translated_menu_link_alter().
1929
 */
1930
function user_translated_menu_link_alter(&$link) {
1931
  // Hide the "User account" link for anonymous users.
1932
  if ($link['link_path'] == 'user' && $link['module'] == 'system' && !$GLOBALS['user']->uid) {
1933
    $link['hidden'] = 1;
1934
  }
1935
}
1936

    
1937
/**
1938
 * Implements hook_admin_paths().
1939
 */
1940
function user_admin_paths() {
1941
  $paths = array(
1942
    'user/*/cancel' => TRUE,
1943
    'user/*/edit' => TRUE,
1944
    'user/*/edit/*' => TRUE,
1945
  );
1946
  return $paths;
1947
}
1948

    
1949
/**
1950
 * Returns $arg or the user ID of the current user if $arg is '%' or empty.
1951
 *
1952
 * Deprecated. Use %user_uid_optional instead.
1953
 *
1954
 * @todo D8: Remove.
1955
 */
1956
function user_uid_only_optional_to_arg($arg) {
1957
  return user_uid_optional_to_arg($arg);
1958
}
1959

    
1960
/**
1961
 * Load either a specified or the current user account.
1962
 *
1963
 * @param $uid
1964
 *   An optional user ID of the user to load. If not provided, the current
1965
 *   user's ID will be used.
1966
 * @return
1967
 *   A fully-loaded $user object upon successful user load, FALSE if user
1968
 *   cannot be loaded.
1969
 *
1970
 * @see user_load()
1971
 * @todo rethink the naming of this in Drupal 8.
1972
 */
1973
function user_uid_optional_load($uid = NULL) {
1974
  if (!isset($uid)) {
1975
    $uid = $GLOBALS['user']->uid;
1976
  }
1977
  return user_load($uid);
1978
}
1979

    
1980
/**
1981
 * Return a user object after checking if any profile category in the path exists.
1982
 */
1983
function user_category_load($uid, &$map, $index) {
1984
  static $user_categories, $accounts;
1985

    
1986
  // Cache $account - this load function will get called for each profile tab.
1987
  if (!isset($accounts[$uid])) {
1988
    $accounts[$uid] = user_load($uid);
1989
  }
1990
  $valid = TRUE;
1991
  if ($account = $accounts[$uid]) {
1992
    // Since the path is like user/%/edit/category_name, the category name will
1993
    // be at a position 2 beyond the index corresponding to the % wildcard.
1994
    $category_index = $index + 2;
1995
    // Valid categories may contain slashes, and hence need to be imploded.
1996
    $category_path = implode('/', array_slice($map, $category_index));
1997
    if ($category_path) {
1998
      // Check that the requested category exists.
1999
      $valid = FALSE;
2000
      if (!isset($user_categories)) {
2001
        $user_categories = _user_categories();
2002
      }
2003
      foreach ($user_categories as $category) {
2004
        if ($category['name'] == $category_path) {
2005
          $valid = TRUE;
2006
          // Truncate the map array in case the category name had slashes.
2007
          $map = array_slice($map, 0, $category_index);
2008
          // Assign the imploded category name to the last map element.
2009
          $map[$category_index] = $category_path;
2010
          break;
2011
        }
2012
      }
2013
    }
2014
  }
2015
  return $valid ? $account : FALSE;
2016
}
2017

    
2018
/**
2019
 * Returns $arg or the user ID of the current user if $arg is '%' or empty.
2020
 *
2021
 * @todo rethink the naming of this in Drupal 8.
2022
 */
2023
function user_uid_optional_to_arg($arg) {
2024
  // Give back the current user uid when called from eg. tracker, aka.
2025
  // with an empty arg. Also use the current user uid when called from
2026
  // the menu with a % for the current account link.
2027
  return empty($arg) || $arg == '%' ? $GLOBALS['user']->uid : $arg;
2028
}
2029

    
2030
/**
2031
 * Menu item title callback for the 'user' path.
2032
 *
2033
 * Anonymous users should see "User account", but authenticated users are
2034
 * expected to see "My account".
2035
 */
2036
function user_menu_title() {
2037
  return user_is_logged_in() ? t('My account') : t('User account');
2038
}
2039

    
2040
/**
2041
 * Menu item title callback - use the user name.
2042
 */
2043
function user_page_title($account) {
2044
  return is_object($account) ? format_username($account) : '';
2045
}
2046

    
2047
/**
2048
 * Discover which external authentication module(s) authenticated a username.
2049
 *
2050
 * @param $authname
2051
 *   A username used by an external authentication module.
2052
 * @return
2053
 *   An associative array with module as key and username as value.
2054
 */
2055
function user_get_authmaps($authname = NULL) {
2056
  $authmaps = db_query("SELECT module, authname FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchAllKeyed();
2057
  return count($authmaps) ? $authmaps : 0;
2058
}
2059

    
2060
/**
2061
 * Save mappings of which external authentication module(s) authenticated
2062
 * a user. Maps external usernames to user ids in the users table.
2063
 *
2064
 * @param $account
2065
 *   A user object.
2066
 * @param $authmaps
2067
 *   An associative array with a compound key and the username as the value.
2068
 *   The key is made up of 'authname_' plus the name of the external authentication
2069
 *   module.
2070
 * @see user_external_login_register()
2071
 */
2072
function user_set_authmaps($account, $authmaps) {
2073
  foreach ($authmaps as $key => $value) {
2074
    $module = explode('_', $key, 2);
2075
    if ($value) {
2076
      db_merge('authmap')
2077
        ->key(array(
2078
          'uid' => $account->uid,
2079
          'module' => $module[1],
2080
        ))
2081
        ->fields(array('authname' => $value))
2082
        ->execute();
2083
    }
2084
    else {
2085
      db_delete('authmap')
2086
        ->condition('uid', $account->uid)
2087
        ->condition('module', $module[1])
2088
        ->execute();
2089
    }
2090
  }
2091
}
2092

    
2093
/**
2094
 * Form builder; the main user login form.
2095
 *
2096
 * @ingroup forms
2097
 */
2098
function user_login($form, &$form_state) {
2099
  global $user;
2100

    
2101
  // If we are already logged on, go to the user page instead.
2102
  if ($user->uid) {
2103
    drupal_goto('user/' . $user->uid);
2104
  }
2105

    
2106
  // Display login form:
2107
  $form['name'] = array('#type' => 'textfield',
2108
    '#title' => t('Username'),
2109
    '#size' => 60,
2110
    '#maxlength' => USERNAME_MAX_LENGTH,
2111
    '#required' => TRUE,
2112
  );
2113

    
2114
  $form['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal')));
2115
  $form['pass'] = array('#type' => 'password',
2116
    '#title' => t('Password'),
2117
    '#description' => t('Enter the password that accompanies your username.'),
2118
    '#required' => TRUE,
2119
  );
2120
  $form['#validate'] = user_login_default_validators();
2121
  $form['actions'] = array('#type' => 'actions');
2122
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in'));
2123

    
2124
  return $form;
2125
}
2126

    
2127
/**
2128
 * Set up a series for validators which check for blocked users,
2129
 * then authenticate against local database, then return an error if
2130
 * authentication fails. Distributed authentication modules are welcome
2131
 * to use hook_form_alter() to change this series in order to
2132
 * authenticate against their user database instead of the local users
2133
 * table. If a distributed authentication module is successful, it
2134
 * should set $form_state['uid'] to a user ID.
2135
 *
2136
 * We use three validators instead of one since external authentication
2137
 * modules usually only need to alter the second validator.
2138
 *
2139
 * @see user_login_name_validate()
2140
 * @see user_login_authenticate_validate()
2141
 * @see user_login_final_validate()
2142
 * @return array
2143
 *   A simple list of validate functions.
2144
 */
2145
function user_login_default_validators() {
2146
  return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate');
2147
}
2148

    
2149
/**
2150
 * A FAPI validate handler. Sets an error if supplied username has been blocked.
2151
 */
2152
function user_login_name_validate($form, &$form_state) {
2153
  if (!empty($form_state['values']['name']) && user_is_blocked($form_state['values']['name'])) {
2154
    // Blocked in user administration.
2155
    form_set_error('name', t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name'])));
2156
  }
2157
}
2158

    
2159
/**
2160
 * A validate handler on the login form. Check supplied username/password
2161
 * against local users table. If successful, $form_state['uid']
2162
 * is set to the matching user ID.
2163
 */
2164
function user_login_authenticate_validate($form, &$form_state) {
2165
  $password = trim($form_state['values']['pass']);
2166
  if (!empty($form_state['values']['name']) && !empty($password)) {
2167
    // Do not allow any login from the current user's IP if the limit has been
2168
    // reached. Default is 50 failed attempts allowed in one hour. This is
2169
    // independent of the per-user limit to catch attempts from one IP to log
2170
    // in to many different user accounts.  We have a reasonably high limit
2171
    // since there may be only one apparent IP for all users at an institution.
2172
    if (!flood_is_allowed('failed_login_attempt_ip', variable_get('user_failed_login_ip_limit', 50), variable_get('user_failed_login_ip_window', 3600))) {
2173
      $form_state['flood_control_triggered'] = 'ip';
2174
      return;
2175
    }
2176
    $account = db_query("SELECT * FROM {users} WHERE name = :name AND status = 1", array(':name' => $form_state['values']['name']))->fetchObject();
2177
    if ($account) {
2178
      if (variable_get('user_failed_login_identifier_uid_only', FALSE)) {
2179
        // Register flood events based on the uid only, so they apply for any
2180
        // IP address. This is the most secure option.
2181
        $identifier = $account->uid;
2182
      }
2183
      else {
2184
        // The default identifier is a combination of uid and IP address. This
2185
        // is less secure but more resistant to denial-of-service attacks that
2186
        // could lock out all users with public user names.
2187
        $identifier = $account->uid . '-' . ip_address();
2188
      }
2189
      $form_state['flood_control_user_identifier'] = $identifier;
2190

    
2191
      // Don't allow login if the limit for this user has been reached.
2192
      // Default is to allow 5 failed attempts every 6 hours.
2193
      if (!flood_is_allowed('failed_login_attempt_user', variable_get('user_failed_login_user_limit', 5), variable_get('user_failed_login_user_window', 21600), $identifier)) {
2194
        $form_state['flood_control_triggered'] = 'user';
2195
        return;
2196
      }
2197
    }
2198
    // We are not limited by flood control, so try to authenticate.
2199
    // Set $form_state['uid'] as a flag for user_login_final_validate().
2200
    $form_state['uid'] = user_authenticate($form_state['values']['name'], $password);
2201
  }
2202
}
2203

    
2204
/**
2205
 * The final validation handler on the login form.
2206
 *
2207
 * Sets a form error if user has not been authenticated, or if too many
2208
 * logins have been attempted. This validation function should always
2209
 * be the last one.
2210
 */
2211
function user_login_final_validate($form, &$form_state) {
2212
  if (empty($form_state['uid'])) {
2213
    // Always register an IP-based failed login event.
2214
    flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600));
2215
    // Register a per-user failed login event.
2216
    if (isset($form_state['flood_control_user_identifier'])) {
2217
      flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 21600), $form_state['flood_control_user_identifier']);
2218
    }
2219

    
2220
    if (isset($form_state['flood_control_triggered'])) {
2221
      if ($form_state['flood_control_triggered'] == 'user') {
2222
        form_set_error('name', format_plural(variable_get('user_failed_login_user_limit', 5), 'Sorry, there has been more than one failed login attempt for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', 'Sorry, there have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array('@url' => url('user/password'))));
2223
      }
2224
      else {
2225
        // We did not find a uid, so the limit is IP-based.
2226
        form_set_error('name', t('Sorry, too many failed login attempts from your IP address. This IP address is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array('@url' => url('user/password'))));
2227
      }
2228
    }
2229
    else {
2230
      form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password', array('query' => array('name' => $form_state['values']['name']))))));
2231
      watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name']));
2232
    }
2233
  }
2234
  elseif (isset($form_state['flood_control_user_identifier'])) {
2235
    // Clear past failures for this user so as not to block a user who might
2236
    // log in and out more than once in an hour.
2237
    flood_clear_event('failed_login_attempt_user', $form_state['flood_control_user_identifier']);
2238
  }
2239
}
2240

    
2241
/**
2242
 * Try to validate the user's login credentials locally.
2243
 *
2244
 * @param $name
2245
 *   User name to authenticate.
2246
 * @param $password
2247
 *   A plain-text password, such as trimmed text from form values.
2248
 * @return
2249
 *   The user's uid on success, or FALSE on failure to authenticate.
2250
 */
2251
function user_authenticate($name, $password) {
2252
  $uid = FALSE;
2253
  if (!empty($name) && !empty($password)) {
2254
    $account = user_load_by_name($name);
2255
    if ($account) {
2256
      // Allow alternate password hashing schemes.
2257
      require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
2258
      if (user_check_password($password, $account)) {
2259
        // Successful authentication.
2260
        $uid = $account->uid;
2261

    
2262
        // Update user to new password scheme if needed.
2263
        if (user_needs_new_hash($account)) {
2264
          user_save($account, array('pass' => $password));
2265
        }
2266
      }
2267
    }
2268
  }
2269
  return $uid;
2270
}
2271

    
2272
/**
2273
 * Finalize the login process. Must be called when logging in a user.
2274
 *
2275
 * The function records a watchdog message about the new session, saves the
2276
 * login timestamp, calls hook_user_login(), and generates a new session.
2277
 *
2278
 * @param array $edit
2279
 *   The array of form values submitted by the user.
2280
 *
2281
 * @see hook_user_login()
2282
 */
2283
function user_login_finalize(&$edit = array()) {
2284
  global $user;
2285
  watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
2286
  // Update the user table timestamp noting user has logged in.
2287
  // This is also used to invalidate one-time login links.
2288
  $user->login = REQUEST_TIME;
2289
  db_update('users')
2290
    ->fields(array('login' => $user->login))
2291
    ->condition('uid', $user->uid)
2292
    ->execute();
2293

    
2294
  // Regenerate the session ID to prevent against session fixation attacks.
2295
  // This is called before hook_user in case one of those functions fails
2296
  // or incorrectly does a redirect which would leave the old session in place.
2297
  drupal_session_regenerate();
2298

    
2299
  user_module_invoke('login', $edit, $user);
2300
}
2301

    
2302
/**
2303
 * Submit handler for the login form. Load $user object and perform standard login
2304
 * tasks. The user is then redirected to the My Account page. Setting the
2305
 * destination in the query string overrides the redirect.
2306
 */
2307
function user_login_submit($form, &$form_state) {
2308
  global $user;
2309
  $user = user_load($form_state['uid']);
2310
  $form_state['redirect'] = 'user/' . $user->uid;
2311

    
2312
  user_login_finalize($form_state);
2313
}
2314

    
2315
/**
2316
 * Helper function for authentication modules. Either logs in or registers
2317
 * the current user, based on username. Either way, the global $user object is
2318
 * populated and login tasks are performed.
2319
 */
2320
function user_external_login_register($name, $module) {
2321
  $account = user_external_load($name);
2322
  if (!$account) {
2323
    // Register this new user.
2324
    $userinfo = array(
2325
      'name' => $name,
2326
      'pass' => user_password(),
2327
      'init' => $name,
2328
      'status' => 1,
2329
      'access' => REQUEST_TIME
2330
    );
2331
    $account = user_save(drupal_anonymous_user(), $userinfo);
2332
    // Terminate if an error occurred during user_save().
2333
    if (!$account) {
2334
      drupal_set_message(t("Error saving user account."), 'error');
2335
      return;
2336
    }
2337
    user_set_authmaps($account, array("authname_$module" => $name));
2338
  }
2339

    
2340
  // Log user in.
2341
  $form_state['uid'] = $account->uid;
2342
  user_login_submit(array(), $form_state);
2343
}
2344

    
2345
/**
2346
 * Generates a unique URL for a user to login and reset their password.
2347
 *
2348
 * @param object $account
2349
 *   An object containing the user account, which must contain at least the
2350
 *   following properties:
2351
 *   - uid: The user ID number.
2352
 *   - login: The UNIX timestamp of the user's last login.
2353
 *
2354
 * @return
2355
 *   A unique URL that provides a one-time log in for the user, from which
2356
 *   they can change their password.
2357
 */
2358
function user_pass_reset_url($account) {
2359
  $timestamp = REQUEST_TIME;
2360
  return url("user/reset/$account->uid/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login, $account->uid), array('absolute' => TRUE));
2361
}
2362

    
2363
/**
2364
 * Generates a URL to confirm an account cancellation request.
2365
 *
2366
 * @param object $account
2367
 *   The user account object, which must contain at least the following
2368
 *   properties:
2369
 *   - uid: The user ID number.
2370
 *   - pass: The hashed user password string.
2371
 *   - login: The UNIX timestamp of the user's last login.
2372
 *
2373
 * @return
2374
 *   A unique URL that may be used to confirm the cancellation of the user
2375
 *   account.
2376
 *
2377
 * @see user_mail_tokens()
2378
 * @see user_cancel_confirm()
2379
 */
2380
function user_cancel_url($account) {
2381
  $timestamp = REQUEST_TIME;
2382
  return url("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login, $account->uid), array('absolute' => TRUE));
2383
}
2384

    
2385
/**
2386
 * Creates a unique hash value for use in time-dependent per-user URLs.
2387
 *
2388
 * This hash is normally used to build a unique and secure URL that is sent to
2389
 * the user by email for purposes such as resetting the user's password. In
2390
 * order to validate the URL, the same hash can be generated again, from the
2391
 * same information, and compared to the hash value from the URL. The URL
2392
 * normally contains both the time stamp and the numeric user ID. The login
2393
 * timestamp and hashed password are retrieved from the database as necessary.
2394
 * For a usage example, see user_cancel_url() and user_cancel_confirm().
2395
 *
2396
 * @param string $password
2397
 *   The hashed user account password value.
2398
 * @param int $timestamp
2399
 *   A UNIX timestamp, typically REQUEST_TIME.
2400
 * @param int $login
2401
 *   The UNIX timestamp of the user's last login.
2402
 * @param int $uid
2403
 *   The user ID of the user account.
2404
 *
2405
 * @return
2406
 *   A string that is safe for use in URLs and SQL statements.
2407
 */
2408
function user_pass_rehash($password, $timestamp, $login, $uid) {
2409
  // Backwards compatibility: Try to determine a $uid if one was not passed.
2410
  // (Since $uid is a required parameter to this function, a PHP warning will
2411
  // be generated if it's not provided, which is an indication that the calling
2412
  // code should be updated. But the code below will try to generate a correct
2413
  // hash in the meantime.)
2414
  if (!isset($uid)) {
2415
    $uids = db_query_range('SELECT uid FROM {users} WHERE pass = :password AND login = :login AND uid > 0', 0, 2, array(':password' => $password, ':login' => $login))->fetchCol();
2416
    // If exactly one user account matches the provided password and login
2417
    // timestamp, proceed with that $uid.
2418
    if (count($uids) == 1) {
2419
      $uid = reset($uids);
2420
    }
2421
    // Otherwise there is no safe hash to return, so return a random string
2422
    // that will never be treated as a valid token.
2423
    else {
2424
      return drupal_random_key();
2425
    }
2426
  }
2427

    
2428
  return drupal_hmac_base64($timestamp . $login . $uid, drupal_get_hash_salt() . $password);
2429
}
2430

    
2431
/**
2432
 * Cancel a user account.
2433
 *
2434
 * Since the user cancellation process needs to be run in a batch, either
2435
 * Form API will invoke it, or batch_process() needs to be invoked after calling
2436
 * this function and should define the path to redirect to.
2437
 *
2438
 * @param $edit
2439
 *   An array of submitted form values.
2440
 * @param $uid
2441
 *   The user ID of the user account to cancel.
2442
 * @param $method
2443
 *   The account cancellation method to use.
2444
 *
2445
 * @see _user_cancel()
2446
 */
2447
function user_cancel($edit, $uid, $method) {
2448
  global $user;
2449

    
2450
  $account = user_load($uid);
2451

    
2452
  if (!$account) {
2453
    drupal_set_message(t('The user account %id does not exist.', array('%id' => $uid)), 'error');
2454
    watchdog('user', 'Attempted to cancel non-existing user account: %id.', array('%id' => $uid), WATCHDOG_ERROR);
2455
    return;
2456
  }
2457

    
2458
  // Initialize batch (to set title).
2459
  $batch = array(
2460
    'title' => t('Cancelling account'),
2461
    'operations' => array(),
2462
  );
2463
  batch_set($batch);
2464

    
2465
  // Modules use hook_user_delete() to respond to deletion.
2466
  if ($method != 'user_cancel_delete') {
2467
    // Allow modules to add further sets to this batch.
2468
    module_invoke_all('user_cancel', $edit, $account, $method);
2469
  }
2470

    
2471
  // Finish the batch and actually cancel the account.
2472
  $batch = array(
2473
    'title' => t('Cancelling user account'),
2474
    'operations' => array(
2475
      array('_user_cancel', array($edit, $account, $method)),
2476
    ),
2477
  );
2478

    
2479
  // After cancelling account, ensure that user is logged out.
2480
  if ($account->uid == $user->uid) {
2481
    // Batch API stores data in the session, so use the finished operation to
2482
    // manipulate the current user's session id.
2483
    $batch['finished'] = '_user_cancel_session_regenerate';
2484
  }
2485

    
2486
  batch_set($batch);
2487

    
2488
  // Batch processing is either handled via Form API or has to be invoked
2489
  // manually.
2490
}
2491

    
2492
/**
2493
 * Implements callback_batch_operation().
2494
 *
2495
 * Last step for cancelling a user account.
2496
 *
2497
 * Since batch and session API require a valid user account, the actual
2498
 * cancellation of a user account needs to happen last.
2499
 *
2500
 * @see user_cancel()
2501
 */
2502
function _user_cancel($edit, $account, $method) {
2503
  global $user;
2504

    
2505
  switch ($method) {
2506
    case 'user_cancel_block':
2507
    case 'user_cancel_block_unpublish':
2508
    default:
2509
      // Send account blocked notification if option was checked.
2510
      if (!empty($edit['user_cancel_notify'])) {
2511
        _user_mail_notify('status_blocked', $account);
2512
      }
2513
      user_save($account, array('status' => 0));
2514
      drupal_set_message(t('%name has been disabled.', array('%name' => $account->name)));
2515
      watchdog('user', 'Blocked user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
2516
      break;
2517

    
2518
    case 'user_cancel_reassign':
2519
    case 'user_cancel_delete':
2520
      // Send account canceled notification if option was checked.
2521
      if (!empty($edit['user_cancel_notify'])) {
2522
        _user_mail_notify('status_canceled', $account);
2523
      }
2524
      user_delete($account->uid);
2525
      drupal_set_message(t('%name has been deleted.', array('%name' => $account->name)));
2526
      watchdog('user', 'Deleted user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
2527
      break;
2528
  }
2529

    
2530
  // After cancelling account, ensure that user is logged out. We can't destroy
2531
  // their session though, as we might have information in it, and we can't
2532
  // regenerate it because batch API uses the session ID, we will regenerate it
2533
  // in _user_cancel_session_regenerate().
2534
  if ($account->uid == $user->uid) {
2535
    $user = drupal_anonymous_user();
2536
  }
2537

    
2538
  // Clear the cache for anonymous users.
2539
  cache_clear_all();
2540
}
2541

    
2542
/**
2543
 * Implements callback_batch_finished().
2544
 *
2545
 * Finished batch processing callback for cancelling a user account.
2546
 *
2547
 * @see user_cancel()
2548
 */
2549
function _user_cancel_session_regenerate() {
2550
  // Regenerate the users session instead of calling session_destroy() as we
2551
  // want to preserve any messages that might have been set.
2552
  drupal_session_regenerate();
2553
}
2554

    
2555
/**
2556
 * Delete a user.
2557
 *
2558
 * @param $uid
2559
 *   A user ID.
2560
 */
2561
function user_delete($uid) {
2562
  user_delete_multiple(array($uid));
2563
}
2564

    
2565
/**
2566
 * Delete multiple user accounts.
2567
 *
2568
 * @param $uids
2569
 *   An array of user IDs.
2570
 */
2571
function user_delete_multiple(array $uids) {
2572
  if (!empty($uids)) {
2573
    $accounts = user_load_multiple($uids, array());
2574

    
2575
    $transaction = db_transaction();
2576
    try {
2577
      foreach ($accounts as $uid => $account) {
2578
        module_invoke_all('user_delete', $account);
2579
        module_invoke_all('entity_delete', $account, 'user');
2580
        field_attach_delete('user', $account);
2581
        drupal_session_destroy_uid($account->uid);
2582
      }
2583

    
2584
      db_delete('users')
2585
        ->condition('uid', $uids, 'IN')
2586
        ->execute();
2587
      db_delete('users_roles')
2588
        ->condition('uid', $uids, 'IN')
2589
        ->execute();
2590
      db_delete('authmap')
2591
        ->condition('uid', $uids, 'IN')
2592
        ->execute();
2593
    }
2594
    catch (Exception $e) {
2595
      $transaction->rollback();
2596
      watchdog_exception('user', $e);
2597
      throw $e;
2598
    }
2599
    entity_get_controller('user')->resetCache();
2600
  }
2601
}
2602

    
2603
/**
2604
 * Page callback wrapper for user_view().
2605
 */
2606
function user_view_page($account) {
2607
  // An administrator may try to view a non-existent account,
2608
  // so we give them a 404 (versus a 403 for non-admins).
2609
  return is_object($account) ? user_view($account) : MENU_NOT_FOUND;
2610
}
2611

    
2612
/**
2613
 * Generate an array for rendering the given user.
2614
 *
2615
 * When viewing a user profile, the $page array contains:
2616
 *
2617
 * - $page['content']['Profile Category']:
2618
 *   Profile categories keyed by their human-readable names.
2619
 * - $page['content']['Profile Category']['profile_machine_name']:
2620
 *   Profile fields keyed by their machine-readable names.
2621
 * - $page['content']['user_picture']:
2622
 *   User's rendered picture.
2623
 * - $page['content']['summary']:
2624
 *   Contains the default "History" profile data for a user.
2625
 * - $page['content']['#account']:
2626
 *   The user account of the profile being viewed.
2627
 *
2628
 * To theme user profiles, copy modules/user/user-profile.tpl.php
2629
 * to your theme directory, and edit it as instructed in that file's comments.
2630
 *
2631
 * @param $account
2632
 *   A user object.
2633
 * @param $view_mode
2634
 *   View mode, e.g. 'full'.
2635
 * @param $langcode
2636
 *   (optional) A language code to use for rendering. Defaults to the global
2637
 *   content language of the current request.
2638
 *
2639
 * @return
2640
 *   An array as expected by drupal_render().
2641
 */
2642
function user_view($account, $view_mode = 'full', $langcode = NULL) {
2643
  if (!isset($langcode)) {
2644
    $langcode = $GLOBALS['language_content']->language;
2645
  }
2646

    
2647
  // Retrieve all profile fields and attach to $account->content.
2648
  user_build_content($account, $view_mode, $langcode);
2649

    
2650
  $build = $account->content;
2651
  // We don't need duplicate rendering info in account->content.
2652
  unset($account->content);
2653

    
2654
  $build += array(
2655
    '#theme' => 'user_profile',
2656
    '#account' => $account,
2657
    '#view_mode' => $view_mode,
2658
    '#language' => $langcode,
2659
  );
2660

    
2661
  // Allow modules to modify the structured user.
2662
  $type = 'user';
2663
  drupal_alter(array('user_view', 'entity_view'), $build, $type);
2664

    
2665
  return $build;
2666
}
2667

    
2668
/**
2669
 * Builds a structured array representing the profile content.
2670
 *
2671
 * @param $account
2672
 *   A user object.
2673
 * @param $view_mode
2674
 *   View mode, e.g. 'full'.
2675
 * @param $langcode
2676
 *   (optional) A language code to use for rendering. Defaults to the global
2677
 *   content language of the current request.
2678
 */
2679
function user_build_content($account, $view_mode = 'full', $langcode = NULL) {
2680
  if (!isset($langcode)) {
2681
    $langcode = $GLOBALS['language_content']->language;
2682
  }
2683

    
2684
  // Remove previously built content, if exists.
2685
  $account->content = array();
2686

    
2687
  // Allow modules to change the view mode.
2688
  $view_mode = key(entity_view_mode_prepare('user', array($account->uid => $account), $view_mode, $langcode));
2689

    
2690
  // Build fields content.
2691
  field_attach_prepare_view('user', array($account->uid => $account), $view_mode, $langcode);
2692
  entity_prepare_view('user', array($account->uid => $account), $langcode);
2693
  $account->content += field_attach_view('user', $account, $view_mode, $langcode);
2694

    
2695
  // Populate $account->content with a render() array.
2696
  module_invoke_all('user_view', $account, $view_mode, $langcode);
2697
  module_invoke_all('entity_view', $account, 'user', $view_mode, $langcode);
2698

    
2699
  // Make sure the current view mode is stored if no module has already
2700
  // populated the related key.
2701
  $account->content += array('#view_mode' => $view_mode);
2702
}
2703

    
2704
/**
2705
 * Implements hook_mail().
2706
 */
2707
function user_mail($key, &$message, $params) {
2708
  $language = $message['language'];
2709
  $variables = array('user' => $params['account']);
2710
  $message['subject'] .= _user_mail_text($key . '_subject', $language, $variables);
2711
  $message['body'][] = _user_mail_text($key . '_body', $language, $variables);
2712
}
2713

    
2714
/**
2715
 * Returns a mail string for a variable name.
2716
 *
2717
 * Used by user_mail() and the settings forms to retrieve strings.
2718
 */
2719
function _user_mail_text($key, $language = NULL, $variables = array(), $replace = TRUE) {
2720
  $langcode = isset($language) ? $language->language : NULL;
2721

    
2722
  if ($admin_setting = variable_get('user_mail_' . $key, FALSE)) {
2723
    // An admin setting overrides the default string.
2724
    $text = $admin_setting;
2725
  }
2726
  else {
2727
    // No override, return default string.
2728
    switch ($key) {
2729
      case 'register_no_approval_required_subject':
2730
        $text = t('Account details for [user:name] at [site:name]', array(), array('langcode' => $langcode));
2731
        break;
2732
      case 'register_no_approval_required_body':
2733
        $text = t("[user:name],
2734

    
2735
Thank you for registering at [site:name]. You may now log in by clicking this link or copying and pasting it to your browser:
2736

    
2737
[user:one-time-login-url]
2738

    
2739
This link can only be used once to log in and will lead you to a page where you can set your password.
2740

    
2741
After setting your password, you will be able to log in at [site:login-url] in the future using:
2742

    
2743
username: [user:name]
2744
password: Your password
2745

    
2746
--  [site:name] team", array(), array('langcode' => $langcode));
2747
        break;
2748

    
2749
      case 'register_admin_created_subject':
2750
        $text = t('An administrator created an account for you at [site:name]', array(), array('langcode' => $langcode));
2751
        break;
2752
      case 'register_admin_created_body':
2753
        $text = t("[user:name],
2754

    
2755
A site administrator at [site:name] has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:
2756

    
2757
[user:one-time-login-url]
2758

    
2759
This link can only be used once to log in and will lead you to a page where you can set your password.
2760

    
2761
After setting your password, you will be able to log in at [site:login-url] in the future using:
2762

    
2763
username: [user:name]
2764
password: Your password
2765

    
2766
--  [site:name] team", array(), array('langcode' => $langcode));
2767
        break;
2768

    
2769
      case 'register_pending_approval_subject':
2770
      case 'register_pending_approval_admin_subject':
2771
        $text = t('Account details for [user:name] at [site:name] (pending admin approval)', array(), array('langcode' => $langcode));
2772
        break;
2773
      case 'register_pending_approval_body':
2774
        $text = t("[user:name],
2775

    
2776
Thank you for registering at [site:name]. 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.
2777

    
2778

    
2779
--  [site:name] team", array(), array('langcode' => $langcode));
2780
        break;
2781
      case 'register_pending_approval_admin_body':
2782
        $text = t("[user:name] has applied for an account.
2783

    
2784
[user:edit-url]", array(), array('langcode' => $langcode));
2785
        break;
2786

    
2787
      case 'password_reset_subject':
2788
        $text = t('Replacement login information for [user:name] at [site:name]', array(), array('langcode' => $langcode));
2789
        break;
2790
      case 'password_reset_body':
2791
        $text = t("[user:name],
2792

    
2793
A request to reset the password for your account has been made at [site:name].
2794

    
2795
You may now log in by clicking this link or copying and pasting it to your browser:
2796

    
2797
[user:one-time-login-url]
2798

    
2799
This link can only be used once to log in and will lead you to a page where you can set your password. It expires after one day and nothing will happen if it's not used.
2800

    
2801
--  [site:name] team", array(), array('langcode' => $langcode));
2802
        break;
2803

    
2804
      case 'status_activated_subject':
2805
        $text = t('Account details for [user:name] at [site:name] (approved)', array(), array('langcode' => $langcode));
2806
        break;
2807
      case 'status_activated_body':
2808
        $text = t("[user:name],
2809

    
2810
Your account at [site:name] has been activated.
2811

    
2812
You may now log in by clicking this link or copying and pasting it into your browser:
2813

    
2814
[user:one-time-login-url]
2815

    
2816
This link can only be used once to log in and will lead you to a page where you can set your password.
2817

    
2818
After setting your password, you will be able to log in at [site:login-url] in the future using:
2819

    
2820
username: [user:name]
2821
password: Your password
2822

    
2823
--  [site:name] team", array(), array('langcode' => $langcode));
2824
        break;
2825

    
2826
      case 'status_blocked_subject':
2827
        $text = t('Account details for [user:name] at [site:name] (blocked)', array(), array('langcode' => $langcode));
2828
        break;
2829
      case 'status_blocked_body':
2830
        $text = t("[user:name],
2831

    
2832
Your account on [site:name] has been blocked.
2833

    
2834
--  [site:name] team", array(), array('langcode' => $langcode));
2835
        break;
2836

    
2837
      case 'cancel_confirm_subject':
2838
        $text = t('Account cancellation request for [user:name] at [site:name]', array(), array('langcode' => $langcode));
2839
        break;
2840
      case 'cancel_confirm_body':
2841
        $text = t("[user:name],
2842

    
2843
A request to cancel your account has been made at [site:name].
2844

    
2845
You may now cancel your account on [site:url-brief] by clicking this link or copying and pasting it into your browser:
2846

    
2847
[user:cancel-url]
2848

    
2849
NOTE: The cancellation of your account is not reversible.
2850

    
2851
This link expires in one day and nothing will happen if it is not used.
2852

    
2853
--  [site:name] team", array(), array('langcode' => $langcode));
2854
        break;
2855

    
2856
      case 'status_canceled_subject':
2857
        $text = t('Account details for [user:name] at [site:name] (canceled)', array(), array('langcode' => $langcode));
2858
        break;
2859
      case 'status_canceled_body':
2860
        $text = t("[user:name],
2861

    
2862
Your account on [site:name] has been canceled.
2863

    
2864
--  [site:name] team", array(), array('langcode' => $langcode));
2865
        break;
2866
    }
2867
  }
2868

    
2869
  if ($replace) {
2870
    // We do not sanitize the token replacement, since the output of this
2871
    // replacement is intended for an e-mail message, not a web browser.
2872
    return token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
2873
  }
2874

    
2875
  return $text;
2876
}
2877

    
2878
/**
2879
 * Token callback to add unsafe tokens for user mails.
2880
 *
2881
 * This function is used by the token_replace() call at the end of
2882
 * _user_mail_text() to set up some additional tokens that can be
2883
 * used in email messages generated by user_mail().
2884
 *
2885
 * @param $replacements
2886
 *   An associative array variable containing mappings from token names to
2887
 *   values (for use with strtr()).
2888
 * @param $data
2889
 *   An associative array of token replacement values. If the 'user' element
2890
 *   exists, it must contain a user account object with the following
2891
 *   properties:
2892
 *   - login: The UNIX timestamp of the user's last login.
2893
 *   - pass: The hashed account login password.
2894
 * @param $options
2895
 *   Unused parameter required by the token_replace() function.
2896
 */
2897
function user_mail_tokens(&$replacements, $data, $options) {
2898
  if (isset($data['user'])) {
2899
    $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user']);
2900
    $replacements['[user:cancel-url]'] = user_cancel_url($data['user']);
2901
  }
2902
}
2903

    
2904
/*** Administrative features ***********************************************/
2905

    
2906
/**
2907
 * Retrieve an array of roles matching specified conditions.
2908
 *
2909
 * @param $membersonly
2910
 *   Set this to TRUE to exclude the 'anonymous' role.
2911
 * @param $permission
2912
 *   A string containing a permission. If set, only roles containing that
2913
 *   permission are returned.
2914
 *
2915
 * @return
2916
 *   An associative array with the role id as the key and the role name as
2917
 *   value.
2918
 */
2919
function user_roles($membersonly = FALSE, $permission = NULL) {
2920
  $query = db_select('role', 'r');
2921
  $query->addTag('translatable');
2922
  $query->fields('r', array('rid', 'name'));
2923
  $query->orderBy('weight');
2924
  $query->orderBy('name');
2925
  if (!empty($permission)) {
2926
    $query->innerJoin('role_permission', 'p', 'r.rid = p.rid');
2927
    $query->condition('p.permission', $permission);
2928
  }
2929
  $result = $query->execute();
2930

    
2931
  $roles = array();
2932
  foreach ($result as $role) {
2933
    switch ($role->rid) {
2934
      // We only translate the built in role names
2935
      case DRUPAL_ANONYMOUS_RID:
2936
        if (!$membersonly) {
2937
          $roles[$role->rid] = t($role->name);
2938
        }
2939
        break;
2940
      case DRUPAL_AUTHENTICATED_RID:
2941
        $roles[$role->rid] = t($role->name);
2942
        break;
2943
      default:
2944
        $roles[$role->rid] = $role->name;
2945
    }
2946
  }
2947

    
2948
  return $roles;
2949
}
2950

    
2951
/**
2952
 * Fetches a user role by role ID.
2953
 *
2954
 * @param $rid
2955
 *   An integer representing the role ID.
2956
 *
2957
 * @return
2958
 *   A fully-loaded role object if a role with the given ID exists, or FALSE
2959
 *   otherwise.
2960
 *
2961
 * @see user_role_load_by_name()
2962
 */
2963
function user_role_load($rid) {
2964
  return db_select('role', 'r')
2965
    ->fields('r')
2966
    ->condition('rid', $rid)
2967
    ->execute()
2968
    ->fetchObject();
2969
}
2970

    
2971
/**
2972
 * Fetches a user role by role name.
2973
 *
2974
 * @param $role_name
2975
 *   A string representing the role name.
2976
 *
2977
 * @return
2978
 *   A fully-loaded role object if a role with the given name exists, or FALSE
2979
 *   otherwise.
2980
 *
2981
 * @see user_role_load()
2982
 */
2983
function user_role_load_by_name($role_name) {
2984
  return db_select('role', 'r')
2985
    ->fields('r')
2986
    ->condition('name', $role_name)
2987
    ->execute()
2988
    ->fetchObject();
2989
}
2990

    
2991
/**
2992
 * Save a user role to the database.
2993
 *
2994
 * @param $role
2995
 *   A role object to modify or add. If $role->rid is not specified, a new
2996
 *   role will be created.
2997
 * @return
2998
 *   Status constant indicating if role was created or updated.
2999
 *   Failure to write the user role record will return FALSE. Otherwise.
3000
 *   SAVED_NEW or SAVED_UPDATED is returned depending on the operation
3001
 *   performed.
3002
 */
3003
function user_role_save($role) {
3004
  if ($role->name) {
3005
    // Prevent leading and trailing spaces in role names.
3006
    $role->name = trim($role->name);
3007
  }
3008
  if (!isset($role->weight)) {
3009
    // Set a role weight to make this new role last.
3010
    $query = db_select('role');
3011
    $query->addExpression('MAX(weight)');
3012
    $role->weight = $query->execute()->fetchField() + 1;
3013
  }
3014

    
3015
  // Let modules modify the user role before it is saved to the database.
3016
  module_invoke_all('user_role_presave', $role);
3017

    
3018
  if (!empty($role->rid) && $role->name) {
3019
    $status = drupal_write_record('role', $role, 'rid');
3020
    module_invoke_all('user_role_update', $role);
3021
  }
3022
  else {
3023
    $status = drupal_write_record('role', $role);
3024
    module_invoke_all('user_role_insert', $role);
3025
  }
3026

    
3027
  // Clear the user access cache.
3028
  drupal_static_reset('user_access');
3029
  drupal_static_reset('user_role_permissions');
3030

    
3031
  return $status;
3032
}
3033

    
3034
/**
3035
 * Delete a user role from database.
3036
 *
3037
 * @param $role
3038
 *   A string with the role name, or an integer with the role ID.
3039
 */
3040
function user_role_delete($role) {
3041
  if (is_int($role)) {
3042
    $role = user_role_load($role);
3043
  }
3044
  else {
3045
    $role = user_role_load_by_name($role);
3046
  }
3047

    
3048
  // If this is the administrator role, delete the user_admin_role variable.
3049
  if ($role->rid == variable_get('user_admin_role')) {
3050
    variable_del('user_admin_role');
3051
  }
3052

    
3053
  db_delete('role')
3054
    ->condition('rid', $role->rid)
3055
    ->execute();
3056
  db_delete('role_permission')
3057
    ->condition('rid', $role->rid)
3058
    ->execute();
3059
  // Update the users who have this role set:
3060
  db_delete('users_roles')
3061
    ->condition('rid', $role->rid)
3062
    ->execute();
3063

    
3064
  module_invoke_all('user_role_delete', $role);
3065

    
3066
  // Clear the user access cache.
3067
  drupal_static_reset('user_access');
3068
  drupal_static_reset('user_role_permissions');
3069
}
3070

    
3071
/**
3072
 * Menu access callback for user role editing.
3073
 */
3074
function user_role_edit_access($role) {
3075
  // Prevent the system-defined roles from being altered or removed.
3076
  if ($role->rid == DRUPAL_ANONYMOUS_RID || $role->rid == DRUPAL_AUTHENTICATED_RID) {
3077
    return FALSE;
3078
  }
3079

    
3080
  return user_access('administer permissions');
3081
}
3082

    
3083
/**
3084
 * Determine the modules that permissions belong to.
3085
 *
3086
 * @return
3087
 *   An associative array in the format $permission => $module.
3088
 */
3089
function user_permission_get_modules() {
3090
  $permissions = array();
3091
  foreach (module_implements('permission') as $module) {
3092
    $perms = module_invoke($module, 'permission');
3093
    foreach ($perms as $key => $value) {
3094
      $permissions[$key] = $module;
3095
    }
3096
  }
3097
  return $permissions;
3098
}
3099

    
3100
/**
3101
 * Change permissions for a user role.
3102
 *
3103
 * This function may be used to grant and revoke multiple permissions at once.
3104
 * For example, when a form exposes checkboxes to configure permissions for a
3105
 * role, the form submit handler may directly pass the submitted values for the
3106
 * checkboxes form element to this function.
3107
 *
3108
 * @param $rid
3109
 *   The ID of a user role to alter.
3110
 * @param $permissions
3111
 *   An associative array, where the key holds the permission name and the value
3112
 *   determines whether to grant or revoke that permission. Any value that
3113
 *   evaluates to TRUE will cause the permission to be granted. Any value that
3114
 *   evaluates to FALSE will cause the permission to be revoked.
3115
 *   @code
3116
 *     array(
3117
 *       'administer nodes' => 0,                // Revoke 'administer nodes'
3118
 *       'administer blocks' => FALSE,           // Revoke 'administer blocks'
3119
 *       'access user profiles' => 1,            // Grant 'access user profiles'
3120
 *       'access content' => TRUE,               // Grant 'access content'
3121
 *       'access comments' => 'access comments', // Grant 'access comments'
3122
 *     )
3123
 *   @endcode
3124
 *   Existing permissions are not changed, unless specified in $permissions.
3125
 *
3126
 * @see user_role_grant_permissions()
3127
 * @see user_role_revoke_permissions()
3128
 */
3129
function user_role_change_permissions($rid, array $permissions = array()) {
3130
  // Grant new permissions for the role.
3131
  $grant = array_filter($permissions);
3132
  if (!empty($grant)) {
3133
    user_role_grant_permissions($rid, array_keys($grant));
3134
  }
3135
  // Revoke permissions for the role.
3136
  $revoke = array_diff_assoc($permissions, $grant);
3137
  if (!empty($revoke)) {
3138
    user_role_revoke_permissions($rid, array_keys($revoke));
3139
  }
3140
}
3141

    
3142
/**
3143
 * Grant permissions to a user role.
3144
 *
3145
 * @param $rid
3146
 *   The ID of a user role to alter.
3147
 * @param $permissions
3148
 *   A list of permission names to grant.
3149
 *
3150
 * @see user_role_change_permissions()
3151
 * @see user_role_revoke_permissions()
3152
 */
3153
function user_role_grant_permissions($rid, array $permissions = array()) {
3154
  $modules = user_permission_get_modules();
3155
  // Grant new permissions for the role.
3156
  foreach ($permissions as $name) {
3157
    db_merge('role_permission')
3158
      ->key(array(
3159
        'rid' => $rid,
3160
        'permission' => $name,
3161
      ))
3162
      ->fields(array(
3163
        'module' => $modules[$name],
3164
      ))
3165
      ->execute();
3166
  }
3167

    
3168
  // Clear the user access cache.
3169
  drupal_static_reset('user_access');
3170
  drupal_static_reset('user_role_permissions');
3171
}
3172

    
3173
/**
3174
 * Revoke permissions from a user role.
3175
 *
3176
 * @param $rid
3177
 *   The ID of a user role to alter.
3178
 * @param $permissions
3179
 *   A list of permission names to revoke.
3180
 *
3181
 * @see user_role_change_permissions()
3182
 * @see user_role_grant_permissions()
3183
 */
3184
function user_role_revoke_permissions($rid, array $permissions = array()) {
3185
  // Revoke permissions for the role.
3186
  db_delete('role_permission')
3187
    ->condition('rid', $rid)
3188
    ->condition('permission', $permissions, 'IN')
3189
    ->execute();
3190

    
3191
  // Clear the user access cache.
3192
  drupal_static_reset('user_access');
3193
  drupal_static_reset('user_role_permissions');
3194
}
3195

    
3196
/**
3197
 * Implements hook_user_operations().
3198
 */
3199
function user_user_operations($form = array(), $form_state = array()) {
3200
  $operations = array(
3201
    'unblock' => array(
3202
      'label' => t('Unblock the selected users'),
3203
      'callback' => 'user_user_operations_unblock',
3204
    ),
3205
    'block' => array(
3206
      'label' => t('Block the selected users'),
3207
      'callback' => 'user_user_operations_block',
3208
    ),
3209
    'cancel' => array(
3210
      'label' => t('Cancel the selected user accounts'),
3211
    ),
3212
  );
3213

    
3214
  if (user_access('administer permissions')) {
3215
    $roles = user_roles(TRUE);
3216
    unset($roles[DRUPAL_AUTHENTICATED_RID]);  // Can't edit authenticated role.
3217

    
3218
    $add_roles = array();
3219
    foreach ($roles as $key => $value) {
3220
      $add_roles['add_role-' . $key] = $value;
3221
    }
3222

    
3223
    $remove_roles = array();
3224
    foreach ($roles as $key => $value) {
3225
      $remove_roles['remove_role-' . $key] = $value;
3226
    }
3227

    
3228
    if (count($roles)) {
3229
      $role_operations = array(
3230
        t('Add a role to the selected users') => array(
3231
          'label' => $add_roles,
3232
        ),
3233
        t('Remove a role from the selected users') => array(
3234
          'label' => $remove_roles,
3235
        ),
3236
      );
3237

    
3238
      $operations += $role_operations;
3239
    }
3240
  }
3241

    
3242
  // If the form has been posted, we need to insert the proper data for
3243
  // role editing if necessary.
3244
  if (!empty($form_state['submitted'])) {
3245
    $operation_rid = explode('-', $form_state['values']['operation']);
3246
    $operation = $operation_rid[0];
3247
    if ($operation == 'add_role' || $operation == 'remove_role') {
3248
      $rid = $operation_rid[1];
3249
      if (user_access('administer permissions')) {
3250
        $operations[$form_state['values']['operation']] = array(
3251
          'callback' => 'user_multiple_role_edit',
3252
          'callback arguments' => array($operation, $rid),
3253
        );
3254
      }
3255
      else {
3256
        watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
3257
        return;
3258
      }
3259
    }
3260
  }
3261

    
3262
  return $operations;
3263
}
3264

    
3265
/**
3266
 * Callback function for admin mass unblocking users.
3267
 */
3268
function user_user_operations_unblock($accounts) {
3269
  $accounts = user_load_multiple($accounts);
3270
  foreach ($accounts as $account) {
3271
    // Skip unblocking user if they are already unblocked.
3272
    if ($account !== FALSE && $account->status == 0) {
3273
      user_save($account, array('status' => 1));
3274
    }
3275
  }
3276
}
3277

    
3278
/**
3279
 * Callback function for admin mass blocking users.
3280
 */
3281
function user_user_operations_block($accounts) {
3282
  $accounts = user_load_multiple($accounts);
3283
  foreach ($accounts as $account) {
3284
    // Skip blocking user if they are already blocked.
3285
    if ($account !== FALSE && $account->status == 1) {
3286
      // For efficiency manually save the original account before applying any
3287
      // changes.
3288
      $account->original = clone $account;
3289
      user_save($account, array('status' => 0));
3290
    }
3291
  }
3292
}
3293

    
3294
/**
3295
 * Callback function for admin mass adding/deleting a user role.
3296
 */
3297
function user_multiple_role_edit($accounts, $operation, $rid) {
3298
  // The role name is not necessary as user_save() will reload the user
3299
  // object, but some modules' hook_user() may look at this first.
3300
  $role_name = db_query('SELECT name FROM {role} WHERE rid = :rid', array(':rid' => $rid))->fetchField();
3301

    
3302
  switch ($operation) {
3303
    case 'add_role':
3304
      $accounts = user_load_multiple($accounts);
3305
      foreach ($accounts as $account) {
3306
        // Skip adding the role to the user if they already have it.
3307
        if ($account !== FALSE && !isset($account->roles[$rid])) {
3308
          $roles = $account->roles + array($rid => $role_name);
3309
          // For efficiency manually save the original account before applying
3310
          // any changes.
3311
          $account->original = clone $account;
3312
          user_save($account, array('roles' => $roles));
3313
        }
3314
      }
3315
      break;
3316
    case 'remove_role':
3317
      $accounts = user_load_multiple($accounts);
3318
      foreach ($accounts as $account) {
3319
        // Skip removing the role from the user if they already don't have it.
3320
        if ($account !== FALSE && isset($account->roles[$rid])) {
3321
          $roles = array_diff($account->roles, array($rid => $role_name));
3322
          // For efficiency manually save the original account before applying
3323
          // any changes.
3324
          $account->original = clone $account;
3325
          user_save($account, array('roles' => $roles));
3326
        }
3327
      }
3328
      break;
3329
  }
3330
}
3331

    
3332
function user_multiple_cancel_confirm($form, &$form_state) {
3333
  $edit = $form_state['input'];
3334

    
3335
  $form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
3336
  $accounts = user_load_multiple(array_keys(array_filter($edit['accounts'])));
3337
  foreach ($accounts as $uid => $account) {
3338
    // Prevent user 1 from being canceled.
3339
    if ($uid <= 1) {
3340
      continue;
3341
    }
3342
    $form['accounts'][$uid] = array(
3343
      '#type' => 'hidden',
3344
      '#value' => $uid,
3345
      '#prefix' => '<li>',
3346
      '#suffix' => check_plain($account->name) . "</li>\n",
3347
    );
3348
  }
3349

    
3350
  // Output a notice that user 1 cannot be canceled.
3351
  if (isset($accounts[1])) {
3352
    $redirect = (count($accounts) == 1);
3353
    $message = t('The user account %name cannot be cancelled.', array('%name' => $accounts[1]->name));
3354
    drupal_set_message($message, $redirect ? 'error' : 'warning');
3355
    // If only user 1 was selected, redirect to the overview.
3356
    if ($redirect) {
3357
      drupal_goto('admin/people');
3358
    }
3359
  }
3360

    
3361
  $form['operation'] = array('#type' => 'hidden', '#value' => 'cancel');
3362

    
3363
  module_load_include('inc', 'user', 'user.pages');
3364
  $form['user_cancel_method'] = array(
3365
    '#type' => 'item',
3366
    '#title' => t('When cancelling these accounts'),
3367
  );
3368
  $form['user_cancel_method'] += user_cancel_methods();
3369
  // Remove method descriptions.
3370
  foreach (element_children($form['user_cancel_method']) as $element) {
3371
    unset($form['user_cancel_method'][$element]['#description']);
3372
  }
3373

    
3374
  // Allow to send the account cancellation confirmation mail.
3375
  $form['user_cancel_confirm'] = array(
3376
    '#type' => 'checkbox',
3377
    '#title' => t('Require e-mail confirmation to cancel account.'),
3378
    '#default_value' => FALSE,
3379
    '#description' => t('When enabled, the user must confirm the account cancellation via e-mail.'),
3380
  );
3381
  // Also allow to send account canceled notification mail, if enabled.
3382
  $form['user_cancel_notify'] = array(
3383
    '#type' => 'checkbox',
3384
    '#title' => t('Notify user when account is canceled.'),
3385
    '#default_value' => FALSE,
3386
    '#access' => variable_get('user_mail_status_canceled_notify', FALSE),
3387
    '#description' => t('When enabled, the user will receive an e-mail notification after the account has been cancelled.'),
3388
  );
3389

    
3390
  return confirm_form($form,
3391
                      t('Are you sure you want to cancel these user accounts?'),
3392
                      'admin/people', t('This action cannot be undone.'),
3393
                      t('Cancel accounts'), t('Cancel'));
3394
}
3395

    
3396
/**
3397
 * Submit handler for mass-account cancellation form.
3398
 *
3399
 * @see user_multiple_cancel_confirm()
3400
 * @see user_cancel_confirm_form_submit()
3401
 */
3402
function user_multiple_cancel_confirm_submit($form, &$form_state) {
3403
  global $user;
3404

    
3405
  if ($form_state['values']['confirm']) {
3406
    foreach ($form_state['values']['accounts'] as $uid => $value) {
3407
      // Prevent programmatic form submissions from cancelling user 1.
3408
      if ($uid <= 1) {
3409
        continue;
3410
      }
3411
      // Prevent user administrators from deleting themselves without confirmation.
3412
      if ($uid == $user->uid) {
3413
        $admin_form_state = $form_state;
3414
        unset($admin_form_state['values']['user_cancel_confirm']);
3415
        $admin_form_state['values']['_account'] = $user;
3416
        user_cancel_confirm_form_submit(array(), $admin_form_state);
3417
      }
3418
      else {
3419
        user_cancel($form_state['values'], $uid, $form_state['values']['user_cancel_method']);
3420
      }
3421
    }
3422
  }
3423
  $form_state['redirect'] = 'admin/people';
3424
}
3425

    
3426
/**
3427
 * Retrieve a list of all user setting/information categories and sort them by weight.
3428
 */
3429
function _user_categories() {
3430
  $categories = module_invoke_all('user_categories');
3431
  usort($categories, '_user_sort');
3432

    
3433
  return $categories;
3434
}
3435

    
3436
function _user_sort($a, $b) {
3437
  $a = (array) $a + array('weight' => 0, 'title' => '');
3438
  $b = (array) $b + array('weight' => 0, 'title' => '');
3439
  return $a['weight'] < $b['weight'] ? -1 : ($a['weight'] > $b['weight'] ? 1 : ($a['title'] < $b['title'] ? -1 : 1));
3440
}
3441

    
3442
/**
3443
 * List user administration filters that can be applied.
3444
 */
3445
function user_filters() {
3446
  // Regular filters
3447
  $filters = array();
3448
  $roles = user_roles(TRUE);
3449
  unset($roles[DRUPAL_AUTHENTICATED_RID]); // Don't list authorized role.
3450
  if (count($roles)) {
3451
    $filters['role'] = array(
3452
      'title' => t('role'),
3453
      'field' => 'ur.rid',
3454
      'options' => array(
3455
        '[any]' => t('any'),
3456
      ) + $roles,
3457
    );
3458
  }
3459

    
3460
  $options = array();
3461
  foreach (module_implements('permission') as $module) {
3462
    $function = $module . '_permission';
3463
    if ($permissions = $function()) {
3464
      asort($permissions);
3465
      foreach ($permissions as $permission => $description) {
3466
        $options[t('@module module', array('@module' => $module))][$permission] = t($permission);
3467
      }
3468
    }
3469
  }
3470
  ksort($options);
3471
  $filters['permission'] = array(
3472
    'title' => t('permission'),
3473
    'options' => array(
3474
      '[any]' => t('any'),
3475
    ) + $options,
3476
  );
3477

    
3478
  $filters['status'] = array(
3479
    'title' => t('status'),
3480
    'field' => 'u.status',
3481
    'options' => array(
3482
      '[any]' => t('any'),
3483
      1 => t('active'),
3484
      0 => t('blocked'),
3485
    ),
3486
  );
3487
  return $filters;
3488
}
3489

    
3490
/**
3491
 * Extends a query object for user administration filters based on session.
3492
 *
3493
 * @param $query
3494
 *   Query object that should be filtered.
3495
 */
3496
function user_build_filter_query(SelectQuery $query) {
3497
  $filters = user_filters();
3498
  // Extend Query with filter conditions.
3499
  foreach (isset($_SESSION['user_overview_filter']) ? $_SESSION['user_overview_filter'] : array() as $filter) {
3500
    list($key, $value) = $filter;
3501
    // This checks to see if this permission filter is an enabled permission for
3502
    // the authenticated role. If so, then all users would be listed, and we can
3503
    // skip adding it to the filter query.
3504
    if ($key == 'permission') {
3505
      $account = new stdClass();
3506
      $account->uid = 'user_filter';
3507
      $account->roles = array(DRUPAL_AUTHENTICATED_RID => 1);
3508
      if (user_access($value, $account)) {
3509
        continue;
3510
      }
3511
      $users_roles_alias = $query->join('users_roles', 'ur', '%alias.uid = u.uid');
3512
      $permission_alias = $query->join('role_permission', 'p', $users_roles_alias . '.rid = %alias.rid');
3513
      $query->condition($permission_alias . '.permission', $value);
3514
    }
3515
    elseif ($key == 'role') {
3516
      $users_roles_alias = $query->join('users_roles', 'ur', '%alias.uid = u.uid');
3517
      $query->condition($users_roles_alias . '.rid' , $value);
3518
    }
3519
    else {
3520
      $query->condition($filters[$key]['field'], $value);
3521
    }
3522
  }
3523
}
3524

    
3525
/**
3526
 * Implements hook_comment_view().
3527
 */
3528
function user_comment_view($comment) {
3529
  if (variable_get('user_signatures', 0) && !empty($comment->signature)) {
3530
    // @todo This alters and replaces the original object value, so a
3531
    //   hypothetical process of loading, viewing, and saving will hijack the
3532
    //   stored data. Consider renaming to $comment->signature_safe or similar
3533
    //   here and elsewhere in Drupal 8.
3534
    $comment->signature = check_markup($comment->signature, $comment->signature_format, '', TRUE);
3535
  }
3536
  else {
3537
    $comment->signature = '';
3538
  }
3539
}
3540

    
3541
/**
3542
 * Returns HTML for a user signature.
3543
 *
3544
 * @param $variables
3545
 *   An associative array containing:
3546
 *   - signature: The user's signature.
3547
 *
3548
 * @ingroup themeable
3549
 */
3550
function theme_user_signature($variables) {
3551
  $signature = $variables['signature'];
3552
  $output = '';
3553

    
3554
  if ($signature) {
3555
    $output .= '<div class="clear">';
3556
    $output .= '<div>—</div>';
3557
    $output .= $signature;
3558
    $output .= '</div>';
3559
  }
3560

    
3561
  return $output;
3562
}
3563

    
3564
/**
3565
 * Get the language object preferred by the user. This user preference can
3566
 * be set on the user account editing page, and is only available if there
3567
 * are more than one languages enabled on the site. If the user did not
3568
 * choose a preferred language, or is the anonymous user, the $default
3569
 * value, or if it is not set, the site default language will be returned.
3570
 *
3571
 * @param $account
3572
 *   User account to look up language for.
3573
 * @param $default
3574
 *   Optional default language object to return if the account
3575
 *   has no valid language.
3576
 */
3577
function user_preferred_language($account, $default = NULL) {
3578
  $language_list = language_list();
3579
  if (!empty($account->language) && isset($language_list[$account->language])) {
3580
    return $language_list[$account->language];
3581
  }
3582
  else {
3583
    return $default ? $default : language_default();
3584
  }
3585
}
3586

    
3587
/**
3588
 * Conditionally create and send a notification email when a certain
3589
 * operation happens on the given user account.
3590
 *
3591
 * @see user_mail_tokens()
3592
 * @see drupal_mail()
3593
 *
3594
 * @param $op
3595
 *   The operation being performed on the account. Possible values:
3596
 *   - 'register_admin_created': Welcome message for user created by the admin.
3597
 *   - 'register_no_approval_required': Welcome message when user
3598
 *     self-registers.
3599
 *   - 'register_pending_approval': Welcome message, user pending admin
3600
 *     approval.
3601
 *   - 'password_reset': Password recovery request.
3602
 *   - 'status_activated': Account activated.
3603
 *   - 'status_blocked': Account blocked.
3604
 *   - 'cancel_confirm': Account cancellation request.
3605
 *   - 'status_canceled': Account canceled.
3606
 *
3607
 * @param $account
3608
 *   The user object of the account being notified. Must contain at
3609
 *   least the fields 'uid', 'name', and 'mail'.
3610
 * @param $language
3611
 *   Optional language to use for the notification, overriding account language.
3612
 *
3613
 * @return
3614
 *   The return value from drupal_mail_system()->mail(), if ends up being
3615
 *   called.
3616
 */
3617
function _user_mail_notify($op, $account, $language = NULL) {
3618
  // By default, we always notify except for canceled and blocked.
3619
  $default_notify = ($op != 'status_canceled' && $op != 'status_blocked');
3620
  $notify = variable_get('user_mail_' . $op . '_notify', $default_notify);
3621
  if ($notify) {
3622
    $params['account'] = $account;
3623
    $language = $language ? $language : user_preferred_language($account);
3624
    $mail = drupal_mail('user', $op, $account->mail, $language, $params);
3625
    if ($op == 'register_pending_approval') {
3626
      // If a user registered requiring admin approval, notify the admin, too.
3627
      // We use the site default language for this.
3628
      drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
3629
    }
3630
  }
3631
  return empty($mail) ? NULL : $mail['result'];
3632
}
3633

    
3634
/**
3635
 * Form element process handler for client-side password validation.
3636
 *
3637
 * This #process handler is automatically invoked for 'password_confirm' form
3638
 * elements to add the JavaScript and string translations for dynamic password
3639
 * validation.
3640
 *
3641
 * @see system_element_info()
3642
 */
3643
function user_form_process_password_confirm($element) {
3644
  global $user;
3645

    
3646
  $js_settings = array(
3647
    'password' => array(
3648
      'strengthTitle' => t('Password strength:'),
3649
      'hasWeaknesses' => t('To make your password stronger:'),
3650
      'tooShort' => t('Make it at least 6 characters'),
3651
      'addLowerCase' => t('Add lowercase letters'),
3652
      'addUpperCase' => t('Add uppercase letters'),
3653
      'addNumbers' => t('Add numbers'),
3654
      'addPunctuation' => t('Add punctuation'),
3655
      'sameAsUsername' => t('Make it different from your username'),
3656
      'confirmSuccess' => t('yes'),
3657
      'confirmFailure' => t('no'),
3658
      'weak' => t('Weak'),
3659
      'fair' => t('Fair'),
3660
      'good' => t('Good'),
3661
      'strong' => t('Strong'),
3662
      'confirmTitle' => t('Passwords match:'),
3663
      'username' => (isset($user->name) ? $user->name : ''),
3664
    ),
3665
  );
3666

    
3667
  $element['#attached']['js'][] = drupal_get_path('module', 'user') . '/user.js';
3668
  $element['#attached']['js'][] = array('data' => $js_settings, 'type' => 'setting');
3669

    
3670
  return $element;
3671
}
3672

    
3673
/**
3674
 * Implements hook_node_load().
3675
 */
3676
function user_node_load($nodes, $types) {
3677
  // Build an array of all uids for node authors, keyed by nid.
3678
  $uids = array();
3679
  foreach ($nodes as $nid => $node) {
3680
    $uids[$nid] = $node->uid;
3681
  }
3682

    
3683
  // Fetch name, picture, and data for these users.
3684
  $user_fields = db_query("SELECT uid, name, picture, data FROM {users} WHERE uid IN (:uids)", array(':uids' => $uids))->fetchAllAssoc('uid');
3685

    
3686
  // Add these values back into the node objects.
3687
  foreach ($uids as $nid => $uid) {
3688
    $nodes[$nid]->name = $user_fields[$uid]->name;
3689
    $nodes[$nid]->picture = $user_fields[$uid]->picture;
3690
    $nodes[$nid]->data = $user_fields[$uid]->data;
3691
  }
3692
}
3693

    
3694
/**
3695
 * Implements hook_image_style_delete().
3696
 */
3697
function user_image_style_delete($style) {
3698
  // If a style is deleted, update the variables.
3699
  // Administrators choose a replacement style when deleting.
3700
  user_image_style_save($style);
3701
}
3702

    
3703
/**
3704
 * Implements hook_image_style_save().
3705
 */
3706
function user_image_style_save($style) {
3707
  // If a style is renamed, update the variables that use it.
3708
  if (isset($style['old_name']) && $style['old_name'] == variable_get('user_picture_style', '')) {
3709
    variable_set('user_picture_style', $style['name']);
3710
  }
3711
}
3712

    
3713
/**
3714
 * Implements hook_action_info().
3715
 */
3716
function user_action_info() {
3717
  return array(
3718
    'user_block_user_action' => array(
3719
      'label' => t('Block current user'),
3720
      'type' => 'user',
3721
      'configurable' => FALSE,
3722
      'triggers' => array('any'),
3723
    ),
3724
  );
3725
}
3726

    
3727
/**
3728
 * Blocks a specific user or the current user, if one is not specified.
3729
 *
3730
 * @param $entity
3731
 *   (optional) An entity object; if it is provided and it has a uid property,
3732
 *   the user with that ID is blocked.
3733
 * @param $context
3734
 *   (optional) An associative array; if no user ID is found in $entity, the
3735
 *   'uid' element of this array determines the user to block.
3736
 *
3737
 * @ingroup actions
3738
 */
3739
function user_block_user_action(&$entity, $context = array()) {
3740
  // First priority: If there is a $entity->uid, block that user.
3741
  // This is most likely a user object or the author if a node or comment.
3742
  if (isset($entity->uid)) {
3743
    $uid = $entity->uid;
3744
  }
3745
  elseif (isset($context['uid'])) {
3746
    $uid = $context['uid'];
3747
  }
3748
  // If neither of those are valid, then block the current user.
3749
  else {
3750
    $uid = $GLOBALS['user']->uid;
3751
  }
3752
  $account = user_load($uid);
3753
  $account = user_save($account, array('status' => 0));
3754
  watchdog('action', 'Blocked user %name.', array('%name' => $account->name));
3755
}
3756

    
3757
/**
3758
 * Implements hook_form_FORM_ID_alter().
3759
 *
3760
 * Add a checkbox for the 'user_register_form' instance settings on the 'Edit
3761
 * field instance' form.
3762
 */
3763
function user_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
3764
  $instance = $form['#instance'];
3765

    
3766
  if ($instance['entity_type'] == 'user' && !$form['#field']['locked']) {
3767
    $form['instance']['settings']['user_register_form'] = array(
3768
      '#type' => 'checkbox',
3769
      '#title' => t('Display on user registration form.'),
3770
      '#description' => t("This is compulsory for 'required' fields."),
3771
      // Field instances created in D7 beta releases before the setting was
3772
      // introduced might be set as 'required' and 'not shown on user_register
3773
      // form'. We make sure the checkbox comes as 'checked' for those.
3774
      '#default_value' => $instance['settings']['user_register_form'] || $instance['required'],
3775
      // Display just below the 'required' checkbox.
3776
      '#weight' => $form['instance']['required']['#weight'] + .1,
3777
      // Disabled when the 'required' checkbox is checked.
3778
      '#states' => array(
3779
        'enabled' => array('input[name="instance[required]"]' => array('checked' => FALSE)),
3780
      ),
3781
      // Checked when the 'required' checkbox is checked. This is done through
3782
      // a custom behavior, since the #states system would also synchronize on
3783
      // uncheck.
3784
      '#attached' => array(
3785
        'js' => array(drupal_get_path('module', 'user') . '/user.js'),
3786
      ),
3787
    );
3788

    
3789
    array_unshift($form['#submit'], 'user_form_field_ui_field_edit_form_submit');
3790
  }
3791
}
3792

    
3793
/**
3794
 * Additional submit handler for the 'Edit field instance' form.
3795
 *
3796
 * Make sure the 'user_register_form' setting is set for required fields.
3797
 */
3798
function user_form_field_ui_field_edit_form_submit($form, &$form_state) {
3799
  $instance = $form_state['values']['instance'];
3800

    
3801
  if (!empty($instance['required'])) {
3802
    form_set_value($form['instance']['settings']['user_register_form'], 1, $form_state);
3803
  }
3804
}
3805

    
3806
/**
3807
 * Form builder; the user registration form.
3808
 *
3809
 * @ingroup forms
3810
 * @see user_account_form()
3811
 * @see user_account_form_validate()
3812
 * @see user_register_submit()
3813
 */
3814
function user_register_form($form, &$form_state) {
3815
  global $user;
3816

    
3817
  $admin = user_access('administer users');
3818

    
3819
  // Pass access information to the submit handler. Running an access check
3820
  // inside the submit function interferes with form processing and breaks
3821
  // hook_form_alter().
3822
  $form['administer_users'] = array(
3823
    '#type' => 'value',
3824
    '#value' => $admin,
3825
  );
3826

    
3827
  // If we aren't admin but already logged on, go to the user page instead.
3828
  if (!$admin && $user->uid) {
3829
    drupal_goto('user/' . $user->uid);
3830
  }
3831

    
3832
  $form['#user'] = drupal_anonymous_user();
3833
  $form['#user_category'] = 'register';
3834

    
3835
  $form['#attached']['library'][] = array('system', 'jquery.cookie');
3836
  $form['#attributes']['class'][] = 'user-info-from-cookie';
3837

    
3838
  // Start with the default user account fields.
3839
  user_account_form($form, $form_state);
3840

    
3841
  // Attach field widgets, and hide the ones where the 'user_register_form'
3842
  // setting is not on.
3843
  $langcode = entity_language('user', $form['#user']);
3844
  field_attach_form('user', $form['#user'], $form, $form_state, $langcode);
3845
  foreach (field_info_instances('user', 'user') as $field_name => $instance) {
3846
    if (empty($instance['settings']['user_register_form'])) {
3847
      $form[$field_name]['#access'] = FALSE;
3848
    }
3849
  }
3850

    
3851
  if ($admin) {
3852
    // Redirect back to page which initiated the create request;
3853
    // usually admin/people/create.
3854
    $form_state['redirect'] = $_GET['q'];
3855
  }
3856

    
3857
  $form['actions'] = array('#type' => 'actions');
3858
  $form['actions']['submit'] = array(
3859
    '#type' => 'submit',
3860
    '#value' => t('Create new account'),
3861
  );
3862

    
3863
  $form['#validate'][] = 'user_register_validate';
3864
  // Add the final user registration form submit handler.
3865
  $form['#submit'][] = 'user_register_submit';
3866

    
3867
  return $form;
3868
}
3869

    
3870
/**
3871
 * Validation function for the user registration form.
3872
 */
3873
function user_register_validate($form, &$form_state) {
3874
  entity_form_field_validate('user', $form, $form_state);
3875
}
3876

    
3877
/**
3878
 * Submit handler for the user registration form.
3879
 *
3880
 * This function is shared by the installation form and the normal registration form,
3881
 * which is why it can't be in the user.pages.inc file.
3882
 *
3883
 * @see user_register_form()
3884
 */
3885
function user_register_submit($form, &$form_state) {
3886
  $admin = $form_state['values']['administer_users'];
3887

    
3888
  if (!variable_get('user_email_verification', TRUE) || $admin) {
3889
    $pass = $form_state['values']['pass'];
3890
  }
3891
  else {
3892
    $pass = user_password();
3893
  }
3894
  $notify = !empty($form_state['values']['notify']);
3895

    
3896
  // Remove unneeded values.
3897
  form_state_values_clean($form_state);
3898

    
3899
  $form_state['values']['pass'] = $pass;
3900
  $form_state['values']['init'] = $form_state['values']['mail'];
3901

    
3902
  $account = $form['#user'];
3903

    
3904
  entity_form_submit_build_entity('user', $account, $form, $form_state);
3905

    
3906
  // Populate $edit with the properties of $account, which have been edited on
3907
  // this form by taking over all values, which appear in the form values too.
3908
  $edit = array_intersect_key((array) $account, $form_state['values']);
3909
  $account = user_save($account, $edit);
3910

    
3911
  // Terminate if an error occurred during user_save().
3912
  if (!$account) {
3913
    drupal_set_message(t("Error saving user account."), 'error');
3914
    $form_state['redirect'] = '';
3915
    return;
3916
  }
3917
  $form_state['user'] = $account;
3918
  $form_state['values']['uid'] = $account->uid;
3919

    
3920
  watchdog('user', 'New user: %name (%email).', array('%name' => $form_state['values']['name'], '%email' => $form_state['values']['mail']), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $account->uid . '/edit'));
3921

    
3922
  // Add plain text password into user account to generate mail tokens.
3923
  $account->password = $pass;
3924

    
3925
  // New administrative account without notification.
3926
  $uri = entity_uri('user', $account);
3927
  if ($admin && !$notify) {
3928
    drupal_set_message(t('Created a new user account for <a href="@url">%name</a>. No e-mail has been sent.', array('@url' => url($uri['path'], $uri['options']), '%name' => $account->name)));
3929
  }
3930
  // No e-mail verification required; log in user immediately.
3931
  elseif (!$admin && !variable_get('user_email_verification', TRUE) && $account->status) {
3932
    _user_mail_notify('register_no_approval_required', $account);
3933
    $form_state['uid'] = $account->uid;
3934
    user_login_submit(array(), $form_state);
3935
    drupal_set_message(t('Registration successful. You are now logged in.'));
3936
    $form_state['redirect'] = '';
3937
  }
3938
  // No administrator approval required.
3939
  elseif ($account->status || $notify) {
3940
    $op = $notify ? 'register_admin_created' : 'register_no_approval_required';
3941
    _user_mail_notify($op, $account);
3942
    if ($notify) {
3943
      drupal_set_message(t('A welcome message with further instructions has been e-mailed to the new user <a href="@url">%name</a>.', array('@url' => url($uri['path'], $uri['options']), '%name' => $account->name)));
3944
    }
3945
    else {
3946
      drupal_set_message(t('A welcome message with further instructions has been sent to your e-mail address.'));
3947
      $form_state['redirect'] = '';
3948
    }
3949
  }
3950
  // Administrator approval required.
3951
  else {
3952
    _user_mail_notify('register_pending_approval', $account);
3953
    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.'));
3954
    $form_state['redirect'] = '';
3955
  }
3956
}
3957

    
3958
/**
3959
 * Implements hook_modules_installed().
3960
 */
3961
function user_modules_installed($modules) {
3962
  // Assign all available permissions to the administrator role.
3963
  $rid = variable_get('user_admin_role', 0);
3964
  if ($rid) {
3965
    $permissions = array();
3966
    foreach ($modules as $module) {
3967
      if ($module_permissions = module_invoke($module, 'permission')) {
3968
        $permissions = array_merge($permissions, array_keys($module_permissions));
3969
      }
3970
    }
3971
    if (!empty($permissions)) {
3972
      user_role_grant_permissions($rid, $permissions);
3973
    }
3974
  }
3975
}
3976

    
3977
/**
3978
 * Implements hook_modules_uninstalled().
3979
 */
3980
function user_modules_uninstalled($modules) {
3981
   db_delete('role_permission')
3982
     ->condition('module', $modules, 'IN')
3983
     ->execute();
3984
}
3985

    
3986
/**
3987
 * Helper function to rewrite the destination to avoid redirecting to login page after login.
3988
 *
3989
 * Third-party authentication modules may use this function to determine the
3990
 * proper destination after a user has been properly logged in.
3991
 */
3992
function user_login_destination() {
3993
  $destination = drupal_get_destination();
3994
  if ($destination['destination'] == 'user/login') {
3995
    $destination['destination'] = 'user';
3996
  }
3997
  return $destination;
3998
}
3999

    
4000
/**
4001
 * Saves visitor information as a cookie so it can be reused.
4002
 *
4003
 * @param $values
4004
 *   An array of key/value pairs to be saved into a cookie.
4005
 */
4006
function user_cookie_save(array $values) {
4007
  foreach ($values as $field => $value) {
4008
    // Set cookie for 365 days.
4009
    setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
4010
  }
4011
}
4012

    
4013
/**
4014
 * Delete a visitor information cookie.
4015
 *
4016
 * @param $cookie_name
4017
 *   A cookie name such as 'homepage'.
4018
 */
4019
function user_cookie_delete($cookie_name) {
4020
  setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
4021
}
4022

    
4023
/**
4024
 * Implements hook_rdf_mapping().
4025
 */
4026
function user_rdf_mapping() {
4027
  return array(
4028
    array(
4029
      'type' => 'user',
4030
      'bundle' => RDF_DEFAULT_BUNDLE,
4031
      'mapping' => array(
4032
        'rdftype' => array('sioc:UserAccount'),
4033
        'name' => array(
4034
          'predicates' => array('foaf:name'),
4035
        ),
4036
        'homepage' => array(
4037
          'predicates' => array('foaf:page'),
4038
          'type' => 'rel',
4039
        ),
4040
      ),
4041
    ),
4042
  );
4043
}
4044

    
4045
/**
4046
 * Implements hook_file_download_access().
4047
 */
4048
function user_file_download_access($field, $entity_type, $entity) {
4049
  if ($entity_type == 'user') {
4050
    return user_view_access($entity);
4051
  }
4052
}
4053

    
4054
/**
4055
 * Implements hook_system_info_alter().
4056
 *
4057
 * Drupal 7 ships with two methods to add additional fields to users: Profile
4058
 * module, a legacy module dating back from 2002, and Field API integration
4059
 * with users. While Field API support for users currently provides less end
4060
 * user features, the inefficient data storage mechanism of Profile module, as
4061
 * well as its lack of consistency with the rest of the entity / field based
4062
 * systems in Drupal 7, make this a sub-optimal solution to those who were not
4063
 * using it in previous releases of Drupal.
4064
 *
4065
 * To prevent new Drupal 7 sites from installing Profile module, and
4066
 * unwittingly ending up with two completely different and incompatible methods
4067
 * of extending users, only make the Profile module available if the profile_*
4068
 * tables are present.
4069
 *
4070
 * @todo: Remove in D8, pending upgrade path.
4071
 */
4072
function user_system_info_alter(&$info, $file, $type) {
4073
  if ($type == 'module' && $file->name == 'profile' && db_table_exists('profile_field')) {
4074
    $info['hidden'] = FALSE;
4075
  }
4076
}