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

3
use Drupal\Component\Utility\Crypt;
4
use Drupal\Core\Database\Query\SelectInterface;
5
use Drupal\Core\Entity\EntityInterface;
6 7
use Drupal\comment\Plugin\Core\Entity\Comment;
use Drupal\entity\Plugin\Core\Entity\EntityDisplay;
8
use Drupal\file\Plugin\Core\Entity\File;
9
use Drupal\user\Plugin\Core\Entity\User;
10
use Drupal\user\UserRole;
11
use Drupal\Core\Template\Attribute;
12
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
13
use Drupal\menu_link\Plugin\Core\Entity\MenuLink;
Crell's avatar
Crell committed
14

Dries's avatar
Dries committed
15 16 17 18 19
/**
 * @file
 * Enables the user registration and login system.
 */

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

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

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

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

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

46 47 48 49 50 51 52 53 54 55
/**
 * Implement hook_help().
 */
function user_help($path, $arg) {
  global $user;

  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 81 82 83 84 85 86 87
      $output .= '</ul>';
      return $output;
    case 'admin/config/people/accounts/fields':
      return '<p>' . t('This form lets administrators add, edit, and arrange fields for storing user data.') . '</p>';
    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>';
  }
}
88

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

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

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

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

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

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

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

213
/**
214
 * Implements hook_field_extra_fields().
215
 */
216
function user_field_extra_fields() {
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
  $fields['user']['user']['form']['account'] = array(
    'label' => t('User name and password'),
    'description' => t('User module account form elements.'),
    'weight' => -10,
  );
  if (config('user.settings')->get('signatures')) {
    $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,
  );
  if (config('system.timezone')->get('user.configurable')) {
    $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,
246
  );
247

248
  return $fields;
249 250
}

251
/**
252
 * Loads multiple users based on certain conditions.
253
 *
254 255 256
 * 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.
257
 *
258 259
 * @param array $uids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
260
 * @param bool $reset
261 262
 *   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.
263
 *
264
 * @return array
265 266
 *   An array of user objects, indexed by uid.
 *
267
 * @see entity_load_multiple()
268 269 270
 * @see user_load()
 * @see user_load_by_mail()
 * @see user_load_by_name()
271
 * @see \Drupal\Core\Entity\Query\QueryInterface
272
 */
273 274
function user_load_multiple(array $uids = NULL, $reset = FALSE) {
  return entity_load_multiple('user', $uids, $reset);
275
}
276 277

/**
278 279 280 281 282 283
 * 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
284 285 286 287
 * 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.
288
 *
289
 * @param int $uid
290
 *   Integer specifying the user ID to load.
291
 * @param bool $reset
292 293 294
 *   TRUE to reset the internal cache and load from the database; FALSE
 *   (default) to load from the internal cache, if set.
 *
295
 * @return object
296
 *   A fully-loaded user object upon successful user load, or FALSE if the user
297 298 299 300 301
 *   cannot be loaded.
 *
 * @see user_load_multiple()
 */
function user_load($uid, $reset = FALSE) {
302
  return entity_load('user', $uid, $reset);
303 304 305
}

/**
306
 * Fetches a user object by email address.
307
 *
308
 * @param string $mail
309
 *   String with the account's e-mail address.
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_mail($mail) {
317
  $users = entity_load_multiple_by_properties('user', array('mail' => $mail));
318 319 320 321
  return reset($users);
}

/**
322
 * Fetches a user object by account name.
323
 *
324
 * @param string $name
325
 *   String with the account's user name.
326
 * @return object|bool
327 328 329 330 331 332
 *   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) {
333
  $users = entity_load_multiple_by_properties('user', array('name' => $name));
334
  return reset($users);
Dries's avatar
Dries committed
335 336
}

337 338 339
/**
 * Verify the syntax of the given name.
 */
Dries's avatar
Dries committed
340
function user_validate_name($name) {
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
  if (!$name) {
    return t('You must enter a username.');
  }
  if (substr($name, 0, 1) == ' ') {
    return t('The username cannot begin with a space.');
  }
  if (substr($name, -1) == ' ') {
    return t('The username cannot end with a space.');
  }
  if (strpos($name, '  ') !== FALSE) {
    return t('The username cannot contain multiple spaces in a row.');
  }
  if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i', $name)) {
    return t('The username contains an illegal character.');
  }
356
  if (preg_match('/[\x{80}-\x{A0}' .         // Non-printable ISO-8859-1 + NBSP
357 358 359 360 361 362 363 364 365
                  '\x{AD}' .                // Soft-hyphen
                  '\x{2000}-\x{200F}' .     // Various space characters
                  '\x{2028}-\x{202F}' .     // Bidirectional text overrides
                  '\x{205F}-\x{206F}' .     // Various text hinting characters
                  '\x{FEFF}' .              // Byte order mark
                  '\x{FF01}-\x{FF60}' .     // Full-width latin
                  '\x{FFF9}-\x{FFFD}' .     // Replacement characters
                  '\x{0}-\x{1F}]/u',        // NULL byte and control characters
                  $name)) {
366 367
    return t('The username contains an illegal character.');
  }
368 369 370
  if (drupal_strlen($name) > USERNAME_MAX_LENGTH) {
    return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
  }
Dries's avatar
Dries committed
371 372
}

373 374 375
/**
 * Generate a random alphanumeric password.
 */
Dries's avatar
Dries committed
376 377
function user_password($length = 10) {
  // This variable contains the list of allowable characters for the
378 379
  // password. Note that the number 0 and the letter 'O' have been
  // removed to avoid confusion between the two. The same is true
380
  // of 'I', 1, and 'l'.
381
  $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
382

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

386 387
  // Declare the password as a blank string.
  $pass = '';
Dries's avatar
Dries committed
388

389
  // Loop the number of times specified by $length.
Dries's avatar
Dries committed
390 391 392 393
  for ($i = 0; $i < $length; $i++) {

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

  return $pass;
Dries's avatar
Dries committed
398 399
}

400 401 402 403 404 405 406 407 408 409
/**
 * Determine the permissions for one or more roles.
 *
 * @param $roles
 *   An array whose keys are the role IDs of interest, such as $user->roles.
 *
 * @return
 *   An array indexed by role ID. Each value is an array whose keys are the
 *   permission strings for the given role ID.
 */
410
function user_role_permissions($roles) {
411
  $cache = &drupal_static(__FUNCTION__, array());
412 413 414

  $role_permissions = $fetch = array();

415 416 417
  foreach ($roles as $rid => $name) {
    if (isset($cache[$rid])) {
      $role_permissions[$rid] = $cache[$rid];
418
    }
419 420 421 422 423 424 425
    else {
      // Add this rid to the list of those needing to be fetched.
      $fetch[] = $rid;
      // Prepare in case no permissions are returned.
      $cache[$rid] = array();
    }
  }
426

427 428 429 430 431 432 433 434 435 436 437
  if ($fetch) {
    // Get from the database permissions that were not in the static variable.
    // Only role IDs with at least one permission assigned will return rows.
    $result = db_query("SELECT rid, permission FROM {role_permission} WHERE rid IN (:fetch)", array(':fetch' => $fetch));

    foreach ($result as $row) {
      $cache[$row->rid][$row->permission] = TRUE;
    }
    foreach ($fetch as $rid) {
      // For every rid, we know we at least assigned an empty array.
      $role_permissions[$rid] = $cache[$rid];
438 439 440 441 442 443
    }
  }

  return $role_permissions;
}

444 445 446 447 448
/**
 * Determine whether the user has a given privilege.
 *
 * @param $string
 *   The permission, such as "administer nodes", being checked for.
Dries's avatar
Dries committed
449 450
 * @param $account
 *   (optional) The account to check, if not given use currently logged in user.
451 452
 *
 * @return
453
 *   Boolean TRUE if the current user has the requested permission.
454 455 456 457 458
 *
 * All permission checks in Drupal should go through this function. This
 * way, we guarantee consistent behavior, and ensure that the superuser
 * can perform all actions.
 */
459
function user_access($string, $account = NULL) {
Dries's avatar
Dries committed
460
  global $user;
461

462
  if (!isset($account)) {
463 464 465
    $account = $user;
  }

466
  // User #1 has all privileges:
467
  if ($account->uid == 1) {
468
    return TRUE;
Dries's avatar
Dries committed
469 470
  }

471 472
  // To reduce the number of SQL queries, we cache the user's permissions
  // in a static variable.
473
  // Use the advanced drupal_static() pattern, since this is called very often.
474 475 476 477 478
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
  }
  $perm = &$drupal_static_fast['perm'];
479
  if (!isset($perm[$account->uid])) {
480
    $role_permissions = user_role_permissions($account->roles);
Dries's avatar
Dries committed
481

482
    $perms = array();
483 484
    foreach ($role_permissions as $one_role) {
      $perms += $one_role;
Dries's avatar
Dries committed
485
    }
486
    $perm[$account->uid] = $perms;
Dries's avatar
Dries committed
487
  }
488

489
  return isset($perm[$account->uid][$string]);
Dries's avatar
Dries committed
490 491
}

492
/**
493
 * Checks for usernames blocked by user administration.
494
 *
495 496 497 498 499 500
 * @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.
501 502
 */
function user_is_blocked($name) {
503 504 505 506 507
  return db_select('users')
    ->fields('users', array('name'))
    ->condition('name', db_like($name), 'LIKE')
    ->condition('status', 0)
    ->execute()->fetchObject();
508 509
}

510
/**
511
 * Implements hook_permission().
512
 */
513
function user_permission() {
514 515 516
  return array(
    'administer permissions' =>  array(
      'title' => t('Administer permissions'),
517
      'restrict access' => TRUE,
518 519 520
    ),
    'administer users' => array(
      'title' => t('Administer users'),
521
      'restrict access' => TRUE,
522 523
    ),
    'access user profiles' => array(
524
      'title' => t('View user profiles'),
525 526 527 528 529
    ),
    'change own username' => array(
      'title' => t('Change own username'),
    ),
    'cancel account' => array(
530
      'title' => t('Cancel own user account'),
531
      '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' => config('user.settings')->get('anonymous'), '@user-settings-url' => url('admin/config/people/accounts'))),
532 533 534
    ),
    'select account cancellation method' => array(
      'title' => t('Select method for cancelling own account'),
535
      'restrict access' => TRUE,
536 537
    ),
  );
Dries's avatar
Dries committed
538 539
}

540
/**
541
 * Implements hook_search_info().
542
 */
543 544 545 546 547 548 549
function user_search_info() {
  return array(
    'title' => 'Users',
  );
}

/**
550
 * Implements hook_search_access().
551 552 553 554 555 556
 */
function user_search_access() {
  return user_access('access user profiles');
}

/**
557
 * Implements hook_search_execute().
558
 */
559
function user_search_execute($keys = NULL, $conditions = NULL) {
560 561 562
  $find = array();
  // Replace wildcards with MySQL/PostgreSQL wildcards.
  $keys = preg_replace('!\*+!', '%', $keys);
563 564
  $query = db_select('users')
    ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
565
  $query->fields('users', array('uid'));
566
  if (user_access('administer users')) {
567 568
    // Administrators can also search in the otherwise private email field, and
    // they don't need to be restricted to only active users.
569
    $query->fields('users', array('mail'));
570
    $query->condition(db_or()->
571 572
      condition('name', '%' . db_like($keys) . '%', 'LIKE')->
      condition('mail', '%' . db_like($keys) . '%', 'LIKE'));
573 574
  }
  else {
575 576 577 578
    // 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);
579
  }
580
  $uids = $query
581
    ->limit(15)
582 583 584 585 586 587 588
    ->execute()
    ->fetchCol();
  $accounts = user_load_multiple($uids);

  $results = array();
  foreach ($accounts as $account) {
    $result = array(
589
      'title' => user_format_name($account),
590 591 592 593
      'link' => url('user/' . $account->uid, array('absolute' => TRUE)),
    );
    if (user_access('administer users')) {
      $result['title'] .= ' (' . $account->mail . ')';
594
    }
595
    $results[] = $result;
Dries's avatar
Dries committed
596
  }
597 598

  return $results;
Dries's avatar
Dries committed
599 600
}

601
/**
602
 * Implements hook_user_view().
603
 */
604 605 606 607 608 609 610 611
function user_user_view(User $account, EntityDisplay $display) {
  if ($display->getComponent('member_for')) {
    $account->content['member_for'] = array(
      '#type' => 'item',
      '#title' => t('Member for'),
      '#markup' => format_interval(REQUEST_TIME - $account->created),
    );
  }
612 613
}

614 615 616 617 618 619 620 621 622
/**
 * 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'];
623 624
}

625
/**
626
 * Form validation handler for the current password on the user account form.
627
 *
628
 * @see AccountFormController::form()
629 630
 */
function user_validate_current_pass(&$form, &$form_state) {
631
  $account = $form_state['user'];
632 633 634 635 636
  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.
    if ((strlen(trim($form_state['values'][$key])) > 0) && ($form_state['values'][$key] != $account->$key)) {
637
      $current_pass_failed = empty($form_state['values']['current_pass']) || !drupal_container()->get('password')->check($form_state['values']['current_pass'], $account);
638 639 640 641 642 643 644 645 646 647
      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;
    }
  }
}

648
/**
649
 * Implements hook_preprocess_HOOK() for block.tpl.php.
650 651
 */
function user_preprocess_block(&$variables) {
652 653
  if ($variables['configuration']['module'] == 'user') {
    switch ($variables['elements']['#plugin_id']) {
654
      case 'user_login_block':
655
        $variables['attributes']['role'] = 'form';
656
        break;
657
      case 'user_new_block':
658
        $variables['attributes']['role'] = 'complementary';
659
        break;
660
      case 'user_online_block':
661
        $variables['attributes']['role'] = 'complementary';
662 663 664 665 666
        break;
    }
  }
}

667 668 669 670 671
/**
 * Format a username.
 *
 * By default, the passed-in object's 'name' property is used if it exists, or
 * else, the site-defined value for the 'anonymous' variable. However, a module
672 673
 * may override this by implementing
 * hook_user_format_name_alter(&$name, $account).
674
 *
675
 * @see hook_user_format_name_alter()
676 677 678 679 680 681 682 683 684
 *
 * @param $account
 *   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.
 */
685
function user_format_name($account) {
686
  $name = !empty($account->name) ? $account->name : config('user.settings')->get('anonymous');
687
  drupal_alter('user_format_name', $name, $account);
688 689 690
  return $name;
}

691 692 693 694 695 696 697 698 699
/**
 * 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;

700 701 702 703 704 705
  // If this function is called from the installer after Drupal has been
  // installed then $user will not be set.
  if (!is_object($user)) {
    return;
  }

706 707 708 709 710 711 712 713
  $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');
  $variables['logged_in'] = ($user->uid > 0);
}

714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
/**
 * Preprocesses variables for theme_username().
 *
 * Modules that make any changes to variables like 'name' or 'extra' must insure
 * that the final string is safe to include directly in the output by using
 * check_plain() or filter_xss().
 *
 * @see template_process_username()
 */
function template_preprocess_username(&$variables) {
  $account = $variables['account'];

  $variables['extra'] = '';
  if (empty($account->uid)) {
   $variables['uid'] = 0;
729
   if (theme_get_setting('features.comment_user_verification')) {
730 731 732 733 734 735 736 737 738 739 740 741
     $variables['extra'] = ' (' . t('not verified') . ')';
   }
  }
  else {
    $variables['uid'] = (int) $account->uid;
  }

  // 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.
742
  $name = $variables['name_raw'] = user_format_name($account);
743 744 745 746 747
  if (drupal_strlen($name) > 20) {
    $name = drupal_substr($name, 0, 15) . '...';
  }
  $variables['name'] = check_plain($name);
  $variables['profile_access'] = user_access('access user profiles');
748

749 750 751
  // Populate link path and attributes if appropriate.
  if ($variables['uid'] && $variables['profile_access']) {
    // We are linking to a local user.
752
    $variables['link_attributes']['title'] = t('View user profile.');
753 754 755 756 757 758
    $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.
759
    $variables['link_attributes']['rel'] = 'nofollow';
760 761 762 763 764 765
    $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.
766
  $variables['attributes'] = array('class' => array('username'));
767 768 769 770 771 772 773 774 775 776 777 778
}

/**
 * Processes variables for theme_username().
 *
 * @see template_preprocess_username()
 */
function template_process_username(&$variables) {
  // Finalize the link_options array for passing to the l() function.
  // This is done in the process phase so that attributes may be added by
  // modules or the theme during the preprocess phase.
  if (isset($variables['link_path'])) {
779
    // $variables['attributes'] contains attributes that should be applied
780 781 782 783 784 785
    // regardless of whether a link is being rendered or not.
    // $variables['link_attributes'] contains attributes that should only be
    // applied if a link is being rendered. Preprocess functions are encouraged
    // to use the former unless they want to add attributes on the link only.
    // If a link is being rendered, these need to be merged. Some attributes are
    // themselves arrays, so the merging needs to be recursive.
786 787 788
    // This purposefully does not use
    // \Drupal\Component\Utility\NestedArray::mergeDeep() for performance
    // reasons, since it is potentially called very often.
789
    $variables['link_options']['attributes'] = array_merge_recursive($variables['link_attributes'], $variables['attributes']);
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
  }
}

/**
 * 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.
805 806
 *   - attributes: An array of attributes to instantiate the
 *     Drupal\Core\Template\Attribute class if not linking to the user's page.
807 808 809 810 811 812 813 814 815 816 817 818 819 820
 *
 * @see template_preprocess_username()
 * @see template_process_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
821
    // $variables['attributes']['class'][] = 'myclass';
822
    $output = '<span' . new Attribute($variables['attributes']) . '>' . $variables['name'] . $variables['extra'] . '</span>';
823 824 825 826
  }
  return $output;
}

827 828 829 830 831 832
/**
 * Determines if the current user is anonymous.
 *
 * @return bool
 *   TRUE if the user is anonymous, FALSE if the user is authenticated.
 */
833
function user_is_anonymous() {
834 835
  // Menu administrators can see items for anonymous when administering.
  return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
836 837
}

838 839 840 841 842 843
/**
 * Determines if the current user is logged in.
 *
 * @return bool
 *   TRUE if the user is logged in, FALSE if the user is anonymous.
 */
844
function user_is_logged_in() {
845
  return (bool) $GLOBALS['user']->uid;
846 847
}

848 849 850 851 852 853
/**
 * 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.
 */
854
function user_register_access() {
855
  return user_is_anonymous() && (config('user.settings')->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY);
856 857
}

Dries's avatar
Dries committed
858
/**
859
 * Implements hook_menu().
Dries's avatar
Dries committed
860
 */
861 862
function user_menu() {
  // Registration and login pages.
863
  $items['user'] = array(
864
    'title' => 'User account',
865
    'title callback' => 'user_menu_title',
866 867
    'page callback' => 'user_page',
    'access callback' => TRUE,
868
    'file' => 'user.pages.inc',
869
    'weight' => -10,
870
    'menu_name' => 'account',
871 872 873
  );

  $items['user/login'] = array(
874
    'title' => 'Log in',
875
    'access callback' => 'user_is_anonymous',
876 877
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
878 879 880 881 882
  // Other authentication methods may add pages below user/login/.
  $items['user/login/default'] = array(
    'title' => 'Username and password',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
Dries's avatar
Dries committed
883

884
  $items['user/register'] = array(
885
    'title' => 'Create new account',
886
    'type' => MENU_LOCAL_TASK,
887
    'route_name' => 'user_register',
888 889 890
  );

  $items['user/password'] = array(
891
    'title' => 'Request new password',
892 893
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_pass'),
894
    'access callback' => TRUE,
895
    'type' => MENU_LOCAL_TASK,
896
    'file' => 'user.pages.inc',
897 898
  );
  $items['user/reset/%/%/%'] = array(
899
    'title' => 'Reset password',
900 901 902 903
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_pass_reset', 2, 3, 4),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
904
    'file' => 'user.pages.inc',
905 906
  );

907 908 909 910 911
  $items['user/logout'] = array(
    'title' => 'Log out',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'user_logout',
    'weight' => 10,
912
    'menu_name' => 'account',
913
    'file' => 'user.pages.inc',
914 915
  );

916
  // User listing pages.
917 918
  $items['admin/people'] = array(
    'title' => 'People',
919
    'description' => 'Manage user accounts, roles, and permissions.',
920 921
    'page callback' => 'user_admin',
    'page arguments' => array('list'),
922
    'access arguments' => array('administer users'),
923
    'position' => 'left',
924
    'weight' => -4,
925
    'file' => 'user.admin.inc',
926
  );
927 928 929 930 931 932 933
  $items['admin/people/people'] = array(
    'title' => 'List',
    'description' => 'Find and manage people interacting with your site.',
    'access arguments' => array('administer users'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'file' => 'user.admin.inc',
  );
934 935

  // Permissions and role forms.
936 937 938 939 940 941 942 943 944
  $items['admin/people/permissions'] = array(
    'title' => 'Permissions',
    'description' => 'Determine access to features by selecting permissions for roles.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_admin_permissions'),
    'access arguments' => array('administer permissions'),
    'file' => 'user.admin.inc',
    'type' => MENU_LOCAL_TASK,
  );
945
  $items['admin/people/roles'] = array(
946 947
    'title' => 'Roles',
    'description' => 'List, edit, or add user roles.',
948
    'route_name' => 'user_role_list',
949 950
    'type' => MENU_LOCAL_TASK,
  );
951 952
  $items['admin/people/roles/add'] = array(
    'title' => 'Add role',
953
    'route_name' => 'user_role_add',
954 955 956 957
    'type' => MENU_LOCAL_ACTION,
  );

  $items['admin/people/roles/manage/%user_role'] = array(
958
    'title' => 'Edit role',
959
    'route_name' => 'user_role_edit',
960
  );
961 962 963 964 965
  $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(
966
    'title' => 'Delete role',
967
    'route_name' => 'user_role_delete',
968 969
    'weight' => 10,
    'context' => MENU_CONTEXT_INLINE,
970
  );
971

972
  $items['admin/people/create'] = array(
973
    'title' => 'Add user',
974
    'page arguments' => array('create'),
975
    'access arguments' => array('administer users'),
976
    'type' => MENU_LOCAL_ACTION,
977
  );
978 979 980

  // Administration pages.
  $items['admin/config/people'] = array(
981
   'title' => 'People',
982
   'description' => 'Configure user accounts.',
983 984
   'position' => 'left',
   'weight' => -20,
985
   'page callback' => 'system_admin_menu_block_page',
986
   'access arguments' => array('access administration pages'),
987 988
   'file' => 'system.admin.inc',
   'file path' => drupal_get_path('module', 'system'),
989 990 991
  );
  $items['admin/config/people/accounts'] = array(
    'title' => 'Account settings',
992
    'description' => 'Configure default behavior of users, including registration requirements, e-mails, and fields.',
993
    'weight' => -10,
994
    'route_name' => 'user_account_settings',
995
  );
996
  $items['admin/config/people/accounts/settings'] = array(
997 998 999
    'title' => 'Settings',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
1000

1001
  $items['user/%user'] = array(
1002
    'title' => 'My account',
1003 1004
    'title callback' => 'user_page_title',
    'title arguments' => array(1),
1005
    'page callback' => 'user_view_page',
1006
    'page arguments' => array(1),
1007
    'access callback' => 'entity_page_access',
1008 1009
    'access arguments' => array(1),
  );
1010
  $items['user/%user/view'] = array(
1011
    'title' => 'View',
1012 1013
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
1014 1015
  $items['user/%user/cancel'] = array(
    'title' => 'Cancel account',
1016
    'page callback' => 'drupal_get_form',
1017
    'page arguments' => array('user_cancel_confirm_form', 1),
1018 1019
    'access callback' => 'entity_page_access',
    'access arguments' => array(1, 'delete'),
1020
    'file' => 'user.pages.inc',
1021 1022 1023 1024 1025
  );
  $items['user/%user/cancel/confirm/%/%'] = array(
    'title' => 'Confirm account cancellation',
    'page callback' => 'user_cancel_confirm',
    'page arguments' => array(1, 4, 5),
1026 1027
    'access callback' => 'entity_page_access',
    'access arguments' => array(1, 'delete'),
1028
    'file' => 'user.pages.inc',
1029
  );
1030
  $items['user/%user/edit'] = array(
1031
    'title' => 'Edit',
1032 1033
    'page callback' => 'entity_get_form',
    'page arguments' => array(1, 'profile'),
1034 1035
    'access callback' => 'entity_page_access',
    'access arguments' => array(1, 'update'),
1036
    'type' => MENU_LOCAL_TASK,
1037
    'file' => 'user.pages.inc',
1038
  );
Dries's avatar
Dries committed
1039
  return $items;
Dries's avatar
Dries committed
1040 1041
}

1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
/**
 * Implements hook_menu_site_status_alter().
 */
function user_menu_site_status_alter(&$menu_site_status, $path) {
  if ($menu_site_status == MENU_SITE_OFFLINE) {
    // If the site is offline, log out unprivileged users.
    if (user_is_logged_in() && !user_access('access site in maintenance mode')) {
      module_load_include('pages.inc', 'user', 'user');
      user_logout();
    }

    if (user_is_anonymous()) {
      switch ($path) {
        case 'user':
          // Forward anonymous user to login page.
          drupal_goto('user/login');
        case 'user/login':
        case 'user/password':
          // Disable offline mode.
          $menu_site_status = MENU_SITE_ONLINE;
          break;
        default:
          if (strpos($path, 'user/reset/') === 0) {
            // Disable offline mode.
            $menu_site_status = MENU_SITE_ONLINE;
          }
          break;
      }
    }
  }
  if (user_is_logged_in()) {
    if ($path == 'user/login') {
      // If user is logged in, redirect to 'user' instead of giving 403.
      drupal_goto('user');
    }
    if ($path == 'user/register') {
      // Authenticated user should be redirected to user edit page.
      drupal_goto('user/' . $GLOBALS['user']->uid . '/edit');
    }
  }
}

1084
/**
1085
 * Implements hook_menu_link_presave().
1086
 */
1087
function user_menu_link_presave(MenuLink $menu_link) {
1088 1089 1090
  // 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
1091
  // user_menu_link_load() to conditionally hide the link.