2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
21 * @copyright 2009 Moodle Pty Ltd (http://moodle.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 define('USER_FILTER_ENROLMENT', 1);
26 define('USER_FILTER_GROUP', 2);
27 define('USER_FILTER_LAST_ACCESS', 3);
28 define('USER_FILTER_ROLE', 4);
29 define('USER_FILTER_STATUS', 5);
30 define('USER_FILTER_STRING', 6);
35 * @throws moodle_exception
36 * @param stdClass $user user to create
37 * @param bool $updatepassword if true, authentication plugin will update password.
38 * @param bool $triggerevent set false if user_created event should not be triggred.
39 * This will not affect user_password_updated event triggering.
40 * @return int id of the newly created user
42 function user_create_user($user, $updatepassword = true, $triggerevent = true) {
45 // Set the timecreate field to the current time.
46 if (!is_object($user)) {
47 $user = (object) $user;
51 if (trim($user->username
) === '') {
52 throw new moodle_exception('invalidusernameblank');
55 if ($user->username
!== core_text
::strtolower($user->username
)) {
56 throw new moodle_exception('usernamelowercase');
59 if ($user->username
!== core_user
::clean_field($user->username
, 'username')) {
60 throw new moodle_exception('invalidusername');
63 // Save the password in a temp value for later.
64 if ($updatepassword && isset($user->password
)) {
66 // Check password toward the password policy.
67 if (!check_password_policy($user->password
, $errmsg, $user)) {
68 throw new moodle_exception($errmsg);
71 $userpassword = $user->password
;
72 unset($user->password
);
75 // Apply default values for user preferences that are stored in users table.
76 if (!isset($user->calendartype
)) {
77 $user->calendartype
= core_user
::get_property_default('calendartype');
79 if (!isset($user->maildisplay
)) {
80 $user->maildisplay
= core_user
::get_property_default('maildisplay');
82 if (!isset($user->mailformat
)) {
83 $user->mailformat
= core_user
::get_property_default('mailformat');
85 if (!isset($user->maildigest
)) {
86 $user->maildigest
= core_user
::get_property_default('maildigest');
88 if (!isset($user->autosubscribe
)) {
89 $user->autosubscribe
= core_user
::get_property_default('autosubscribe');
91 if (!isset($user->trackforums
)) {
92 $user->trackforums
= core_user
::get_property_default('trackforums');
94 if (!isset($user->lang
)) {
95 $user->lang
= core_user
::get_property_default('lang');
97 if (!isset($user->city
)) {
98 $user->city
= core_user
::get_property_default('city');
100 if (!isset($user->country
)) {
101 // The default value of $CFG->country is 0, but that isn't a valid property for the user field, so switch to ''.
102 $user->country
= core_user
::get_property_default('country') ?
: '';
105 $user->timecreated
= time();
106 $user->timemodified
= $user->timecreated
;
108 // Validate user data object.
109 $uservalidation = core_user
::validate($user);
110 if ($uservalidation !== true) {
111 foreach ($uservalidation as $field => $message) {
112 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER
);
113 $user->$field = core_user
::clean_field($user->$field, $field);
117 // Insert the user into the database.
118 $newuserid = $DB->insert_record('user', $user);
120 // Create USER context for this user.
121 $usercontext = context_user
::instance($newuserid);
123 // Update user password if necessary.
124 if (isset($userpassword)) {
125 // Get full database user row, in case auth is default.
126 $newuser = $DB->get_record('user', array('id' => $newuserid));
127 $authplugin = get_auth_plugin($newuser->auth
);
128 $authplugin->user_update_password($newuser, $userpassword);
131 // Trigger event If required.
133 \core\event\user_created
::create_from_userid($newuserid)->trigger();
136 // Purge the associated caches for the current user only.
137 $presignupcache = \cache
::make('core', 'presignup');
138 $presignupcache->purge_current_user();
144 * Update a user with a user object (will compare against the ID)
146 * @throws moodle_exception
147 * @param stdClass $user the user to update
148 * @param bool $updatepassword if true, authentication plugin will update password.
149 * @param bool $triggerevent set false if user_updated event should not be triggred.
150 * This will not affect user_password_updated event triggering.
152 function user_update_user($user, $updatepassword = true, $triggerevent = true) {
155 // Set the timecreate field to the current time.
156 if (!is_object($user)) {
157 $user = (object) $user;
161 if (isset($user->username
)) {
162 if ($user->username
!== core_text
::strtolower($user->username
)) {
163 throw new moodle_exception('usernamelowercase');
165 if ($user->username
!== core_user
::clean_field($user->username
, 'username')) {
166 throw new moodle_exception('invalidusername');
171 // Unset password here, for updating later, if password update is required.
172 if ($updatepassword && isset($user->password
)) {
174 // Check password toward the password policy.
175 if (!check_password_policy($user->password
, $errmsg, $user)) {
176 throw new moodle_exception($errmsg);
179 $passwd = $user->password
;
180 unset($user->password
);
183 // Make sure calendartype, if set, is valid.
184 if (empty($user->calendartype
)) {
185 // Unset this variable, must be an empty string, which we do not want to update the calendartype to.
186 unset($user->calendartype
);
189 $user->timemodified
= time();
191 // Validate user data object.
192 $uservalidation = core_user
::validate($user);
193 if ($uservalidation !== true) {
194 foreach ($uservalidation as $field => $message) {
195 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER
);
196 $user->$field = core_user
::clean_field($user->$field, $field);
200 $DB->update_record('user', $user);
202 if ($updatepassword) {
203 // Get full user record.
204 $updateduser = $DB->get_record('user', array('id' => $user->id
));
206 // If password was set, then update its hash.
207 if (isset($passwd)) {
208 $authplugin = get_auth_plugin($updateduser->auth
);
209 if ($authplugin->can_change_password()) {
210 $authplugin->user_update_password($updateduser, $passwd);
214 // Trigger event if required.
216 \core\event\user_updated
::create_from_userid($user->id
)->trigger();
221 * Marks user deleted in internal user database and notifies the auth plugin.
222 * Also unenrols user from all roles and does other cleanup.
224 * @todo Decide if this transaction is really needed (look for internal TODO:)
225 * @param object $user Userobject before delete (without system magic quotes)
226 * @return boolean success
228 function user_delete_user($user) {
229 return delete_user($user);
235 * @param array $userids id of users to retrieve
238 function user_get_users_by_id($userids) {
240 return $DB->get_records_list('user', 'id', $userids);
244 * Returns the list of default 'displayable' fields
246 * Contains database field names but also names used to generate information, such as enrolledcourses
248 * @return array of user fields
250 function user_get_default_fields() {
251 return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
252 'address', 'phone1', 'phone2', 'department',
253 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
254 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
255 'city', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
256 'groups', 'roles', 'preferences', 'enrolledcourses', 'suspended', 'lastcourseaccess'
262 * Give user record from mdl_user, build an array contains all user details.
264 * Warning: description file urls are 'webservice/pluginfile.php' is use.
265 * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
267 * @throws moodle_exception
268 * @param stdClass $user user record from mdl_user
269 * @param stdClass $course moodle course
270 * @param array $userfields required fields
273 function user_get_user_details($user, $course = null, array $userfields = array()) {
274 global $USER, $DB, $CFG, $PAGE;
275 require_once($CFG->dirroot
. "/user/profile/lib.php"); // Custom field library.
276 require_once($CFG->dirroot
. "/lib/filelib.php"); // File handling on description and friends.
278 $defaultfields = user_get_default_fields();
280 if (empty($userfields)) {
281 $userfields = $defaultfields;
284 foreach ($userfields as $thefield) {
285 if (!in_array($thefield, $defaultfields)) {
286 throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
290 // Make sure id and fullname are included.
291 if (!in_array('id', $userfields)) {
292 $userfields[] = 'id';
295 if (!in_array('fullname', $userfields)) {
296 $userfields[] = 'fullname';
299 if (!empty($course)) {
300 $context = context_course
::instance($course->id
);
301 $usercontext = context_user
::instance($user->id
);
302 $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) ||
has_capability('moodle/user:viewdetails', $usercontext));
304 $context = context_user
::instance($user->id
);
305 $usercontext = $context;
306 $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
309 $currentuser = ($user->id
== $USER->id
);
310 $isadmin = is_siteadmin($USER);
312 // This does not need to include custom profile fields as it is only used to check specific
314 $showuseridentityfields = \core_user\fields
::get_identity_fields($context, false);
316 if (!empty($course)) {
317 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
319 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
321 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
322 if (!empty($course)) {
323 $canviewuseremail = has_capability('moodle/course:useremail', $context);
325 $canviewuseremail = false;
327 $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly
) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id
));
328 if (!empty($course)) {
329 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
331 $canaccessallgroups = false;
334 if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id
)) {
335 // Skip this user details.
339 $userdetails = array();
340 $userdetails['id'] = $user->id
;
342 if (in_array('username', $userfields)) {
343 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
344 $userdetails['username'] = $user->username
;
347 if ($isadmin or $canviewfullnames) {
348 if (in_array('firstname', $userfields)) {
349 $userdetails['firstname'] = $user->firstname
;
351 if (in_array('lastname', $userfields)) {
352 $userdetails['lastname'] = $user->lastname
;
355 $userdetails['fullname'] = fullname($user, $canviewfullnames);
357 if (in_array('customfields', $userfields)) {
358 $categories = profile_get_user_fields_with_data_by_category($user->id
);
359 $userdetails['customfields'] = array();
360 foreach ($categories as $categoryid => $fields) {
361 foreach ($fields as $formfield) {
362 if ($formfield->is_visible() and !$formfield->is_empty()) {
364 // TODO: Part of MDL-50728, this conditional coding must be moved to
365 // proper profile fields API so they are self-contained.
366 // We only use display_data in fields that require text formatting.
367 if ($formfield->field
->datatype
== 'text' or $formfield->field
->datatype
== 'textarea') {
368 $fieldvalue = $formfield->display_data();
370 // Cases: datetime, checkbox and menu.
371 $fieldvalue = $formfield->data
;
374 $userdetails['customfields'][] =
375 array('name' => $formfield->field
->name
, 'value' => $fieldvalue,
376 'type' => $formfield->field
->datatype
, 'shortname' => $formfield->field
->shortname
);
380 // Unset customfields if it's empty.
381 if (empty($userdetails['customfields'])) {
382 unset($userdetails['customfields']);
387 if (in_array('profileimageurl', $userfields)) {
388 $userpicture = new user_picture($user);
389 $userpicture->size
= 1; // Size f1.
390 $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
392 if (in_array('profileimageurlsmall', $userfields)) {
393 if (!isset($userpicture)) {
394 $userpicture = new user_picture($user);
396 $userpicture->size
= 0; // Size f2.
397 $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
400 // Hidden user field.
401 if ($canviewhiddenuserfields) {
402 $hiddenfields = array();
403 // Address, phone1 and phone2 not appears in hidden fields list but require viewhiddenfields capability
404 // according to user/profile.php.
405 if (!empty($user->address
) && in_array('address', $userfields)) {
406 $userdetails['address'] = $user->address
;
409 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
412 if (!empty($user->phone1
) && in_array('phone1', $userfields) &&
413 (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) {
414 $userdetails['phone1'] = $user->phone1
;
416 if (!empty($user->phone2
) && in_array('phone2', $userfields) &&
417 (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) {
418 $userdetails['phone2'] = $user->phone2
;
421 if (isset($user->description
) &&
422 ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
423 if (in_array('description', $userfields)) {
424 // Always return the descriptionformat if description is requested.
425 list($userdetails['description'], $userdetails['descriptionformat']) =
426 external_format_text($user->description
, $user->descriptionformat
,
427 $usercontext->id
, 'user', 'profile', null);
431 if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country
) {
432 $userdetails['country'] = $user->country
;
435 if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city
) {
436 $userdetails['city'] = $user->city
;
439 if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) {
440 $userdetails['suspended'] = (bool)$user->suspended
;
443 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
444 if ($user->firstaccess
) {
445 $userdetails['firstaccess'] = $user->firstaccess
;
447 $userdetails['firstaccess'] = 0;
450 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
451 if ($user->lastaccess
) {
452 $userdetails['lastaccess'] = $user->lastaccess
;
454 $userdetails['lastaccess'] = 0;
458 // Hidden fields restriction to lastaccess field applies to both site and course access time.
459 if (in_array('lastcourseaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
460 if (isset($user->lastcourseaccess
)) {
461 $userdetails['lastcourseaccess'] = $user->lastcourseaccess
;
463 $userdetails['lastcourseaccess'] = 0;
467 if (in_array('email', $userfields) && (
469 or (!isset($hiddenfields['email']) and (
470 $user->maildisplay
== core_user
::MAILDISPLAY_EVERYONE
471 or ($user->maildisplay
== core_user
::MAILDISPLAY_COURSE_MEMBERS_ONLY
and enrol_sharing_course($user, $USER))
472 or $canviewuseremail // TODO: Deprecate/remove for MDL-37479.
474 or in_array('email', $showuseridentityfields)
476 $userdetails['email'] = $user->email
;
479 if (in_array('interests', $userfields)) {
480 $interests = core_tag_tag
::get_item_tags_array('core', 'user', $user->id
, core_tag_tag
::BOTH_STANDARD_AND_NOT
, 0, false);
482 $userdetails['interests'] = join(', ', $interests);
486 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
487 if (in_array('idnumber', $userfields) && $user->idnumber
) {
488 if (in_array('idnumber', $showuseridentityfields) or $currentuser or
489 has_capability('moodle/user:viewalldetails', $context)) {
490 $userdetails['idnumber'] = $user->idnumber
;
493 if (in_array('institution', $userfields) && $user->institution
) {
494 if (in_array('institution', $showuseridentityfields) or $currentuser or
495 has_capability('moodle/user:viewalldetails', $context)) {
496 $userdetails['institution'] = $user->institution
;
499 // Isset because it's ok to have department 0.
500 if (in_array('department', $userfields) && isset($user->department
)) {
501 if (in_array('department', $showuseridentityfields) or $currentuser or
502 has_capability('moodle/user:viewalldetails', $context)) {
503 $userdetails['department'] = $user->department
;
507 if (in_array('roles', $userfields) && !empty($course)) {
509 $roles = get_user_roles($context, $user->id
, false);
510 $userdetails['roles'] = array();
511 foreach ($roles as $role) {
512 $userdetails['roles'][] = array(
513 'roleid' => $role->roleid
,
514 'name' => $role->name
,
515 'shortname' => $role->shortname
,
516 'sortorder' => $role->sortorder
521 // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
522 if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
523 $usergroups = groups_get_all_groups($course->id
, $user->id
, $course->defaultgroupingid
,
524 'g.id, g.name,g.description,g.descriptionformat');
525 $userdetails['groups'] = array();
526 foreach ($usergroups as $group) {
527 list($group->description
, $group->descriptionformat
) =
528 external_format_text($group->description
, $group->descriptionformat
,
529 $context->id
, 'group', 'description', $group->id
);
530 $userdetails['groups'][] = array('id' => $group->id
, 'name' => $group->name
,
531 'description' => $group->description
, 'descriptionformat' => $group->descriptionformat
);
534 // List of courses where the user is enrolled.
535 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
536 $enrolledcourses = array();
537 if ($mycourses = enrol_get_users_courses($user->id
, true)) {
538 foreach ($mycourses as $mycourse) {
539 if ($mycourse->category
) {
540 $coursecontext = context_course
::instance($mycourse->id
);
541 $enrolledcourse = array();
542 $enrolledcourse['id'] = $mycourse->id
;
543 $enrolledcourse['fullname'] = format_string($mycourse->fullname
, true, array('context' => $coursecontext));
544 $enrolledcourse['shortname'] = format_string($mycourse->shortname
, true, array('context' => $coursecontext));
545 $enrolledcourses[] = $enrolledcourse;
548 $userdetails['enrolledcourses'] = $enrolledcourses;
553 if (in_array('preferences', $userfields) && $currentuser) {
554 $preferences = array();
555 $userpreferences = get_user_preferences();
556 foreach ($userpreferences as $prefname => $prefvalue) {
557 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
559 $userdetails['preferences'] = $preferences;
562 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
563 $extrafields = ['auth', 'confirmed', 'lang', 'theme', 'timezone', 'mailformat'];
564 foreach ($extrafields as $extrafield) {
565 if (in_array($extrafield, $userfields) && isset($user->$extrafield)) {
566 $userdetails[$extrafield] = $user->$extrafield;
571 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
572 if (isset($userdetails['lang'])) {
573 $userdetails['lang'] = clean_param($userdetails['lang'], PARAM_LANG
);
575 if (isset($userdetails['theme'])) {
576 $userdetails['theme'] = clean_param($userdetails['theme'], PARAM_THEME
);
583 * Tries to obtain user details, either recurring directly to the user's system profile
584 * or through one of the user's course enrollments (course profile).
586 * You can use the $userfields parameter to reduce the amount of a user record that is required by the method.
587 * The minimum user fields are:
590 * * all potential fullname fields
592 * @param stdClass $user The user.
593 * @param array $userfields An array of userfields to be returned, the values must be a
594 * subset of user_get_default_fields (optional)
595 * @return array if unsuccessful or the allowed user details.
597 function user_get_user_details_courses($user, array $userfields = []) {
601 $systemprofile = false;
602 if (can_view_user_details_cap($user) ||
($user->id
== $USER->id
) ||
has_coursecontact_role($user->id
)) {
603 $systemprofile = true;
606 // Try using system profile.
607 if ($systemprofile) {
608 $userdetails = user_get_user_details($user, null, $userfields);
610 // Try through course profile.
611 // Get the courses that the user is enrolled in (only active).
612 $courses = enrol_get_users_courses($user->id
, true);
613 foreach ($courses as $course) {
614 if (user_can_view_profile($user, $course)) {
615 $userdetails = user_get_user_details($user, $course, $userfields);
624 * Check if $USER have the necessary capabilities to obtain user details.
626 * @param stdClass $user
627 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
628 * @return bool true if $USER can view user details.
630 function can_view_user_details_cap($user, $course = null) {
631 // Check $USER has the capability to view the user details at user context.
632 $usercontext = context_user
::instance($user->id
);
633 $result = has_capability('moodle/user:viewdetails', $usercontext);
634 // Otherwise can $USER see them at course context.
635 if (!$result && !empty($course)) {
636 $context = context_course
::instance($course->id
);
637 $result = has_capability('moodle/user:viewdetails', $context);
643 * Return a list of page types
644 * @param string $pagetype current page type
645 * @param stdClass $parentcontext Block's parent context
646 * @param stdClass $currentcontext Current context of block
649 function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
650 return array('user-profile' => get_string('page-user-profile', 'pagetype'));
654 * Count the number of failed login attempts for the given user, since last successful login.
656 * @param int|stdclass $user user id or object.
657 * @param bool $reset Resets failed login count, if set to true.
659 * @return int number of failed login attempts since the last successful login.
661 function user_count_login_failures($user, $reset = true) {
664 if (!is_object($user)) {
665 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST
);
667 if ($user->deleted
) {
668 // Deleted user, nothing to do.
671 $count = get_user_preferences('login_failed_count_since_success', 0, $user);
673 set_user_preference('login_failed_count_since_success', 0, $user);
679 * Converts a string into a flat array of menu items, where each menu items is a
680 * stdClass with fields type, url, title.
682 * @param string $text the menu items definition
683 * @param moodle_page $page the current page
686 function user_convert_text_to_menu_items($text, $page) {
687 global $OUTPUT, $CFG;
689 $lines = explode("\n", $text);
695 foreach ($lines as $line) {
697 $bits = explode('|', $line, 2);
699 if (preg_match("/^#+$/", $line)) {
700 $itemtype = 'divider';
701 } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
702 // Every item must have a name to be valid.
705 $bits[0] = ltrim($bits[0], '-');
709 $child = new stdClass();
710 $child->itemtype
= $itemtype;
711 if ($itemtype === 'divider') {
712 // Add the divider to the list of children and skip link
714 $children[] = $child;
719 $namebits = explode(',', $bits[0], 2);
720 if (count($namebits) == 2) {
721 // Check the validity of the identifier part of the string.
722 if (clean_param($namebits[0], PARAM_STRINGID
) !== '') {
723 // Treat this as a language string.
724 $child->title
= get_string($namebits[0], $namebits[1]);
725 $child->titleidentifier
= implode(',', $namebits);
728 if (empty($child->title
)) {
729 // Use it as is, don't even clean it.
730 $child->title
= $bits[0];
731 $child->titleidentifier
= str_replace(" ", "-", $bits[0]);
735 if (!array_key_exists(1, $bits) or empty($bits[1])) {
736 // Set the url to null, and set the itemtype to invalid.
738 $child->itemtype
= "invalid";
740 // Nasty hack to replace the grades with the direct url.
741 if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
742 $bits[1] = user_mygrades_url();
745 // Make sure the url is a moodle url.
746 $bits[1] = new moodle_url(trim($bits[1]));
748 $child->url
= $bits[1];
750 // Add this child to the list of children.
751 $children[] = $child;
757 * Get a list of essential user navigation items.
759 * @param stdclass $user user object.
760 * @param moodle_page $page page object.
761 * @param array $options associative array.
763 * - avatarsize=35 (size of avatar image)
764 * @return stdClass $returnobj navigation information object, where:
766 * $returnobj->navitems array array of links where each link is a
767 * stdClass with fields url, title, and
769 * $returnobj->metadata array array of useful user metadata to be
770 * used when constructing navigation;
774 * asotherrole bool whether viewing as another role
775 * rolename string name of the role
778 * These fields are for the currently-logged in user, or for
779 * the user that the real user is currently logged in as.
781 * userid int the id of the user in question
782 * userfullname string the user's full name
783 * userprofileurl moodle_url the url of the user's profile
784 * useravatar string a HTML fragment - the rendered
785 * user_picture for this user
786 * userloginfail string an error string denoting the number
787 * of login failures since last login
790 * These fields are for when asotheruser is true, and
791 * correspond to the underlying "real user".
793 * asotheruser bool whether viewing as another user
794 * realuserid int the id of the user in question
795 * realuserfullname string the user's full name
796 * realuserprofileurl moodle_url the url of the user's profile
797 * realuseravatar string a HTML fragment - the rendered
798 * user_picture for this user
800 * MNET PROVIDER FIELDS
801 * asmnetuser bool whether viewing as a user from an
803 * mnetidprovidername string name of the MNet provider
804 * mnetidproviderwwwroot string URL of the MNet provider
806 function user_get_user_navigation_info($user, $page, $options = array()) {
807 global $OUTPUT, $DB, $SESSION, $CFG;
809 $returnobject = new stdClass();
810 $returnobject->navitems
= array();
811 $returnobject->metadata
= array();
813 $guest = isguestuser();
814 if (!isloggedin() ||
$guest) {
815 $returnobject->unauthenticateduser
= [
817 'content' => $guest ?
'loggedinasguest' : 'loggedinnot',
820 return $returnobject;
823 $course = $page->course
;
825 // Query the environment.
826 $context = context_course
::instance($course->id
);
828 // Get basic user metadata.
829 $returnobject->metadata
['userid'] = $user->id
;
830 $returnobject->metadata
['userfullname'] = fullname($user);
831 $returnobject->metadata
['userprofileurl'] = new moodle_url('/user/profile.php', array(
835 $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
836 if (!empty($options['avatarsize'])) {
837 $avataroptions['size'] = $options['avatarsize'];
839 $returnobject->metadata
['useravatar'] = $OUTPUT->user_picture (
840 $user, $avataroptions
842 // Build a list of items for a regular user.
844 // Query MNet status.
845 if ($returnobject->metadata
['asmnetuser'] = is_mnet_remote_user($user)) {
846 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid
));
847 $returnobject->metadata
['mnetidprovidername'] = $mnetidprovider->name
;
848 $returnobject->metadata
['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot
;
851 // Did the user just log in?
852 if (isset($SESSION->justloggedin
)) {
853 // Don't unset this flag as login_info still needs it.
854 if (!empty($CFG->displayloginfailures
)) {
855 // Don't reset the count either, as login_info() still needs it too.
856 if ($count = user_count_login_failures($user, false)) {
858 // Get login failures string.
860 $a->attempts
= html_writer
::tag('span', $count, array('class' => 'value mr-1 font-weight-bold'));
861 $returnobject->metadata
['userloginfail'] =
862 get_string('failedloginattempts', '', $a);
868 $returnobject->metadata
['asotherrole'] = false;
870 // Before we add the last items (usually a logout + switch role link), add any
871 // custom-defined items.
872 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems
, $page);
873 $custommenucount = 0;
874 foreach ($customitems as $item) {
875 $returnobject->navitems
[] = $item;
876 if ($item->itemtype
!== 'divider' && $item->itemtype
!== 'invalid') {
881 if ($custommenucount > 0) {
882 // Only add a divider if we have customusermenuitems.
883 $divider = new stdClass();
884 $divider->itemtype
= 'divider';
885 $returnobject->navitems
[] = $divider;
888 // Links: Preferences.
889 $preferences = new stdClass();
890 $preferences->itemtype
= 'link';
891 $preferences->url
= new moodle_url('/user/preferences.php');
892 $preferences->title
= get_string('preferences');
893 $preferences->titleidentifier
= 'preferences,moodle';
894 $returnobject->navitems
[] = $preferences;
897 if (is_role_switched($course->id
)) {
898 if ($role = $DB->get_record('role', array('id' => $user->access
['rsw'][$context->path
]))) {
899 // Build role-return link instead of logout link.
900 $rolereturn = new stdClass();
901 $rolereturn->itemtype
= 'link';
902 $rolereturn->url
= new moodle_url('/course/switchrole.php', array(
904 'sesskey' => sesskey(),
906 'returnurl' => $page->url
->out_as_local_url(false)
908 $rolereturn->title
= get_string('switchrolereturn');
909 $rolereturn->titleidentifier
= 'switchrolereturn,moodle';
910 $returnobject->navitems
[] = $rolereturn;
912 $returnobject->metadata
['asotherrole'] = true;
913 $returnobject->metadata
['rolename'] = role_get_name($role, $context);
917 // Build switch role link.
918 $roles = get_switchable_roles($context);
919 if (is_array($roles) && (count($roles) > 0)) {
920 $switchrole = new stdClass();
921 $switchrole->itemtype
= 'link';
922 $switchrole->url
= new moodle_url('/course/switchrole.php', array(
925 'returnurl' => $page->url
->out_as_local_url(false)
927 $switchrole->title
= get_string('switchroleto');
928 $switchrole->titleidentifier
= 'switchroleto,moodle';
929 $returnobject->navitems
[] = $switchrole;
933 if ($returnobject->metadata
['asotheruser'] = \core\session\manager
::is_loggedinas()) {
934 $realuser = \core\session\manager
::get_realuser();
936 // Save values for the real user, as $user will be full of data for the
937 // user is disguised as.
938 $returnobject->metadata
['realuserid'] = $realuser->id
;
939 $returnobject->metadata
['realuserfullname'] = fullname($realuser);
940 $returnobject->metadata
['realuserprofileurl'] = new moodle_url('/user/profile.php', [
941 'id' => $realuser->id
943 $returnobject->metadata
['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
945 // Build a user-revert link.
946 $userrevert = new stdClass();
947 $userrevert->itemtype
= 'link';
948 $userrevert->url
= new moodle_url('/course/loginas.php', [
950 'sesskey' => sesskey()
952 $userrevert->title
= get_string('logout');
953 $userrevert->titleidentifier
= 'logout,moodle';
954 $returnobject->navitems
[] = $userrevert;
956 // Build a logout link.
957 $logout = new stdClass();
958 $logout->itemtype
= 'link';
959 $logout->url
= new moodle_url('/login/logout.php', ['sesskey' => sesskey()]);
960 $logout->title
= get_string('logout');
961 $logout->titleidentifier
= 'logout,moodle';
962 $returnobject->navitems
[] = $logout;
965 return $returnobject;
969 * Add password to the list of used hashes for this user.
971 * This is supposed to be used from:
972 * 1/ change own password form
973 * 2/ password reset process
974 * 3/ user signup in auth plugins if password changing supported
976 * @param int $userid user id
977 * @param string $password plaintext password
980 function user_add_password_history($userid, $password) {
983 if (empty($CFG->passwordreuselimit
) or $CFG->passwordreuselimit
< 0) {
987 // Note: this is using separate code form normal password hashing because
988 // we need to have this under control in the future. Also the auth
989 // plugin might not store the passwords locally at all.
991 $record = new stdClass();
992 $record->userid
= $userid;
993 $record->hash
= password_hash($password, PASSWORD_DEFAULT
);
994 $record->timecreated
= time();
995 $DB->insert_record('user_password_history', $record);
998 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
999 foreach ($records as $record) {
1001 if ($i > $CFG->passwordreuselimit
) {
1002 $DB->delete_records('user_password_history', array('id' => $record->id
));
1008 * Was this password used before on change or reset password page?
1010 * The $CFG->passwordreuselimit setting determines
1011 * how many times different password needs to be used
1012 * before allowing previously used password again.
1014 * @param int $userid user id
1015 * @param string $password plaintext password
1016 * @return bool true if password reused
1018 function user_is_previously_used_password($userid, $password) {
1021 if (empty($CFG->passwordreuselimit
) or $CFG->passwordreuselimit
< 0) {
1028 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1029 foreach ($records as $record) {
1031 if ($i > $CFG->passwordreuselimit
) {
1032 $DB->delete_records('user_password_history', array('id' => $record->id
));
1035 // NOTE: this is slow but we cannot compare the hashes directly any more.
1036 if (password_verify($password, $record->hash
)) {
1045 * Remove a user device from the Moodle database (for PUSH notifications usually).
1047 * @param string $uuid The device UUID.
1048 * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1049 * @return bool true if removed, false if the device didn't exists in the database
1052 function user_remove_user_device($uuid, $appid = "") {
1055 $conditions = array('uuid' => $uuid, 'userid' => $USER->id
);
1056 if (!empty($appid)) {
1057 $conditions['appid'] = $appid;
1060 if (!$DB->count_records('user_devices', $conditions)) {
1064 $DB->delete_records('user_devices', $conditions);
1070 * Trigger user_list_viewed event.
1072 * @param stdClass $course course object
1073 * @param stdClass $context course context object
1076 function user_list_view($course, $context) {
1078 $event = \core\event\user_list_viewed
::create(array(
1079 'objectid' => $course->id
,
1080 'courseid' => $course->id
,
1081 'context' => $context,
1083 'courseshortname' => $course->shortname
,
1084 'coursefullname' => $course->fullname
1091 * Returns the url to use for the "Grades" link in the user navigation.
1093 * @param int $userid The user's ID.
1094 * @param int $courseid The course ID if available.
1095 * @return mixed A URL to be directed to for "Grades".
1097 function user_mygrades_url($userid = null, $courseid = SITEID
) {
1100 if (isset($CFG->grade_mygrades_report
) && $CFG->grade_mygrades_report
!= 'external') {
1101 if (isset($userid) && $USER->id
!= $userid) {
1102 // Send to the gradebook report.
1103 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report
. '/index.php',
1104 array('id' => $courseid, 'userid' => $userid));
1106 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report
. '/index.php');
1108 } else if (isset($CFG->grade_mygrades_report
) && $CFG->grade_mygrades_report
== 'external'
1109 && !empty($CFG->gradereport_mygradeurl
)) {
1110 $url = $CFG->gradereport_mygradeurl
;
1112 $url = $CFG->wwwroot
;
1118 * Check if the current user has permission to view details of the supplied user.
1120 * This function supports two modes:
1121 * If the optional $course param is omitted, then this function finds all shared courses and checks whether the current user has
1122 * permission in any of them, returning true if so.
1123 * If the $course param is provided, then this function checks permissions in ONLY that course.
1125 * @param object $user The other user's details.
1126 * @param object $course if provided, only check permissions in this course.
1127 * @param context $usercontext The user context if available.
1128 * @return bool true for ability to view this user, else false.
1130 function user_can_view_profile($user, $course = null, $usercontext = null) {
1133 if ($user->deleted
) {
1137 // Do we need to be logged in?
1138 if (empty($CFG->forceloginforprofiles
)) {
1141 if (!isloggedin() ||
isguestuser()) {
1142 // User is not logged in and forceloginforprofile is set, we need to return now.
1147 // Current user can always view their profile.
1148 if ($USER->id
== $user->id
) {
1152 // Use callbacks so that (primarily) local plugins can prevent or allow profile access.
1153 $forceallow = false;
1154 $plugintypes = get_plugins_with_function('control_view_profile');
1155 foreach ($plugintypes as $plugins) {
1156 foreach ($plugins as $pluginfunction) {
1157 $result = $pluginfunction($user, $course, $usercontext);
1159 case core_user
::VIEWPROFILE_DO_NOT_PREVENT
:
1160 // If the plugin doesn't stop access, just continue to next plugin or use
1161 // default behaviour.
1163 case core_user
::VIEWPROFILE_FORCE_ALLOW
:
1164 // Record that we are definitely going to allow it (unless another plugin
1165 // returns _PREVENT).
1168 case core_user
::VIEWPROFILE_PREVENT
:
1169 // If any plugin returns PREVENT then we return false, regardless of what
1170 // other plugins said.
1179 // Course contacts have visible profiles always.
1180 if (has_coursecontact_role($user->id
)) {
1184 // If we're only checking the capabilities in the single provided course.
1185 if (isset($course)) {
1186 // Confirm that $user is enrolled in the $course we're checking.
1187 if (is_enrolled(context_course
::instance($course->id
), $user)) {
1188 $userscourses = array($course);
1191 // Else we're checking whether the current user can view $user's profile anywhere, so check user context first.
1192 if (empty($usercontext)) {
1193 $usercontext = context_user
::instance($user->id
);
1195 if (has_capability('moodle/user:viewdetails', $usercontext) ||
has_capability('moodle/user:viewalldetails', $usercontext)) {
1198 // This returns context information, so we can preload below.
1199 $userscourses = enrol_get_all_users_courses($user->id
);
1202 if (empty($userscourses)) {
1206 foreach ($userscourses as $userscourse) {
1207 context_helper
::preload_from_record($userscourse);
1208 $coursecontext = context_course
::instance($userscourse->id
);
1209 if (has_capability('moodle/user:viewdetails', $coursecontext) ||
1210 has_capability('moodle/user:viewalldetails', $coursecontext)) {
1211 if (!groups_user_groups_visible($userscourse, $user->id
)) {
1212 // Not a member of the same group.
1222 * Returns users tagged with a specified tag.
1224 * @param core_tag_tag $tag
1225 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1226 * are displayed on the page and the per-page limit may be bigger
1227 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1228 * to display items in the same context first
1229 * @param int $ctx context id where to search for records
1230 * @param bool $rec search in subcontexts as well
1231 * @param int $page 0-based number of page being displayed
1232 * @return \core_tag\output\tagindex
1234 function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1237 if ($ctx && $ctx != context_system
::instance()->id
) {
1240 // Users can only be displayed in system context.
1241 $usercount = $tag->count_tagged_items('core', 'user',
1242 'it.deleted=:notdeleted', array('notdeleted' => 0));
1244 $perpage = $exclusivemode ?
24 : 5;
1246 $totalpages = ceil($usercount / $perpage);
1249 $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage,
1250 'it.deleted=:notdeleted', array('notdeleted' => 0));
1251 $renderer = $PAGE->get_renderer('core', 'user');
1252 $content .= $renderer->user_list($userlist, $exclusivemode);
1255 return new core_tag\output\tagindex
($tag, 'core', 'user', $content,
1256 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1260 * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access a course.
1262 * @param int $accesssince The unix timestamp to compare to users' last access
1263 * @param string $tableprefix
1264 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1267 function user_get_course_lastaccess_sql($accesssince = null, $tableprefix = 'ul', $haveaccessed = false) {
1268 return user_get_lastaccess_sql('timeaccess', $accesssince, $tableprefix, $haveaccessed);
1272 * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access the system.
1274 * @param int $accesssince The unix timestamp to compare to users' last access
1275 * @param string $tableprefix
1276 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1279 function user_get_user_lastaccess_sql($accesssince = null, $tableprefix = 'u', $haveaccessed = false) {
1280 return user_get_lastaccess_sql('lastaccess', $accesssince, $tableprefix, $haveaccessed);
1284 * Returns SQL that can be used to limit a query to a period where the user last accessed or
1285 * did not access something recorded by a given table.
1287 * @param string $columnname The name of the access column to check against
1288 * @param int $accesssince The unix timestamp to compare to users' last access
1289 * @param string $tableprefix The query prefix of the table to check
1290 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1293 function user_get_lastaccess_sql($columnname, $accesssince, $tableprefix, $haveaccessed = false) {
1294 if (empty($accesssince)) {
1298 // Only users who have accessed since $accesssince.
1299 if ($haveaccessed) {
1300 if ($accesssince == -1) {
1301 // Include all users who have logged in at some point.
1302 $sql = "({$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0)";
1304 // Users who have accessed since the specified time.
1305 $sql = "{$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0
1306 AND {$tableprefix}.{$columnname} >= {$accesssince}";
1309 // Only users who have not accessed since $accesssince.
1311 if ($accesssince == -1) {
1312 // Users who have never accessed.
1313 $sql = "({$tableprefix}.{$columnname} IS NULL OR {$tableprefix}.{$columnname} = 0)";
1315 // Users who have not accessed since the specified time.
1316 $sql = "({$tableprefix}.{$columnname} IS NULL
1317 OR ({$tableprefix}.{$columnname} != 0 AND {$tableprefix}.{$columnname} < {$accesssince}))";
1325 * Callback for inplace editable API.
1327 * @param string $itemtype - Only user_roles is supported.
1328 * @param string $itemid - Courseid and userid separated by a :
1329 * @param string $newvalue - json encoded list of roleids.
1330 * @return \core\output\inplace_editable
1332 function core_user_inplace_editable($itemtype, $itemid, $newvalue) {
1333 if ($itemtype === 'user_roles') {
1334 return \core_user\output\user_roles_editable
::update($itemid, $newvalue);
1339 * Map an internal field name to a valid purpose from: "https://www.w3.org/TR/WCAG21/#input-purposes"
1341 * @param integer $userid
1342 * @param string $fieldname
1343 * @return string $purpose (empty string if there is no mapping).
1345 function user_edit_map_field_purpose($userid, $fieldname) {
1348 $currentuser = ($userid == $USER->id
) && !\core\session\manager
::is_loggedinas();
1349 // These are the fields considered valid to map and auto fill from a browser.
1350 // We do not include fields that are in a collapsed section by default because
1351 // the browser could auto-fill the field and cause a new value to be saved when
1352 // that field was never visible.
1353 $validmappings = array(
1354 'username' => 'username',
1355 'password' => 'current-password',
1356 'firstname' => 'given-name',
1357 'lastname' => 'family-name',
1358 'middlename' => 'additional-name',
1360 'country' => 'country',
1361 'lang' => 'language'
1365 // Only set a purpose when editing your own user details.
1366 if ($currentuser && isset($validmappings[$fieldname])) {
1367 $purpose = ' autocomplete="' . $validmappings[$fieldname] . '" ';