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

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

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

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

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

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

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

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

48 49 50 51 52 53 54 55
/**
 * Implement hook_help().
 */
function user_help($path, $arg) {
  switch ($path) {
    case 'admin/help#user':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
56
      $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>';
57 58 59
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Creating and managing users') . '</dt>';
60
      $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>';
61
      $output .= '<dt>' . t('User roles and permissions') . '</dt>';
62
      $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>';
63
      $output .= '<dt>' . t('Account settings') . '</dt>';
64
      $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>';
65 66 67 68
      $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>';
69
    case 'admin/people/permissions':
70 71
      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':
72
      $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>';
73
      $output .= '<p>' . t('Drupal has three special user roles:') . '</p>';
74 75 76
      $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>';
77
      $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>';
78 79 80
      $output .= '</ul>';
      return $output;
    case 'admin/config/people/accounts/fields':
81 82 83
      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>';
84 85 86 87 88 89
    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>';
  }
}
90

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

114 115 116 117 118
/**
 * Implements hook_page_build().
 */
function user_page_build(&$page) {
  $path = drupal_get_path('module', 'user');
119
  $page['#attached']['css'][$path . '/css/user.module.css'] = array('every_page' => TRUE);
120 121
}

122 123 124 125
/**
 * Implements hook_entity_bundle_info().
 */
function user_entity_bundle_info() {
126
  $bundles['user']['user']['label'] = t('User');
127 128 129
  return $bundles;
}

130
/**
131
 * Entity URI callback.
132
 */
133 134
function user_uri($user) {
  return array(
135
    'path' => 'user/' . $user->id(),
136
  );
137 138
}

139 140 141
/**
 * Entity label callback.
 *
142 143 144
 * 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.
 *
145 146 147 148 149 150 151 152
 * @param $entity_type
 *   The entity type.
 * @param $entity
 *   The entity object.
 *
 * @return
 *   The name of the user.
 *
153
 * @see user_format_name()
154 155
 */
function user_label($entity_type, $entity) {
156
  return $entity->getUsername();
157 158
}

159 160 161
/**
 * Populates $entity->account for each prepared entity.
 *
162 163
 * Called by Drupal\Core\Entity\EntityRenderControllerInterface::buildContent()
 * implementations.
164 165 166 167 168 169 170
 *
 * @param array $entities
 *   The entities keyed by entity ID.
 */
function user_attach_accounts(array $entities) {
  $uids = array();
  foreach ($entities as $entity) {
171
    $uids[] = $entity->getAuthorId();
172 173 174 175 176
  }
  $uids = array_unique($uids);
  $accounts = user_load_multiple($uids);
  $anonymous = drupal_anonymous_user();
  foreach ($entities as $id => $entity) {
177 178
    if (isset($accounts[$entity->getAuthorId()])) {
      $entities[$id]->account = $accounts[$entity->getAuthorId()];
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    }
    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');
}

198
/**
199
 * Implements hook_field_extra_fields().
200
 */
201
function user_field_extra_fields() {
202 203 204 205 206
  $fields['user']['user']['form']['account'] = array(
    'label' => t('User name and password'),
    'description' => t('User module account form elements.'),
    'weight' => -10,
  );
207
  if (Drupal::config('user.settings')->get('signatures')) {
208 209 210 211 212 213 214 215 216 217 218
    $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,
  );
219
  if (Drupal::config('system.date')->get('timezone.user.configurable')) {
220 221 222 223 224 225 226 227 228 229 230
    $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,
231
  );
232

233
  return $fields;
234 235
}

Dries's avatar
Dries committed
236
/**
237
 * Loads multiple users based on certain conditions.
Dries's avatar
Dries committed
238
 *
239 240 241
 * 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
242
 *
243 244
 * @param array $uids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
245
 * @param bool $reset
246 247
 *   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.
248
 *
249
 * @return array
250 251
 *   An array of user objects, indexed by uid.
 *
252
 * @see entity_load_multiple()
253 254 255
 * @see user_load()
 * @see user_load_by_mail()
 * @see user_load_by_name()
256
 * @see \Drupal\Core\Entity\Query\QueryInterface
Dries's avatar
Dries committed
257
 */
258
function user_load_multiple(array $uids = NULL, $reset = FALSE) {
259
  return entity_load_multiple('user', $uids, $reset);
260
}
261 262

/**
263 264 265 266 267 268
 * 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
269 270 271 272
 * 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.
273
 *
274
 * @param int $uid
275
 *   Integer specifying the user ID to load.
276
 * @param bool $reset
277 278 279
 *   TRUE to reset the internal cache and load from the database; FALSE
 *   (default) to load from the internal cache, if set.
 *
280
 * @return object
281
 *   A fully-loaded user object upon successful user load, or NULL if the user
282 283 284 285 286
 *   cannot be loaded.
 *
 * @see user_load_multiple()
 */
function user_load($uid, $reset = FALSE) {
287
  return entity_load('user', $uid, $reset);
288 289 290
}

/**
291
 * Fetches a user object by email address.
292
 *
293
 * @param string $mail
294
 *   String with the account's e-mail address.
295
 * @return object|bool
296 297 298 299 300 301
 *   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) {
302
  $users = entity_load_multiple_by_properties('user', array('mail' => $mail));
303
  return $users ? reset($users) : FALSE;
304 305 306
}

/**
307
 * Fetches a user object by account name.
308
 *
309
 * @param string $name
310
 *   String with the account's user name.
311
 * @return object|bool
312 313 314 315 316 317
 *   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) {
318
  $users = entity_load_multiple_by_properties('user', array('name' => $name));
319
  return $users ? reset($users) : FALSE;
320 321
}

Dries's avatar
Dries committed
322 323
/**
 * Verify the syntax of the given name.
324 325 326 327 328 329 330 331
 *
 * @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
332
 */
333
function user_validate_name($name) {
334 335 336 337 338 339 340 341
  $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();
342
  }
343 344
}

Dries's avatar
Dries committed
345 346 347
/**
 * Generate a random alphanumeric password.
 */
348 349
function user_password($length = 10) {
  // This variable contains the list of allowable characters for the
350 351
  // password. Note that the number 0 and the letter 'O' have been
  // removed to avoid confusion between the two. The same is true
352
  // of 'I', 1, and 'l'.
353
  $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
Dries's avatar
Dries committed
354

355 356
  // Zero-based count of characters in the allowable list:
  $len = strlen($allowable_characters) - 1;
357

Dries's avatar
Dries committed
358 359
  // Declare the password as a blank string.
  $pass = '';
360

Dries's avatar
Dries committed
361
  // Loop the number of times specified by $length.
362 363 364 365
  for ($i = 0; $i < $length; $i++) {

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

  return $pass;
370 371
}

372 373 374
/**
 * Determine the permissions for one or more roles.
 *
375 376
 * @param array $roles
 *   An array of role IDs.
377
 *
378 379 380
 * @return array
 *   An array indexed by role ID. Each value is an array of permission strings
 *   for the given role.
381
 */
382 383 384 385 386 387
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();
388
  foreach ($roles as $rid) {
389
    $role_permissions[$rid] = isset($entities[$rid]) ? $entities[$rid]->getPermissions() : array();
390
  }
391 392
  return $role_permissions;
}
393

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
/**
 * 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();
412 413 414 415
  }
  return $role_permissions;
}

Dries's avatar
Dries committed
416 417 418 419 420
/**
 * Determine whether the user has a given privilege.
 *
 * @param $string
 *   The permission, such as "administer nodes", being checked for.
421
 * @param \Drupal\Core\Session\AccountInterface $account
422
 *   (optional) The account to check, if not given use currently logged in user.
Dries's avatar
Dries committed
423
 *
424
 * @return bool
425
 *   Boolean TRUE if the current user has the requested permission.
Dries's avatar
Dries committed
426
 *
427 428
 * @deprecated as of Drupal 8.0. Use
 *   \Drupal\Core\Session\AccountInterface::hasPermission()
Dries's avatar
Dries committed
429
 */
430
function user_access($string, AccountInterface $account = NULL) {
431
  global $user;
432

433
  if (!isset($account)) {
434 435
    // 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.
436
    $account = Drupal::request()->attributes->get('_account') ?: $user;
437 438
  }

439
  return $account->hasPermission($string);
440 441
}

442
/**
443
 * Checks for usernames blocked by user administration.
444
 *
445 446 447 448 449 450
 * @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.
451 452
 */
function user_is_blocked($name) {
453 454 455 456 457
  return db_select('users')
    ->fields('users', array('name'))
    ->condition('name', db_like($name), 'LIKE')
    ->condition('status', 0)
    ->execute()->fetchObject();
458 459
}

Dries's avatar
Dries committed
460
/**
461
 * Implements hook_permission().
Dries's avatar
Dries committed
462
 */
463
function user_permission() {
464 465 466
  return array(
    'administer permissions' =>  array(
      'title' => t('Administer permissions'),
467
      'restrict access' => TRUE,
468 469 470
    ),
    'administer users' => array(
      'title' => t('Administer users'),
471
      'restrict access' => TRUE,
472 473
    ),
    'access user profiles' => array(
474
      'title' => t('View user profiles'),
475 476 477 478 479
    ),
    'change own username' => array(
      'title' => t('Change own username'),
    ),
    'cancel account' => array(
480
      'title' => t('Cancel own user account'),
481
      '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'))),
482 483 484
    ),
    'select account cancellation method' => array(
      'title' => t('Select method for cancelling own account'),
485
      'restrict access' => TRUE,
486 487
    ),
  );
488 489
}

Dries's avatar
Dries committed
490
/**
491
 * Implements hook_search_info().
Dries's avatar
Dries committed
492
 */
493 494 495 496 497 498 499
function user_search_info() {
  return array(
    'title' => 'Users',
  );
}

/**
500
 * Implements hook_search_access().
501 502 503 504 505 506
 */
function user_search_access() {
  return user_access('access user profiles');
}

/**
507
 * Implements hook_search_execute().
508
 */
509
function user_search_execute($keys = NULL, $conditions = NULL) {
510 511
  // Replace wildcards with MySQL/PostgreSQL wildcards.
  $keys = preg_replace('!\*+!', '%', $keys);
512 513
  $query = db_select('users')
    ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
514
  $query->fields('users', array('uid'));
515
  if (user_access('administer users')) {
516 517
    // Administrators can also search in the otherwise private email field, and
    // they don't need to be restricted to only active users.
518
    $query->fields('users', array('mail'));
519
    $query->condition(db_or()->
520 521
      condition('name', '%' . db_like($keys) . '%', 'LIKE')->
      condition('mail', '%' . db_like($keys) . '%', 'LIKE'));
522 523
  }
  else {
524 525 526 527
    // Regular users can only search via usernames, and we do not show them
    // blocked accounts.
    $query->condition('name', '%' . db_like($keys) . '%', 'LIKE')
      ->condition('status', 1);
528
  }
529
  $uids = $query
530
    ->limit(15)
531 532 533 534 535 536 537
    ->execute()
    ->fetchCol();
  $accounts = user_load_multiple($uids);

  $results = array();
  foreach ($accounts as $account) {
    $result = array(
538
      'title' => user_format_name($account),
539
      'link' => url('user/' . $account->id(), array('absolute' => TRUE)),
540 541
    );
    if (user_access('administer users')) {
542
      $result['title'] .= ' (' . $account->getEmail() . ')';
543
    }
544
    $results[] = $result;
545
  }
546 547

  return $results;
548 549
}

Dries's avatar
Dries committed
550
/**
551
 * Implements hook_user_view().
Dries's avatar
Dries committed
552
 */
553
function user_user_view(UserInterface $account, EntityDisplay $display) {
554 555 556 557
  if ($display->getComponent('member_for')) {
    $account->content['member_for'] = array(
      '#type' => 'item',
      '#title' => t('Member for'),
558
      '#markup' => format_interval(REQUEST_TIME - $account->getCreatedTime()),
559 560
    );
  }
561 562
}

563 564 565 566 567 568 569 570 571
/**
 * 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'];
572 573
}

574
/**
575
 * Form validation handler for the current password on the user account form.
576
 *
577
 * @see AccountFormController::form()
578 579
 */
function user_validate_current_pass(&$form, &$form_state) {
580
  $account = $form_state['user'];
581 582 583 584
  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.
585 586
    $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)) {
587
      $current_pass_failed = empty($form_state['values']['current_pass']) || !Drupal::service('password')->check($form_state['values']['current_pass'], $account);
588 589 590 591 592 593 594 595 596 597
      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;
    }
  }
}

598
/**
599
 * Implements hook_preprocess_HOOK() for block.html.twig.
600 601
 */
function user_preprocess_block(&$variables) {
602 603
  if ($variables['configuration']['module'] == 'user') {
    switch ($variables['elements']['#plugin_id']) {
604
      case 'user_login_block':
605
        $variables['attributes']['role'] = 'form';
606
        break;
607
      case 'user_new_block':
608
        $variables['attributes']['role'] = 'complementary';
609
        break;
610
      case 'user_online_block':
611
        $variables['attributes']['role'] = 'complementary';
612 613 614 615 616
        break;
    }
  }
}

617 618 619
/**
 * Format a username.
 *
620
 * @param \Drupal\Core\Session\Interface $account
621 622 623 624 625 626
 *   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.
627 628
 *
 * @deprecated Use \Drupal\Core\Session\Interface::getUsername() instead.
629
 */
630 631
function user_format_name(AccountInterface $account) {
  return $account->getUsername();
632 633
}

634 635 636 637 638 639 640 641 642
/**
 * 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;

643 644 645 646 647 648
  // If this function is called from the installer after Drupal has been
  // installed then $user will not be set.
  if (!is_object($user)) {
    return;
  }

649 650 651 652 653
  $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');
654
  $variables['logged_in'] = $user->isAuthenticated();
655 656
}

657 658 659
/**
 * Preprocesses variables for theme_username().
 *
660
 * Modules that make any changes to variables like 'name' or 'extra' must ensure
661 662 663 664
 * that the final string is safe to include directly in the output by using
 * check_plain() or filter_xss().
 */
function template_preprocess_username(&$variables) {
665
  $account = $variables['account'] ?: drupal_anonymous_user();
666 667

  $variables['extra'] = '';
668 669 670 671 672
  $variables['uid'] = $account->id();
  if (empty($variables['uid'])) {
    if (theme_get_setting('features.comment_user_verification')) {
      $variables['extra'] = ' (' . t('not verified') . ')';
    }
673 674 675 676 677 678 679
  }

  // 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.
680
  $name = $variables['name_raw'] = $account->getUsername();
681 682 683 684 685
  if (drupal_strlen($name) > 20) {
    $name = drupal_substr($name, 0, 15) . '...';
  }
  $variables['name'] = check_plain($name);
  $variables['profile_access'] = user_access('access user profiles');
686

687 688 689
  // Populate link path and attributes if appropriate.
  if ($variables['uid'] && $variables['profile_access']) {
    // We are linking to a local user.
690
    $variables['link_options']['attributes']['title'] = t('View user profile.');
691 692 693 694 695 696
    $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.
697
    $variables['link_options']['attributes']['rel'] = 'nofollow';
698 699 700 701 702 703
    $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.
704
  $variables['link_options']['attributes']['class'] = array('username');
705 706 707 708 709 710 711 712 713 714 715 716 717 718
}

/**
 * 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.
719 720
 *   - attributes: An array of attributes to instantiate the
 *     Drupal\Core\Template\Attribute class if not linking to the user's page.
721 722 723 724 725 726 727 728 729 730 731 732 733
 *
 * @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
734
    // $variables['attributes']['class'][] = 'myclass';
735
    $output = '<span' . new Attribute($variables['attributes']) . '>' . $variables['name'] . $variables['extra'] . '</span>';
736 737 738 739
  }
  return $output;
}

740 741 742 743 744 745
/**
 * Determines if the current user is anonymous.
 *
 * @return bool
 *   TRUE if the user is anonymous, FALSE if the user is authenticated.
 */
746
function user_is_anonymous() {
747
  // Menu administrators can see items for anonymous when administering.
748
  return $GLOBALS['user']->isAnonymous() || !empty($GLOBALS['menu_admin']);
749 750
}

751 752 753 754 755
/**
 * Determines if the current user is logged in.
 *
 * @return bool
 *   TRUE if the user is logged in, FALSE if the user is anonymous.
756 757
 *
 * @deprecated Use \Drupal\Core\Session\UserSession::isAuthenticated().
758
 */
759
function user_is_logged_in() {
760
  return $GLOBALS['user']->isAuthenticated();
761 762
}

763 764 765 766 767 768
/**
 * 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.
 */
769
function user_register_access() {
770
  return user_is_anonymous() && (Drupal::config('user.settings')->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY);
771 772
}

773
/**
774
 * Implements hook_menu().
775
 */
776 777
function user_menu() {
  // Registration and login pages.
778
  $items['user'] = array(
779
    'title' => 'User account',
780 781
    'title callback' => 'user_menu_title',
    'weight' => -10,
782
    'route_name' => 'user_page',
783
    'menu_name' => 'account',
784 785 786
  );

  $items['user/login'] = array(
787
    'title' => 'Log in',
788 789
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
790 791 792 793 794
  // Other authentication methods may add pages below user/login/.
  $items['user/login/default'] = array(
    'title' => 'Username and password',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
795

796
  $items['user/register'] = array(
797
    'title' => 'Create new account',
798
    'type' => MENU_LOCAL_TASK,
799
    'route_name' => 'user_register',
800 801 802
  );

  $items['user/password'] = array(
803
    'title' => 'Request new password',
804
    'route_name' => 'user_pass',
805 806 807
    'type' => MENU_LOCAL_TASK,
  );
  $items['user/reset/%/%/%'] = array(
808
    'title' => 'Reset password',
809 810 811 812
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_pass_reset', 2, 3, 4),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
813
    'file' => 'user.pages.inc',
814 815
  );

816 817
  $items['user/logout'] = array(
    'title' => 'Log out',
818
    'route_name' => 'user_logout',
819
    'weight' => 10,
820
    'menu_name' => 'account',
821 822
  );

823
  // User listing pages.
824 825
  $items['admin/people'] = array(
    'title' => 'People',
826
    'description' => 'Manage user accounts, roles, and permissions.',
827
    'page callback' => 'user_admin_account',
828
    'access arguments' => array('administer users'),
829
    'position' => 'left',
830
    'weight' => -4,
831
    'file' => 'user.admin.inc',
832
  );
833
  // Permissions and role forms.
834 835 836
  $items['admin/people/permissions'] = array(
    'title' => 'Permissions',
    'description' => 'Determine access to features by selecting permissions for roles.',
837
    'route_name' => 'user_admin_permissions',
838 839
    'type' => MENU_LOCAL_TASK,
  );
840
  $items['admin/people/roles'] = array(
841 842
    'title' => 'Roles',
    'description' => 'List, edit, or add user roles.',
843
    'route_name' => 'user_role_list',
844 845
    'type' => MENU_LOCAL_TASK,
  );
846 847
  $items['admin/people/roles/add'] = array(
    'title' => 'Add role',
848
    'route_name' => 'user_role_add',
849 850 851 852
    'type' => MENU_LOCAL_ACTION,
  );

  $items['admin/people/roles/manage/%user_role'] = array(
853
    'title' => 'Edit role',
854
    'route_name' => 'user_role_edit',
855
  );
856 857 858 859 860
  $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(
861
    'title' => 'Delete role',
862
    'route_name' => 'user_role_delete',
863 864
    'weight' => 10,
    'context' => MENU_CONTEXT_INLINE,
865
  );
866

867
  $items['admin/people/create'] = array(
868
    'title' => 'Add user',
869
    'route_name' => 'user_admin_create',
870
    'type' => MENU_LOCAL_ACTION,
871
  );
872 873 874 875 876 877
  $items['admin/people/cancel'] = array(
    'title' => 'Cancel user',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_multiple_cancel_confirm'),
    'access arguments' => array('administer users'),
    'file' => 'user.admin.inc',
878
    'type' => MENU_CALLBACK,
879
  );
880 881 882

  // Administration pages.
  $items['admin/config/people'] = array(
883 884 885 886 887
    'title' => 'People',
    'description' => 'Configure user accounts.',
    'position' => 'left',
    'weight' => -20,
    'route_name' => 'user_admin_index',
888
  );
889

890 891
  $items['admin/config/people/accounts'] = array(
    'title' => 'Account settings',
892
    'description' => 'Configure default behavior of users, including registration requirements, e-mails, and fields.',
893
    'weight' => -10,
894
    'route_name' => 'user_account_settings',
895
  );
896
  $items['admin/config/people/accounts/settings'] = array(
897 898 899
    'title' => 'Settings',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
900

901
  $items['user/%user'] = array(
902
    'title' => 'My account',
903 904
    'title callback' => 'user_page_title',
    'title arguments' => array(1),
905
    'page callback' => 'user_view_page',
906
    'page arguments' => array(1),
907
    'access callback' => 'entity_page_access',
908 909
    'access arguments' => array(1),
  );
910
  $items['user/%user/view'] = array(
911
    'title' => 'View',
912 913
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
914 915
  $items['user/%user/cancel'] = array(
    'title' => 'Cancel account',
916
    'page callback' => 'drupal_get_form',
917
    'page arguments' => array('user_cancel_confirm_form', 1),
918 919
    'access callback' => 'entity_page_access',
    'access arguments' => array(1, 'delete'),
920
    'file' => 'user.pages.inc',
921 922 923 924 925
  );
  $items['user/%user/cancel/confirm/%/%'] = array(
    'title' => 'Confirm account cancellation',
    'page callback' => 'user_cancel_confirm',
    'page arguments' => array(1, 4, 5),
926 927
    'access callback' => 'entity_page_access',
    'access arguments' => array(1, 'delete'),
928
    'file' => 'user.pages.inc',
929
  );
930
  $items['user/%user/edit'] = array(
931
    'title' => 'Edit',
932
    'route_name' => 'user_edit',
933 934
    'type' => MENU_LOCAL_TASK,
  );
Dries's avatar
Dries committed
935
  return $items;
936 937
}

938
/**
939
 * Implements hook_menu_link_presave().
940
 */
941
function user_menu_link_presave(MenuLink $menu_link) {
942 943 944
  // 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
945
  // user_menu_link_load() to conditionally hide the link.
946 947
  if ($menu_link->link_path == 'user' && $menu_link->module == 'system') {
    $menu_link->options['alter'] = TRUE;
948 949
  }

950
  // Force the Logout link to appear on the top-level of 'account' menu by
951
  // default (i.e., unless it has been customized).
952 953
  if ($menu_link->link_path == 'user/logout' && $menu_link->module == 'system' && empty($menu_link->customized)) {
    $menu_link->plid = 0;
954 955 956
  }
}

957 958 959 960 961 962 963 964 965 966 967
/**
 * 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);
  }
}

968
/**
969
 * Implements hook_menu_link_load().
970
 */
971
function user_menu_link_load($menu_links) {
972
  // Hide the "User account" link for anonymous users.
973
  foreach ($menu_links as $link) {
974
    if ($link['link_path'] == 'user' && $link['module'] == 'system' && !$GLOBALS['user']->id()) {
975 976
      $link['hidden'] = 1;
    }
977 978 979
  }
}

980 981 982 983 984 985 986 987
/**
 * Implements hook_admin_paths().
 */
function user_admin_paths() {
  $paths = array(
    'user/*/cancel' => TRUE,
    'user/*/edit' => TRUE,
    'user/*/edit/*' => TRUE,
988 989
    'user/*/translations' => TRUE,
    'user/*/translations/*' => TRUE,
990 991 992 993
  );
  return $paths;
}

994 995 996 997 998