forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.php
1423 lines (1267 loc) · 52.7 KB
/
lib.php
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
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* External user API
*
* @package core_user
* @copyright 2009 Moodle Pty Ltd (http://moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define('USER_FILTER_ENROLMENT', 1);
define('USER_FILTER_GROUP', 2);
define('USER_FILTER_LAST_ACCESS', 3);
define('USER_FILTER_ROLE', 4);
define('USER_FILTER_STATUS', 5);
define('USER_FILTER_STRING', 6);
/**
* Creates a user
*
* @throws moodle_exception
* @param stdClass|array $user user to create
* @param bool $updatepassword if true, authentication plugin will update password.
* @param bool $triggerevent set false if user_created event should not be triggred.
* This will not affect user_password_updated event triggering.
* @return int id of the newly created user
*/
function user_create_user($user, $updatepassword = true, $triggerevent = true) {
global $DB;
// Set the timecreate field to the current time.
if (!is_object($user)) {
$user = (object) $user;
}
// Check username.
if (trim($user->username) === '') {
throw new moodle_exception('invalidusernameblank');
}
if ($user->username !== core_text::strtolower($user->username)) {
throw new moodle_exception('usernamelowercase');
}
if ($user->username !== core_user::clean_field($user->username, 'username')) {
throw new moodle_exception('invalidusername');
}
// Save the password in a temp value for later.
if ($updatepassword && isset($user->password)) {
// Check password toward the password policy.
if (!check_password_policy($user->password, $errmsg, $user)) {
throw new moodle_exception($errmsg);
}
$userpassword = $user->password;
unset($user->password);
}
// Apply default values for user preferences that are stored in users table.
if (!isset($user->calendartype)) {
$user->calendartype = core_user::get_property_default('calendartype');
}
if (!isset($user->maildisplay)) {
$user->maildisplay = core_user::get_property_default('maildisplay');
}
if (!isset($user->mailformat)) {
$user->mailformat = core_user::get_property_default('mailformat');
}
if (!isset($user->maildigest)) {
$user->maildigest = core_user::get_property_default('maildigest');
}
if (!isset($user->autosubscribe)) {
$user->autosubscribe = core_user::get_property_default('autosubscribe');
}
if (!isset($user->trackforums)) {
$user->trackforums = core_user::get_property_default('trackforums');
}
if (!isset($user->lang)) {
$user->lang = core_user::get_property_default('lang');
}
if (!isset($user->city)) {
$user->city = core_user::get_property_default('city');
}
if (!isset($user->country)) {
// The default value of $CFG->country is 0, but that isn't a valid property for the user field, so switch to ''.
$user->country = core_user::get_property_default('country') ?: '';
}
$user->timecreated = time();
$user->timemodified = $user->timecreated;
// Validate user data object.
$uservalidation = core_user::validate($user);
if ($uservalidation !== true) {
foreach ($uservalidation as $field => $message) {
debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
$user->$field = core_user::clean_field($user->$field, $field);
}
}
// Insert the user into the database.
$newuserid = $DB->insert_record('user', $user);
// Create USER context for this user.
$usercontext = context_user::instance($newuserid);
// Update user password if necessary.
if (isset($userpassword)) {
// Get full database user row, in case auth is default.
$newuser = $DB->get_record('user', array('id' => $newuserid));
$authplugin = get_auth_plugin($newuser->auth);
$authplugin->user_update_password($newuser, $userpassword);
}
// Trigger event If required.
if ($triggerevent) {
\core\event\user_created::create_from_userid($newuserid)->trigger();
}
// Purge the associated caches for the current user only.
$presignupcache = \cache::make('core', 'presignup');
$presignupcache->purge_current_user();
return $newuserid;
}
/**
* Update a user with a user object (will compare against the ID)
*
* @throws moodle_exception
* @param stdClass|array $user the user to update
* @param bool $updatepassword if true, authentication plugin will update password.
* @param bool $triggerevent set false if user_updated event should not be triggred.
* This will not affect user_password_updated event triggering.
*/
function user_update_user($user, $updatepassword = true, $triggerevent = true) {
global $DB, $CFG;
// Set the timecreate field to the current time.
if (!is_object($user)) {
$user = (object) $user;
}
// Communication api update for user.
if (core_communication\api::is_available()) {
$usercourses = enrol_get_users_courses($user->id);
$currentrecord = $DB->get_record('user', ['id' => $user->id]);
if (!empty($currentrecord) && isset($user->suspended) && $currentrecord->suspended !== $user->suspended) {
foreach ($usercourses as $usercourse) {
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$usercourse->id
);
// If the record updated the suspended for a user.
if ($user->suspended === 0) {
$communication->add_members_to_room([$user->id]);
} else if ($user->suspended === 1) {
$communication->remove_members_from_room([$user->id]);
}
}
}
}
// Check username.
if (isset($user->username)) {
if ($user->username !== core_text::strtolower($user->username)) {
throw new moodle_exception('usernamelowercase');
} else {
if ($user->username !== core_user::clean_field($user->username, 'username')) {
throw new moodle_exception('invalidusername');
}
}
}
// Unset password here, for updating later, if password update is required.
if ($updatepassword && isset($user->password)) {
// Check password toward the password policy.
if (!check_password_policy($user->password, $errmsg, $user)) {
throw new moodle_exception($errmsg);
}
$passwd = $user->password;
unset($user->password);
}
// Make sure calendartype, if set, is valid.
if (empty($user->calendartype)) {
// Unset this variable, must be an empty string, which we do not want to update the calendartype to.
unset($user->calendartype);
}
$user->timemodified = time();
// Validate user data object.
$uservalidation = core_user::validate($user);
if ($uservalidation !== true) {
foreach ($uservalidation as $field => $message) {
debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
$user->$field = core_user::clean_field($user->$field, $field);
}
}
$DB->update_record('user', $user);
if ($updatepassword) {
// Get full user record.
$updateduser = $DB->get_record('user', array('id' => $user->id));
// If password was set, then update its hash.
if (isset($passwd)) {
$authplugin = get_auth_plugin($updateduser->auth);
if ($authplugin->can_change_password()) {
$authplugin->user_update_password($updateduser, $passwd);
}
}
}
// Trigger event if required.
if ($triggerevent) {
\core\event\user_updated::create_from_userid($user->id)->trigger();
}
}
/**
* Marks user deleted in internal user database and notifies the auth plugin.
* Also unenrols user from all roles and does other cleanup.
*
* @todo Decide if this transaction is really needed (look for internal TODO:)
* @param object $user Userobject before delete (without system magic quotes)
* @return boolean success
*/
function user_delete_user($user) {
return delete_user($user);
}
/**
* Get users by id
*
* @param array $userids id of users to retrieve
* @return array
*/
function user_get_users_by_id($userids) {
global $DB;
return $DB->get_records_list('user', 'id', $userids);
}
/**
* Returns the list of default 'displayable' fields
*
* Contains database field names but also names used to generate information, such as enrolledcourses
*
* @return array of user fields
*/
function user_get_default_fields() {
return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
'address', 'phone1', 'phone2', 'department',
'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
'city', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
'groups', 'roles', 'preferences', 'enrolledcourses', 'suspended', 'lastcourseaccess'
);
}
/**
*
* Give user record from mdl_user, build an array contains all user details.
*
* Warning: description file urls are 'webservice/pluginfile.php' is use.
* it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
*
* @throws moodle_exception
* @param stdClass $user user record from mdl_user
* @param stdClass $course moodle course
* @param array $userfields required fields
* @return array|null
*/
function user_get_user_details($user, $course = null, array $userfields = array()) {
global $USER, $DB, $CFG, $PAGE;
require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library.
require_once($CFG->dirroot . "/lib/filelib.php"); // File handling on description and friends.
$defaultfields = user_get_default_fields();
if (empty($userfields)) {
$userfields = $defaultfields;
}
foreach ($userfields as $thefield) {
if (!in_array($thefield, $defaultfields)) {
throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
}
}
// Make sure id and fullname are included.
if (!in_array('id', $userfields)) {
$userfields[] = 'id';
}
if (!in_array('fullname', $userfields)) {
$userfields[] = 'fullname';
}
if (!empty($course)) {
$context = context_course::instance($course->id);
$usercontext = context_user::instance($user->id);
$canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext));
} else {
$context = context_user::instance($user->id);
$usercontext = $context;
$canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
}
$currentuser = ($user->id == $USER->id);
$isadmin = is_siteadmin($USER);
// This does not need to include custom profile fields as it is only used to check specific
// fields below.
$showuseridentityfields = \core_user\fields::get_identity_fields($context, false);
if (!empty($course)) {
$canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
} else {
$canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
}
$canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
if (!empty($course)) {
$canviewuseremail = has_capability('moodle/course:useremail', $context);
} else {
$canviewuseremail = false;
}
$cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
if (!empty($course)) {
$canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
} else {
$canaccessallgroups = false;
}
if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
// Skip this user details.
return null;
}
$userdetails = array();
$userdetails['id'] = $user->id;
if (in_array('username', $userfields)) {
if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
$userdetails['username'] = $user->username;
}
}
if ($isadmin or $canviewfullnames) {
if (in_array('firstname', $userfields)) {
$userdetails['firstname'] = $user->firstname;
}
if (in_array('lastname', $userfields)) {
$userdetails['lastname'] = $user->lastname;
}
}
$userdetails['fullname'] = fullname($user, $canviewfullnames);
if (in_array('customfields', $userfields)) {
$categories = profile_get_user_fields_with_data_by_category($user->id);
$userdetails['customfields'] = array();
foreach ($categories as $categoryid => $fields) {
foreach ($fields as $formfield) {
if ($formfield->is_visible() and !$formfield->is_empty()) {
$userdetails['customfields'][] = [
'name' => $formfield->field->name,
'value' => $formfield->data,
'displayvalue' => $formfield->display_data(),
'type' => $formfield->field->datatype,
'shortname' => $formfield->field->shortname
];
}
}
}
// Unset customfields if it's empty.
if (empty($userdetails['customfields'])) {
unset($userdetails['customfields']);
}
}
// Profile image.
if (in_array('profileimageurl', $userfields)) {
$userpicture = new user_picture($user);
$userpicture->size = 1; // Size f1.
$userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
}
if (in_array('profileimageurlsmall', $userfields)) {
if (!isset($userpicture)) {
$userpicture = new user_picture($user);
}
$userpicture->size = 0; // Size f2.
$userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
}
// Hidden user field.
if ($canviewhiddenuserfields) {
$hiddenfields = array();
} else {
$hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
}
if (!empty($user->address) && (in_array('address', $userfields)
&& in_array('address', $showuseridentityfields) || $isadmin)) {
$userdetails['address'] = $user->address;
}
if (!empty($user->phone1) && (in_array('phone1', $userfields)
&& in_array('phone1', $showuseridentityfields) || $isadmin)) {
$userdetails['phone1'] = $user->phone1;
}
if (!empty($user->phone2) && (in_array('phone2', $userfields)
&& in_array('phone2', $showuseridentityfields) || $isadmin)) {
$userdetails['phone2'] = $user->phone2;
}
if (isset($user->description) &&
((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
if (in_array('description', $userfields)) {
// Always return the descriptionformat if description is requested.
list($userdetails['description'], $userdetails['descriptionformat']) =
\core_external\util::format_text($user->description, $user->descriptionformat,
$usercontext, 'user', 'profile', null);
}
}
if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
$userdetails['country'] = $user->country;
}
if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
$userdetails['city'] = $user->city;
}
if (in_array('timezone', $userfields) && (!isset($hiddenfields['timezone']) || $isadmin) && $user->timezone) {
$userdetails['timezone'] = $user->timezone;
}
if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) {
$userdetails['suspended'] = (bool)$user->suspended;
}
if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
if ($user->firstaccess) {
$userdetails['firstaccess'] = $user->firstaccess;
} else {
$userdetails['firstaccess'] = 0;
}
}
if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
if ($user->lastaccess) {
$userdetails['lastaccess'] = $user->lastaccess;
} else {
$userdetails['lastaccess'] = 0;
}
}
// Hidden fields restriction to lastaccess field applies to both site and course access time.
if (in_array('lastcourseaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
if (isset($user->lastcourseaccess)) {
$userdetails['lastcourseaccess'] = $user->lastcourseaccess;
} else {
$userdetails['lastcourseaccess'] = 0;
}
}
if (in_array('email', $userfields) && (
$currentuser
or (!isset($hiddenfields['email']) and (
$user->maildisplay == core_user::MAILDISPLAY_EVERYONE
or ($user->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY and enrol_sharing_course($user, $USER))
or $canviewuseremail // TODO: Deprecate/remove for MDL-37479.
))
or in_array('email', $showuseridentityfields)
)) {
$userdetails['email'] = $user->email;
}
if (in_array('interests', $userfields)) {
$interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
if ($interests) {
$userdetails['interests'] = join(', ', $interests);
}
}
// Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
if (in_array('idnumber', $userfields) && $user->idnumber) {
if (in_array('idnumber', $showuseridentityfields) or $currentuser or
has_capability('moodle/user:viewalldetails', $context)) {
$userdetails['idnumber'] = $user->idnumber;
}
}
if (in_array('institution', $userfields) && $user->institution) {
if (in_array('institution', $showuseridentityfields) or $currentuser or
has_capability('moodle/user:viewalldetails', $context)) {
$userdetails['institution'] = $user->institution;
}
}
// Isset because it's ok to have department 0.
if (in_array('department', $userfields) && isset($user->department)) {
if (in_array('department', $showuseridentityfields) or $currentuser or
has_capability('moodle/user:viewalldetails', $context)) {
$userdetails['department'] = $user->department;
}
}
if (in_array('roles', $userfields) && !empty($course)) {
// Not a big secret.
$roles = get_user_roles($context, $user->id, false);
$userdetails['roles'] = array();
foreach ($roles as $role) {
$userdetails['roles'][] = array(
'roleid' => $role->roleid,
'name' => $role->name,
'shortname' => $role->shortname,
'sortorder' => $role->sortorder
);
}
}
// Return user groups.
if (in_array('groups', $userfields) && !empty($course)) {
if ($usergroups = groups_get_all_groups($course->id, $user->id)) {
$userdetails['groups'] = [];
foreach ($usergroups as $group) {
if ($course->groupmode == SEPARATEGROUPS && !$canaccessallgroups && $user->id != $USER->id) {
// In separate groups, I only have to see the groups shared between both users.
if (!groups_is_member($group->id, $USER->id)) {
continue;
}
}
$userdetails['groups'][] = [
'id' => $group->id,
'name' => format_string($group->name),
'description' => format_text($group->description, $group->descriptionformat, ['context' => $context]),
'descriptionformat' => $group->descriptionformat
];
}
}
}
// List of courses where the user is enrolled.
if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
$enrolledcourses = array();
if ($mycourses = enrol_get_users_courses($user->id, true)) {
foreach ($mycourses as $mycourse) {
if ($mycourse->category) {
$coursecontext = context_course::instance($mycourse->id);
$enrolledcourse = array();
$enrolledcourse['id'] = $mycourse->id;
$enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
$enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
$enrolledcourses[] = $enrolledcourse;
}
}
$userdetails['enrolledcourses'] = $enrolledcourses;
}
}
// User preferences.
if (in_array('preferences', $userfields) && $currentuser) {
$preferences = array();
$userpreferences = get_user_preferences();
foreach ($userpreferences as $prefname => $prefvalue) {
$preferences[] = array('name' => $prefname, 'value' => $prefvalue);
}
$userdetails['preferences'] = $preferences;
}
if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
$extrafields = ['auth', 'confirmed', 'lang', 'theme', 'mailformat'];
foreach ($extrafields as $extrafield) {
if (in_array($extrafield, $userfields) && isset($user->$extrafield)) {
$userdetails[$extrafield] = $user->$extrafield;
}
}
}
// Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
if (isset($userdetails['lang'])) {
$userdetails['lang'] = clean_param($userdetails['lang'], PARAM_LANG);
}
if (isset($userdetails['theme'])) {
$userdetails['theme'] = clean_param($userdetails['theme'], PARAM_THEME);
}
return $userdetails;
}
/**
* Tries to obtain user details, either recurring directly to the user's system profile
* or through one of the user's course enrollments (course profile).
*
* You can use the $userfields parameter to reduce the amount of a user record that is required by the method.
* The minimum user fields are:
* * id
* * deleted
* * all potential fullname fields
*
* @param stdClass $user The user.
* @param array $userfields An array of userfields to be returned, the values must be a
* subset of user_get_default_fields (optional)
* @return array if unsuccessful or the allowed user details.
*/
function user_get_user_details_courses($user, array $userfields = []) {
global $USER;
$userdetails = null;
$systemprofile = false;
if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
$systemprofile = true;
}
// Try using system profile.
if ($systemprofile) {
$userdetails = user_get_user_details($user, null, $userfields);
} else {
// Try through course profile.
// Get the courses that the user is enrolled in (only active).
$courses = enrol_get_users_courses($user->id, true);
foreach ($courses as $course) {
if (user_can_view_profile($user, $course)) {
$userdetails = user_get_user_details($user, $course, $userfields);
}
}
}
return $userdetails;
}
/**
* Check if $USER have the necessary capabilities to obtain user details.
*
* @param stdClass $user
* @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
* @return bool true if $USER can view user details.
*/
function can_view_user_details_cap($user, $course = null) {
// Check $USER has the capability to view the user details at user context.
$usercontext = context_user::instance($user->id);
$result = has_capability('moodle/user:viewdetails', $usercontext);
// Otherwise can $USER see them at course context.
if (!$result && !empty($course)) {
$context = context_course::instance($course->id);
$result = has_capability('moodle/user:viewdetails', $context);
}
return $result;
}
/**
* Return a list of page types
* @param string $pagetype current page type
* @param stdClass $parentcontext Block's parent context
* @param stdClass $currentcontext Current context of block
* @return array
*/
function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
return array('user-profile' => get_string('page-user-profile', 'pagetype'));
}
/**
* Count the number of failed login attempts for the given user, since last successful login.
*
* @param int|stdclass $user user id or object.
* @param bool $reset Resets failed login count, if set to true.
*
* @return int number of failed login attempts since the last successful login.
*/
function user_count_login_failures($user, $reset = true) {
global $DB;
if (!is_object($user)) {
$user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
}
if ($user->deleted) {
// Deleted user, nothing to do.
return 0;
}
$count = get_user_preferences('login_failed_count_since_success', 0, $user);
if ($reset) {
set_user_preference('login_failed_count_since_success', 0, $user);
}
return $count;
}
/**
* Converts a string into a flat array of menu items, where each menu items is a
* stdClass with fields type, url, title.
*
* @param string $text the menu items definition
* @param moodle_page $page the current page
* @return array
*/
function user_convert_text_to_menu_items($text, $page) {
global $OUTPUT, $CFG;
$lines = explode("\n", $text);
$items = array();
$lastchild = null;
$lastdepth = null;
$lastsort = 0;
$children = array();
foreach ($lines as $line) {
$line = trim($line);
$bits = explode('|', $line, 2);
$itemtype = 'link';
if (preg_match("/^#+$/", $line)) {
$itemtype = 'divider';
} else if (!array_key_exists(0, $bits) or empty($bits[0])) {
// Every item must have a name to be valid.
continue;
} else {
$bits[0] = ltrim($bits[0], '-');
}
// Create the child.
$child = new stdClass();
$child->itemtype = $itemtype;
if ($itemtype === 'divider') {
// Add the divider to the list of children and skip link
// processing.
$children[] = $child;
continue;
}
// Name processing.
$namebits = explode(',', $bits[0], 2);
if (count($namebits) == 2) {
// Check the validity of the identifier part of the string.
if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
// Treat this as a language string.
$child->title = get_string($namebits[0], $namebits[1]);
$child->titleidentifier = implode(',', $namebits);
}
}
if (empty($child->title)) {
// Use it as is, don't even clean it.
$child->title = $bits[0];
$child->titleidentifier = str_replace(" ", "-", $bits[0]);
}
// URL processing.
if (!array_key_exists(1, $bits) or empty($bits[1])) {
// Set the url to null, and set the itemtype to invalid.
$bits[1] = null;
$child->itemtype = "invalid";
} else {
// Nasty hack to replace the grades with the direct url.
if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
$bits[1] = user_mygrades_url();
}
// Make sure the url is a moodle url.
$bits[1] = new moodle_url(trim($bits[1]));
}
$child->url = $bits[1];
// Add this child to the list of children.
$children[] = $child;
}
return $children;
}
/**
* Get a list of essential user navigation items.
*
* @param stdclass $user user object.
* @param moodle_page $page page object.
* @param array $options associative array.
* options are:
* - avatarsize=35 (size of avatar image)
* @return stdClass $returnobj navigation information object, where:
*
* $returnobj->navitems array array of links where each link is a
* stdClass with fields url, title, and
* pix
* $returnobj->metadata array array of useful user metadata to be
* used when constructing navigation;
* fields include:
*
* ROLE FIELDS
* asotherrole bool whether viewing as another role
* rolename string name of the role
*
* USER FIELDS
* These fields are for the currently-logged in user, or for
* the user that the real user is currently logged in as.
*
* userid int the id of the user in question
* userfullname string the user's full name
* userprofileurl moodle_url the url of the user's profile
* useravatar string a HTML fragment - the rendered
* user_picture for this user
* userloginfail string an error string denoting the number
* of login failures since last login
*
* "REAL USER" FIELDS
* These fields are for when asotheruser is true, and
* correspond to the underlying "real user".
*
* asotheruser bool whether viewing as another user
* realuserid int the id of the user in question
* realuserfullname string the user's full name
* realuserprofileurl moodle_url the url of the user's profile
* realuseravatar string a HTML fragment - the rendered
* user_picture for this user
*
* MNET PROVIDER FIELDS
* asmnetuser bool whether viewing as a user from an
* MNet provider
* mnetidprovidername string name of the MNet provider
* mnetidproviderwwwroot string URL of the MNet provider
*/
function user_get_user_navigation_info($user, $page, $options = array()) {
global $OUTPUT, $DB, $SESSION, $CFG;
$returnobject = new stdClass();
$returnobject->navitems = array();
$returnobject->metadata = array();
$guest = isguestuser();
if (!isloggedin() || $guest) {
$returnobject->unauthenticateduser = [
'guest' => $guest,
'content' => $guest ? 'loggedinasguest' : 'loggedinnot',
];
return $returnobject;
}
$course = $page->course;
// Query the environment.
$context = context_course::instance($course->id);
// Get basic user metadata.
$returnobject->metadata['userid'] = $user->id;
$returnobject->metadata['userfullname'] = fullname($user);
$returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
'id' => $user->id
));
$avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
if (!empty($options['avatarsize'])) {
$avataroptions['size'] = $options['avatarsize'];
}
$returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
$user, $avataroptions
);
// Build a list of items for a regular user.
// Query MNet status.
if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
$mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
$returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
$returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
}
// Did the user just log in?
if (isset($SESSION->justloggedin)) {
// Don't unset this flag as login_info still needs it.
if (!empty($CFG->displayloginfailures)) {
// Don't reset the count either, as login_info() still needs it too.
if ($count = user_count_login_failures($user, false)) {
// Get login failures string.
$a = new stdClass();
$a->attempts = html_writer::tag('span', $count, array('class' => 'value mr-1 font-weight-bold'));
$returnobject->metadata['userloginfail'] =
get_string('failedloginattempts', '', $a);
}
}
}
$returnobject->metadata['asotherrole'] = false;
// Before we add the last items (usually a logout + switch role link), add any
// custom-defined items.
$customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
$custommenucount = 0;
foreach ($customitems as $item) {
$returnobject->navitems[] = $item;
if ($item->itemtype !== 'divider' && $item->itemtype !== 'invalid') {
$custommenucount++;
}
}
if ($custommenucount > 0) {
// Only add a divider if we have customusermenuitems.
$divider = new stdClass();
$divider->itemtype = 'divider';
$returnobject->navitems[] = $divider;
}
// Links: Preferences.
$preferences = new stdClass();
$preferences->itemtype = 'link';
$preferences->url = new moodle_url('/user/preferences.php');
$preferences->title = get_string('preferences');
$preferences->titleidentifier = 'preferences,moodle';
$returnobject->navitems[] = $preferences;
if (is_role_switched($course->id)) {
if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
// Build role-return link instead of logout link.
$rolereturn = new stdClass();
$rolereturn->itemtype = 'link';
$rolereturn->url = new moodle_url('/course/switchrole.php', array(
'id' => $course->id,
'sesskey' => sesskey(),
'switchrole' => 0,
'returnurl' => $page->url->out_as_local_url(false)
));
$rolereturn->title = get_string('switchrolereturn');
$rolereturn->titleidentifier = 'switchrolereturn,moodle';
$returnobject->navitems[] = $rolereturn;
$returnobject->metadata['asotherrole'] = true;
$returnobject->metadata['rolename'] = role_get_name($role, $context);
}
} else {
// Build switch role link.
$roles = get_switchable_roles($context);
if (is_array($roles) && (count($roles) > 0)) {
$switchrole = new stdClass();
$switchrole->itemtype = 'link';
$switchrole->url = new moodle_url('/course/switchrole.php', array(
'id' => $course->id,
'switchrole' => -1,
'returnurl' => $page->url->out_as_local_url(false)
));
$switchrole->title = get_string('switchroleto');
$switchrole->titleidentifier = 'switchroleto,moodle';
$returnobject->navitems[] = $switchrole;
}
}
if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
$realuser = \core\session\manager::get_realuser();
// Save values for the real user, as $user will be full of data for the
// user is disguised as.
$returnobject->metadata['realuserid'] = $realuser->id;
$returnobject->metadata['realuserfullname'] = fullname($realuser);
$returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', [
'id' => $realuser->id
]);
$returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
// Build a user-revert link.
$userrevert = new stdClass();
$userrevert->itemtype = 'link';
$userrevert->url = new moodle_url('/course/loginas.php', [
'id' => $course->id,
'sesskey' => sesskey()
]);
$userrevert->title = get_string('logout');
$userrevert->titleidentifier = 'logout,moodle';
$returnobject->navitems[] = $userrevert;
} else {
// Build a logout link.
$logout = new stdClass();
$logout->itemtype = 'link';
$logout->url = new moodle_url('/login/logout.php', ['sesskey' => sesskey()]);
$logout->title = get_string('logout');
$logout->titleidentifier = 'logout,moodle';
$returnobject->navitems[] = $logout;
}
return $returnobject;
}
/**
* Add password to the list of used hashes for this user.
*
* This is supposed to be used from:
* 1/ change own password form
* 2/ password reset process