user.module 88.7 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
use Drupal\Core\Session\AccountInterface;
7 8
use Drupal\comment\Plugin\Core\Entity\Comment;
use Drupal\entity\Plugin\Core\Entity\EntityDisplay;
9
use Drupal\file\Plugin\Core\Entity\File;
10
use Drupal\user\Plugin\Core\Entity\User;
11
use Drupal\user\UserInterface;
12
use Drupal\user\UserRole;
13
use Drupal\user\RoleInterface;
14
use Drupal\Core\Template\Attribute;
15
use Symfony\Component\HttpFoundation\RedirectResponse;
16
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
17
use Drupal\menu_link\Plugin\Core\Entity\MenuLink;
Crell's avatar
Crell committed
18

Dries's avatar
 
Dries committed
19 20 21 22 23
/**
 * @file
 * Enables the user registration and login system.
 */

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

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

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

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

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

50 51 52 53 54 55 56 57 58 59
/**
 * Implement hook_help().
 */
function user_help($path, $arg) {
  global $user;

  switch ($path) {
    case 'admin/help#user':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
60
      $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>';
61 62 63
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Creating and managing users') . '</dt>';
64
      $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>';
65
      $output .= '<dt>' . t('User roles and permissions') . '</dt>';
66
      $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>';
67
      $output .= '<dt>' . t('Account settings') . '</dt>';
68
      $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>';
69 70 71 72
      $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>';
73
    case 'admin/people/permissions':
74 75
      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':
76
      $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>';
77
      $output .= '<p>' . t('Drupal has three special user roles:') . '</p>';
78 79 80
      $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>';
81
      $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>';
82 83 84 85 86 87 88 89 90 91
      $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>';
  }
}
92

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

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

128 129 130 131
/**
 * Implements hook_entity_bundle_info().
 */
function user_entity_bundle_info() {
132
  $bundles['user']['user']['label'] = t('User');
133 134 135
  return $bundles;
}

136
/**
137
 * Entity URI callback.
138
 */
139 140
function user_uri($user) {
  return array(
141
    'path' => 'user/' . $user->id(),
142
  );
143 144
}

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

165 166 167
/**
 * Populates $entity->account for each prepared entity.
 *
168 169
 * Called by Drupal\Core\Entity\EntityRenderControllerInterface::buildContent()
 * implementations.
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 200 201 202 203
 *
 * @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');
}

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

217
/**
218
 * Implements hook_field_extra_fields().
219
 */
220
function user_field_extra_fields() {
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 246 247 248 249
  $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,
250
  );
251

252
  return $fields;
253 254
}

Dries's avatar
Dries committed
255
/**
256
 * Loads multiple users based on certain conditions.
Dries's avatar
Dries committed
257
 *
258 259 260
 * 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
261
 *
262 263
 * @param array $uids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
264
 * @param bool $reset
265 266
 *   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.
267
 *
268
 * @return array
269 270
 *   An array of user objects, indexed by uid.
 *
271
 * @see entity_load_multiple()
272 273 274
 * @see user_load()
 * @see user_load_by_mail()
 * @see user_load_by_name()
275
 * @see \Drupal\Core\Entity\Query\QueryInterface
Dries's avatar
Dries committed
276
 */
277
function user_load_multiple(array $uids = NULL, $reset = FALSE) {
278 279 280 281 282 283
  $entities = entity_load_multiple('user', $uids, $reset);
  // Return BC-entities.
  foreach ($entities as $id => $entity) {
    $entities[$id] = $entity->getBCEntity();
  }
  return $entities;
284
}
285 286

/**
287 288 289 290 291 292
 * 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
293 294 295 296
 * 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.
297
 *
298
 * @param int $uid
299
 *   Integer specifying the user ID to load.
300
 * @param bool $reset
301 302 303
 *   TRUE to reset the internal cache and load from the database; FALSE
 *   (default) to load from the internal cache, if set.
 *
304
 * @return object
305
 *   A fully-loaded user object upon successful user load, or FALSE if the user
306 307 308 309 310
 *   cannot be loaded.
 *
 * @see user_load_multiple()
 */
function user_load($uid, $reset = FALSE) {
311 312
  $user = entity_load('user', $uid, $reset);
  return $user ? $user->getBCEntity() : FALSE;
313 314 315
}

/**
316
 * Fetches a user object by email address.
317
 *
318
 * @param string $mail
319
 *   String with the account's e-mail address.
320
 * @return object|bool
321 322 323 324 325 326
 *   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) {
327
  $users = entity_load_multiple_by_properties('user', array('mail' => $mail));
328
  return $users ? reset($users)->getBCEntity() : FALSE;
329 330 331
}

/**
332
 * Fetches a user object by account name.
333
 *
334
 * @param string $name
335
 *   String with the account's user name.
336
 * @return object|bool
337 338 339 340 341 342
 *   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) {
343
  $users = entity_load_multiple_by_properties('user', array('name' => $name));
344
  return $users ? reset($users)->getBCEntity() : FALSE;
Dries's avatar
 
Dries committed
345 346
}

Dries's avatar
Dries committed
347 348 349
/**
 * Verify the syntax of the given name.
 */
Dries's avatar
 
Dries committed
350
function user_validate_name($name) {
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
  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.');
  }
366
  if (preg_match('/[\x{80}-\x{A0}' .         // Non-printable ISO-8859-1 + NBSP
367 368 369 370 371 372 373 374 375
                  '\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)) {
376 377
    return t('The username contains an illegal character.');
  }
378 379 380
  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
381 382
}

Dries's avatar
Dries committed
383 384 385
/**
 * Generate a random alphanumeric password.
 */
Dries's avatar
 
Dries committed
386 387
function user_password($length = 10) {
  // This variable contains the list of allowable characters for the
388 389
  // password. Note that the number 0 and the letter 'O' have been
  // removed to avoid confusion between the two. The same is true
390
  // of 'I', 1, and 'l'.
391
  $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
Dries's avatar
Dries committed
392

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

Dries's avatar
Dries committed
396 397
  // Declare the password as a blank string.
  $pass = '';
Dries's avatar
 
Dries committed
398

Dries's avatar
Dries committed
399
  // Loop the number of times specified by $length.
Dries's avatar
 
Dries committed
400 401 402 403
  for ($i = 0; $i < $length; $i++) {

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

  return $pass;
Dries's avatar
 
Dries committed
408 409
}

410 411 412 413
/**
 * Determine the permissions for one or more roles.
 *
 * @param $roles
414
 *   An array whose values are the role IDs of interest, such as $user->roles.
415 416 417 418 419
 *
 * @return
 *   An array indexed by role ID. Each value is an array whose keys are the
 *   permission strings for the given role ID.
 */
420
function user_role_permissions($roles) {
421
  $cache = &drupal_static(__FUNCTION__, array());
422 423 424

  $role_permissions = $fetch = array();

425
  foreach ($roles as $rid) {
426 427
    if (isset($cache[$rid])) {
      $role_permissions[$rid] = $cache[$rid];
428
    }
429 430 431 432 433 434 435
    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();
    }
  }
436

437 438 439 440 441 442 443 444 445 446 447
  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];
448 449 450 451 452 453
    }
  }

  return $role_permissions;
}

Dries's avatar
Dries committed
454 455 456 457 458
/**
 * Determine whether the user has a given privilege.
 *
 * @param $string
 *   The permission, such as "administer nodes", being checked for.
459
 * @param \Drupal\Core\Session\AccountInterface $account
Dries's avatar
 
Dries committed
460
 *   (optional) The account to check, if not given use currently logged in user.
Dries's avatar
Dries committed
461 462
 *
 * @return
463
 *   Boolean TRUE if the current user has the requested permission.
Dries's avatar
Dries committed
464 465 466 467 468
 *
 * 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.
 */
469
function user_access($string, AccountInterface $account = NULL) {
Dries's avatar
 
Dries committed
470
  global $user;
471

472
  if (!isset($account)) {
473 474 475
    $account = $user;
  }

476 477 478
  // Make sure we are working with the BC decorator.
  $account = $account instanceof User ? $account->getBCEntity() : $account;

479
  // User #1 has all privileges:
480
  if ($account->uid == 1) {
481
    return TRUE;
Dries's avatar
 
Dries committed
482 483
  }

Dries's avatar
Dries committed
484 485
  // To reduce the number of SQL queries, we cache the user's permissions
  // in a static variable.
486
  // Use the advanced drupal_static() pattern, since this is called very often.
487 488 489 490 491
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
  }
  $perm = &$drupal_static_fast['perm'];
492
  if (!isset($perm[$account->uid])) {
493
    $role_permissions = user_role_permissions($account->getRoles());
Dries's avatar
 
Dries committed
494

495
    $perms = array();
496 497
    foreach ($role_permissions as $one_role) {
      $perms += $one_role;
Dries's avatar
 
Dries committed
498
    }
499
    $perm[$account->uid] = $perms;
Dries's avatar
 
Dries committed
500
  }
501

502
  return isset($perm[$account->uid][$string]);
Dries's avatar
 
Dries committed
503 504
}

505
/**
506
 * Checks for usernames blocked by user administration.
507
 *
508 509 510 511 512 513
 * @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.
514 515
 */
function user_is_blocked($name) {
516 517 518 519 520
  return db_select('users')
    ->fields('users', array('name'))
    ->condition('name', db_like($name), 'LIKE')
    ->condition('status', 0)
    ->execute()->fetchObject();
521 522
}

Dries's avatar
Dries committed
523
/**
524
 * Implements hook_permission().
Dries's avatar
Dries committed
525
 */
526
function user_permission() {
527 528 529
  return array(
    'administer permissions' =>  array(
      'title' => t('Administer permissions'),
530
      'restrict access' => TRUE,
531 532 533
    ),
    'administer users' => array(
      'title' => t('Administer users'),
534
      'restrict access' => TRUE,
535 536
    ),
    'access user profiles' => array(
537
      'title' => t('View user profiles'),
538 539 540 541 542
    ),
    'change own username' => array(
      'title' => t('Change own username'),
    ),
    'cancel account' => array(
543
      'title' => t('Cancel own user account'),
544
      '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'))),
545 546 547
    ),
    'select account cancellation method' => array(
      'title' => t('Select method for cancelling own account'),
548
      'restrict access' => TRUE,
549 550
    ),
  );
Dries's avatar
 
Dries committed
551 552
}

Dries's avatar
Dries committed
553
/**
554
 * Implements hook_search_info().
Dries's avatar
Dries committed
555
 */
556 557 558 559 560 561 562
function user_search_info() {
  return array(
    'title' => 'Users',
  );
}

/**
563
 * Implements hook_search_access().
564 565 566 567 568 569
 */
function user_search_access() {
  return user_access('access user profiles');
}

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

  $results = array();
  foreach ($accounts as $account) {
    $result = array(
602
      'title' => user_format_name($account),
603 604 605 606
      'link' => url('user/' . $account->uid, array('absolute' => TRUE)),
    );
    if (user_access('administer users')) {
      $result['title'] .= ' (' . $account->mail . ')';
607
    }
608
    $results[] = $result;
Dries's avatar
 
Dries committed
609
  }
610 611

  return $results;
Dries's avatar
 
Dries committed
612 613
}

Dries's avatar
Dries committed
614
/**
615
 * Implements hook_user_view().
Dries's avatar
Dries committed
616
 */
617
function user_user_view(UserInterface $account, EntityDisplay $display) {
618 619 620 621 622 623 624
  if ($display->getComponent('member_for')) {
    $account->content['member_for'] = array(
      '#type' => 'item',
      '#title' => t('Member for'),
      '#markup' => format_interval(REQUEST_TIME - $account->created),
    );
  }
625 626
}

627 628 629 630 631 632 633 634 635
/**
 * 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'];
636 637
}

638
/**
639
 * Form validation handler for the current password on the user account form.
640
 *
641
 * @see AccountFormController::form()
642 643
 */
function user_validate_current_pass(&$form, &$form_state) {
644
  $account = $form_state['user'];
645 646 647 648 649
  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)) {
650
      $current_pass_failed = empty($form_state['values']['current_pass']) || !drupal_container()->get('password')->check($form_state['values']['current_pass'], $account);
651 652 653 654 655 656 657 658 659 660
      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;
    }
  }
}

661
/**
662
 * Implements hook_preprocess_HOOK() for block.html.twig.
663 664
 */
function user_preprocess_block(&$variables) {
665 666
  if ($variables['configuration']['module'] == 'user') {
    switch ($variables['elements']['#plugin_id']) {
667
      case 'user_login_block':
668
        $variables['attributes']['role'] = 'form';
669
        break;
670
      case 'user_new_block':
671
        $variables['attributes']['role'] = 'complementary';
672
        break;
673
      case 'user_online_block':
674
        $variables['attributes']['role'] = 'complementary';
675 676 677 678 679
        break;
    }
  }
}

680 681 682 683 684
/**
 * 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
685 686
 * may override this by implementing
 * hook_user_format_name_alter(&$name, $account).
687
 *
688
 * @see hook_user_format_name_alter()
689 690 691 692 693 694 695 696 697
 *
 * @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.
 */
698
function user_format_name($account) {
699
  $name = !empty($account->name) ? $account->name : config('user.settings')->get('anonymous');
700
  drupal_alter('user_format_name', $name, $account);
701 702 703
  return $name;
}

704 705 706 707 708 709 710 711 712
/**
 * 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;

713 714 715 716 717 718
  // If this function is called from the installer after Drupal has been
  // installed then $user will not be set.
  if (!is_object($user)) {
    return;
  }

719 720 721 722 723 724 725 726
  $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);
}

727 728 729
/**
 * Preprocesses variables for theme_username().
 *
730
 * Modules that make any changes to variables like 'name' or 'extra' must ensure
731 732 733 734 735 736 737
 * 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'];
738 739 740
  if ($account instanceof User) {
    $account = $account->getBCEntity();
  }
741 742 743 744

  $variables['extra'] = '';
  if (empty($account->uid)) {
   $variables['uid'] = 0;
745
   if (theme_get_setting('features.comment_user_verification')) {
746 747 748 749 750 751 752 753 754 755 756 757
     $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.
758
  $name = $variables['name_raw'] = user_format_name($account);
759 760 761 762 763
  if (drupal_strlen($name) > 20) {
    $name = drupal_substr($name, 0, 15) . '...';
  }
  $variables['name'] = check_plain($name);
  $variables['profile_access'] = user_access('access user profiles');
764

765 766 767
  // Populate link path and attributes if appropriate.
  if ($variables['uid'] && $variables['profile_access']) {
    // We are linking to a local user.
768
    $variables['link_options']['attributes']['title'] = t('View user profile.');
769 770 771 772 773 774
    $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.
775
    $variables['link_options']['attributes']['rel'] = 'nofollow';
776 777 778 779 780 781
    $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.
782
  $variables['link_options']['attributes']['class'] = array('username');
783 784 785 786 787 788 789 790 791 792 793 794 795 796
}

/**
 * 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.
797 798
 *   - attributes: An array of attributes to instantiate the
 *     Drupal\Core\Template\Attribute class if not linking to the user's page.
799 800 801 802 803 804 805 806 807 808 809 810 811 812
 *
 * @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
813
    // $variables['attributes']['class'][] = 'myclass';
814
    $output = '<span' . new Attribute($variables['attributes']) . '>' . $variables['name'] . $variables['extra'] . '</span>';
815 816 817 818
  }
  return $output;
}

819 820 821 822 823 824
/**
 * Determines if the current user is anonymous.
 *
 * @return bool
 *   TRUE if the user is anonymous, FALSE if the user is authenticated.
 */
825
function user_is_anonymous() {
826 827
  // Menu administrators can see items for anonymous when administering.
  return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
828 829
}

830 831 832 833 834 835
/**
 * Determines if the current user is logged in.
 *
 * @return bool
 *   TRUE if the user is logged in, FALSE if the user is anonymous.
 */
836
function user_is_logged_in() {
837
  return (bool) $GLOBALS['user']->uid;
838 839
}

840 841 842 843 844 845
/**
 * 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.
 */
846
function user_register_access() {
847
  return user_is_anonymous() && (config('user.settings')->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY);
848 849
}

Dries's avatar
 
Dries committed
850
/**
851
 * Implements hook_menu().
Dries's avatar
 
Dries committed
852
 */
853 854
function user_menu() {
  // Registration and login pages.
855
  $items['user'] = array(
856
    'title' => 'User account',
857
    'title callback' => 'user_menu_title',
858 859
    'page callback' => 'user_page',
    'access callback' => TRUE,
860
    'file' => 'user.pages.inc',
861
    'weight' => -10,
862
    'menu_name' => 'account',
863 864 865
  );

  $items['user/login'] = array(
866
    'title' => 'Log in',
867
    'access callback' => 'user_is_anonymous',
868 869
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
870 871 872 873 874
  // 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
875

876
  $items['user/register'] = array(
877
    'title' => 'Create new account',
878
    'type' => MENU_LOCAL_TASK,
879
    'route_name' => 'user_register',
880 881 882
  );

  $items['user/password'] = array(
883
    'title' => 'Request new password',
884 885
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_pass'),
886
    'access callback' => TRUE,
887
    'type' => MENU_LOCAL_TASK,
888
    'file' => 'user.pages.inc',
889 890
  );
  $items['user/reset/%/%/%'] = array(
891
    'title' => 'Reset password',
892 893 894 895
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_pass_reset', 2, 3, 4),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
896
    'file' => 'user.pages.inc',
897 898
  );

899 900
  $items['user/logout'] = array(
    'title' => 'Log out',
901
    'route_name' => 'user_logout',
902
    'weight' => 10,
903
    'menu_name' => 'account',
904 905
  );

906
  // User listing pages.
907 908
  $items['admin/people'] = array(
    'title' => 'People',
909
    'description' => 'Manage user accounts, roles, and permissions.',
910
    'page callback' => 'user_admin_account',
911
    'access arguments' => array('administer users'),
912
    'position' => 'left',
913
    'weight' => -4,
914
    'file' => 'user.admin.inc',
915
  );
916
  // Permissions and role forms.
917 918 919 920 921 922 923 924 925
  $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,
  );
926
  $items['admin/people/roles'] = array(
927 928
    'title' => 'Roles',
    'description' => 'List, edit, or add user roles.',
929
    'route_name' => 'user_role_list',
930 931
    'type' => MENU_LOCAL_TASK,
  );
932 933
  $items['admin/people/roles/add'] = array(
    'title' => 'Add role',
934
    'route_name' => 'user_role_add',
935 936 937 938
    'type' => MENU_LOCAL_ACTION,
  );

  $items['admin/people/roles/manage/%user_role'] = array(
939
    'title' => 'Edit role',
940
    'route_name' => 'user_role_edit',
941
  );
942 943 944 945 946
  $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(
947
    'title' => 'Delete role',
948
    'route_name' => 'user_role_delete',
949 950
    'weight' => 10,
    'context' => MENU_CONTEXT_INLINE,
951
  );
952

953
  $items['admin/people/create'] = array(
954
    'title' => 'Add user',
955
    'route_name' => 'user_admin_create',
956
    'type' => MENU_LOCAL_ACTION,
957
  );
958 959 960 961 962 963
  $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',
964
    'type' => MENU_CALLBACK,
965
  );
966 967 968

  // Administration pages.
  $items['admin/config/people'] = array(
969
   'title' => 'People',
970
   'description' => 'Configure user accounts.',
971 972
   'position' => 'left',
   'weight' => -20,
973
   'page callback' => 'system_admin_menu_block_page',
974
   'access arguments' => array('access administration pages'),
975 976
   'file' => 'system.admin.inc',
   'file path' => drupal_get_path('module', 'system'),
977 978 979
  );
  $items['admin/config/people/accounts'] = array(
    'title' => 'Account settings',
980
    'description' => 'Configure default behavior of users, including registration requirements, e-mails, and fields.',
981
    'weight' => -10,
982
    'route_name' => 'user_account_settings',
983
  );
984
  $items['admin/config/people/accounts/settings'] = array(
985 986 987
    'title' => 'Settings',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
988

989
  $items['user/%user'] = array(
990
    'title' => 'My account',
991 992
    'title callback' => 'user_page_title',
    'title arguments' => array(1),
993
    'page callback' => 'user_view_page',
994
    'page arguments' => array(1),
995
    'access callback' => 'entity_page_access',
996 997
    'access arguments' => array(1),
  );
998
  $items['user/%user/view'] = array(
999
    'title' => 'View',
1000 1001
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
1002 1003
  $items['user/%user/cancel'] = array(
    'title' => 'Cancel account',
1004
    'page callback' => 'drupal_get_form',
1005
    'page arguments' => array('user_cancel_confirm_form', 1),
1006 1007
    'access callback' => 'entity_page_access',
    'access arguments' => array(1, 'delete'),
1008
    'file' => 'user.pages.inc',
1009 1010 1011 1012 1013
  );
  $items['user/%user/cancel/confirm/%/%'] = array(
    'title' => 'Confirm account cancellation',
    'page callback' => 'user_cancel_confirm',
    'page arguments' => array(1, 4, 5),
1014 1015
    'access callback' => 'entity_page_access',
    'access arguments' => array(1, 'delete'),
1016
    'file' => 'user.pages.inc',
1017
  );
1018
  $items['user/%user/edit'] = array(
1019
    'title' => 'Edit',
1020 1021
    'page callback' => 'entity_get_form',
    'page arguments' => array(1, 'profile'),
1022 1023
    'access callback' => 'entity_page_access',
    'access arguments' => array(1, 'update'),
1024
    'type' => MENU_LOCAL_TASK,
1025
    'file' => 'user.pages.inc',
1026
  );
Dries's avatar
 
Dries committed
1027
  return $items;
Dries's avatar
 
Dries committed
1028 1029
}

1030
/**
1031
 * Implements hook_menu_link_presave().
1032
 */
1033
function user_menu_link_presave(MenuLink $menu_link) {
webchick's avatar