-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser.module
More file actions
2157 lines (1990 loc) · 72.2 KB
/
Copy pathuser.module
File metadata and controls
2157 lines (1990 loc) · 72.2 KB
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
<?php
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\entity\Plugin\Core\Entity\EntityDisplay;
use Drupal\file\Plugin\Core\Entity\File;
use Drupal\user\Plugin\Core\Entity\User;
use Drupal\user\UserInterface;
use Drupal\user\RoleInterface;
use Drupal\Core\Template\Attribute;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\menu_link\Plugin\Core\Entity\MenuLink;
/**
* @file
* Enables the user registration and login system.
*/
/**
* Maximum length of username text field.
*/
const USERNAME_MAX_LENGTH = 60;
/**
* Maximum length of user e-mail text field.
*/
const EMAIL_MAX_LENGTH = 254;
/**
* 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($path, $arg) {
switch ($path) {
case 'admin/help#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 (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>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Creating and managing users') . '</dt>';
$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>';
$output .= '<dt>' . t('User roles and permissions') . '</dt>';
$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>';
$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, 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>';
$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>';
case 'admin/people/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 'admin/people/roles':
$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 'admin/config/people/accounts/fields':
return '<p>' . t('This form lets administrators add and edit fields for storing user data.') . '</p>';
case 'admin/config/people/accounts/form-display':
return '<p>' . t('This form lets administrators configure how form fields should be displayed when editing a user profile.') . '</p>';
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>';
}
}
/**
* 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_entity_bundle_info().
*/
function user_entity_bundle_info() {
$bundles['user']['user']['label'] = t('User');
return $bundles;
}
/**
* Entity URI callback.
*/
function user_uri($user) {
return array(
'path' => 'user/' . $user->id(),
);
}
/**
* Entity label callback.
*
* 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.
*
* @param $entity_type
* The entity type.
* @param $entity
* The entity object.
*
* @return
* The name of the user.
*
* @see user_format_name()
*/
function user_label($entity_type, $entity) {
return $entity->getUsername();
}
/**
* Populates $entity->account for each prepared entity.
*
* Called by Drupal\Core\Entity\EntityRenderControllerInterface::buildContent()
* implementations.
*
* @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');
}
/**
* Implements hook_field_extra_fields().
*/
function user_field_extra_fields() {
$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.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 object
* 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.
*/
function user_validate_name($name) {
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.');
}
if (preg_match('/[\x{80}-\x{A0}' . // Non-printable ISO-8859-1 + NBSP
'\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)) {
return t('The username contains an illegal character.');
}
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));
}
}
/**
* 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++) {
// Each iteration, pick a random character from the
// allowable string and append it to the password:
$pass .= $allowable_characters[mt_rand(0, $len)];
}
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 as of 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::request()->attributes->get('_account') ?: $user;
}
return $account->hasPermission($string);
}
/**
* Checks for usernames blocked by user administration.
*
* @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.
*/
function user_is_blocked($name) {
return db_select('users')
->fields('users', array('name'))
->condition('name', db_like($name), 'LIKE')
->condition('status', 0)
->execute()->fetchObject();
}
/**
* Implements hook_permission().
*/
function user_permission() {
return array(
'administer permissions' => array(
'title' => t('Administer permissions'),
'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' => 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_search_info().
*/
function user_search_info() {
return array(
'title' => 'Users',
);
}
/**
* Implements hook_search_access().
*/
function user_search_access() {
return user_access('access user profiles');
}
/**
* Implements hook_search_execute().
*/
function user_search_execute($keys = NULL, $conditions = NULL) {
// Replace wildcards with MySQL/PostgreSQL wildcards.
$keys = preg_replace('!\*+!', '%', $keys);
$query = db_select('users')
->extend('Drupal\Core\Database\Query\PagerSelectExtender');
$query->fields('users', array('uid'));
if (user_access('administer users')) {
// Administrators can also search in the otherwise private email field, and
// they don't need to be restricted to only active users.
$query->fields('users', array('mail'));
$query->condition(db_or()->
condition('name', '%' . db_like($keys) . '%', 'LIKE')->
condition('mail', '%' . db_like($keys) . '%', 'LIKE'));
}
else {
// 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);
}
$uids = $query
->limit(15)
->execute()
->fetchCol();
$accounts = user_load_multiple($uids);
$results = array();
foreach ($accounts as $account) {
$result = array(
'title' => user_format_name($account),
'link' => url('user/' . $account->id(), array('absolute' => TRUE)),
);
if (user_access('administer users')) {
$result['title'] .= ' (' . $account->getEmail() . ')';
}
$results[] = $result;
}
return $results;
}
/**
* Implements hook_user_view().
*/
function user_user_view(UserInterface $account, EntityDisplay $display) {
if ($display->getComponent('member_for')) {
$account->content['member_for'] = array(
'#type' => 'item',
'#title' => t('Member for'),
'#markup' => format_interval(REQUEST_TIME - $account->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 AccountFormController::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->getPropertyDefinition($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_container()->get('password')->check($form_state['values']['current_pass'], $account);
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;
}
}
}
/**
* Implements hook_preprocess_HOOK() for block.html.twig.
*/
function user_preprocess_block(&$variables) {
if ($variables['configuration']['module'] == 'user') {
switch ($variables['elements']['#plugin_id']) {
case 'user_login_block':
$variables['attributes']['role'] = 'form';
break;
case 'user_new_block':
$variables['attributes']['role'] = 'complementary';
break;
case 'user_online_block':
$variables['attributes']['role'] = 'complementary';
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 Use \Drupal\Core\Session\Interface::getUsername() instead.
*/
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) {
global $user;
// 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, 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->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 filter_xss().
*/
function template_preprocess_username(&$variables) {
$account = $variables['account'] ?: drupal_anonymous_user();
$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['name'] = check_plain($name);
$variables['profile_access'] = user_access('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.
* - 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;
}
/**
* Determines if the current user is anonymous.
*
* @return bool
* TRUE if the user is anonymous, FALSE if the user is authenticated.
*/
function user_is_anonymous() {
// Menu administrators can see items for anonymous when administering.
return $GLOBALS['user']->isAnonymous() || !empty($GLOBALS['menu_admin']);
}
/**
* Determines if the current user is logged in.
*
* @return bool
* TRUE if the user is logged in, FALSE if the user is anonymous.
*
* @deprecated Use \Drupal\Core\Session\UserSession::isAuthenticated().
*/
function user_is_logged_in() {
return $GLOBALS['user']->isAuthenticated();
}
/**
* 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.
*/
function user_register_access() {
return user_is_anonymous() && (config('user.settings')->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY);
}
/**
* Implements hook_menu().
*/
function user_menu() {
// Registration and login pages.
$items['user'] = array(
'title' => 'User account',
'title callback' => 'user_menu_title',
'weight' => -10,
'route_name' => 'user_page',
'menu_name' => 'account',
);
$items['user/login'] = array(
'title' => 'Log in',
'type' => MENU_DEFAULT_LOCAL_TASK,
);
// Other authentication methods may add pages below user/login/.
$items['user/login/default'] = array(
'title' => 'Username and password',
'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['user/register'] = array(
'title' => 'Create new account',
'type' => MENU_LOCAL_TASK,
'route_name' => 'user_register',
);
$items['user/password'] = array(
'title' => 'Request new password',
'route_name' => 'user_pass',
'type' => MENU_LOCAL_TASK,
);
$items['user/reset/%/%/%'] = array(
'title' => 'Reset password',
'page callback' => 'drupal_get_form',
'page arguments' => array('user_pass_reset', 2, 3, 4),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
'file' => 'user.pages.inc',
);
$items['user/logout'] = array(
'title' => 'Log out',
'route_name' => 'user_logout',
'weight' => 10,
'menu_name' => 'account',
);
// User listing pages.
$items['admin/people'] = array(
'title' => 'People',
'description' => 'Manage user accounts, roles, and permissions.',
'page callback' => 'user_admin_account',
'access arguments' => array('administer users'),
'position' => 'left',
'weight' => -4,
'file' => 'user.admin.inc',
);
// Permissions and role forms.
$items['admin/people/permissions'] = array(
'title' => 'Permissions',
'description' => 'Determine access to features by selecting permissions for roles.',
'route_name' => 'user_admin_permissions',
'type' => MENU_LOCAL_TASK,
);
$items['admin/people/roles'] = array(
'title' => 'Roles',
'description' => 'List, edit, or add user roles.',
'route_name' => 'user_role_list',
'type' => MENU_LOCAL_TASK,
);
$items['admin/people/roles/add'] = array(
'title' => 'Add role',
'route_name' => 'user_role_add',
'type' => MENU_LOCAL_ACTION,
);
$items['admin/people/roles/manage/%user_role'] = array(
'title' => 'Edit role',
'route_name' => 'user_role_edit',
);
$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(
'title' => 'Delete role',
'route_name' => 'user_role_delete',
'weight' => 10,
'context' => MENU_CONTEXT_INLINE,
);
$items['admin/people/create'] = array(
'title' => 'Add user',
'route_name' => 'user_admin_create',
'type' => MENU_LOCAL_ACTION,
);
$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',
'type' => MENU_CALLBACK,
);
// Administration pages.
$items['admin/config/people'] = array(
'title' => 'People',
'description' => 'Configure user accounts.',
'position' => 'left',
'weight' => -20,
'page callback' => 'system_admin_menu_block_page',
'access arguments' => array('access administration pages'),
'file' => 'system.admin.inc',
'file path' => drupal_get_path('module', 'system'),
);
$items['admin/config/people/accounts'] = array(
'title' => 'Account settings',
'description' => 'Configure default behavior of users, including registration requirements, e-mails, and fields.',
'weight' => -10,
'route_name' => 'user_account_settings',
);
$items['admin/config/people/accounts/settings'] = array(
'title' => 'Settings',
'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['user/%user'] = array(
'title' => 'My account',
'title callback' => 'user_page_title',
'title arguments' => array(1),
'page callback' => 'user_view_page',
'page arguments' => array(1),
'access callback' => 'entity_page_access',
'access arguments' => array(1),
);
$items['user/%user/view'] = array(
'title' => 'View',
'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['user/%user/cancel'] = array(
'title' => 'Cancel account',
'page callback' => 'drupal_get_form',
'page arguments' => array('user_cancel_confirm_form', 1),
'access callback' => 'entity_page_access',
'access arguments' => array(1, 'delete'),
'file' => 'user.pages.inc',
);
$items['user/%user/cancel/confirm/%/%'] = array(
'title' => 'Confirm account cancellation',
'page callback' => 'user_cancel_confirm',
'page arguments' => array(1, 4, 5),
'access callback' => 'entity_page_access',
'access arguments' => array(1, 'delete'),
'file' => 'user.pages.inc',
);
$items['user/%user/edit'] = array(
'title' => 'Edit',
'page callback' => 'entity_get_form',
'page arguments' => array(1),
'access callback' => 'entity_page_access',
'access arguments' => array(1, 'update'),
'type' => MENU_LOCAL_TASK,
'file' => 'user.pages.inc',
);
return $items;
}
/**
* 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->link_path == 'user' && $menu_link->module == 'system') {
$menu_link->options['alter'] = TRUE;
}
// Force the Logout link to appear on the top-level of 'account' menu by
// default (i.e., unless it has been customized).
if ($menu_link->link_path == 'user/logout' && $menu_link->module == 'system' && empty($menu_link->customized)) {
$menu_link->plid = 0;
}
}
/**
* Implements hook_menu_breadcrumb_alter().
*/
function user_menu_breadcrumb_alter(&$active_trail, $item) {
// Remove "My account" from the breadcrumb when $item is descendant-or-self
// of system path user/%.
if (isset($active_trail[1]['module']) && $active_trail[1]['module'] == 'system' && $active_trail[1]['link_path'] == 'user' && strpos($item['path'], 'user/%') === 0) {
array_splice($active_trail, 1, 1);
}
}
/**
* Implements hook_menu_link_load().
*/
function user_menu_link_load($menu_links) {
// Hide the "User account" link for anonymous users.
foreach ($menu_links as $link) {
if ($link['link_path'] == 'user' && $link['module'] == 'system' && !$GLOBALS['user']->id()) {
$link['hidden'] = 1;
}
}
}
/**
* Implements hook_admin_paths().