forked from backdrop/backdrop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.module
3472 lines (3192 loc) · 116 KB
/
user.module
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
/**
* @file
* Enables the user registration and login system.
*/
/**
* Maximum length of username text field.
*/
define('USERNAME_MAX_LENGTH', 60);
/**
* Users can login with username only.
*/
define('USER_LOGIN_USERNAME_ONLY', 'username_only');
/**
* Users can login with email address only.
*/
define('USER_LOGIN_EMAIL_ONLY', 'email_only');
/**
* Users can login using either username or email address.
*/
define('USER_LOGIN_USERNAME_OR_EMAIL', 'username_or_email');
/**
* Only administrators can create user accounts.
*/
define('USER_REGISTER_ADMINISTRATORS_ONLY', 'admin_only');
/**
* Visitors can create their own accounts.
*/
define('USER_REGISTER_VISITORS', 'visitors');
/**
* Visitors can create accounts, but they don't become active without
* administrative approval.
*/
define('USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL', 'visitors_admin_approval');
/**
* Password strength modifier to encourage longer passwords.
*/
define('USER_PASSWORD_STRENGTH_MODIFIER', 0.7);
/**
* Password strength levels: weak, fair, good and strong.
*/
define('USER_PASSWORD_STRENGTH_WEAK', 0);
define('USER_PASSWORD_STRENGTH_FAIR', 50);
define('USER_PASSWORD_STRENGTH_GOOD', 70);
define('USER_PASSWORD_STRENGTH_STRONG', 90);
/**
* Invokes a user hook in every module.
*
* We cannot use module_invoke() for this, because the arguments need to
* be passed by reference.
*
* @param $type
* A text string that controls which user hook to invoke. Valid choices are:
* - login: Invokes hook_user_login().
* @param $edit
* An associative array variable containing form values to be passed
* as the first parameter of the hook function.
* @param $account
* The user account object to be passed as the second parameter of the hook
* function.
*/
function user_module_invoke($type, &$edit, $account) {
foreach (module_implements('user_' . $type) as $module) {
$function = $module . '_user_' . $type;
$function($edit, $account);
}
}
/**
* Implements hook_theme().
*/
function user_theme() {
$base = array(
'file' => 'user.theme.inc',
);
return array(
'user_picture' => array(
'variables' => array('account' => NULL),
'template' => 'templates/user-picture',
) + $base,
'user_profile' => array(
'render element' => 'elements',
'template' => 'templates/user-profile',
) + $base,
'user_list' => array(
'variables' => array('users' => NULL, 'title' => NULL),
) + $base,
'user_admin_permissions' => array(
'render element' => 'form',
) + $base,
'user_admin_roles' => array(
'render element' => 'form',
) + $base,
'user_permission_description' => array(
'variables' => array('permission_item' => NULL),
) + $base,
'user_signature' => array(
'variables' => array('signature' => NULL),
) + $base,
'username' => array(
'variables' => array('account' => NULL),
) + $base,
);
}
/**
* Implements hook_entity_info().
*/
function user_entity_info() {
$entity_info = array(
'user' => array(
'label' => t('User account'),
'bundle label' => t('Type'),
'controller class' => 'UserStorageController',
'base table' => 'users',
'fieldable' => TRUE,
'redirect support' => TRUE,
'entity class' => 'User',
'entity keys' => array(
'id' => 'uid',
),
'bundles' => array(
'user' => array(
'label' => t('User account'),
'admin' => array(
'path' => 'admin/config/people/manage',
'access arguments' => array('administer account settings'),
),
),
),
'view modes' => array(
'full' => array(
'label' => t('User account'),
'custom settings' => FALSE,
),
'token' => array(
'label' => t('Tokens'),
'custom settings' => FALSE,
),
),
),
);
// If the cache table has been created, then enable entity caching on nodes.
if (db_table_exists('cache_entity_user')) {
$entity_info['user']['entity cache'] = TRUE;
$entity_info['user']['field cache'] = FALSE;
}
return $entity_info;
}
/**
* Implements hook_layout_context_info().
*/
function user_layout_context_info() {
$info['user'] = array(
'title' => t('User account'),
// Define the class which is used to handle this context.
'class' => 'EntityLayoutContext',
// Define menu paths where the user ID is a "known" context.
'menu paths' => array(
'user/%user',
'user/%user/view',
'user/%user/edit',
),
// Given the menu paths defined above, identify the part of the path that
// is needed to generate this context.
'path placeholder' => '%user',
// Given an argument, define the callback that will be responsible for
// loading the main context data.
'load callback' => 'user_load',
);
return $info;
}
/**
* Implements hook_field_info_alter().
*/
function user_field_info_alter(&$info) {
// Add the 'user_register_form' instance setting to all field types.
foreach ($info as $field_type => &$field_type_info) {
$field_type_info += array('instance_settings' => array());
$field_type_info['instance_settings'] += array(
'user_register_form' => FALSE,
);
}
}
/**
* Implements hook_field_extra_fields().
*/
function user_field_extra_fields() {
$return['user']['user'] = array(
'form' => array(
'account' => array(
'label' => t('User name and password'),
'description' => t('User module account form elements.'),
'weight' => -10,
),
'account_settings' => array(
'label' => t('Account status and user roles'),
'description' => t('User module account settings form elements.'),
'weight' => 1,
),
'timezone' => array(
'label' => t('Timezone'),
'description' => t('User module timezone form element.'),
'weight' => 6,
),
),
'display' => array(
'member_for' => array(
'label' => t('Member for'),
'description' => t('User module \'member for\' view element.'),
'weight' => 5,
),
),
);
return $return;
}
/**
* Load 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 $uids
* An array of user IDs.
* @param $conditions
* (deprecated) An associative array of conditions on the {users}
* table, where the keys are the database fields and the values are the
* values those fields must have. Instead, it is preferable to use
* EntityFieldQuery to retrieve a list of entity IDs loadable by
* this function.
* @param $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
* An array of user objects, indexed by uid.
*
* @see entity_load()
* @see user_load()
* @see user_load_by_mail()
* @see user_load_by_name()
* @see EntityFieldQuery
*
* @todo Remove $conditions for consistency with other loaders.
*/
function user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) {
return entity_load('user', $uids, $conditions, $reset);
}
/**
* Loads a user object.
*
* Backdrop 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 backdrop_save_session(FALSE); first.
* See
* @link http://drupal.org/node/218104 Safely impersonating another user @endlink
* for more information.
*
* @param $uid
* Integer specifying the user ID to load.
* @param $reset
* TRUE to reset the internal cache and load from the database; FALSE
* (default) to load from the internal cache, if set.
*
* @return
* A fully-loaded user object upon successful user load, or FALSE if the user
* cannot be loaded.
*
* @see user_load_multiple()
*/
function user_load($uid, $reset = FALSE) {
$users = user_load_multiple(array($uid), array(), $reset);
return reset($users);
}
/**
* Fetch a user object by email address.
*
* @param $mail
* String with the account's email address.
* @return
* 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 = user_load_multiple(array(), array('mail' => $mail));
return reset($users);
}
/**
* Fetch a user object by account name.
*
* @param $name
* String with the account's user name.
* @return
* 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 = user_load_multiple(array(), array('name' => $name));
return reset($users);
}
/**
* Save a new or updated user.
*
* @param User $account
* The user entity object to add or modify.
* @return int
* Either SAVED_NEW or SAVED_UPDATED depending on the operation performed.
*
* @see entity_create()
* @see user_load()
*/
function user_save($account) {
return $account->save();
}
/**
* Element validate handler for the password field.
*
* Set a default value if one-time login link goes out,
* set a form error if not and password value is empty.
*/
function user_pass_required_validate($element, &$form_state, $form) {
$values = $form_state['values'];
if ($values['notify'] == 1) {
$form_state['values']['pass'] = user_password(22);
}
else {
if (empty($values['pass']) && $values['pass'] !== '0') {
$message = t('!name field is required.', array('!name' => $element['#title']));
form_set_error('pass', $message);
}
}
}
/**
* 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.');
}
// cspell:disable
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.
// cspell:enable
$name)) {
return t('The username contains an illegal character.');
}
if (backdrop_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));
}
}
/**
* Validates an image uploaded by a user.
*
* @see user_account_form()
*/
function user_validate_picture(&$form, &$form_state) {
$site_config = config('system.core');
// If required, validate the uploaded picture.
$validators = array(
'file_validate_is_image' => array(),
'file_validate_image_orientation' => array(TRUE),
'file_validate_image_resolution' => array($site_config->get('user_picture_dimensions')),
'file_validate_size' => array((int) $site_config->get('user_picture_file_size') * 1024),
);
// Save the file as a temporary file.
$file = file_save_upload('picture_upload', $validators);
if ($file === FALSE) {
form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => $site_config->get('user_picture_path'))));
}
elseif ($file !== NULL) {
$form_state['values']['picture_upload'] = $file;
}
}
/**
* 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(backdrop_random_bytes(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;
}
/**
* Checks if a user role has a permission.
*
* @param string $role_name
* The role machine name.
* @param string $permission_name
* The permission to check.
*
* @return bool
* TRUE if the role has the permission, FALSE if it does not have the
* permission.
*
* @since 1.26.0 Function added
*/
function user_role_has_permission($role_name, $permission_name) {
$role = user_role_load($role_name);
return $role ? in_array($permission_name, $role->permissions) : FALSE;
}
/**
* Determine the permissions for one or more roles.
*
* @param $role_names
* An unindexed array of role names, such as those in $user->roles.
*
* @return
* An array of permission strings for all the given role names.
*/
function user_role_permissions($role_names = array()) {
$all_roles = user_roles(FALSE, NULL, TRUE);
$role_permissions = array();
foreach ($role_names as $role_name) {
if (isset($all_roles[$role_name])) {
foreach ($all_roles[$role_name]->permissions as $permission) {
if (!in_array($permission, $role_permissions)) {
$role_permissions[] = $permission;
}
}
}
}
return $role_permissions;
}
/**
* Determine whether the user has a given privilege.
*
* @param $string
* The permission, such as "administer nodes", being checked for.
* @param $account
* (optional) The account to check, if not given use currently logged in user.
*
* @return
* Boolean TRUE if the user has the requested permission.
*
* All permission checks in Backdrop should go through this function. This
* way, we guarantee consistent behavior, and ensure that the superuser
* can perform all actions.
*/
function user_access($permission_name, $account = NULL) {
global $user;
if (!isset($account)) {
$account = $user;
}
// User #1 has all privileges:
if ($account->uid == 1) {
return TRUE;
}
// To reduce the number of SQL queries, we cache the user's permissions
// in a static variable.
// Use the advanced backdrop_static() pattern, since this is called very often.
static $backdrop_static_fast;
if (!isset($backdrop_static_fast)) {
$backdrop_static_fast['perm'] = &backdrop_static(__FUNCTION__);
}
$perm = &$backdrop_static_fast['perm'];
if (!isset($perm[$account->uid])) {
$perm[$account->uid] = user_role_permissions($account->roles);
}
return in_array($permission_name, $perm[$account->uid]);
}
/**
* 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();
}
/**
* Checks if a user has a role.
*
* @param string $role_name
* A string representing the role name.
* @param User $account
* (optional) A user account. Defaults to the current user.
*
* @return bool
* TRUE or FALSE.
*
* @since 1.14.0 First parameter changed from $rid to $role_name.
*/
function user_has_role($role_name, $account = NULL) {
if (!$account) {
$account = $GLOBALS['user'];
}
return in_array($role_name, $account->roles);
}
/**
* Implements hook_permission().
*/
function user_permission() {
return array(
'administer permissions' => array(
'title' => t('Administer permissions'),
'restrict access' => TRUE,
'warning' => t('Grant any permission to any user role.'),
),
'administer users' => array(
'title' => t('Administer user accounts'),
'restrict access' => TRUE,
'warning' => t('Create, edit and delete user accounts.'),
),
'assign roles' => array(
'title' => t('Assign user roles'),
'restrict access' => TRUE,
'warning' => t('Assign any user role to any user account.'),
),
'administer account settings' => array(
'title' => t('Administer user account settings'),
'description' => t('Manage settings that apply to all user accounts.'),
'restrict access' => TRUE,
'warning' => t('Change the way user account registrations work, potentially avoiding administrator approval.'),
),
'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_get_translated('system.core', 'anonymous'), '@user-settings-url' => url('admin/config/people/settings'))),
),
'select account cancellation method' => array(
'title' => t('Select method for cancelling own account'),
'restrict access' => TRUE,
'warning' => t('Allows people to choose to permanently delete their user account and all content created by them (potential for irreversible data loss).'),
),
);
}
/**
* Implements hook_config_info().
*/
function user_config_info() {
$prefixes['user.flood'] = array(
'label' => t('User flood'),
'group' => t('Configuration'),
);
$prefixes['user.mail'] = array(
'label' => t('User email templates'),
'group' => t('Configuration'),
);
$prefixes['user.role'] = array(
'name_key' => 'name',
'label_key' => 'label',
'group' => t('User roles'),
);
return $prefixes;
}
/**
* Implements hook_views_api().
*/
function user_views_api() {
return array(
'api' => '3.0',
'path' => backdrop_get_path('module', 'user') . '/views',
);
}
/**
* Implements hook_file_download().
*
* Ensure that user pictures (avatars) are always downloadable.
*/
function user_file_download($uri) {
if (strpos(file_uri_target($uri), config_get('system.core', 'user_picture_path') . '/picture-') === 0) {
$info = image_get_info($uri);
return array('Content-Type' => $info['mime_type']);
}
}
/**
* Implements hook_file_move().
*/
function user_file_move(File $file, File $source) {
// If a user's picture is replaced with a new one, update the record in
// the users table.
if (isset($file->fid) && isset($source->fid) && $file->fid != $source->fid) {
db_update('users')
->fields(array(
'picture' => $file->fid,
))
->condition('picture', $source->fid)
->execute();
}
}
/**
* Implements hook_file_predelete().
*/
function user_file_predelete(File $file) {
// Remove any references to the file.
db_update('users')
->fields(array('picture' => 0))
->condition('picture', $file->fid)
->execute();
}
/**
* Implements hook_search_info().
*/
function user_search_info() {
return array(
'title' => 'User accounts',
);
}
/**
* 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) {
$find = array();
// Escape for LIKE matching.
$keys = db_like($keys);
// Replace wildcards with MySQL wildcards.
$keys = preg_replace('!\*+!', '%', $keys);
$query = db_select('users')->extend('PagerDefault');
$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', '%' . $keys . '%', 'LIKE')->
condition('mail', '%' . $keys . '%', 'LIKE'));
}
else {
// Regular users can only search via usernames, and we do not show them
// blocked accounts.
$query->condition('name', '%' . $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->uid, array('absolute' => TRUE)),
);
if (user_access('administer users')) {
$result['title'] .= ' (' . $account->mail . ')';
}
$results[] = $result;
}
return $results;
}
/**
* Implements hook_user_view().
*/
function user_user_view($account) {
$account->content['user_picture'] = array(
'#markup' => theme('user_picture', array('account' => $account)),
'#weight' => -10,
);
$account->content['member_for'] = array(
'#type' => 'item',
'#title' => t('Member for'),
'#markup' => format_interval(REQUEST_TIME - $account->created),
'#weight' => 5,
);
}
/**
* Helper function to add default user account fields to user registration and edit form.
*
* @see user_account_form_validate()
* @see user_validate_current_pass()
* @see user_validate_picture()
* @see user_validate_mail()
* @see user_password_policy_validate()
*/
function user_account_form(&$form, &$form_state) {
global $user;
$site_config = config('system.core');
$account = $form['#user'];
$register = ($form['#user']->uid > 0 ? FALSE : TRUE);
$admin_users = user_access('administer users');
$admin_roles = user_access('assign roles');
$form['#validate'][] = 'user_account_form_validate';
module_load_include('password.inc', 'user', 'user');
$reject_weak = user_password_reject_weak($user->name);
if ($reject_weak) {
$form['#validate'][] = 'user_password_policy_validate';
}
// Account information.
$form['account'] = array(
'#type' => 'container',
'#weight' => -10,
);
// Only show name field on registration form or user can change own username.
$form['account']['name'] = array(
'#type' => 'textfield',
'#title' => t('Username'),
'#maxlength' => USERNAME_MAX_LENGTH,
'#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
'#required' => TRUE,
'#attributes' => array(
'class' => array('username'),
// Add attributes to field to prevent spell-jacking and unwanted
// automatic changes caused by the browser.
'autocapitalize' => 'none',
'autocorrect' => 'off',
'spellcheck' => 'false',
),
'#default_value' => (!$register ? $account->name : ''),
'#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin_users),
'#weight' => -10,
);
// Autofocus the username field (on the registration form only).
if ($register) {
$form['account']['name']['#attributes']['autofocus'] = 'autofocus';
}
$form['account']['mail'] = array(
'#type' => 'email',
'#title' => t('Email address'),
'#description' => t('A valid email address. All emails from the system will be sent to this address. The email address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by email.'),
'#required' => TRUE,
'#default_value' => (!$register ? $account->mail : ''),
'#attributes' => array(
// Add attributes to field to prevent spell-jacking and unwanted
// automatic changes caused by the browser.
'autocapitalize' => 'none',
'autocorrect' => 'off',
'spellcheck' => 'false',
),
);
// Display password field only for existing users or when user is allowed to
// assign a password during registration.
if (!$register) {
$form['account']['pass'] = array(
'#title' => t('New password'),
'#type' => 'password',
'#password_toggle' => TRUE,
'#password_strength' => TRUE,
);
// To skip the current password field, the user must have logged in via a
// one-time link and have the token in the URL. Store this in $form_state
// so it persists even on subsequent Ajax requests.
if (!isset($form_state['user_pass_reset'])) {
$form_state['user_pass_reset'] = isset($_SESSION['pass_reset_' . $account->uid]) && isset($_GET['pass-reset-token']) && ($_GET['pass-reset-token'] == $_SESSION['pass_reset_' . $account->uid]);
}
$protected_values = array();
$current_pass_description = '';
// The user may only change their own password without their current
// password if they logged in via a one-time login link.
if (!$form_state['user_pass_reset']) {
$protected_values['mail'] = $form['account']['mail']['#title'];
$protected_values['pass'] = t('Password');
$request_new = l(t('Reset password'), 'user/password', array('attributes' => array('title' => t('Reset password via one-time login link.'))));
$current_pass_description = t('Required if you want to change the %mail or %pass below. !request_new.', array('%mail' => $protected_values['mail'], '%pass' => $protected_values['pass'], '!request_new' => $request_new));
}
// The user must enter their current password to change to a new one.
if ($user->uid == $account->uid) {
$form['account']['current_pass_required_values'] = array(
'#type' => 'value',
'#value' => $protected_values,
);
$form['account']['current_pass'] = array(
'#type' => 'password',
'#title' => t('Current password'),
'#access' => !empty($protected_values),
'#description' => $current_pass_description,
'#weight' => -5,
'#password_toggle' => TRUE,
// Do not let web browsers remember this password, since we are
// trying to confirm that the person submitting the form actually
// knows the current one.
'#attributes' => array('autocomplete' => 'off'),
);
$form['#validate'][] = 'user_validate_current_pass';
}
}
else {
if (!$site_config->get('user_email_verification') && !$admin_users) {
// Someone registers a new account and may set a password directly.
$form['account']['pass'] = array(
'#type' => 'password',
'#title' => t('Password'),
'#password_toggle' => TRUE,
'#password_strength' => TRUE,
'#required' => TRUE,
);
}
if ($admin_users) {
// An admin creates an account.
$form['account']['notify'] = array(
'#type' => 'checkbox',
'#title' => t('Notify user of new account'),
'#default_value' => 1,
'#description' => t('The user will receive an email with a one-time login link which leads to a page where they can set their password.'),
);
$form['account']['pass'] = array(
'#type' => 'password',
'#title' => t('Password'),
'#password_toggle' => TRUE,
'#password_strength' => TRUE,
'#required' => FALSE,
'#element_validate' => array('user_pass_required_validate'),
'#states' => array(
'visible' => array(
':input[name="notify"]' => array('checked' => FALSE),
),
'required' => array(
':input[name="notify"]' => array('checked' => FALSE),
),
),
);
}
}
$description = !$register && $user->uid == $account->uid ? t('The current password must be entered to set a new password.') : '';
// If weak passwords are being rejected, append the list of password strength
// criteria to the help text of the password field.
if ($reject_weak) {
$description .= !empty($description) ? '<br /><br />' : '';
$description .= _user_password_policy_help();
}
$form['account']['pass']['#description'] = $description;
$form['additional_settings'] = array(
'#type' => 'vertical_tabs',
'#weight' => 99,
'#attached' => array(
'js' => array(backdrop_get_path('module', 'user') . '/js/user.admin.js'),
),
);
$form['account_settings'] = array(
'#type' => 'fieldset',
'#title' => t('Account settings'),
'#weight' => 1,
'#access' => $admin_users || $admin_roles,
'#group' => 'additional_settings',
);
if ($admin_users) {
$status = isset($account->status) ? $account->status : 1;
}
else {
$status = $register ? $site_config->get('user_register') == USER_REGISTER_VISITORS : $account->status;
}
$form['account_settings']['status'] = array(
'#type' => 'radios',
'#title' => t('Status'),
'#default_value' => $status,
'#options' => array(t('Blocked'), t('Active')),
'#access' => $admin_users,
);
$roles = user_roles(TRUE, NULL, TRUE);
$form['account_settings']['roles'] = array(
'#type' => 'checkboxes',
'#title' => t('Roles'),
'#default_value' => (!$register && isset($account->roles) ? $account->roles : array()),
'#options' => array(),
'#access' => count($roles) && $admin_roles,
);
// Lock the authenticated role, which cannot be removed.
$form['account_settings']['roles'][BACKDROP_AUTHENTICATED_ROLE] = array(
'#disabled' => TRUE,
'#value' => 'authenticated',
);
// Add each role as a checkbox option with a description.
foreach ($roles as $role_name => $role) {
$form['account_settings']['roles']['#options'][$role_name] = $role->label;
if (strlen($role->description)) {
$form['account_settings']['roles'][$role_name]['#description'] = filter_xss_admin($role->description);
}
}
$form['personalization'] = array(
'#type' => 'fieldset',
'#title' => t('Personalization'),
'#weight' => 2,
'#access' => (!$register && ($site_config->get('user_signatures') || $site_config->get('user_pictures'))),
'#group' => 'additional_settings',
);
// Signature.
if ($site_config->get('user_signatures')) {
$form['personalization']['signature'] = array(
'#type' => 'text_format',
'#title' => t('Signature'),