summaryrefslogtreecommitdiffstats
path: root/core/modules/user/user.module
blob: 3fe1f1c6759c02694c39eb4185d95571e82497f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
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
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
<?php

use Drupal\Component\Utility\Crypt;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\AnonymousUserSession;
use \Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\user\Entity\User;
use Drupal\user\UserInterface;
use Drupal\user\RoleInterface;
use Drupal\Core\Template\Attribute;
use Drupal\Core\TypedData\DataDefinition;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\menu_link\Entity\MenuLink;

/**
 * @file
 * Enables the user registration and login system.
 */

/**
 * Maximum length of username text field.
 */
const USERNAME_MAX_LENGTH = 60;

/**
 * Only administrators can create user accounts.
 */
const USER_REGISTER_ADMINISTRATORS_ONLY = 'admin_only';

/**
 * Visitors can create their own accounts.
 */
const USER_REGISTER_VISITORS = 'visitors';

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

/**
 * Implement hook_help().
 */
function user_help($route_name, Request $request) {
  switch ($route_name) {
    case 'help.page.user':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $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 and permissions. For more information, see the <a href="!user_docs">online documentation for the User module</a>.', array('!user_docs' => 'https://drupal.org/documentation/modules/user')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Creating and managing users') . '</dt>';
      $output .= '<dd>' . t('Through the <a href="!people">People administration page</a> you can create and cancel user accounts and assign users to roles. By editing one particular user you change the username, e-mail address, and password.', array('!people' => \Drupal::url('user.admin_account'))) . '</dd>';
      $output .= '<dt>' . t('User roles') . '</dt>';
      $output .= '<dd>' . t('<em>User roles</em> are used to group and classify users; each user can be assigned one or more roles. Typically there are three pre-defined roles: <em>Anonymous user</em> (users that are not logged in), <em>Authenticated user</em> (users that are registered and logged in), and <em>Administrator</em> (users that are registered, logged in as administrator). You can create additional roles on the <a href="!roles">Roles page</a>.', array('!roles' => \Drupal::url('user.role_list'))) . '</dd>';
      $output .= '<dt>' . t('Permissions') . '</dt>';
      $output .= '<dd>' . t('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' => \Drupal::url('user.admin_permissions'))) . '</dd>';
      $output .= '<dt>' . t('Account settings') . '</dt>';
      $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, default administrator role (this role will be automatically assigned new permissions whenever a module is enabled), 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 users receive when they register or request a password recovery.', array('!accounts'  => \Drupal::url('user.account_settings'))) . '</dd>';
      $output .= '<dt>' . t('Managing user account fields') . '</dt>';
      $output .= '<dd>' . t('Because User accounts are an <a href="!entity_help">entity type</a>, you can extend them by adding <a href="!field_help">fields</a> through the Manage fields tab on the <a href="!accounts">Account settings page</a>. By adding fields for e.g., a picture, a biography, or address, you can a create a custom profile for the users of the website.', array('!entity_help' => \Drupal::url('help.page', array('name' => 'entity')),'!field_help'=>\Drupal::url('help.page', array('name' => 'field')), '!accounts' => \Drupal::url('user.account_settings'))) . '</dd>';
      $output .= '</dl>';
      return $output;

    case 'user.admin_create':
      return '<p>' . t("This web page allows administrators to register new users. Users' e-mail addresses and usernames must be unique.") . '</p>';

    case 'user.admin_permissions':
      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 'user.role_list':
      $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>';
      $output .= '<p>' . t('Drupal has three special user roles:') . '</p>';
      $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>';
      $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>';
      $output .= '</ul>';
      return $output;

    case 'field_ui.overview_user':
      return '<p>' . t('This form lets administrators add and edit fields for storing user data.') . '</p>';

    case 'field_ui.form_display_overview_user':
      return '<p>' . t('This form lets administrators configure how form fields should be displayed when editing a user profile.') . '</p>';

    case 'field_ui.display_overview_user':
      return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
  }
}

/**
 * Implements hook_theme().
 */
function user_theme() {
  return array(
    'user' => array(
      'render element' => 'elements',
      'file' => 'user.pages.inc',
      'template' => 'user',
    ),
    'user_permission_description' => array(
      'variables' => array('permission_item' => NULL, 'hide' => NULL),
      'file' => 'user.admin.inc',
    ),
    'user_signature' => array(
      'variables' => array('signature' => NULL),
    ),
    'username' => array(
      'variables' => array('account' => NULL, 'attributes' => array()),
    ),
  );
}

/**
 * Implements hook_page_build().
 */
function user_page_build(&$page) {
  $path = drupal_get_path('module', 'user');
  $page['#attached']['css'][$path . '/css/user.module.css'] = array('every_page' => TRUE);
}

/**
 * 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;
  }

  // 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.
  // Similarly, provide a permissions hash, so that permission-dependent data
  // can be reliably cached on the client side.
  $user = \Drupal::currentUser();
  $javascript['settings']['data'][] = array(
    'user' => array(
      'uid' => $user->id(),
      'permissionsHash' => \Drupal::service('user.permissions_hash')->generate($user),
    ),
  );
}

/**
 * Entity URI callback.
 */
function user_uri($user) {
  return new Url('user.view', array(
    'user' => $user->id(),
  ));
}

/**
 * Populates $entity->account for each prepared entity.
 *
 * Called by Drupal\Core\Entity\EntityViewBuilderInterface::buildComponents()
 * implementations.
 *
 * @param array &$build
 *   A renderable array representing the entity content.
 * @param \Drupal\user\EntityOwnerInterface[] $entities
 *   The entities keyed by entity ID.
 */
function user_attach_accounts(array &$build, array $entities) {
  $uids = array();
  foreach ($entities as $entity) {
    $uids[] = $entity->getOwnerId();
  }
  $uids = array_unique($uids);
  $accounts = user_load_multiple($uids);
  $anonymous = entity_create('user', array('uid' => 0));

  foreach ($entities as $id => $entity) {
    if (isset($accounts[$entity->getOwnerId()])) {
      $entities[$id]->setOwner($accounts[$entity->getOwnerId()]);
    }
    else {
      $entities[$id]->setOwner($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() {
  $field_definitions = \Drupal::entityManager()->getFieldDefinitions('user', 'user');
  return isset($field_definitions['user_picture']);
}

/**
 * Implements hook_entity_extra_field_info().
 */
function user_entity_extra_field_info() {
  $fields['user']['user']['form']['account'] = array(
    'label' => t('User name and password'),
    'description' => t('User module account form elements.'),
    'weight' => -10,
  );
  if (\Drupal::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 (\Drupal::config('system.date')->get('timezone.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,
  );

  return $fields;
}

/**
 * Loads multiple users based on certain conditions.
 *
 * 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.
 *
 * @param array $uids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
 * @param bool $reset
 *   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.
 *
 * @return array
 *   An array of user objects, indexed by uid.
 *
 * @see entity_load_multiple()
 * @see user_load()
 * @see user_load_by_mail()
 * @see user_load_by_name()
 * @see \Drupal\Core\Entity\Query\QueryInterface
 */
function user_load_multiple(array $uids = NULL, $reset = FALSE) {
  return entity_load_multiple('user', $uids, $reset);
}

/**
 * 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
 * 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.
 *
 * @param int $uid
 *   Integer specifying the user ID to load.
 * @param bool $reset
 *   TRUE to reset the internal cache and load from the database; FALSE
 *   (default) to load from the internal cache, if set.
 *
 * @return \Drupal\user\UserInterface
 *   A fully-loaded user object upon successful user load, or NULL if the user
 *   cannot be loaded.
 *
 * @see user_load_multiple()
 */
function user_load($uid, $reset = FALSE) {
  return entity_load('user', $uid, $reset);
}

/**
 * Fetches a user object by email address.
 *
 * @param string $mail
 *   String with the account's e-mail address.
 * @return object|bool
 *   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) {
  $users = entity_load_multiple_by_properties('user', array('mail' => $mail));
  return $users ? reset($users) : FALSE;
}

/**
 * Fetches a user object by account name.
 *
 * @param string $name
 *   String with the account's user name.
 * @return object|bool
 *   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) {
  $users = entity_load_multiple_by_properties('user', array('name' => $name));
  return $users ? reset($users) : FALSE;
}

/**
 * Verify the syntax of the given name.
 *
 * @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.
 *
 */
function user_validate_name($name) {
  $definition = DataDefinition::create('string')
    ->addConstraint('UserName', array());
  $data = \Drupal::typedDataManager()->create($definition);
  $data->setValue($name);
  $violations = $data->validate();
  if (count($violations) > 0) {
    return $violations[0]->getMessage();
  }
}

/**
 * Generate a random alphanumeric password.
 */
function user_password($length = 10) {
  // This variable contains the list of allowable characters for the
  // password. Note that the number 0 and the letter 'O' have been
  // removed to avoid confusion between the two. The same is true
  // of 'I', 1, and 'l'.
  $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';

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

  // Declare the password as a blank string.
  $pass = '';

  // Loop the number of times specified by $length.
  for ($i = 0; $i < $length; $i++) {
    do {
      // Find a secure random number within the range needed.
      $index = ord(Crypt::randomBytes(1));
    } while ($index > $len);

    // Each iteration, pick a random character from the
    // allowable string and append it to the password:
    $pass .= $allowable_characters[$index];
  }

  return $pass;
}

/**
 * Determine the permissions for one or more roles.
 *
 * @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(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();
  foreach ($roles as $rid) {
    $role_permissions[$rid] = isset($entities[$rid]) ? $entities[$rid]->getPermissions() : array();
  }
  return $role_permissions;
}

/**
 * Determine the permissions for one or more roles during update.
 *
 * A separate version is needed because during update the entity system can't
 * be used and in non-update situations the entity system is preferred because
 * of the hook system.
 *
 * @param array $roles
 *   An array of role IDs.
 *
 * @return array
 *   An array indexed by role ID. Each value is an array of permission strings
 *   for the given role.
 */
function _user_role_permissions_update($roles) {
  $role_permissions = array();
  foreach ($roles as $rid) {
    $role_permissions[$rid] = \Drupal::config("user.role.$rid")->get('permissions') ?: array();
  }
  return $role_permissions;
}

/**
 * Determine whether the user has a given privilege.
 *
 * @param $string
 *   The permission, such as "administer nodes", being checked for.
 * @param \Drupal\Core\Session\AccountInterface $account
 *   (optional) The account to check, if not given use currently logged in user.
 *
 * @return bool
 *   Boolean TRUE if the current user has the requested permission.
 *
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal\Core\Session\AccountInterface::hasPermission().
 */
function user_access($string, AccountInterface $account = NULL) {
  global $user;

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

  return $account->hasPermission($string);
}

/**
 * Checks for usernames blocked by user administration.
 *
 * @param $name
 *   A string containing a name of the user.
 *
 * @return bool
 *   TRUE if the user is blocked, FALSE otherwise.
 */
function user_is_blocked($name) {
  return (bool) \Drupal::entityQuery('user')
    ->condition('name', $name)
    ->condition('status', 0)
    ->execute();
}

/**
 * Implements hook_permission().
 */
function user_permission() {
  return array(
    'administer permissions' =>  array(
      'title' => t('Administer permissions'),
      'restrict access' => TRUE,
    ),
    '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,
    ),
    'administer users' => array(
      'title' => t('Administer users'),
      'restrict access' => TRUE,
    ),
    'access user profiles' => array(
      'title' => t('View user profiles'),
    ),
    'change own username' => array(
      'title' => t('Change own username'),
    ),
    'cancel account' => array(
      'title' => t('Cancel own user account'),
      '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'))),
    ),
    'select account cancellation method' => array(
      'title' => t('Select method for cancelling own account'),
      'restrict access' => TRUE,
    ),
  );
}

/**
 * Implements hook_user_view().
 */
function user_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
  if ($display->getComponent('member_for')) {
    $build['member_for'] = array(
      '#type' => 'item',
      '#title' => t('Member for'),
      '#markup' => format_interval(REQUEST_TIME - $account->getCreatedTime()),
    );
  }
}

/**
 * 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'];
}

/**
 * Form validation handler for the current password on the user account form.
 *
 * @see AccountForm::form()
 */
function user_validate_current_pass(&$form, &$form_state) {
  $account = $form_state['user'];
  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.
    $current_value = $account->hasField($key) ? $account->get($key)->value : $account->$key;
    if ((strlen(trim($form_state['values'][$key])) > 0) && ($form_state['values'][$key] != $current_value)) {
      $current_pass_failed = empty($form_state['values']['current_pass']) || !\Drupal::service('password')->check($form_state['values']['current_pass'], $account);
      if ($current_pass_failed) {
        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);
      }
      // We only need to check the password once.
      break;
    }
  }
}

/**
 * Implements hook_preprocess_HOOK() for block templates.
 */
function user_preprocess_block(&$variables) {
  if ($variables['configuration']['provider'] == 'user') {
    switch ($variables['elements']['#plugin_id']) {
      case 'user_login_block':
        $variables['attributes']['role'] = 'form';
        break;
    }
  }
}

/**
 * Format a username.
 *
 * @param \Drupal\Core\Session\Interface $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.
 *
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal\Core\Session\Interface::getUsername().
 */
function user_format_name(AccountInterface $account) {
  return $account->getUsername();
}

/**
 * Implements hook_template_preprocess_default_variables_alter().
 *
 * @see user_user_login()
 * @see user_user_logout()
 */
function user_template_preprocess_default_variables_alter(&$variables) {
  $user = \Drupal::currentUser();

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

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

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

/**
 * Preprocesses variables for theme_username().
 *
 * Modules that make any changes to variables like 'name' or 'extra' must ensure
 * that the final string is safe to include directly in the output by using
 * check_plain() or \Drupal\Component\Utility\Xss::filter().
 */
function template_preprocess_username(&$variables) {
  $account = $variables['account'] ?: new AnonymousUserSession();

  $variables['extra'] = '';
  $variables['uid'] = $account->id();
  if (empty($variables['uid'])) {
    if (theme_get_setting('features.comment_user_verification')) {
      $variables['extra'] = ' (' . t('not verified') . ')';
    }
  }

  // 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.
  $name = $variables['name_raw'] = $account->getUsername();
  if (drupal_strlen($name) > 20) {
    $name = drupal_substr($name, 0, 15) . '...';
    $variables['truncated'] = TRUE;
  }
  else {
    $variables['truncated'] = FALSE;
  }
  $variables['name'] = check_plain($name);
  $variables['profile_access'] = \Drupal::currentUser()->hasPermission('access user profiles');

  // Populate link path and attributes if appropriate.
  if ($variables['uid'] && $variables['profile_access']) {
    // We are linking to a local user.
    $variables['link_options']['attributes']['title'] = t('View user profile.');
    $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.
    $variables['link_options']['attributes']['rel'] = 'nofollow';
    $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.
  $variables['link_options']['attributes']['class'] = array('username');
}

/**
 * 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.
 *   - truncated: A boolean indicating if $variables['name'] has been shortened.
 *   - 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.
 *   - attributes: An array of attributes to instantiate the
 *     Drupal\Core\Template\Attribute class if not linking to the user's page.
 *
 * @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
    // $variables['attributes']['class'][] = 'myclass';
    $output = '<span' . new Attribute($variables['attributes']) . '>' . $variables['name'] . $variables['extra'] . '</span>';
  }
  return $output;
}

/**
 * Implements hook_menu_link_presave().
 */
function user_menu_link_presave(MenuLink $menu_link) {
  // 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
  // user_menu_link_load() to conditionally hide the link.
  if ($menu_link->machine_name == 'user.page') {
    $menu_link->options['alter'] = TRUE;
  }
}

/**
 * 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]['machine_name'] == 'user.page' && strpos($item['path'], 'user/%') === 0) {
    array_splice($active_trail, 1, 1);
  }
}

/**
 * Implements hook_translated_menu_link_alter().
 */
function user_translated_menu_link_alter(MenuLink &$menu_link) {
  // Hide the "User account" link for anonymous users.
  if ($menu_link->machine_name == 'user.page' && \Drupal::currentUser()->isAnonymous()) {
    $menu_link->hidden = 1;
  }
}

/**
 * Try to validate the user's login credentials locally.
 *
 * @param $name
 *   User name to authenticate.
 * @param $password
 *   A plain-text password, such as trimmed text from form values.
 * @return
 *   The user's uid on success, or FALSE on failure to authenticate.
 *
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal\user\UserAuth::authenticate() instead.
 */
function user_authenticate($name, $password) {
  return \Drupal::service('user.auth')->authenticate($name, $password);
}

/**
 * Finalizes the login process and logs in a user.
 *
 * The function logs in the user, records a watchdog message about the new
 * session, saves the login timestamp, calls hook_user_login(), and generates a
 * new session.
 *
 * The global $user object is replaced with the passed in account.
 *
 * @param \Drupal\user\UserInterface $account
 *   The account to log in.
 *
 * @see hook_user_login()
 */
function user_login_finalize(UserInterface $account) {
  global $user;
  $user = $account;
  watchdog('user', 'Session opened for %name.', array('%name' => $account->getUsername()));
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $account->setLastLoginTime(REQUEST_TIME);
  \Drupal::entityManager()
    ->getStorage('user')
    ->updateLastLoginTimestamp($account);

  // Regenerate the session ID to prevent against session fixation attacks.
  // This is called before hook_user in case one of those functions fails
  // or incorrectly does a redirect which would leave the old session in place.
  \Drupal::service('session_manager')->regenerate();

  \Drupal::moduleHandler()->invokeAll('user_login', array($account));
}

/**
 * Implements hook_user_login().
 */
function user_user_login($account) {
  // Reset static cache of default variables in template_preprocess() to reflect
  // the new user.
  drupal_static_reset('template_preprocess');
}

/**
 * Implements hook_user_logout().
 */
function user_user_logout($account) {
  // Reset static cache of default variables in template_preprocess() to reflect
  // the new user.
  drupal_static_reset('template_preprocess');
}

/**
 * Generates a unique URL for a user to login and reset their password.
 *
 * @param object $account
 *   An object containing the user account, which must contain at least the
 *   following properties:
 *   - uid: The user ID number.
 *   - login: The UNIX timestamp of the user's last login.
 * @param array $options
 *   (optional) A keyed array of settings. Supported options are:
 *   - langcode: A language code to be used when generating locale-sensitive
 *    URLs. If langcode is NULL the users preferred language is used.
 *
 * @return
 *   A unique URL that provides a one-time log in for the user, from which
 *   they can change their password.
 */
function user_pass_reset_url($account, $options = array()) {
  $timestamp = REQUEST_TIME;
  $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
  $url_options = array('absolute' => TRUE, 'language' => \Drupal::languageManager()->getLanguage($langcode));
  return url("user/reset/" . $account->id() . "/$timestamp/" . user_pass_rehash($account->getPassword(), $timestamp, $account->getLastLoginTime()), $url_options);
}

/**
 * Generates a URL to confirm an account cancellation request.
 *
 * @param object $account
 *   The user account object, which must contain at least the following
 *   properties:
 *   - uid: The user ID number.
 *   - pass: The hashed user password string.
 *   - login: The UNIX timestamp of the user's last login.
 * @param array $options
 *   (optional) A keyed array of settings. Supported options are:
 *   - langcode: A language code to be used when generating locale-sensitive
 *     URLs. If langcode is NULL the users preferred language is used.
 *
 * @return
 *   A unique URL that may be used to confirm the cancellation of the user
 *   account.
 *
 * @see user_mail_tokens()
 * @see user_cancel_confirm()
 */
function user_cancel_url($account, $options = array()) {
  $timestamp = REQUEST_TIME;
  $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
  $url_options = array('absolute' => TRUE, 'language' => \Drupal::languageManager()->getLanguage($langcode));
  return url("user/" . $account->id() . "/cancel/confirm/$timestamp/" . user_pass_rehash($account->getPassword(), $timestamp, $account->getLastLoginTime()), $url_options);
}

/**
 * Creates a unique hash value for use in time-dependent per-user URLs.
 *
 * This hash is normally used to build a unique and secure URL that is sent to
 * the user by email for purposes such as resetting the user's password. In
 * order to validate the URL, the same hash can be generated again, from the
 * same information, and compared to the hash value from the URL. The URL
 * normally contains both the time stamp and the numeric user ID. The login
 * timestamp and hashed password are retrieved from the database as necessary.
 * For a usage example, see user_cancel_url() and user_cancel_confirm().
 *
 * @param string $password
 *   The hashed user account password value.
 * @param int $timestamp
 *   A UNIX timestamp, typically REQUEST_TIME.
 * @param int $login
 *   The UNIX timestamp of the user's last login.
 *
 * @return
 *   A string that is safe for use in URLs and SQL statements.
 */
function user_pass_rehash($password, $timestamp, $login) {
  return Crypt::hmacBase64($timestamp . $login, drupal_get_hash_salt() . $password);
}

/**
 * Cancel a user account.
 *
 * Since the user cancellation process needs to be run in a batch, either
 * Form API will invoke it, or batch_process() needs to be invoked after calling
 * this function and should define the path to redirect to.
 *
 * @param $edit
 *   An array of submitted form values.
 * @param $uid
 *   The user ID of the user account to cancel.
 * @param $method
 *   The account cancellation method to use.
 *
 * @see _user_cancel()
 */
function user_cancel($edit, $uid, $method) {
  $account = user_load($uid);

  if (!$account) {
    drupal_set_message(t('The user account %id does not exist.', array('%id' => $uid)), 'error');
    watchdog('user', 'Attempted to cancel non-existing user account: %id.', array('%id' => $uid), WATCHDOG_ERROR);
    return;
  }

  // Initialize batch (to set title).
  $batch = array(
    'title' => t('Cancelling account'),
    'operations' => array(),
  );
  batch_set($batch);

  // When the 'user_cancel_delete' method is used, user_delete() is called,
  // which invokes hook_user_predelete() and hook_user_delete(). Modules
  // should use those hooks to respond to the account deletion.
  if ($method != 'user_cancel_delete') {
    // Allow modules to add further sets to this batch.
    \Drupal::moduleHandler()->invokeAll('user_cancel', array($edit, $account, $method));
  }

  // Finish the batch and actually cancel the account.
  $batch = array(
    'title' => t('Cancelling user account'),
    'operations' => array(
      array('_user_cancel', array($edit, $account, $method)),
    ),
  );

  // After cancelling account, ensure that user is logged out.
  if ($account->id() == \Drupal::currentUser()->id()) {
    // Batch API stores data in the session, so use the finished operation to
    // manipulate the current user's session id.
    $batch['finished'] = '_user_cancel_session_regenerate';
  }

  batch_set($batch);

  // Batch processing is either handled via Form API or has to be invoked
  // manually.
}

/**
 * Last batch processing step for cancelling a user account.
 *
 * Since batch and session API require a valid user account, the actual
 * cancellation of a user account needs to happen last.
 *
 * @see user_cancel()
 */
function _user_cancel($edit, $account, $method) {
  global $user;

  switch ($method) {
    case 'user_cancel_block':
    case 'user_cancel_block_unpublish':
    default:
      // Send account blocked notification if option was checked.
      if (!empty($edit['user_cancel_notify'])) {
        _user_mail_notify('status_blocked', $account);
      }
      $account->block();
      $account->save();
      drupal_set_message(t('%name has been disabled.', array('%name' => $account->getUsername())));
      watchdog('user', 'Blocked user: %name %email.', array('%name' => $account->getUsername(), '%email' => '<' . $account->getEmail() . '>'), WATCHDOG_NOTICE);
      break;

    case 'user_cancel_reassign':
    case 'user_cancel_delete':
      // Send account canceled notification if option was checked.
      if (!empty($edit['user_cancel_notify'])) {
        _user_mail_notify('status_canceled', $account);
      }
      $account->delete();
      drupal_set_message(t('%name has been deleted.', array('%name' => $account->getUsername())));
      watchdog('user', 'Deleted user: %name %email.', array('%name' => $account->getUsername(), '%email' => '<' . $account->getEmail() . '>'), WATCHDOG_NOTICE);
      break;
  }

  // After cancelling account, ensure that user is logged out. We can't destroy
  // their session though, as we might have information in it, and we can't
  // regenerate it because batch API uses the session ID, we will regenerate it
  // in _user_cancel_session_regenerate().
  if ($account->id() == $user->id()) {
    $user = new AnonymousUserSession();
  }

  // Clear the cache for anonymous users.
  Cache::invalidateTags(array('content' => TRUE));
}

/**
 * Finished batch processing callback for cancelling a user account.
 *
 * @see user_cancel()
 */
function _user_cancel_session_regenerate() {
  // Regenerate the users session instead of calling session_destroy() as we
  // want to preserve any messages that might have been set.
  \Drupal::service('session_manager')->regenerate();
}

/**
 * Helper function to return available account cancellation methods.
 *
 * See documentation of hook_user_cancel_methods_alter().
 *
 * @return array
 *   An array containing all account cancellation methods as form elements.
 *
 * @see hook_user_cancel_methods_alter()
 * @see user_admin_settings()
 */
function user_cancel_methods() {
  $user_settings = \Drupal::config('user.settings');
  $anonymous_name = $user_settings->get('anonymous');
  $methods = array(
    'user_cancel_block' => array(
      'title' => t('Disable the account and keep its content.'),
      'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will remain attributed to your user name.'),
    ),
    'user_cancel_block_unpublish' => array(
      'title' => t('Disable the account and unpublish its content.'),
      'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will be hidden from everyone but administrators.'),
    ),
    'user_cancel_reassign' => array(
      'title' => t('Delete the account and make its content belong to the %anonymous-name user.', array('%anonymous-name' => $anonymous_name)),
      'description' => t('Your account will be removed and all account information deleted. All of your content will be assigned to the %anonymous-name user.', array('%anonymous-name' => $anonymous_name)),
    ),
    'user_cancel_delete' => array(
      'title' => t('Delete the account and its content.'),
      'description' => t('Your account will be removed and all account information deleted. All of your content will also be deleted.'),
      'access' => \Drupal::currentUser()->hasPermission('administer users'),
    ),
  );
  // Allow modules to customize account cancellation methods.
  \Drupal::moduleHandler()->alter('user_cancel_methods', $methods);

  // Turn all methods into real form elements.
  $form = array(
    '#options' => array(),
    '#default_value' => $user_settings->get('cancel_method'),
  );
  foreach ($methods as $name => $method) {
    $form['#options'][$name] = $method['title'];
    // Add the description for the confirmation form. This description is never
    // shown for the cancel method option, only on the confirmation form.
    // Therefore, we use a custom #confirm_description property.
    if (isset($method['description'])) {
      $form[$name]['#confirm_description'] = $method['description'];
    }
    if (isset($method['access'])) {
      $form[$name]['#access'] = $method['access'];
    }
  }
  return $form;
}

/**
 * Delete a user.
 *
 * @param $uid
 *   A user ID.
 */
function user_delete($uid) {
  user_delete_multiple(array($uid));
}

/**
 * Delete multiple user accounts.
 *
 * @param $uids
 *   An array of user IDs.
 *
 * @see hook_user_predelete()
 * @see hook_user_delete()
 */
function user_delete_multiple(array $uids) {
  entity_delete_multiple('user', $uids);
}

/**
 * Generate an array for rendering the given user.
 *
 * When viewing a user profile, the $page array contains:
 *
 * - $page['content']['member_for']:
 *   Contains the default "Member for" profile data for a user.
 * - $page['content']['#user']:
 *   The user account of the profile being viewed.
 *
 * To theme user profiles, copy core/modules/user/templates/user.html.twig
 * to your theme directory, and edit it as instructed in that file's comments.
 *
 * @param $account
 *   A user object.
 * @param $view_mode
 *   View mode, e.g. 'full'.
 * @param $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
 *
 * @return
 *   An array as expected by drupal_render().
 */
function user_view($account, $view_mode = 'full', $langcode = NULL) {
  return entity_view($account, $view_mode, $langcode);
}

/**
 * Constructs a drupal_render() style array from an array of loaded users.
 *
 * @param $accounts
 *   An array of user accounts as returned by user_load_multiple().
 * @param $view_mode
 *   (optional) View mode, e.g., 'full', 'teaser'... Defaults to 'teaser.'
 * @param $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
 *
 * @return
 *   An array in the format expected by drupal_render().
 */
function user_view_multiple($accounts, $view_mode = 'full', $langcode = NULL) {
  return entity_view_multiple($accounts, $view_mode, $langcode);
}

/**
 * Implements hook_mail().
 */
function user_mail($key, &$message, $params) {
  $token_service = \Drupal::token();
  $language_manager = \Drupal::languageManager();
  $langcode = $message['langcode'];
  $variables = array('user' => $params['account']);

  $language = \Drupal::languageManager()->getLanguage($params['account']->getPreferredLangcode());
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);
  $mail_config = \Drupal::config('user.mail');

   // We do not sanitize the token replacement, since the output of this
   // replacement is intended for an e-mail message, not a web browser.
  $token_options = array('langcode' => $langcode, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE);
  $message['subject'] .= $token_service->replace($mail_config->get($key . '.subject'), $variables, $token_options);
  $message['body'][] = $token_service->replace($mail_config->get($key . '.body'), $variables, $token_options);

  $language_manager->setConfigOverrideLanguage($original_language);

}

/**
 * Token callback to add unsafe tokens for user mails.
 *
 * This function is used by \Drupal\Core\Utility\Token::replace() to set up
 * some additional tokens that can be used in email messages generated by
 * user_mail().
 *
 * @param $replacements
 *   An associative array variable containing mappings from token names to
 *   values (for use with strtr()).
 * @param $data
 *   An associative array of token replacement values. If the 'user' element
 *   exists, it must contain a user account object with the following
 *   properties:
 *   - login: The UNIX timestamp of the user's last login.
 *   - pass: The hashed account login password.
 * @param $options
 *   Unused parameter required by \Drupal\Core\Utility\Token::replace().
 */
function user_mail_tokens(&$replacements, $data, $options) {
  if (isset($data['user'])) {
    $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user'], $options);
    $replacements['[user:cancel-url]'] = user_cancel_url($data['user'], $options);
  }
}

/*** Administrative features ***********************************************/

/**
 * Retrieve an array of roles matching specified conditions.
 *
 * @param $membersonly
 *   Set this to TRUE to exclude the 'anonymous' role.
 * @param $permission
 *   A string containing a permission. If set, only roles containing that
 *   permission are returned.
 *
 * @return
 *   An associative array with the role id as the key and the role name as
 *   value.
 */
function user_role_names($membersonly = FALSE, $permission = NULL) {
  return array_map(function ($item) {
    return $item->label();
  }, user_roles($membersonly, $permission));
}

/**
 * Implements hook_user_role_insert().
 */
function user_user_role_insert(RoleInterface $role) {
  // Ignore the authenticated and anonymous roles or the role is being synced.
  if (in_array($role->id(), array(DRUPAL_AUTHENTICATED_RID, DRUPAL_ANONYMOUS_RID)) || $role->isSyncing()) {
    return;
  }

  $add_id = 'user_add_role_action.' . $role->id();
  if (!entity_load('action', $add_id)) {
    $action = entity_create('action', array(
      'id' => $add_id,
      'type' => 'user',
      'label' => t('Add the @label role to the selected users', array('@label' => $role->label())),
      'configuration' => array(
        'rid' => $role->id(),
      ),
      'plugin' => 'user_add_role_action',
    ));
    $action->save();
  }
  $remove_id = 'user_remove_role_action.' . $role->id();
  if (!entity_load('action', $remove_id)) {
    $action = entity_create('action', array(
      'id' => $remove_id,
      'type' => 'user',
      'label' => t('Remove the @label role from the selected users', array('@label' => $role->label())),
      'configuration' => array(
        'rid' => $role->id(),
      ),
      'plugin' => 'user_remove_role_action',
    ));
    $action->save();
  }
}

/**
 * Implements hook_user_role_delete().
 */
function user_user_role_delete(RoleInterface $role) {
  // Ignore the authenticated and anonymous roles or the role is being synced.
  if (in_array($role->id(), array(DRUPAL_AUTHENTICATED_RID, DRUPAL_ANONYMOUS_RID)) || $role->isSyncing()) {
    return;
  }

  $actions = entity_load_multiple('action', array(
    'user_add_role_action.' . $role->id(),
    'user_remove_role_action.' . $role->id(),
  ));
  foreach ($actions as $action) {
    $action->delete();
  }
}

/**
 * Retrieve an array of roles matching specified conditions.
 *
 * @param $membersonly
 *   Set this to TRUE to exclude the 'anonymous' role.
 * @param $permission
 *   A string containing a permission. If set, only roles containing that
 *   permission are returned.
 *
 * @return
 *   An associative array with the role id as the key and the role object as
 *   value.
 */
function user_roles($membersonly = FALSE, $permission = NULL) {
  $user_roles = &drupal_static(__FUNCTION__);

  // Do not cache roles for specific permissions. This data is not requested
  // frequently enough to justify the additional memory use.
  if (empty($permission)) {
    $cid = $membersonly ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
    if (isset($user_roles[$cid])) {
      return $user_roles[$cid];
    }
  }

  $roles = entity_load_multiple('user_role');
  if ($membersonly) {
    unset($roles[DRUPAL_ANONYMOUS_RID]);
  }

  if (!empty($permission)) {
    $roles = array_filter($roles, function ($role) use ($permission) {
      return $role->hasPermission($permission);
    });
  }

  if (empty($permission)) {
    $user_roles[$cid] = $roles;
  }

  return $roles;
}

/**
 * Fetches a user role by role ID.
 *
 * @param $rid
 *   A string representing the role ID.
 *
 * @return
 *   A fully-loaded role object if a role with the given ID exists, or NULL
 *   otherwise.
 */
function user_role_load($rid) {
  return entity_load('user_role', $rid);
}

/**
 * Determine the modules that permissions belong to.
 *
 * @return
 *   An associative array in the format $permission => $module.
 */
function user_permission_get_modules() {
  $permissions = array();
  foreach (\Drupal::moduleHandler()->getImplementations('permission') as $module) {
    $perms = \Drupal::moduleHandler()->invoke($module, 'permission');
    foreach ($perms as $key => $value) {
      $permissions[$key] = $module;
    }
  }
  return $permissions;
}

/**
 * Change permissions for a user role.
 *
 * This function may be used to grant and revoke multiple permissions at once.
 * For example, when a form exposes checkboxes to configure permissions for a
 * role, the form submit handler may directly pass the submitted values for the
 * checkboxes form element to this function.
 *
 * @param $rid
 *   The ID of a user role to alter.
 * @param $permissions
 *   An associative array, where the key holds the permission name and the value
 *   determines whether to grant or revoke that permission. Any value that
 *   evaluates to TRUE will cause the permission to be granted. Any value that
 *   evaluates to FALSE will cause the permission to be revoked.
 *   @code
 *     array(
 *       'administer nodes' => 0,                // Revoke 'administer nodes'
 *       'administer blocks' => FALSE,           // Revoke 'administer blocks'
 *       'access user profiles' => 1,            // Grant 'access user profiles'
 *       'access content' => TRUE,               // Grant 'access content'
 *       'access comments' => 'access comments', // Grant 'access comments'
 *     )
 *   @endcode
 *   Existing permissions are not changed, unless specified in $permissions.
 *
 * @see user_role_grant_permissions()
 * @see user_role_revoke_permissions()
 */
function user_role_change_permissions($rid, array $permissions = array()) {
  // Grant new permissions for the role.
  $grant = array_filter($permissions);
  if (!empty($grant)) {
    user_role_grant_permissions($rid, array_keys($grant));
  }
  // Revoke permissions for the role.
  $revoke = array_diff_assoc($permissions, $grant);
  if (!empty($revoke)) {
    user_role_revoke_permissions($rid, array_keys($revoke));
  }
}

/**
 * Grant permissions to a user role.
 *
 * @param $rid
 *   The ID of a user role to alter.
 * @param $permissions
 *   A list of permission names to grant.
 *
 * @see user_role_change_permissions()
 * @see user_role_revoke_permissions()
 */
function user_role_grant_permissions($rid, array $permissions = array()) {
  // Grant new permissions for the role.
  $role = entity_load('user_role', $rid);
  foreach ($permissions as $permission) {
    $role->grantPermission($permission);
  }
  $role->save();
}

/**
 * Revoke permissions from a user role.
 *
 * @param $rid
 *   The ID of a user role to alter.
 * @param $permissions
 *   A list of permission names to revoke.
 *
 * @see user_role_change_permissions()
 * @see user_role_grant_permissions()
 */
function user_role_revoke_permissions($rid, array $permissions = array()) {
  // Revoke permissions for the role.
  $role = entity_load('user_role', $rid);
  foreach ($permissions as $permission) {
    $role->revokePermission($permission);
  }
  $role->save();
}

/**
 * Returns HTML for a user signature.
 *
 * @param $variables
 *   An associative array containing:
 *   - signature: The user's signature.
 *
 * @ingroup themeable
 */
function theme_user_signature($variables) {
  $signature = $variables['signature'];
  $output = '';

  if ($signature) {
    $output .= '<div class="clear">';
    $output .= '<div></div>';
    $output .= $signature;
    $output .= '</div>';
  }

  return $output;
}

/**
 * Conditionally create and send a notification email when a certain
 * operation happens on the given user account.
 *
 * @see user_mail_tokens()
 * @see drupal_mail()
 *
 * @param $op
 *   The operation being performed on the account. Possible values:
 *   - 'register_admin_created': Welcome message for user created by the admin.
 *   - 'register_no_approval_required': Welcome message when user
 *     self-registers.
 *   - 'register_pending_approval': Welcome message, user pending admin
 *     approval.
 *   - 'password_reset': Password recovery request.
 *   - 'status_activated': Account activated.
 *   - 'status_blocked': Account blocked.
 *   - 'cancel_confirm': Account cancellation request.
 *   - 'status_canceled': Account canceled.
 *
 * @param $account
 *   The user object of the account being notified. Must contain at
 *   least the fields 'uid', 'name', and 'mail'.
 * @param $langcode
 *   Optional language code to use for the notification, overriding account
 *   language.
 *
 * @return
 *   The return value from drupal_mail_system()->mail(), if ends up being
 *   called.
 */
function _user_mail_notify($op, $account, $langcode = NULL) {
  // By default, we always notify except for canceled and blocked.
  $notify = \Drupal::config('user.settings')->get('notify.' . $op);
  if ($notify || ($op != 'status_canceled' && $op != 'status_blocked')) {
    $params['account'] = $account;
    $langcode = $langcode ? $langcode : $account->getPreferredLangcode();
    // Get the custom site notification email to use as the from email address
    // if it has been set.
    $site_mail = \Drupal::config('system.site')->get('mail_notification');
    // If the custom site notification email has not been set, we use the site
    // default for this.
    if (empty($site_mail)) {
      $site_mail = \Drupal::config('system.site')->get('mail');
    }
    if (empty($site_mail)) {
      $site_mail = ini_get('sendmail_from');
    }
    $mail = drupal_mail('user', $op, $account->getEmail(), $langcode, $params, $site_mail);
    if ($op == 'register_pending_approval') {
      // If a user registered requiring admin approval, notify the admin, too.
      // We use the site default language for this.
      drupal_mail('user', 'register_pending_approval_admin', $site_mail, \Drupal::languageManager()->getDefaultLanguage()->id, $params);
    }
  }
  return empty($mail) ? NULL : $mail['result'];
}

/**
 * Form element process handler for client-side password validation.
 *
 * This #process handler is automatically invoked for 'password_confirm' form
 * elements to add the JavaScript and string translations for dynamic password
 * validation.
 *
 * @see system_element_info()
 */
function user_form_process_password_confirm($element) {
  $password_settings = array(
    'confirmTitle' => t('Passwords match:'),
    'confirmSuccess' => t('yes'),
    'confirmFailure' => t('no'),
    'showStrengthIndicator' => FALSE,
  );

  if (\Drupal::config('user.settings')->get('password_strength')) {
    $password_settings['showStrengthIndicator'] = TRUE;
    $password_settings += array(
      'strengthTitle' => t('Password strength:'),
      'hasWeaknesses' => t('To make your password stronger:'),
      'tooShort' => t('Make it at least 6 characters'),
      'addLowerCase' => t('Add lowercase letters'),
      'addUpperCase' => t('Add uppercase letters'),
      'addNumbers' => t('Add numbers'),
      'addPunctuation' => t('Add punctuation'),
      'sameAsUsername' => t('Make it different from your username'),
      'weak' => t('Weak'),
      'fair' => t('Fair'),
      'good' => t('Good'),
      'strong' => t('Strong'),
      'username' => \Drupal::currentUser()->getUsername(),
    );
  }

  $js_settings = array(
    'password' => $password_settings,
  );

  $element['#attached']['library'][] = 'user/drupal.user';
  // Ensure settings are only added once per page.
  static $already_added = FALSE;
  if (!$already_added) {
    $already_added = TRUE;
    $element['#attached']['js'][] = array('data' => $js_settings, 'type' => 'setting');
  }

  return $element;
}

/**
 * Implements hook_modules_installed().
 */
function user_modules_installed($modules) {
  // Assign all available permissions to the administrator role.
  $rid = \Drupal::config('user.settings')->get('admin_role');
  if ($rid) {
    $permissions = array();
    foreach ($modules as $module) {
      if ($module_permissions = \Drupal::moduleHandler()->invoke($module, 'permission')) {
        $permissions = array_merge($permissions, array_keys($module_permissions));
      }
    }
    if (!empty($permissions)) {
      user_role_grant_permissions($rid, $permissions);
    }
  }
}

/**
 * Implements hook_modules_uninstalled().
 */
function user_modules_uninstalled($modules) {
  // Remove any potentially orphan module data stored for users.
  \Drupal::service('user.data')->delete($modules);
  // User signatures require Filter module.
  if (in_array('filter', $modules)) {
    \Drupal::config('user.settings')->set('signatures', FALSE)->save();
  }
}

/**
 * Saves visitor information as a cookie so it can be reused.
 *
 * @param $values
 *   An array of key/value pairs to be saved into a cookie.
 */
function user_cookie_save(array $values) {
  foreach ($values as $field => $value) {
    // Set cookie for 365 days.
    setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
  }
}

/**
 * Delete a visitor information cookie.
 *
 * @param $cookie_name
 *   A cookie name such as 'homepage'.
 */
function user_cookie_delete($cookie_name) {
  setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
}

/**
 * Implements hook_file_download_access().
 */
function user_file_download_access($field, EntityInterface $entity, File $file) {
  if ($entity->getEntityTypeId() == 'user') {
    return $entity->access('view');
  }
}

/**
 * Implements hook_toolbar().
 */
function user_toolbar() {
  $user = \Drupal::currentUser();

  // Add logout & user account links or login link.
  if ($user->isAuthenticated()) {
    $links = array(
      'account' => array(
        'title' => t('View profile'),
        'href' => 'user',
        'html' => TRUE,
        'attributes' => array(
          'title' => t('User account'),
        ),
      ),
      'account_edit' => array(
        'title' => t('Edit profile'),
        'href' => 'user/' . $user->id() . '/edit',
        'html' => TRUE,
        'attributes' => array(
          'title' => t('Edit user account'),
        ),
      ),
      'logout' => array(
        'title' => t('Log out'),
        'href' => 'user/logout',
      ),
    );
  }
  else {
     $links = array(
      'login' => array(
        'title' => t('Log in'),
        'href' => 'user',
      ),
    );
  }

  $items['user'] = array(
    '#type' => 'toolbar_item',
    'tab' => array(
      '#type' => 'link',
      '#title' => $user->getUsername(),
      '#href' => 'user',
      '#attributes' => array(
        'title' => t('My account'),
        'class' => array('toolbar-icon', 'toolbar-icon-user'),
      ),
    ),
    'tray' => array(
      '#heading' => t('User account actions'),
      'user_links' => array(
        '#theme' => 'links__toolbar_user',
        '#links' => $links,
        '#attributes' => array(
          'class' => array('menu'),
        ),
      ),
    ),
    '#weight' => 100,
    '#attached' => array(
      'library' => array(
        'user/drupal.user.icons',
      ),
    ),
  );

  return $items;
}

/**
 * Logs the current user out.
 */
function user_logout() {
  $user = \Drupal::currentUser();

  watchdog('user', 'Session closed for %name.', array('%name' => $user->getUsername()));

  \Drupal::moduleHandler()->invokeAll('user_logout', array($user));

  // Destroy the current session, and reset $user to the anonymous user.
  session_destroy();
}