user.module 68.6 KB
Newer Older
1 2
<?php

3
use Drupal\Component\Utility\Crypt;
4
use Drupal\Core\Entity\EntityInterface;
5
use Drupal\Core\Session\AccountInterface;
6 7 8
use Drupal\entity\Entity\EntityDisplay;
use Drupal\file\Entity\File;
use Drupal\user\Entity\User;
9
use Drupal\user\UserInterface;
10
use Drupal\user\RoleInterface;
11
use Drupal\Core\Template\Attribute;
12
use Symfony\Component\HttpFoundation\RedirectResponse;
13
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
14
use Drupal\menu_link\Entity\MenuLink;
Crell's avatar
Crell committed
15

16 17 18 19 20
/**
 * @file
 * Enables the user registration and login system.
 */

21 22 23
/**
 * Maximum length of username text field.
 */
24
const USERNAME_MAX_LENGTH = 60;
25 26 27 28

/**
 * Maximum length of user e-mail text field.
 */
29
const EMAIL_MAX_LENGTH = 255;
30

31 32 33
/**
 * Only administrators can create user accounts.
 */
34
const USER_REGISTER_ADMINISTRATORS_ONLY = 'admin_only';
35 36 37 38

/**
 * Visitors can create their own accounts.
 */
39
const USER_REGISTER_VISITORS = 'visitors';
40 41 42 43 44

/**
 * Visitors can create accounts, but they don't become active without
 * administrative approval.
 */
45
const USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL = 'visitors_admin_approval';
46

47 48 49 50 51 52 53 54
/**
 * Implement hook_help().
 */
function user_help($path, $arg) {
  switch ($path) {
    case 'admin/help#user':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
55
      $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>';
56 57 58
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Creating and managing users') . '</dt>';
59
      $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>';
60
      $output .= '<dt>' . t('User roles and permissions') . '</dt>';
61
      $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/roles'))) . '</dd>';
62
      $output .= '<dt>' . t('Account settings') . '</dt>';
63
      $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 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>';
64 65 66 67
      $output .= '</dl>';
      return $output;
    case 'admin/people/create':
      return '<p>' . t("This web page allows administrators to register new users. Users' e-mail addresses and usernames must be unique.") . '</p>';
68
    case 'admin/people/permissions':
69 70
      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/roles'), '@settings' => url('admin/config/people/accounts'))) . '</p>';
    case 'admin/people/roles':
71
      $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>';
72
      $output .= '<p>' . t('Drupal has three special user roles:') . '</p>';
73 74 75
      $output .= '<ul>';
      $output .= '<li>' . t("Anonymous user: this role is used for users that don't have a user account or that are not authenticated.") . '</li>';
      $output .= '<li>' . t('Authenticated user: this role is automatically granted to all logged in users.') . '</li>';
76
      $output .= '<li>' . t('Administrator role: this role is automatically granted all new permissions when you install a new module. Configure which role is the administrator role on the <a href="@account_settings">Account settings page</a>.', array('@account_settings' => url('admin/config/people/accounts'))) . '</li>';
77 78 79
      $output .= '</ul>';
      return $output;
    case 'admin/config/people/accounts/fields':
80 81 82
      return '<p>' . t('This form lets administrators add and edit fields for storing user data.') . '</p>';
    case 'admin/config/people/accounts/form-display':
      return '<p>' . t('This form lets administrators configure how form fields should be displayed when editing a user profile.') . '</p>';
83 84 85 86 87 88
    case 'admin/config/people/accounts/display':
      return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
    case 'admin/people/search':
      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>';
  }
}
89

90
/**
91
 * Implements hook_theme().
92 93 94
 */
function user_theme() {
  return array(
95
    'user' => array(
96
      'render element' => 'elements',
97
      'file' => 'user.pages.inc',
98
      'template' => 'user',
99
    ),
100 101 102 103
    'user_permission_description' => array(
      'variables' => array('permission_item' => NULL, 'hide' => NULL),
      'file' => 'user.admin.inc',
    ),
104
    'user_signature' => array(
105
      'variables' => array('signature' => NULL),
106
    ),
107
    'username' => array(
108
      'variables' => array('account' => NULL, 'attributes' => array()),
109
    ),
110 111 112
  );
}

113 114 115 116 117
/**
 * Implements hook_page_build().
 */
function user_page_build(&$page) {
  $path = drupal_get_path('module', 'user');
118
  $page['#attached']['css'][$path . '/css/user.module.css'] = array('every_page' => TRUE);
119 120 121 122 123 124 125 126 127 128 129

  // Provide the user ID in drupalSettings to allow JavaScript code to customize
  // the experience for the end user, rather than the server side, which would
  // break the render cache.
  global $user;
  $page['#attached']['js'][] = array(
    'type' => 'setting',
    'data' => array('user' => array(
      'uid' => $user->id(),
    )),
  );
130 131
}

132 133 134 135
/**
 * Implements hook_entity_bundle_info().
 */
function user_entity_bundle_info() {
136
  $bundles['user']['user']['label'] = t('User');
137 138 139
  return $bundles;
}

140
/**
141
 * Entity URI callback.
142
 */
143 144
function user_uri($user) {
  return array(
145
    'path' => 'user/' . $user->id(),
146
  );
147 148
}

149 150 151
/**
 * Entity label callback.
 *
152 153 154
 * This label callback has langcode for security reasons. The username is the
 * visual identifier for a user and needs to be consistent in all languages.
 *
155 156 157 158 159 160 161 162
 * @param $entity_type
 *   The entity type.
 * @param $entity
 *   The entity object.
 *
 * @return
 *   The name of the user.
 *
163
 * @see user_format_name()
164 165
 */
function user_label($entity_type, $entity) {
166
  return $entity->getUsername();
167 168
}

169 170 171
/**
 * Populates $entity->account for each prepared entity.
 *
172 173
 * Called by Drupal\Core\Entity\EntityRenderControllerInterface::buildContent()
 * implementations.
174 175 176 177 178 179 180
 *
 * @param array $entities
 *   The entities keyed by entity ID.
 */
function user_attach_accounts(array $entities) {
  $uids = array();
  foreach ($entities as $entity) {
181
    $uids[] = $entity->getAuthorId();
182 183 184 185 186
  }
  $uids = array_unique($uids);
  $accounts = user_load_multiple($uids);
  $anonymous = drupal_anonymous_user();
  foreach ($entities as $id => $entity) {
187 188
    if (isset($accounts[$entity->getAuthorId()])) {
      $entities[$id]->account = $accounts[$entity->getAuthorId()];
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
    }
    else {
      $entities[$id]->account = $anonymous;
    }
  }
}

/**
 * Returns whether this site supports the default user picture feature.
 *
 * This approach preserves compatibility with node/comment templates. Alternate
 * user picture implementations (e.g., Gravatar) should provide their own
 * add/edit/delete forms and populate the 'picture' variable during the
 * preprocess stage.
 */
function user_picture_enabled() {
  return (bool) field_info_instance('user', 'user_picture', 'user');
}

208
/**
209
 * Implements hook_field_extra_fields().
210
 */
211
function user_field_extra_fields() {
212 213 214 215 216
  $fields['user']['user']['form']['account'] = array(
    'label' => t('User name and password'),
    'description' => t('User module account form elements.'),
    'weight' => -10,
  );
217
  if (Drupal::config('user.settings')->get('signatures')) {
218 219 220 221 222 223 224 225 226 227 228
    $fields['user']['user']['form']['signature_settings'] = array(
      'label' => t('Signature settings'),
      'description' => t('User module form element.'),
      'weight' => 1,
    );
  }
  $fields['user']['user']['form']['language'] = array(
    'label' => t('Language settings'),
    'description' => t('User module form element.'),
    'weight' => 0,
  );
229
  if (Drupal::config('system.date')->get('timezone.user.configurable')) {
230 231 232 233 234 235 236 237 238 239 240
    $fields['user']['user']['form']['timezone'] = array(
      'label' => t('Timezone'),
      'description' => t('System module form element.'),
      'weight' => 6,
    );
  }

  $fields['user']['user']['display']['member_for'] = array(
    'label' => t('Member for'),
    'description' => t('User module \'member for\' view element.'),
    'weight' => 5,
241
  );
242

243
  return $fields;
244 245
}

Dries's avatar
Dries committed
246
/**
247
 * Loads multiple users based on certain conditions.
Dries's avatar
Dries committed
248
 *
249 250 251
 * This function should be used whenever you need to load more than one user
 * from the database. Users are loaded into memory and will not require
 * database access if loaded again during the same page request.
Dries's avatar
Dries committed
252
 *
253 254
 * @param array $uids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
255
 * @param bool $reset
256 257
 *   A boolean indicating that the internal cache should be reset. Use this if
 *   loading a user object which has been altered during the page request.
258
 *
259
 * @return array
260 261
 *   An array of user objects, indexed by uid.
 *
262
 * @see entity_load_multiple()
263 264 265
 * @see user_load()
 * @see user_load_by_mail()
 * @see user_load_by_name()
266
 * @see \Drupal\Core\Entity\Query\QueryInterface
Dries's avatar
Dries committed
267
 */
268
function user_load_multiple(array $uids = NULL, $reset = FALSE) {
269
  return entity_load_multiple('user', $uids, $reset);
270
}
271 272

/**
273 274 275 276 277 278
 * Loads a user object.
 *
 * Drupal has a global $user object, which represents the currently-logged-in
 * user. So to avoid confusion and to avoid clobbering the global $user object,
 * it is a good idea to assign the result of this function to a different local
 * variable, generally $account. If you actually do want to act as the user you
279 280 281 282
 * are loading, it is essential to call drupal_save_session(FALSE); first.
 * See
 * @link http://drupal.org/node/218104 Safely impersonating another user @endlink
 * for more information.
283
 *
284
 * @param int $uid
285
 *   Integer specifying the user ID to load.
286
 * @param bool $reset
287 288 289
 *   TRUE to reset the internal cache and load from the database; FALSE
 *   (default) to load from the internal cache, if set.
 *
290
 * @return object
291
 *   A fully-loaded user object upon successful user load, or NULL if the user
292 293 294 295 296
 *   cannot be loaded.
 *
 * @see user_load_multiple()
 */
function user_load($uid, $reset = FALSE) {
297
  return entity_load('user', $uid, $reset);
298 299 300
}

/**
301
 * Fetches a user object by email address.
302
 *
303
 * @param string $mail
304
 *   String with the account's e-mail address.
305
 * @return object|bool
306 307 308 309 310 311
 *   A fully-loaded $user object upon successful user load or FALSE if user
 *   cannot be loaded.
 *
 * @see user_load_multiple()
 */
function user_load_by_mail($mail) {
312
  $users = entity_load_multiple_by_properties('user', array('mail' => $mail));
313
  return $users ? reset($users) : FALSE;
314 315 316
}

/**
317
 * Fetches a user object by account name.
318
 *
319
 * @param string $name
320
 *   String with the account's user name.
321
 * @return object|bool
322 323 324 325 326 327
 *   A fully-loaded $user object upon successful user load or FALSE if user
 *   cannot be loaded.
 *
 * @see user_load_multiple()
 */
function user_load_by_name($name) {
328
  $users = entity_load_multiple_by_properties('user', array('name' => $name));
329
  return $users ? reset($users) : FALSE;
330 331
}

Dries's avatar
Dries committed
332 333
/**
 * Verify the syntax of the given name.
334 335 336 337 338 339 340 341
 *
 * @param string $name
 *   The user name to validate.
 *
 * @return string|null
 *   A translated violation message if the name is invalid or NULL if the name
 *   is valid.
 *
Dries's avatar
Dries committed
342
 */
343
function user_validate_name($name) {
344 345 346 347 348 349 350 351
  $data = \Drupal::typedData()->create(array(
    'type' => 'string',
    'constraints' => array('UserName' => array()),
  ));
  $data->setValue($name);
  $violations = $data->validate();
  if (count($violations) > 0) {
    return $violations[0]->getMessage();
352
  }
353 354
}

Dries's avatar
Dries committed
355 356 357
/**
 * Generate a random alphanumeric password.
 */
358 359
function user_password($length = 10) {
  // This variable contains the list of allowable characters for the
360 361
  // password. Note that the number 0 and the letter 'O' have been
  // removed to avoid confusion between the two. The same is true
362
  // of 'I', 1, and 'l'.
363
  $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
Dries's avatar
Dries committed
364

365 366
  // Zero-based count of characters in the allowable list:
  $len = strlen($allowable_characters) - 1;
367

Dries's avatar
Dries committed
368 369
  // Declare the password as a blank string.
  $pass = '';
370

Dries's avatar
Dries committed
371
  // Loop the number of times specified by $length.
372 373 374 375
  for ($i = 0; $i < $length; $i++) {

    // Each iteration, pick a random character from the
    // allowable string and append it to the password:
376
    $pass .= $allowable_characters[mt_rand(0, $len)];
377 378 379
  }

  return $pass;
380 381
}

382 383 384
/**
 * Determine the permissions for one or more roles.
 *
385 386
 * @param array $roles
 *   An array of role IDs.
387
 *
388 389 390
 * @return array
 *   An array indexed by role ID. Each value is an array of permission strings
 *   for the given role.
391
 */
392 393 394 395 396 397
function user_role_permissions(array $roles) {
  if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
    return _user_role_permissions_update($roles);
  }
  $entities = entity_load_multiple('user_role', $roles);
  $role_permissions = array();
398
  foreach ($roles as $rid) {
399
    $role_permissions[$rid] = isset($entities[$rid]) ? $entities[$rid]->getPermissions() : array();
400
  }
401 402
  return $role_permissions;
}
403

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
/**
 * Determine the permissions for one or more roles during update.
 *
 * A separate version is needed because during update the entity system can't
 * be used and in non-update situations the entity system is preferred because
 * of the hook system.
 *
 * @param array $roles
 *   An array of role IDs.
 *
 * @return array
 *   An array indexed by role ID. Each value is an array of permission strings
 *   for the given role.
 */
function _user_role_permissions_update($roles) {
  $role_permissions = array();
  foreach ($roles as $rid) {
    $role_permissions[$rid] = Drupal::config("user.role.$rid")->get('permissions') ?: array();
422 423 424 425
  }
  return $role_permissions;
}

Dries's avatar
Dries committed
426 427 428 429 430
/**
 * Determine whether the user has a given privilege.
 *
 * @param $string
 *   The permission, such as "administer nodes", being checked for.
431
 * @param \Drupal\Core\Session\AccountInterface $account
432
 *   (optional) The account to check, if not given use currently logged in user.
Dries's avatar
Dries committed
433
 *
434
 * @return bool
435
 *   Boolean TRUE if the current user has the requested permission.
Dries's avatar
Dries committed
436
 *
437 438
 * @deprecated as of Drupal 8.0. Use
 *   \Drupal\Core\Session\AccountInterface::hasPermission()
Dries's avatar
Dries committed
439
 */
440
function user_access($string, AccountInterface $account = NULL) {
441
  global $user;
442

443
  if (!isset($account)) {
444 445
    // In the installer request session is not set, so we have to fall back
    // to the global $user. In all other cases the session key is preferred.
446
    $account = Drupal::request()->attributes->get('_account') ?: $user;
447 448
  }

449
  return $account->hasPermission($string);
450 451
}

452
/**
453
 * Checks for usernames blocked by user administration.
454
 *
455 456 457 458 459 460
 * @param $name
 *   A string containing a name of the user.
 *
 * @return
 *   Object with property 'name' (the user name), if the user is blocked;
 *   FALSE if the user is not blocked.
461 462
 */
function user_is_blocked($name) {
463 464 465 466 467
  return db_select('users')
    ->fields('users', array('name'))
    ->condition('name', db_like($name), 'LIKE')
    ->condition('status', 0)
    ->execute()->fetchObject();
468 469
}

Dries's avatar
Dries committed
470
/**
471
 * Implements hook_permission().
Dries's avatar
Dries committed
472
 */
473
function user_permission() {
474 475 476
  return array(
    'administer permissions' =>  array(
      'title' => t('Administer permissions'),
477
      'restrict access' => TRUE,
478
    ),
479 480 481 482 483
    'administer account settings' => array(
      'title' => t('Administer account settings'),
      'description' => t('Configure site-wide settings and behavior for <a href="@url">user accounts and registration</a>.', array('@url' => url('admin/config/people'))),
      'restrict access' => TRUE,
    ),
484 485
    'administer users' => array(
      'title' => t('Administer users'),
486
      'restrict access' => TRUE,
487 488
    ),
    'access user profiles' => array(
489
      'title' => t('View user profiles'),
490 491 492 493 494
    ),
    'change own username' => array(
      'title' => t('Change own username'),
    ),
    'cancel account' => array(
495
      'title' => t('Cancel own user account'),
496
      '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' => Drupal::config('user.settings')->get('anonymous'), '@user-settings-url' => url('admin/config/people/accounts'))),
497 498 499
    ),
    'select account cancellation method' => array(
      'title' => t('Select method for cancelling own account'),
500
      'restrict access' => TRUE,
501 502
    ),
  );
503 504
}

Dries's avatar
Dries committed
505
/**
506
 * Implements hook_user_view().
Dries's avatar
Dries committed
507
 */
508
function user_user_view(UserInterface $account, EntityDisplay $display) {
509 510 511 512
  if ($display->getComponent('member_for')) {
    $account->content['member_for'] = array(
      '#type' => 'item',
      '#title' => t('Member for'),
513
      '#markup' => format_interval(REQUEST_TIME - $account->getCreatedTime()),
514 515
    );
  }
516 517
}

518 519 520 521 522 523 524 525 526
/**
 * Sets the value of the user register and profile forms' langcode element.
 */
function _user_language_selector_langcode_value($element, $input, &$form_state) {
  // Only add to the description if the form element have a description.
  if (isset($form_state['complete_form']['language']['preferred_langcode']['#description'])) {
    $form_state['complete_form']['language']['preferred_langcode']['#description'] .= ' ' . t("This is also assumed to be the primary language of this account's profile information.");
  }
  return $form_state['values']['preferred_langcode'];
527 528
}

529
/**
530
 * Form validation handler for the current password on the user account form.
531
 *
532
 * @see AccountFormController::form()
533 534
 */
function user_validate_current_pass(&$form, &$form_state) {
535
  $account = $form_state['user'];
536 537 538 539
  foreach ($form_state['values']['current_pass_required_values'] as $key => $name) {
    // This validation only works for required textfields (like mail) or
    // form values like password_confirm that have their own validation
    // that prevent them from being empty if they are changed.
540 541
    $current_value = $account->getPropertyDefinition($key) ? $account->get($key)->value : $account->$key;
    if ((strlen(trim($form_state['values'][$key])) > 0) && ($form_state['values'][$key] != $current_value)) {
542
      $current_pass_failed = empty($form_state['values']['current_pass']) || !Drupal::service('password')->check($form_state['values']['current_pass'], $account);
543 544 545 546 547 548 549 550 551 552
      if ($current_pass_failed) {
        form_set_error('current_pass', t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => $name)));
        form_set_error($key);
      }
      // We only need to check the password once.
      break;
    }
  }
}

553
/**
554
 * Implements hook_preprocess_HOOK() for block.html.twig.
555 556
 */
function user_preprocess_block(&$variables) {
557 558
  if ($variables['configuration']['module'] == 'user') {
    switch ($variables['elements']['#plugin_id']) {
559
      case 'user_login_block':
560
        $variables['attributes']['role'] = 'form';
561
        break;
562
      case 'user_new_block':
563
        $variables['attributes']['role'] = 'complementary';
564
        break;
565
      case 'user_online_block':
566
        $variables['attributes']['role'] = 'complementary';
567 568 569 570 571
        break;
    }
  }
}

572 573 574
/**
 * Format a username.
 *
575
 * @param \Drupal\Core\Session\Interface $account
576 577 578 579 580 581
 *   The account object for the user whose name is to be formatted.
 *
 * @return
 *   An unsanitized string with the username to display. The code receiving
 *   this result must ensure that check_plain() is called on it before it is
 *   printed to the page.
582 583
 *
 * @deprecated Use \Drupal\Core\Session\Interface::getUsername() instead.
584
 */
585 586
function user_format_name(AccountInterface $account) {
  return $account->getUsername();
587 588
}

589 590 591 592 593 594 595 596 597
/**
 * Implements hook_template_preprocess_default_variables_alter().
 *
 * @see user_user_login()
 * @see user_user_logout()
 */
function user_template_preprocess_default_variables_alter(&$variables) {
  global $user;

598 599 600 601 602 603
  // If this function is called from the installer after Drupal has been
  // installed then $user will not be set.
  if (!is_object($user)) {
    return;
  }

604 605 606 607 608
  $variables['user'] = clone $user;
  // Remove password and session IDs, since themes should not need nor see them.
  unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);

  $variables['is_admin'] = user_access('access administration pages');
609
  $variables['logged_in'] = $user->isAuthenticated();
610 611
}

612 613 614
/**
 * Preprocesses variables for theme_username().
 *
615
 * Modules that make any changes to variables like 'name' or 'extra' must ensure
616 617 618 619
 * that the final string is safe to include directly in the output by using
 * check_plain() or filter_xss().
 */
function template_preprocess_username(&$variables) {
620
  $account = $variables['account'] ?: drupal_anonymous_user();
621 622

  $variables['extra'] = '';
623 624 625 626 627
  $variables['uid'] = $account->id();
  if (empty($variables['uid'])) {
    if (theme_get_setting('features.comment_user_verification')) {
      $variables['extra'] = ' (' . t('not verified') . ')';
    }
628 629 630 631 632 633 634
  }

  // Set the name to a formatted name that is safe for printing and
  // that won't break tables by being too long. Keep an unshortened,
  // unsanitized version, in case other preprocess functions want to implement
  // their own shortening logic or add markup. If they do so, they must ensure
  // that $variables['name'] is safe for printing.
635
  $name = $variables['name_raw'] = $account->getUsername();
636 637 638 639 640
  if (drupal_strlen($name) > 20) {
    $name = drupal_substr($name, 0, 15) . '...';
  }
  $variables['name'] = check_plain($name);
  $variables['profile_access'] = user_access('access user profiles');
641

642 643 644
  // Populate link path and attributes if appropriate.
  if ($variables['uid'] && $variables['profile_access']) {
    // We are linking to a local user.
645
    $variables['link_options']['attributes']['title'] = t('View user profile.');
646 647 648 649 650 651
    $variables['link_path'] = 'user/' . $variables['uid'];
  }
  elseif (!empty($account->homepage)) {
    // Like the 'class' attribute, the 'rel' attribute can hold a
    // space-separated set of values, so initialize it as an array to make it
    // easier for other preprocess functions to append to it.
652
    $variables['link_options']['attributes']['rel'] = 'nofollow';
653 654 655 656 657 658
    $variables['link_path'] = $account->homepage;
    $variables['homepage'] = $account->homepage;
  }
  // We do not want the l() function to check_plain() a second time.
  $variables['link_options']['html'] = TRUE;
  // Set a default class.
659
  $variables['link_options']['attributes']['class'] = array('username');
660 661 662 663 664 665 666 667 668 669 670 671 672 673
}

/**
 * Returns HTML for a username, potentially linked to the user's page.
 *
 * @param $variables
 *   An associative array containing:
 *   - account: The user object to format.
 *   - name: The user's name, sanitized.
 *   - extra: Additional text to append to the user's name, sanitized.
 *   - link_path: The path or URL of the user's profile page, home page, or
 *     other desired page to link to for more information about the user.
 *   - link_options: An array of options to pass to the l() function's $options
 *     parameter if linking the user's name to the user's page.
674 675
 *   - attributes: An array of attributes to instantiate the
 *     Drupal\Core\Template\Attribute class if not linking to the user's page.
676 677 678 679 680 681 682 683 684 685 686 687 688
 *
 * @see template_preprocess_username()
 */
function theme_username($variables) {
  if (isset($variables['link_path'])) {
    // We have a link path, so we should generate a link using l().
    // Additional classes may be added as array elements like
    // $variables['link_options']['attributes']['class'][] = 'myclass';
    $output = l($variables['name'] . $variables['extra'], $variables['link_path'], $variables['link_options']);
  }
  else {
    // Modules may have added important attributes so they must be included
    // in the output. Additional classes may be added as array elements like
689
    // $variables['attributes']['class'][] = 'myclass';
690
    $output = '<span' . new Attribute($variables['attributes']) . '>' . $variables['name'] . $variables['extra'] . '</span>';
691 692 693 694
  }
  return $output;
}

695 696 697 698 699 700
/**
 * Determines if the current user is anonymous.
 *
 * @return bool
 *   TRUE if the user is anonymous, FALSE if the user is authenticated.
 */
701
function user_is_anonymous() {
702
  // Menu administrators can see items for anonymous when administering.
703
  return $GLOBALS['user']->isAnonymous() || !empty($GLOBALS['menu_admin']);
704 705
}

706 707 708 709 710
/**
 * Determines if the current user is logged in.
 *
 * @return bool
 *   TRUE if the user is logged in, FALSE if the user is anonymous.
711 712
 *
 * @deprecated Use \Drupal\Core\Session\UserSession::isAuthenticated().
713
 */
714
function user_is_logged_in() {
715
  return $GLOBALS['user']->isAuthenticated();
716 717
}

718 719 720 721 722 723
/**
 * Determines if the current user has access to the user registration page.
 *
 * @return bool
 *   TRUE if the user is not already logged in and can register for an account.
 */
724
function user_register_access() {
725
  return user_is_anonymous() && (Drupal::config('user.settings')->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY);
726 727
}

728
/**
729
 * Implements hook_menu().
730
 */
731 732
function user_menu() {
  // Registration and login pages.
733
  $items['user'] = array(
734
    'title' => 'User account',
735 736
    'title callback' => 'user_menu_title',
    'weight' => -10,
737
    'route_name' => 'user.page',
738
    'menu_name' => 'account',
739 740 741
  );

  $items['user/login'] = array(
742
    'title' => 'Log in',
743 744
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
745 746 747 748 749
  // Other authentication methods may add pages below user/login/.
  $items['user/login/default'] = array(
    'title' => 'Username and password',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
750

751
  $items['user/register'] = array(
752
    'title' => 'Create new account',
753
    'type' => MENU_LOCAL_TASK,
754
    'route_name' => 'user.register',
755 756 757
  );

  $items['user/password'] = array(
758
    'title' => 'Request new password',
759
    'route_name' => 'user.pass',
760 761 762
    'type' => MENU_LOCAL_TASK,
  );
  $items['user/reset/%/%/%'] = array(
763
    'title' => 'Reset password',
764 765 766 767
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_pass_reset', 2, 3, 4),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
768
    'file' => 'user.pages.inc',
769 770
  );

771 772
  $items['user/logout'] = array(
    'title' => 'Log out',
773
    'route_name' => 'user.logout',
774
    'weight' => 10,
775
    'menu_name' => 'account',
776 777
  );

778
  // User listing pages.
779 780
  $items['admin/people'] = array(
    'title' => 'People',
781
    'description' => 'Manage user accounts, roles, and permissions.',
782
    'page callback' => 'user_admin_account',
783
    'access arguments' => array('administer users'),
784
    'position' => 'left',
785
    'weight' => -4,
786
    'file' => 'user.admin.inc',
787
  );
788
  // Permissions and role forms.
789 790 791
  $items['admin/people/permissions'] = array(
    'title' => 'Permissions',
    'description' => 'Determine access to features by selecting permissions for roles.',
792
    'route_name' => 'user.admin_permissions',
793 794
    'type' => MENU_LOCAL_TASK,
  );
795
  $items['admin/people/roles'] = array(
796 797
    'title' => 'Roles',
    'description' => 'List, edit, or add user roles.',
798
    'route_name' => 'user.role_list',
799 800
    'type' => MENU_LOCAL_TASK,
  );
801 802
  $items['admin/people/roles/add'] = array(
    'title' => 'Add role',
803
    'route_name' => 'user.role_add',
804 805 806 807
    'type' => MENU_LOCAL_ACTION,
  );

  $items['admin/people/roles/manage/%user_role'] = array(
808
    'title' => 'Edit role',
809
    'route_name' => 'user.role_edit',
810
  );
811 812 813 814 815
  $items['admin/people/roles/manage/%user_role/edit'] = array(
    'title' => 'Edit',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/people/roles/manage/%user_role/delete'] = array(
816
    'title' => 'Delete role',
817
    'route_name' => 'user.role_delete',
818 819
    'weight' => 10,
    'context' => MENU_CONTEXT_INLINE,
820
  );
821

822
  $items['admin/people/create'] = array(
823
    'title' => 'Add user',
824
    'route_name' => 'user.admin_create',
825
    'type' => MENU_LOCAL_ACTION,
826
  );
827 828 829

  // Administration pages.
  $items['admin/config/people'] = array(
830 831 832 833
    'title' => 'People',
    'description' => 'Configure user accounts.',
    'position' => 'left',
    'weight' => -20,
834
    'route_name' => 'user.admin_index',
835
  );
836

837 838
  $items['admin/config/people/accounts'] = array(
    'title' => 'Account settings',
839
    'description' => 'Configure default behavior of users, including registration requirements, e-mails, and fields.',
840
    'weight' => -10,
841
    'route_name' => 'user.account_settings',
842
  );
843
  $items['admin/config/people/accounts/settings'] = array(
844 845 846
    'title' => 'Settings',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
847

848
  $items['user/%user'] = array(
849
    'title' => 'My account',
850 851
    'title callback' => 'user_page_title',
    'title arguments' => array(1),
852
    'page callback' => 'user_view_page',
853
    'page arguments' => array(1),
854
    'access callback' => 'entity_page_access',
855 856
    'access arguments' => array(1),
  );
857
  $items['user/%user/view'] = array(
858
    'title' => 'View',
859 860
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
861
  $items['user/%user/cancel'] = array(
862
    'route_name' => 'user.cancel_confirm',
863 864 865 866 867
  );
  $items['user/%user/cancel/confirm/%/%'] = array(
    'title' => 'Confirm account cancellation',
    'page callback' => 'user_cancel_confirm',
    'page arguments' => array(1, 4, 5),
868 869
    'access callback' => 'entity_page_access',
    'access arguments' => array(1, 'delete'),
870
    'file' => 'user.pages.inc',
871
  );
872
  $items['user/%user/edit'] = array(
873
    'title' => 'Edit',
874
    'route_name' => 'user.edit',
875 876
    'type' => MENU_LOCAL_TASK,
  );
Dries's avatar
Dries committed
877
  return $items;
878 879
}

880
/**
881
 * Implements hook_menu_link_presave().
882
 */
883
function user_menu_link_presave(MenuLink $menu_link) {
884 885 886
  // The path 'user' must be accessible for anonymous users, but only visible
  // for authenticated users. Authenticated users should see "My account", but
  // anonymous users should not see it at all. Therefore, invoke
887
  // user_menu_link_load() to conditionally hide the link.
888 889
  if ($menu_link->link_path == 'user' && $menu_link->module == 'system') {
    $menu_link->options['alter'] = TRUE;
890 891
  }

892
  // Force the Logout link to appear on the top-level of 'account' menu by
893
  // default (i.e., unless it has been customized).
894 895
  if ($menu_link->link_path == 'user/logout' && $menu_link->module == 'system' && empty($menu_link->customized)) {
    $menu_link->plid = 0;
896 897 898
  }
}

899 900 901 902 903 904 905 906 907 908 909
/**
 * Implements hook_menu_breadcrumb_alter().
 */
function user_menu_breadcrumb_alter(&$active_trail, $item) {
  // Remove "My account" from the breadcrumb when $item is descendant-or-self
  // of system path user/%.
  if (isset($active_trail[1]['module']) && $active_trail[1]['module'] == 'system' && $active_trail[1]['link_path'] == 'user' && strpos($item['path'], 'user/%') === 0) {
    array_splice($active_trail, 1, 1);
  }
}

910
/**
911
 * Implements hook_menu_link_load().
912
 */
913
function user_menu_link_load($menu_links) {
914
  // Hide the "User account" link for anonymous users.
915
  foreach ($menu_links as $link) {
916
    if ($link['link_path'] == 'user' && $link['module'] == 'system' && !$GLOBALS['user']->id()) {
917 918
      $link['hidden'] = 1;
    }
919 920 921
  }
}

922 923 924 925 926 927 928 929
/**
 * Implements hook_admin_paths().
 */
function user_admin_paths() {
  $paths = array(
    'user/*/cancel' => TRUE,
    'user/*/edit' => TRUE,
    'user/*/edit/*' => TRUE,
930 931
    'user/*/translations' => TRUE,
    'user/*/translations/*' => TRUE,
932 933 934 935
  );
  return $paths;
}

936 937 938 939 940 941 942 943 944 945 946
/**
 * Returns $arg or the user ID of the current user if $arg is '%' or empty.
 *
 * Deprecated. Use %user_uid_optional instead.
 *
 * @todo D8: Remove.
 */
function user_uid_only_optional_to_arg($arg) {
  return user_uid_optional_to_arg($arg);
}

947
/**
948
 * Load either a specified or the current user account.
949 950 951 952 953
 *
 * @param $uid
 *   An optional user ID of the user to load. If not provided, the current
 *   user's ID will be used.
 * @return
954
 *   A fully-loaded $user object upon successful user load, NULL if user
955 956 957
 *   cannot be loaded.
 *
 * @see user_load()
958
 * @todo rethink the naming of this in Drupal 8.
959 960 961
 */
function user_uid_optional_load($uid = NULL) {
  if (!isset($uid)) {
962
    $uid = $GLOBALS['user']->id();
963 964
  }
  return user_load($uid);
965 966
}

967
/**
968 969 970
 * Returns $arg or the user ID of the current user if $arg is '%' or empty.
 *
 * @todo rethink the naming of this in Drupal 8.
971
 */
972
function user_uid_optional_to_arg($arg) {
973 974 975
  // Give back the current user uid when called from eg. tracker, aka.
  // with an empty arg. Also use the current user uid when called from
  // the menu with a % for the current account link.
976
  return empty($arg) || $arg == '%' ? $GLOBALS['user']->id() : $arg;
977 978
}

979
/**
980
 * Menu item title callback for the 'user' path.
981
 *
982 983
 * Anonymous users should see a title based on the requested page, but
 * authenticated users are expected to see "My account".
984
 */
985
function user_menu_title() {
986
  if ($GLOBALS['user']->isAnonymous()) {
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
    switch (current_path()) {
      case 'user' :
      case 'user/login' :
        return t('Log in');
      case 'user/register' :
        return t('Create new account');
      case 'user/password' :
        return t('Request new password');
      default :
        return t('User account');
    }
  }
  else {
    return t('My account');
  }
1002 1003
}

1004
/**
1005
 * Menu item title callback - use the user name.
1006
 */
1007 1008
function user_page_title(UserInterface $account = NULL) {
  return $account ? $account->getUsername() : '';
1009 1010
}

1011
/**
1012
 * Try to validate the user's login credentials locally.