This repository has been archived by the owner on May 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
user.module
3303 lines (2966 loc) · 114 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
// $Id: user.module,v 1.1102 2010-01-11 16:25:16 webchick Exp $
/**
* @file
* Enables the user registration and login system.
*/
/**
* Maximum length of username text field.
*/
define('USERNAME_MAX_LENGTH', 60);
/**
* Maximum length of user e-mail text field.
*/
define('EMAIL_MAX_LENGTH', 254);
/**
* Implement hook_help().
*/
function user_help($path, $arg) {
global $user;
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/handbook/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/config/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/config/people/permissions'), '@roles' => url('admin/config/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 user pictures), 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/config/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/config/people/roles'), '@settings' => url('admin/config/people/accounts'))) . '</p>';
case 'admin/config/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 in <a href="@permissions">user permissions</a>. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the <em>role names</em> of the various roles. To delete a role choose "edit".', array('@permissions' => url('admin/config/people/permissions'))) . '</p>';
$output .= '<p>'. t('By default, Drupal comes with two 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 .= '</ul>';
return $output;
case 'admin/config/people/accounts/fields':
return '<p>' . t('This form lets administrators add, edit, and arrange fields for storing user data.') . '</p>';
case 'admin/config/people/accounts/display':
return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
case 'admin/people/search':
return '<p>' . t('Enter a simple pattern ("*" may be used as a wildcard match) to search for a username or e-mail address. For example, one may search for "br" and Drupal might return "brian", "brad", and "brenda@example.com".') . '</p>';
}
}
/**
* Invokes hook_user() in every module.
*
* We cannot use module_invoke() for this, because the arguments need to
* be passed by reference.
*/
function user_module_invoke($type, &$edit, $account, $category = NULL) {
foreach (module_implements('user_' . $type) as $module) {
$function = $module . '_user_' . $type;
$function($edit, $account, $category);
}
}
/**
* Implements hook_theme().
*/
function user_theme() {
return array(
'user_picture' => array(
'variables' => array('account' => NULL),
'template' => 'user-picture',
),
'user_profile' => array(
'render element' => 'elements',
'template' => 'user-profile',
'file' => 'user.pages.inc',
),
'user_profile_category' => array(
'render element' => 'element',
'template' => 'user-profile-category',
'file' => 'user.pages.inc',
),
'user_profile_item' => array(
'render element' => 'element',
'template' => 'user-profile-item',
'file' => 'user.pages.inc',
),
'user_list' => array(
'variables' => array('users' => NULL, 'title' => NULL),
),
'user_admin_permissions' => array(
'render element' => 'form',
'file' => 'user.admin.inc',
),
'user_admin_new_role' => array(
'render element' => 'form',
'file' => 'user.admin.inc',
),
'user_filters' => array(
'render element' => 'form',
'file' => 'user.admin.inc',
),
'user_signature' => array(
'variables' => array('signature' => NULL),
),
);
}
/**
* Implements hook_entity_info().
*/
function user_entity_info() {
$return = array(
'user' => array(
'label' => t('User'),
'controller class' => 'UserController',
'base table' => 'users',
'fieldable' => TRUE,
'object keys' => array(
'id' => 'uid',
),
'bundles' => array(
'user' => array(
'label' => t('User'),
'admin' => array(
'path' => 'admin/config/people/accounts',
'access arguments' => array('administer users'),
),
),
),
'view modes' => array(
'full' => array(
'label' => t('User account'),
),
),
),
);
return $return;
}
/**
* Implements hook_field_extra_fields().
*/
function user_field_extra_fields() {
$return['user']['user'] = array(
'account' => array(
'label' => 'User name and password',
'description' => t('User module account form elements'),
'weight' => -10,
),
'timezone' => array(
'label' => 'Timezone',
'description' => t('User module timezone form element.'),
'weight' => 6,
),
'summary' => array(
'label' => 'History',
'description' => t('User module history view element.'),
'weight' => 5,
),
);
return $return;
}
function user_external_load($authname) {
$uid = db_query("SELECT uid FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchField();
if ($uid) {
return user_load($uid);
}
else {
return FALSE;
}
}
/**
* 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
* An array of conditions to match against the {users} table. These
* should be supplied in the form array('field_name' => 'field_value').
* @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()
*/
function user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) {
return entity_load('user', $uids, $conditions, $reset);
}
/**
* Controller class for users.
*
* This extends the DrupalDefaultEntityController class, adding required
* special handling for user objects.
*/
class UserController extends DrupalDefaultEntityController {
function attachLoad(&$queried_users) {
// Build an array of user picture IDs so that these can be fetched later.
$picture_fids = array();
foreach ($queried_users as $key => $record) {
$picture_fids[] = $record->picture;
$queried_users[$key] = drupal_unpack($record);
$queried_users[$key]->roles = array();
if ($record->uid) {
$queried_users[$record->uid]->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
}
else {
$queried_users[$record->uid]->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
}
}
// Add any additional roles from the database.
$result = db_query('SELECT r.rid, r.name, ur.uid FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid IN (:uids)', array(':uids' => array_keys($queried_users)));
foreach ($result as $record) {
$queried_users[$record->uid]->roles[$record->rid] = $record->name;
}
// Add the full file objects for user pictures if enabled.
if (!empty($picture_fids) && variable_get('user_pictures', 1) == 1) {
$pictures = file_load_multiple($picture_fids);
foreach ($queried_users as $account) {
if (!empty($account->picture) && isset($pictures[$account->picture])) {
$account->picture = $pictures[$account->picture];
}
else {
$account->picture = NULL;
}
}
}
// Call the default attachLoad() method. This will add fields and call
// hook_user_load().
parent::attachLoad($queried_users);
}
}
/**
* Fetch a user object.
*
* @param $uid
* Integer specifying the user id.
* @param $reset
* A boolean indicating that the internal cache should be reset.
* @return
* A fully-loaded $user object upon successful user load or FALSE if 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 e-mail 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 changes to a user account or add a new user.
*
* @param $account
* (optional) The user object to modify or add. If you want to modify
* an existing user account, you will need to ensure that (a) $account
* is an object, and (b) you have set $account->uid to the numeric
* user ID of the user account you wish to modify. If you
* want to create a new user account, you can set $account->is_new to
* TRUE or omit the $account->uid field.
* @param $edit
* An array of fields and values to save. For example array('name'
* => 'My name'). Keys that do not belong to columns in the user-related
* tables are added to the a serialized array in the 'data' column
* and will be loaded in the $user->data array by user_load().
* Setting a field to NULL deletes it from the data column, if you are
* modifying an existing user account.
* @param $category
* (optional) The category for storing profile information in.
*
* @return
* A fully-loaded $user object upon successful save or FALSE if the save failed.
*/
function user_save($account, $edit = array(), $category = 'account') {
$transaction = db_transaction();
try {
$table = drupal_get_schema('users');
$user_fields = $table['fields'];
if (!empty($edit['pass'])) {
// Allow alternate password hashing schemes.
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
$edit['pass'] = user_hash_password(trim($edit['pass']));
// Abort if the hashing failed and returned FALSE.
if (!$edit['pass']) {
return FALSE;
}
}
else {
// Avoid overwriting an existing password with a blank password.
unset($edit['pass']);
}
// Get the fields form so we can recognize the fields in the $edit
// form that should not go into the serialized data array.
$field_form = array();
$field_form_state = array();
$edit = (object) $edit;
field_attach_form('user', $edit, $field_form, $field_form_state);
// Presave fields.
field_attach_presave('user', $edit);
$edit = (array) $edit;
if (!isset($account->is_new)) {
$account->is_new = empty($account->uid);
}
user_module_invoke('presave', $edit, $account, $category);
if (is_object($account) && !$account->is_new) {
$data = unserialize(db_query('SELECT data FROM {users} WHERE uid = :uid', array(':uid' => $account->uid))->fetchField());
// Consider users edited by an administrator as logged in, if they haven't
// already, so anonymous users can view the profile (if allowed).
if (empty($edit['access']) && empty($account->access) && user_access('administer users')) {
$edit['access'] = REQUEST_TIME;
}
foreach ($edit as $key => $value) {
// Form fields that don't pertain to the users, user_roles, or
// Field API are automatically serialized into the users.data
// column.
if (!in_array($key, array('roles', 'is_new')) && empty($user_fields[$key]) && empty($field_form[$key])) {
if ($value === NULL) {
unset($data[$key]);
}
else {
$data[$key] = $value;
}
}
}
// Process picture uploads.
if (!empty($edit['picture']->fid)) {
$picture = $edit['picture'];
// If the picture is a temporary file move it to its final location and
// make it permanent.
if (($picture->status & FILE_STATUS_PERMANENT) == 0) {
$info = image_get_info($picture->uri);
$picture_directory = variable_get('file_default_scheme', 'public') . '://' . variable_get('user_picture_path', 'pictures');
// Prepare the pictures directory.
file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY);
$destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '.' . $info['extension']);
if ($picture = file_move($picture, $destination, FILE_EXISTS_REPLACE)) {
$picture->status |= FILE_STATUS_PERMANENT;
$edit['picture'] = file_save($picture);
}
}
}
$edit['picture'] = empty($edit['picture']->fid) ? 0 : $edit['picture']->fid;
$edit['data'] = $data;
// Do not allow 'uid' to be changed.
$edit['uid'] = $account->uid;
// Save changes to the user table.
$success = drupal_write_record('users', $edit, 'uid');
if ($success === FALSE) {
// The query failed - better to abort the save than risk further
// data loss.
return FALSE;
}
// If the picture changed or was unset, remove the old one. This step needs
// to occur after updating the {users} record so that user_file_references()
// doesn't report it in use and block the deletion.
if (!empty($account->picture->fid) && ($edit['picture'] != $account->picture->fid)) {
file_delete($account->picture);
}
// Reload user roles if provided.
if (isset($edit['roles']) && is_array($edit['roles'])) {
db_delete('users_roles')
->condition('uid', $account->uid)
->execute();
$query = db_insert('users_roles')->fields(array('uid', 'rid'));
foreach (array_keys($edit['roles']) as $rid) {
if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
$query->values(array(
'uid' => $account->uid,
'rid' => $rid,
));
}
}
$query->execute();
}
// Delete a blocked user's sessions to kick them if they are online.
if (isset($edit['status']) && $edit['status'] == 0) {
drupal_session_destroy_uid($account->uid);
}
// If the password changed, delete all open sessions and recreate
// the current one.
if (!empty($edit['pass'])) {
drupal_session_destroy_uid($account->uid);
if ($account->uid == $GLOBALS['user']->uid) {
drupal_session_regenerate();
}
}
// Save Field data.
$object = (object) $edit;
field_attach_update('user', $object);
// Refresh user object.
$user = user_load($account->uid, TRUE);
// Send emails after we have the new user object.
if (isset($edit['status']) && $edit['status'] != $account->status) {
// The user's status is changing; conditionally send notification email.
$op = $edit['status'] == 1 ? 'status_activated' : 'status_blocked';
_user_mail_notify($op, $user);
}
user_module_invoke('update', $edit, $user, $category);
}
else {
// Allow 'uid' to be set by the caller. There is no danger of writing an
// existing user as drupal_write_record will do an INSERT.
if (empty($edit['uid'])) {
$edit['uid'] = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
}
// Allow 'created' to be set by the caller.
if (!isset($edit['created'])) {
$edit['created'] = REQUEST_TIME;
}
// Consider users created by an administrator as already logged in, so
// anonymous users can view the profile (if allowed).
if (empty($edit['access']) && user_access('administer users')) {
$edit['access'] = REQUEST_TIME;
}
$edit['mail'] = trim($edit['mail']);
$success = drupal_write_record('users', $edit);
if ($success === FALSE) {
// On a failed INSERT some other existing user's uid may be returned.
// We must abort to avoid overwriting their account.
return FALSE;
}
// Build the initial user object.
$user = user_load($edit['uid'], TRUE);
$object = (object) $edit;
field_attach_insert('user', $object);
user_module_invoke('insert', $edit, $user, $category);
// Note, we wait with saving the data column to prevent module-handled
// fields from being saved there.
$data = array();
foreach ($edit as $key => $value) {
// Form fields that don't pertain to the users, user_roles, or
// Field API are automatically serialized into the user.data
// column.
if ((!in_array($key, array('roles', 'is_new'))) && (empty($user_fields[$key]) && empty($field_form[$key])) && ($value !== NULL)) {
$data[$key] = $value;
}
}
if (!empty($data)) {
$data_array = array('uid' => $user->uid, 'data' => $data);
drupal_write_record('users', $data_array, 'uid');
}
// Save user roles (delete just to be safe).
if (isset($edit['roles']) && is_array($edit['roles'])) {
db_delete('users_roles')
->condition('uid', $edit['uid'])
->execute();
$query = db_insert('users_roles')->fields(array('uid', 'rid'));
foreach (array_keys($edit['roles']) as $rid) {
if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
$query->values(array(
'uid' => $edit['uid'],
'rid' => $rid,
));
}
}
$query->execute();
}
// Build the finished user object.
$user = user_load($edit['uid'], TRUE);
}
return $user;
}
catch (Exception $e) {
$transaction->rollback('user', $e->getMessage(), array(), WATCHDOG_ERROR);
}
}
/**
* 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));
}
}
function user_validate_mail($mail) {
$mail = trim($mail);
if (!$mail) {
return t('You must enter an e-mail address.');
}
if (!valid_email_address($mail)) {
return t('The e-mail address %mail is not valid.', array('%mail' => $mail));
}
}
function user_validate_picture(&$form, &$form_state) {
// If required, validate the uploaded picture.
$validators = array(
'file_validate_is_image' => array(),
'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 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' => variable_get('user_picture_path', 'pictures'))));
}
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++) {
// 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 $roles
* An array whose keys are the role IDs of interest, such as $user->roles.
*
* @return
* An array indexed by role ID. Each value is an array whose keys are the
* permission strings for the given role ID.
*/
function user_role_permissions($roles = array()) {
$cache = &drupal_static(__FUNCTION__, array());
$role_permissions = $fetch = array();
if ($roles) {
foreach ($roles as $rid => $name) {
if (isset($cache[$rid])) {
$role_permissions[$rid] = $cache[$rid];
}
else {
// Add this rid to the list of those needing to be fetched.
$fetch[] = $rid;
// Prepare in case no permissions are returned.
$cache[$rid] = array();
}
}
if ($fetch) {
// Get from the database permissions that were not in the static variable.
// Only role IDs with at least one permission assigned will return rows.
$result = db_query("SELECT rid, permission FROM {role_permission} WHERE rid IN (:fetch)", array(':fetch' => $fetch));
foreach ($result as $row) {
$cache[$row->rid][$row->permission] = TRUE;
}
foreach ($fetch as $rid) {
// For every rid, we know we at least assigned an empty array.
$role_permissions[$rid] = $cache[$rid];
}
}
}
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 current user has the requested permission.
*
* All permission checks in Drupal should go through this function. This
* way, we guarantee consistent behavior, and ensure that the superuser
* can perform all actions.
*/
function user_access($string, $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 drupal_static() pattern, since this is called very often.
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
$drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
}
$perm = &$drupal_static_fast['perm'];
if (!isset($perm[$account->uid])) {
$role_permissions = user_role_permissions($account->roles);
$perms = array();
foreach ($role_permissions as $one_role) {
$perms += $one_role;
}
$perm[$account->uid] = $perms;
}
return isset($perm[$account->uid][$string]);
}
/**
* Checks for usernames blocked by user administration.
*
* @return boolean TRUE for blocked users, FALSE for active.
*/
function user_is_blocked($name) {
$deny = db_query("SELECT name FROM {users} WHERE status = 0 AND name = LOWER(:name)", array(':name' => $name))->fetchObject();
return $deny;
}
/**
* Implements hook_permission().
*/
function user_permission() {
return array(
'administer permissions' => array(
'title' => t('Administer permissions'),
'description' => drupal_placeholder(array('text' => t('Warning: Give to trusted roles only; this permission has security implications.'))),
),
'administer users' => array(
'title' => t('Administer users'),
'description' => drupal_placeholder(array('text' => t('Warning: Give to trusted roles only; this permission has security implications.'))),
),
'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 transfered to the %anonymous-name user depending on the configured <a href="@user-settings-url">user settings</a>.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')), '@user-settings-url' => url('admin/config/people/accounts'))),
),
'select account cancellation method' => array(
'title' => t('Select method for cancelling own account'),
'description' => drupal_placeholder(array('text' => t('Warning: Give to trusted roles only; this permission has security implications.'))),
),
);
}
/**
* Implements hook_file_download().
*
* Ensure that user pictures (avatars) are always downloadable.
*/
function user_file_download($uri) {
if (strpos(file_uri_target($uri), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) {
$info = image_get_info($uri);
return array('Content-Type' => $info['mime_type']);
}
}
/**
* Implements hook_file_references().
*/
function user_file_references($file) {
// Determine if the file is used by this module.
$file_used = (bool) db_query_range('SELECT 1 FROM {users} WHERE picture = :fid', 0, 1, array(':fid' => $file->fid))->fetchField();
if ($file_used) {
// Return the name of the module and how many references it has to the file.
return array('user' => $count);
}
}
/**
* Implements hook_file_delete().
*/
function user_file_delete($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' => '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) {
$find = array();
// Replace wildcards with MySQL/PostgreSQL wildcards.
$keys = preg_replace('!\*+!', '%', $keys);
$query = db_select('users')->extend('PagerDefault');
$query->fields('users', array('name', 'uid', 'mail'));
if (user_access('administer users')) {
// Administrators can also search in the otherwise private email field.
$query->condition(db_or()->
where('LOWER(name) LIKE LOWER(:name)', array(':name' => "%$keys%"))->
where('LOWER(mail) LIKE LOWER(:mail)', array(':mail' => "%$keys%")));
}
else {
$query->where('LOWER(name) LIKE LOWER(:name)', array(':name' => "%$keys%"));
}
$result = $query
->limit(15)
->execute();
foreach ($result as $account) {
$find[] = array('title' => $account->name . ' (' . $account->mail . ')', 'link' => url('user/' . $account->uid, array('absolute' => TRUE)));
}
return $find;
}
/**
* Implements hook_element_info().
*/
function user_element_info() {
$types['user_profile_category'] = array(
'#theme_wrappers' => array('user_profile_category'),
);
$types['user_profile_item'] = array(
'#theme' => 'user_profile_item',
);
return $types;
}
/**
* Implements hook_user_view().
*/
function user_user_view($account) {
$account->content['user_picture'] = array(
'#markup' => theme('user_picture', array('account' => $account)),
'#weight' => -10,
);
if (!isset($account->content['summary'])) {
$account->content['summary'] = array();
}
$account->content['summary'] += array(
'#type' => 'user_profile_category',
'#attributes' => array('class' => array('user-member')),
'#weight' => 5,
'#title' => t('History'),
);
$account->content['summary']['member_for'] = array(
'#type' => 'user_profile_item',
'#title' => t('Member for'),
'#markup' => format_interval(REQUEST_TIME - $account->created),
);
}
/**
* Helper function to add default user account fields to user registration and edit form.
*/
function user_account_form(&$form, &$form_state) {
global $user;
$account = $form['#user'];
$register = ($form['#user']->uid > 0 ? FALSE : TRUE);
$admin = user_access('administer users');
$form['#validate'][] = 'user_account_form_validate';
// Account information.
$form['account'] = array(
'#type' => 'fieldset',
'#title' => t('Account information'),
'#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')),
'#default_value' => (!$register ? $account->name : ''),
'#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin),
);
$form['account']['mail'] = array(
'#type' => 'textfield',
'#title' => t('E-mail address'),
'#maxlength' => EMAIL_MAX_LENGTH,
'#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail 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 e-mail.'),
'#required' => TRUE,
'#default_value' => (!$register ? $account->mail : ''),
);
// Display password field only for existing users or when user is allowed to
// assign a password during registration.
if (!$register) {
$form['account']['pass'] = array(
'#type' => 'password_confirm',
'#size' => 25,
'#description' => t('To change the current user password, enter the new password in both fields.'),
);
}
elseif (!variable_get('user_email_verification', TRUE) || $admin) {
$form['account']['pass'] = array(
'#type' => 'password_confirm',
'#size' => 25,
'#description' => t('Provide a password for the new account in both fields.'),
'#required' => TRUE,
);
}
if ($admin) {
$status = (isset($account->status) ? $account->status : 1);
}
else {
$status = (variable_get('user_register', 1) == 1);
}
$form['account']['status'] = array(
'#type' => 'radios',
'#title' => t('Status'),
'#default_value' => $status,
'#options' => array(t('Blocked'), t('Active')),
'#access' => $admin,
);
$roles = user_roles(TRUE);
// The disabled checkbox subelement for the 'authenticated user' role
// must be generated separately and added to the checkboxes element,
// because of a limitation in Form API not supporting a single disabled
// checkbox within a set of checkboxes.
// @todo This should be solved more elegantly. See issue #119038.
$checkbox_authenticated = array(
'#type' => 'checkbox',
'#title' => $roles[DRUPAL_AUTHENTICATED_RID],
'#default_value' => TRUE,
'#disabled' => TRUE,
);
unset($roles[DRUPAL_AUTHENTICATED_RID]);
$form['account']['roles'] = array(
'#type' => 'checkboxes',
'#title' => t('Roles'),
'#default_value' => (!$register && isset($account->roles) ? array_keys($account->roles) : array()),
'#options' => $roles,
'#access' => $roles && user_access('administer permissions'),
DRUPAL_AUTHENTICATED_RID => $checkbox_authenticated,
);
$form['account']['notify'] = array(
'#type' => 'checkbox',
'#title' => t('Notify user of new account'),
'#access' => $register && $admin,
);
// Signature.
$form['signature_settings'] = array(
'#type' => 'fieldset',
'#title' => t('Signature settings'),
'#weight' => 1,