user.module 65.5 KB
Newer Older
Dries's avatar
 
Dries committed
1 2
<?php

3
use Drupal\Component\Utility\Crypt;
4
use Drupal\Core\Entity\EntityInterface;
5
use Drupal\Core\Session\AccountInterface;
6
use \Drupal\Core\Entity\Display\EntityViewDisplayInterface;
7 8
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 Drupal\Core\TypedData\DataDefinition;
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

Dries's avatar
 
Dries committed
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
/**
 * Only administrators can create user accounts.
 */
30
const USER_REGISTER_ADMINISTRATORS_ONLY = 'admin_only';
31 32 33 34

/**
 * Visitors can create their own accounts.
 */
35
const USER_REGISTER_VISITORS = 'visitors';
36 37 38 39 40

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

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

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

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

/**
 * Implements hook_js_alter().
 */
function user_js_alter(&$javascript) {
  // If >=1 JavaScript asset has declared a dependency on drupalSettings, the
  // 'settings' key will exist. Thus when that key does not exist, return early.
  if (!isset($javascript['settings'])) {
    return;
  }
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.
130 131 132
  // Similarly, provide a permissions hash, so that permission-dependent data
  // can be reliably cached on the client side.
  $user = \Drupal::currentUser();
133 134
  $javascript['settings']['data'][] = array(
    'user' => array(
135 136
      'uid' => $user->id(),
      'permissionsHash' => \Drupal::service('user.permissions_hash')->generate($user),
137
    ),
138
  );
139 140
}

141 142 143 144
/**
 * Implements hook_entity_bundle_info().
 */
function user_entity_bundle_info() {
145
  $bundles['user']['user']['label'] = t('User');
146 147 148
  return $bundles;
}

149
/**
150
 * Entity URI callback.
151
 */
152 153
function user_uri($user) {
  return array(
154
    'path' => 'user/' . $user->id(),
155
  );
156 157
}

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

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

232
  return $fields;
233 234
}

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

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

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

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

Dries's avatar
Dries committed
321 322
/**
 * Verify the syntax of the given name.
323 324 325 326 327 328 329 330
 *
 * @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
331
 */
Dries's avatar
 
Dries committed
332
function user_validate_name($name) {
333 334
  $definition = DataDefinition::create('string')
    ->setConstraints(array('UserName' => array()));
335
  $data = \Drupal::typedDataManager()->create($definition);
336 337 338 339
  $data->setValue($name);
  $violations = $data->validate();
  if (count($violations) > 0) {
    return $violations[0]->getMessage();
340
  }
Dries's avatar
 
Dries committed
341 342
}

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

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

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

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

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

  return $pass;
Dries's avatar
 
Dries committed
368 369
}

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

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
/**
 * 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) {
409
    $role_permissions[$rid] = \Drupal::config("user.role.$rid")->get('permissions') ?: array();
410 411 412 413
  }
  return $role_permissions;
}

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

431
  if (!isset($account)) {
432 433
    // 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.
434
    $account = \Drupal::currentUser() ?: $user;
435 436
  }

437
  return $account->hasPermission($string);
Dries's avatar
 
Dries committed
438 439
}

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

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

Dries's avatar
Dries committed
493
/**
494
 * Implements hook_user_view().
Dries's avatar
Dries committed
495
 */
496
function user_user_view(UserInterface $account, EntityViewDisplayInterface $display) {
497 498 499 500
  if ($display->getComponent('member_for')) {
    $account->content['member_for'] = array(
      '#type' => 'item',
      '#title' => t('Member for'),
501
      '#markup' => format_interval(REQUEST_TIME - $account->getCreatedTime()),
502 503
    );
  }
504 505
}

506 507 508 509 510 511 512 513 514
/**
 * 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'];
515 516
}

517
/**
518
 * Form validation handler for the current password on the user account form.
519
 *
520
 * @see AccountFormController::form()
521 522
 */
function user_validate_current_pass(&$form, &$form_state) {
523
  $account = $form_state['user'];
524 525 526 527
  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.
528
    $current_value = $account->hasField($key) ? $account->get($key)->value : $account->$key;
529
    if ((strlen(trim($form_state['values'][$key])) > 0) && ($form_state['values'][$key] != $current_value)) {
530
      $current_pass_failed = empty($form_state['values']['current_pass']) || !\Drupal::service('password')->check($form_state['values']['current_pass'], $account);
531
      if ($current_pass_failed) {
532 533
        form_set_error('current_pass', $form_state, t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => $name)));
        form_set_error($key, $form_state);
534 535 536 537 538 539 540
      }
      // We only need to check the password once.
      break;
    }
  }
}

541
/**
542
 * Implements hook_preprocess_HOOK() for block templates.
543 544
 */
function user_preprocess_block(&$variables) {
545 546
  if ($variables['configuration']['module'] == 'user') {
    switch ($variables['elements']['#plugin_id']) {
547
      case 'user_login_block':
548
        $variables['attributes']['role'] = 'form';
549 550 551 552 553
        break;
    }
  }
}

554 555 556
/**
 * Format a username.
 *
557
 * @param \Drupal\Core\Session\Interface $account
558 559 560 561 562 563
 *   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.
564 565
 *
 * @deprecated Use \Drupal\Core\Session\Interface::getUsername() instead.
566
 */
567 568
function user_format_name(AccountInterface $account) {
  return $account->getUsername();
569 570
}

571 572 573 574 575 576 577
/**
 * Implements hook_template_preprocess_default_variables_alter().
 *
 * @see user_user_login()
 * @see user_user_logout()
 */
function user_template_preprocess_default_variables_alter(&$variables) {
578
  $user = \Drupal::currentUser();
579

580 581 582 583 584 585
  // If this function is called from the installer after Drupal has been
  // installed then $user will not be set.
  if (!is_object($user)) {
    return;
  }

586
  $variables['user'] = clone $user;
587
  // Remove password and session IDs, $form_state, since themes should not need nor see them.
588 589
  unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);

590
  $variables['is_admin'] = $user->hasPermission('access administration pages');
591
  $variables['logged_in'] = $user->isAuthenticated();
592 593
}

594 595 596
/**
 * Preprocesses variables for theme_username().
 *
597
 * Modules that make any changes to variables like 'name' or 'extra' must ensure
598 599 600 601
 * that the final string is safe to include directly in the output by using
 * check_plain() or filter_xss().
 */
function template_preprocess_username(&$variables) {
602
  $account = $variables['account'] ?: drupal_anonymous_user();
603 604

  $variables['extra'] = '';
605 606 607 608 609
  $variables['uid'] = $account->id();
  if (empty($variables['uid'])) {
    if (theme_get_setting('features.comment_user_verification')) {
      $variables['extra'] = ' (' . t('not verified') . ')';
    }
610 611 612 613 614 615 616
  }

  // 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.
617
  $name = $variables['name_raw'] = $account->getUsername();
618 619 620 621
  if (drupal_strlen($name) > 20) {
    $name = drupal_substr($name, 0, 15) . '...';
  }
  $variables['name'] = check_plain($name);
622
  $variables['profile_access'] = \Drupal::currentUser()->hasPermission('access user profiles');
623

624 625 626
  // Populate link path and attributes if appropriate.
  if ($variables['uid'] && $variables['profile_access']) {
    // We are linking to a local user.
627
    $variables['link_options']['attributes']['title'] = t('View user profile.');
628 629 630 631 632 633
    $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.
634
    $variables['link_options']['attributes']['rel'] = 'nofollow';
635 636 637 638 639 640
    $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.
641
  $variables['link_options']['attributes']['class'] = array('username');
642 643 644 645 646 647 648 649 650 651 652 653 654 655
}

/**
 * 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.
656 657
 *   - attributes: An array of attributes to instantiate the
 *     Drupal\Core\Template\Attribute class if not linking to the user's page.
658 659 660 661 662 663 664 665 666 667 668 669 670
 *
 * @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
671
    // $variables['attributes']['class'][] = 'myclass';
672
    $output = '<span' . new Attribute($variables['attributes']) . '>' . $variables['name'] . $variables['extra'] . '</span>';
673 674 675 676
  }
  return $output;
}

677 678 679 680 681 682
/**
 * Determines if the current user is anonymous.
 *
 * @return bool
 *   TRUE if the user is anonymous, FALSE if the user is authenticated.
 */
683
function user_is_anonymous() {
684
  // Menu administrators can see items for anonymous when administering.
685
  return $GLOBALS['user']->isAnonymous() || !empty($GLOBALS['menu_admin']);
686 687
}

688 689 690 691 692
/**
 * Determines if the current user is logged in.
 *
 * @return bool
 *   TRUE if the user is logged in, FALSE if the user is anonymous.
693 694
 *
 * @deprecated Use \Drupal\Core\Session\UserSession::isAuthenticated().
695
 */
696
function user_is_logged_in() {
697
  return $GLOBALS['user']->isAuthenticated();
698 699
}

700 701 702 703 704 705
/**
 * 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.
 */
706
function user_register_access() {
707
  return user_is_anonymous() && (\Drupal::config('user.settings')->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY);
708 709
}

Dries's avatar
 
Dries committed
710
/**
711
 * Implements hook_menu().
Dries's avatar
 
Dries committed
712
 */
713 714
function user_menu() {
  // Registration and login pages.
715
  $items['user'] = array(
716
    'title' => 'User account',
717 718
    'title callback' => 'user_menu_title',
    'weight' => -10,
719
    'route_name' => 'user.page',
720
    'menu_name' => 'account',
721 722
  );

723 724
  // Since menu_get_ancestors() does not support multiple placeholders in a row,
  // this MENU_CALLBACK cannot be removed yet.
725
  $items['user/reset/%/%/%'] = array(
726
    'title' => 'Reset password',
727
    'route_name' => 'user.reset',
728 729 730
    'type' => MENU_CALLBACK,
  );

731 732
  $items['user/logout'] = array(
    'title' => 'Log out',
733
    'route_name' => 'user.logout',
734
    'weight' => 10,
735
    'menu_name' => 'account',
736 737
  );

738
  // User listing pages.
739 740
  $items['admin/people'] = array(
    'title' => 'People',
741
    'description' => 'Manage user accounts, roles, and permissions.',
742
    'route_name' => 'user.admin_account',
743
    'position' => 'left',
744
    'weight' => -4,
745
  );
746

747
  // Permissions and role forms.
748 749 750
  $items['admin/people/permissions'] = array(
    'title' => 'Permissions',
    'description' => 'Determine access to features by selecting permissions for roles.',
751
    'route_name' => 'user.admin_permissions',
752
    'type' => MENU_SIBLING_LOCAL_TASK,
753
  );
754 755

  $items['admin/people/roles/manage/%user_role'] = array(
756
    'title' => 'Edit role',
757
    'route_name' => 'user.role_edit',
758 759
  );

760 761
  // Administration pages.
  $items['admin/config/people'] = array(
762 763 764 765
    'title' => 'People',
    'description' => 'Configure user accounts.',
    'position' => 'left',
    'weight' => -20,
766
    'route_name' => 'user.admin_index',
767
  );
768

769 770
  $items['admin/config/people/accounts'] = array(
    'title' => 'Account settings',
771
    'description' => 'Configure default behavior of users, including registration requirements, e-mails, and fields.',
772
    'weight' => -10,
773
    'route_name' => 'user.account_settings',
774 775
  );

776
  $items['user/%user'] = array(
777
    'title' => 'My account',
778 779
    'title callback' => 'user_page_title',
    'title arguments' => array(1),
780
    'route_name' => 'user.view',
781
  );
782
  $items['user/%user/cancel'] = array(
783
    'route_name' => 'user.cancel',
784 785 786
  );
  $items['user/%user/cancel/confirm/%/%'] = array(
    'title' => 'Confirm account cancellation',
787
    'route_name' => 'user.cancel_confirm',
788
  );
Dries's avatar
 
Dries committed
789
  return $items;
Dries's avatar
 
Dries committed
790 791
}

792
/**
793
 * Implements hook_menu_link_presave().
794
 */
795
function user_menu_link_presave(MenuLink $menu_link) {
796 797 798
  // 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
799
  // user_menu_link_load() to conditionally hide the link.
800
  if ($menu_link->link_path == 'user' && $menu_link->module == 'system') {
801
    $menu_link->options['alter'] = TRUE;
802
  }
803 804 805 806 807 808

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

811 812 813 814 815 816 817 818 819 820 821
/**
 * 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);
  }
}

822
/**
823
 * Implements hook_translated_menu_link_alter().
824
 */
825
function user_translated_menu_link_alter(MenuLink &$menu_link) {
826
  // Hide the "User account" link for anonymous users.
827 828
  if ($menu_link->link_path == 'user' && $menu_link->module == 'system' && \Drupal::currentUser()->isAnonymous()) {
    $menu_link->hidden = 1;
829 830 831
  }
}

832 833 834 835