Merge branch 'install_402_STABLE' of https://git.in.moodle.com/amosbot/moodle-install...
[moodle.git] / user / lib.php
blob8cb675004b868f40d8eb355d18ca9e792ada2b3c
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
18 * External user API
20 * @package core_user
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);
32 /**
33 * Creates a user
35 * @throws moodle_exception
36 * @param stdClass|array $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) {
43 global $DB;
45 // Set the timecreate field to the current time.
46 if (!is_object($user)) {
47 $user = (object) $user;
50 // Check username.
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.
132 if ($triggerevent) {
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();
140 return $newuserid;
144 * Update a user with a user object (will compare against the ID)
146 * @throws moodle_exception
147 * @param stdClass|array $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) {
153 global $DB;
155 // Set the timecreate field to the current time.
156 if (!is_object($user)) {
157 $user = (object) $user;
160 // Check username.
161 if (isset($user->username)) {
162 if ($user->username !== core_text::strtolower($user->username)) {
163 throw new moodle_exception('usernamelowercase');
164 } else {
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 // Validate user data object.
190 $uservalidation = core_user::validate($user);
191 if ($uservalidation !== true) {
192 foreach ($uservalidation as $field => $message) {
193 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
194 $user->$field = core_user::clean_field($user->$field, $field);
198 $currentrecord = $DB->get_record('user', ['id' => $user->id]);
199 $changedattributes = [];
200 foreach ($user as $attributekey => $attributevalue) {
201 // We explicitly want to ignore 'timemodified' attribute for checking, if an update is needed.
202 if (!property_exists($currentrecord, $attributekey) || $attributekey === 'timemodified') {
203 continue;
205 if ($currentrecord->{$attributekey} != $attributevalue) {
206 $changedattributes[$attributekey] = $attributevalue;
209 if (!empty($changedattributes)) {
210 $changedattributes['timemodified'] = time();
211 $updaterecord = (object) $changedattributes;
212 $updaterecord->id = $currentrecord->id;
213 $DB->update_record('user', $updaterecord);
216 if ($updatepassword) {
217 // If there have been changes, update user record with changed attributes.
218 if (!empty($changedattributes)) {
219 foreach ($changedattributes as $attributekey => $attributevalue) {
220 $currentrecord->{$attributekey} = $attributevalue;
224 // If password was set, then update its hash.
225 if (isset($passwd)) {
226 $authplugin = get_auth_plugin($currentrecord->auth);
227 if ($authplugin->can_change_password()) {
228 $authplugin->user_update_password($currentrecord, $passwd);
232 // Trigger event if required.
233 if ($triggerevent) {
234 \core\event\user_updated::create_from_userid($user->id)->trigger();
239 * Marks user deleted in internal user database and notifies the auth plugin.
240 * Also unenrols user from all roles and does other cleanup.
242 * @todo Decide if this transaction is really needed (look for internal TODO:)
243 * @param object $user Userobject before delete (without system magic quotes)
244 * @return boolean success
246 function user_delete_user($user) {
247 return delete_user($user);
251 * Get users by id
253 * @param array $userids id of users to retrieve
254 * @return array
256 function user_get_users_by_id($userids) {
257 global $DB;
258 return $DB->get_records_list('user', 'id', $userids);
262 * Returns the list of default 'displayable' fields
264 * Contains database field names but also names used to generate information, such as enrolledcourses
266 * @return array of user fields
268 function user_get_default_fields() {
269 return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
270 'address', 'phone1', 'phone2', 'department',
271 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
272 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
273 'city', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
274 'groups', 'roles', 'preferences', 'enrolledcourses', 'suspended', 'lastcourseaccess'
280 * Give user record from mdl_user, build an array contains all user details.
282 * Warning: description file urls are 'webservice/pluginfile.php' is use.
283 * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
285 * @throws moodle_exception
286 * @param stdClass $user user record from mdl_user
287 * @param stdClass $course moodle course
288 * @param array $userfields required fields
289 * @return array|null
291 function user_get_user_details($user, $course = null, array $userfields = array()) {
292 global $USER, $DB, $CFG, $PAGE;
293 require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library.
294 require_once($CFG->dirroot . "/lib/filelib.php"); // File handling on description and friends.
296 $defaultfields = user_get_default_fields();
298 if (empty($userfields)) {
299 $userfields = $defaultfields;
302 foreach ($userfields as $thefield) {
303 if (!in_array($thefield, $defaultfields)) {
304 throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
308 // Make sure id and fullname are included.
309 if (!in_array('id', $userfields)) {
310 $userfields[] = 'id';
313 if (!in_array('fullname', $userfields)) {
314 $userfields[] = 'fullname';
317 if (!empty($course)) {
318 $context = context_course::instance($course->id);
319 $usercontext = context_user::instance($user->id);
320 $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext));
321 } else {
322 $context = context_user::instance($user->id);
323 $usercontext = $context;
324 $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
327 $currentuser = ($user->id == $USER->id);
328 $isadmin = is_siteadmin($USER);
330 // This does not need to include custom profile fields as it is only used to check specific
331 // fields below.
332 $showuseridentityfields = \core_user\fields::get_identity_fields($context, false);
334 if (!empty($course)) {
335 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
336 } else {
337 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
339 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
340 if (!empty($course)) {
341 $canviewuseremail = has_capability('moodle/course:useremail', $context);
342 } else {
343 $canviewuseremail = false;
345 $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
346 if (!empty($course)) {
347 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
348 } else {
349 $canaccessallgroups = false;
352 if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
353 // Skip this user details.
354 return null;
357 $userdetails = array();
358 $userdetails['id'] = $user->id;
360 if (in_array('username', $userfields)) {
361 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
362 $userdetails['username'] = $user->username;
365 if ($isadmin or $canviewfullnames) {
366 if (in_array('firstname', $userfields)) {
367 $userdetails['firstname'] = $user->firstname;
369 if (in_array('lastname', $userfields)) {
370 $userdetails['lastname'] = $user->lastname;
373 $userdetails['fullname'] = fullname($user, $canviewfullnames);
375 if (in_array('customfields', $userfields)) {
376 $categories = profile_get_user_fields_with_data_by_category($user->id);
377 $userdetails['customfields'] = array();
378 foreach ($categories as $categoryid => $fields) {
379 foreach ($fields as $formfield) {
380 if ($formfield->show_field_content()) {
381 $userdetails['customfields'][] = [
382 'name' => $formfield->field->name,
383 'value' => $formfield->data,
384 'displayvalue' => $formfield->display_data(),
385 'type' => $formfield->field->datatype,
386 'shortname' => $formfield->field->shortname
391 // Unset customfields if it's empty.
392 if (empty($userdetails['customfields'])) {
393 unset($userdetails['customfields']);
397 // Profile image.
398 if (in_array('profileimageurl', $userfields)) {
399 $userpicture = new user_picture($user);
400 $userpicture->size = 1; // Size f1.
401 $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
403 if (in_array('profileimageurlsmall', $userfields)) {
404 if (!isset($userpicture)) {
405 $userpicture = new user_picture($user);
407 $userpicture->size = 0; // Size f2.
408 $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
411 // Hidden user field.
412 if ($canviewhiddenuserfields) {
413 $hiddenfields = array();
414 } else {
415 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
419 if (!empty($user->address) && (in_array('address', $userfields)
420 && in_array('address', $showuseridentityfields) || $isadmin)) {
421 $userdetails['address'] = $user->address;
423 if (!empty($user->phone1) && (in_array('phone1', $userfields)
424 && in_array('phone1', $showuseridentityfields) || $isadmin)) {
425 $userdetails['phone1'] = $user->phone1;
427 if (!empty($user->phone2) && (in_array('phone2', $userfields)
428 && in_array('phone2', $showuseridentityfields) || $isadmin)) {
429 $userdetails['phone2'] = $user->phone2;
432 if (isset($user->description) &&
433 ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
434 if (in_array('description', $userfields)) {
435 // Always return the descriptionformat if description is requested.
436 list($userdetails['description'], $userdetails['descriptionformat']) =
437 \core_external\util::format_text($user->description, $user->descriptionformat,
438 $usercontext, 'user', 'profile', null);
442 if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
443 $userdetails['country'] = $user->country;
446 if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
447 $userdetails['city'] = $user->city;
450 if (in_array('timezone', $userfields) && (!isset($hiddenfields['timezone']) || $isadmin) && $user->timezone) {
451 $userdetails['timezone'] = $user->timezone;
454 if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) {
455 $userdetails['suspended'] = (bool)$user->suspended;
458 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
459 if ($user->firstaccess) {
460 $userdetails['firstaccess'] = $user->firstaccess;
461 } else {
462 $userdetails['firstaccess'] = 0;
465 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
466 if ($user->lastaccess) {
467 $userdetails['lastaccess'] = $user->lastaccess;
468 } else {
469 $userdetails['lastaccess'] = 0;
473 // Hidden fields restriction to lastaccess field applies to both site and course access time.
474 if (in_array('lastcourseaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
475 if (isset($user->lastcourseaccess)) {
476 $userdetails['lastcourseaccess'] = $user->lastcourseaccess;
477 } else {
478 $userdetails['lastcourseaccess'] = 0;
482 if (in_array('email', $userfields) && (
483 $currentuser
484 or (!isset($hiddenfields['email']) and (
485 $user->maildisplay == core_user::MAILDISPLAY_EVERYONE
486 or ($user->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY and enrol_sharing_course($user, $USER))
487 or $canviewuseremail // TODO: Deprecate/remove for MDL-37479.
489 or in_array('email', $showuseridentityfields)
490 )) {
491 $userdetails['email'] = $user->email;
494 if (in_array('interests', $userfields)) {
495 $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
496 if ($interests) {
497 $userdetails['interests'] = join(', ', $interests);
501 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
502 if (in_array('idnumber', $userfields) && $user->idnumber) {
503 if (in_array('idnumber', $showuseridentityfields) or $currentuser or
504 has_capability('moodle/user:viewalldetails', $context)) {
505 $userdetails['idnumber'] = $user->idnumber;
508 if (in_array('institution', $userfields) && $user->institution) {
509 if (in_array('institution', $showuseridentityfields) or $currentuser or
510 has_capability('moodle/user:viewalldetails', $context)) {
511 $userdetails['institution'] = $user->institution;
514 // Isset because it's ok to have department 0.
515 if (in_array('department', $userfields) && isset($user->department)) {
516 if (in_array('department', $showuseridentityfields) or $currentuser or
517 has_capability('moodle/user:viewalldetails', $context)) {
518 $userdetails['department'] = $user->department;
522 if (in_array('roles', $userfields) && !empty($course)) {
523 // Not a big secret.
524 $roles = get_user_roles($context, $user->id, false);
525 $userdetails['roles'] = array();
526 foreach ($roles as $role) {
527 $userdetails['roles'][] = array(
528 'roleid' => $role->roleid,
529 'name' => $role->name,
530 'shortname' => $role->shortname,
531 'sortorder' => $role->sortorder
536 // Return user groups.
537 if (in_array('groups', $userfields) && !empty($course)) {
538 if ($usergroups = groups_get_all_groups($course->id, $user->id)) {
539 $userdetails['groups'] = [];
540 foreach ($usergroups as $group) {
541 if ($course->groupmode == SEPARATEGROUPS && !$canaccessallgroups && $user->id != $USER->id) {
542 // In separate groups, I only have to see the groups shared between both users.
543 if (!groups_is_member($group->id, $USER->id)) {
544 continue;
548 $userdetails['groups'][] = [
549 'id' => $group->id,
550 'name' => format_string($group->name),
551 'description' => format_text($group->description, $group->descriptionformat, ['context' => $context]),
552 'descriptionformat' => $group->descriptionformat
557 // List of courses where the user is enrolled.
558 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
559 $enrolledcourses = array();
560 if ($mycourses = enrol_get_users_courses($user->id, true)) {
561 foreach ($mycourses as $mycourse) {
562 if ($mycourse->category) {
563 $coursecontext = context_course::instance($mycourse->id);
564 $enrolledcourse = array();
565 $enrolledcourse['id'] = $mycourse->id;
566 $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
567 $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
568 $enrolledcourses[] = $enrolledcourse;
571 $userdetails['enrolledcourses'] = $enrolledcourses;
575 // User preferences.
576 if (in_array('preferences', $userfields) && $currentuser) {
577 $preferences = array();
578 $userpreferences = get_user_preferences();
579 foreach ($userpreferences as $prefname => $prefvalue) {
580 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
582 $userdetails['preferences'] = $preferences;
585 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
586 $extrafields = ['auth', 'confirmed', 'lang', 'theme', 'mailformat'];
587 foreach ($extrafields as $extrafield) {
588 if (in_array($extrafield, $userfields) && isset($user->$extrafield)) {
589 $userdetails[$extrafield] = $user->$extrafield;
594 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
595 if (isset($userdetails['lang'])) {
596 $userdetails['lang'] = clean_param($userdetails['lang'], PARAM_LANG);
598 if (isset($userdetails['theme'])) {
599 $userdetails['theme'] = clean_param($userdetails['theme'], PARAM_THEME);
602 return $userdetails;
606 * Tries to obtain user details, either recurring directly to the user's system profile
607 * or through one of the user's course enrollments (course profile).
609 * You can use the $userfields parameter to reduce the amount of a user record that is required by the method.
610 * The minimum user fields are:
611 * * id
612 * * deleted
613 * * all potential fullname fields
615 * @param stdClass $user The user.
616 * @param array $userfields An array of userfields to be returned, the values must be a
617 * subset of user_get_default_fields (optional)
618 * @return array if unsuccessful or the allowed user details.
620 function user_get_user_details_courses($user, array $userfields = []) {
621 global $USER;
622 $userdetails = null;
624 $systemprofile = false;
625 if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
626 $systemprofile = true;
629 // Try using system profile.
630 if ($systemprofile) {
631 $userdetails = user_get_user_details($user, null, $userfields);
632 } else {
633 // Try through course profile.
634 // Get the courses that the user is enrolled in (only active).
635 $courses = enrol_get_users_courses($user->id, true);
636 foreach ($courses as $course) {
637 if (user_can_view_profile($user, $course)) {
638 $userdetails = user_get_user_details($user, $course, $userfields);
643 return $userdetails;
647 * Check if $USER have the necessary capabilities to obtain user details.
649 * @param stdClass $user
650 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
651 * @return bool true if $USER can view user details.
653 function can_view_user_details_cap($user, $course = null) {
654 // Check $USER has the capability to view the user details at user context.
655 $usercontext = context_user::instance($user->id);
656 $result = has_capability('moodle/user:viewdetails', $usercontext);
657 // Otherwise can $USER see them at course context.
658 if (!$result && !empty($course)) {
659 $context = context_course::instance($course->id);
660 $result = has_capability('moodle/user:viewdetails', $context);
662 return $result;
666 * Return a list of page types
667 * @param string $pagetype current page type
668 * @param stdClass $parentcontext Block's parent context
669 * @param stdClass $currentcontext Current context of block
670 * @return array
672 function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
673 return array('user-profile' => get_string('page-user-profile', 'pagetype'));
677 * Count the number of failed login attempts for the given user, since last successful login.
679 * @param int|stdclass $user user id or object.
680 * @param bool $reset Resets failed login count, if set to true.
682 * @return int number of failed login attempts since the last successful login.
684 function user_count_login_failures($user, $reset = true) {
685 global $DB;
687 if (!is_object($user)) {
688 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
690 if ($user->deleted) {
691 // Deleted user, nothing to do.
692 return 0;
694 $count = get_user_preferences('login_failed_count_since_success', 0, $user);
695 if ($reset) {
696 set_user_preference('login_failed_count_since_success', 0, $user);
698 return $count;
702 * Converts a string into a flat array of menu items, where each menu items is a
703 * stdClass with fields type, url, title.
705 * @param string $text the menu items definition
706 * @param moodle_page $page the current page
707 * @return array
709 function user_convert_text_to_menu_items($text, $page) {
710 $lines = explode("\n", $text);
711 $children = array();
712 foreach ($lines as $line) {
713 $line = trim($line);
714 $bits = explode('|', $line, 2);
715 $itemtype = 'link';
716 if (preg_match("/^#+$/", $line)) {
717 $itemtype = 'divider';
718 } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
719 // Every item must have a name to be valid.
720 continue;
721 } else {
722 $bits[0] = ltrim($bits[0], '-');
725 // Create the child.
726 $child = new stdClass();
727 $child->itemtype = $itemtype;
728 if ($itemtype === 'divider') {
729 // Add the divider to the list of children and skip link
730 // processing.
731 $children[] = $child;
732 continue;
735 // Name processing.
736 $namebits = explode(',', $bits[0], 2);
737 if (count($namebits) == 2) {
738 $namebits[1] = $namebits[1] ?: 'core';
739 // Check the validity of the identifier part of the string.
740 if (clean_param($namebits[0], PARAM_STRINGID) !== '' && clean_param($namebits[1], PARAM_COMPONENT) !== '') {
741 // Treat this as a language string.
742 $child->title = get_string($namebits[0], $namebits[1]);
743 $child->titleidentifier = implode(',', $namebits);
746 if (empty($child->title)) {
747 // Use it as is, don't even clean it.
748 $child->title = $bits[0];
749 $child->titleidentifier = str_replace(" ", "-", $bits[0]);
752 // URL processing.
753 if (!array_key_exists(1, $bits) or empty($bits[1])) {
754 // Set the url to null, and set the itemtype to invalid.
755 $bits[1] = null;
756 $child->itemtype = "invalid";
757 } else {
758 // Nasty hack to replace the grades with the direct url.
759 if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
760 $bits[1] = user_mygrades_url();
763 // Make sure the url is a moodle url.
764 $bits[1] = new moodle_url(trim($bits[1]));
766 $child->url = $bits[1];
768 // Add this child to the list of children.
769 $children[] = $child;
771 return $children;
775 * Get a list of essential user navigation items.
777 * @param stdclass $user user object.
778 * @param moodle_page $page page object.
779 * @param array $options associative array.
780 * options are:
781 * - avatarsize=35 (size of avatar image)
782 * @return stdClass $returnobj navigation information object, where:
784 * $returnobj->navitems array array of links where each link is a
785 * stdClass with fields url, title, and
786 * pix
787 * $returnobj->metadata array array of useful user metadata to be
788 * used when constructing navigation;
789 * fields include:
791 * ROLE FIELDS
792 * asotherrole bool whether viewing as another role
793 * rolename string name of the role
795 * USER FIELDS
796 * These fields are for the currently-logged in user, or for
797 * the user that the real user is currently logged in as.
799 * userid int the id of the user in question
800 * userfullname string the user's full name
801 * userprofileurl moodle_url the url of the user's profile
802 * useravatar string a HTML fragment - the rendered
803 * user_picture for this user
804 * userloginfail string an error string denoting the number
805 * of login failures since last login
807 * "REAL USER" FIELDS
808 * These fields are for when asotheruser is true, and
809 * correspond to the underlying "real user".
811 * asotheruser bool whether viewing as another user
812 * realuserid int the id of the user in question
813 * realuserfullname string the user's full name
814 * realuserprofileurl moodle_url the url of the user's profile
815 * realuseravatar string a HTML fragment - the rendered
816 * user_picture for this user
818 * MNET PROVIDER FIELDS
819 * asmnetuser bool whether viewing as a user from an
820 * MNet provider
821 * mnetidprovidername string name of the MNet provider
822 * mnetidproviderwwwroot string URL of the MNet provider
824 function user_get_user_navigation_info($user, $page, $options = array()) {
825 global $OUTPUT, $DB, $SESSION, $CFG;
827 $returnobject = new stdClass();
828 $returnobject->navitems = array();
829 $returnobject->metadata = array();
831 $guest = isguestuser();
832 if (!isloggedin() || $guest) {
833 $returnobject->unauthenticateduser = [
834 'guest' => $guest,
835 'content' => $guest ? 'loggedinasguest' : 'loggedinnot',
838 return $returnobject;
841 $course = $page->course;
843 // Query the environment.
844 $context = context_course::instance($course->id);
846 // Get basic user metadata.
847 $returnobject->metadata['userid'] = $user->id;
848 $returnobject->metadata['userfullname'] = fullname($user);
849 $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
850 'id' => $user->id
853 $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
854 if (!empty($options['avatarsize'])) {
855 $avataroptions['size'] = $options['avatarsize'];
857 $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
858 $user, $avataroptions
860 // Build a list of items for a regular user.
862 // Query MNet status.
863 if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
864 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
865 $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
866 $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
869 // Did the user just log in?
870 if (isset($SESSION->justloggedin)) {
871 // Don't unset this flag as login_info still needs it.
872 if (!empty($CFG->displayloginfailures)) {
873 // Don't reset the count either, as login_info() still needs it too.
874 if ($count = user_count_login_failures($user, false)) {
876 // Get login failures string.
877 $a = new stdClass();
878 $a->attempts = html_writer::tag('span', $count, array('class' => 'value mr-1 font-weight-bold'));
879 $returnobject->metadata['userloginfail'] =
880 get_string('failedloginattempts', '', $a);
886 $returnobject->metadata['asotherrole'] = false;
888 // Before we add the last items (usually a logout + switch role link), add any
889 // custom-defined items.
890 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
891 $custommenucount = 0;
892 foreach ($customitems as $item) {
893 $returnobject->navitems[] = $item;
894 if ($item->itemtype !== 'divider' && $item->itemtype !== 'invalid') {
895 $custommenucount++;
899 if ($custommenucount > 0) {
900 // Only add a divider if we have customusermenuitems.
901 $divider = new stdClass();
902 $divider->itemtype = 'divider';
903 $returnobject->navitems[] = $divider;
906 // Links: Preferences.
907 $preferences = new stdClass();
908 $preferences->itemtype = 'link';
909 $preferences->url = new moodle_url('/user/preferences.php');
910 $preferences->title = get_string('preferences');
911 $preferences->titleidentifier = 'preferences,moodle';
912 $returnobject->navitems[] = $preferences;
915 if (is_role_switched($course->id)) {
916 if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
917 // Build role-return link instead of logout link.
918 $rolereturn = new stdClass();
919 $rolereturn->itemtype = 'link';
920 $rolereturn->url = new moodle_url('/course/switchrole.php', array(
921 'id' => $course->id,
922 'sesskey' => sesskey(),
923 'switchrole' => 0,
924 'returnurl' => $page->url->out_as_local_url(false)
926 $rolereturn->title = get_string('switchrolereturn');
927 $rolereturn->titleidentifier = 'switchrolereturn,moodle';
928 $returnobject->navitems[] = $rolereturn;
930 $returnobject->metadata['asotherrole'] = true;
931 $returnobject->metadata['rolename'] = role_get_name($role, $context);
934 } else {
935 // Build switch role link.
936 $roles = get_switchable_roles($context);
937 if (is_array($roles) && (count($roles) > 0)) {
938 $switchrole = new stdClass();
939 $switchrole->itemtype = 'link';
940 $switchrole->url = new moodle_url('/course/switchrole.php', array(
941 'id' => $course->id,
942 'switchrole' => -1,
943 'returnurl' => $page->url->out_as_local_url(false)
945 $switchrole->title = get_string('switchroleto');
946 $switchrole->titleidentifier = 'switchroleto,moodle';
947 $returnobject->navitems[] = $switchrole;
951 if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
952 $realuser = \core\session\manager::get_realuser();
954 // Save values for the real user, as $user will be full of data for the
955 // user is disguised as.
956 $returnobject->metadata['realuserid'] = $realuser->id;
957 $returnobject->metadata['realuserfullname'] = fullname($realuser);
958 $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', [
959 'id' => $realuser->id
961 $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
963 // Build a user-revert link.
964 $userrevert = new stdClass();
965 $userrevert->itemtype = 'link';
966 $userrevert->url = new moodle_url('/course/loginas.php', [
967 'id' => $course->id,
968 'sesskey' => sesskey()
970 $userrevert->title = get_string('logout');
971 $userrevert->titleidentifier = 'logout,moodle';
972 $returnobject->navitems[] = $userrevert;
973 } else {
974 // Build a logout link.
975 $logout = new stdClass();
976 $logout->itemtype = 'link';
977 $logout->url = new moodle_url('/login/logout.php', ['sesskey' => sesskey()]);
978 $logout->title = get_string('logout');
979 $logout->titleidentifier = 'logout,moodle';
980 $returnobject->navitems[] = $logout;
983 return $returnobject;
987 * Add password to the list of used hashes for this user.
989 * This is supposed to be used from:
990 * 1/ change own password form
991 * 2/ password reset process
992 * 3/ user signup in auth plugins if password changing supported
994 * @param int $userid user id
995 * @param string $password plaintext password
996 * @return void
998 function user_add_password_history($userid, $password) {
999 global $CFG, $DB;
1001 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1002 return;
1005 // Note: this is using separate code form normal password hashing because
1006 // we need to have this under control in the future. Also the auth
1007 // plugin might not store the passwords locally at all.
1009 $record = new stdClass();
1010 $record->userid = $userid;
1011 $record->hash = password_hash($password, PASSWORD_DEFAULT);
1012 $record->timecreated = time();
1013 $DB->insert_record('user_password_history', $record);
1015 $i = 0;
1016 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1017 foreach ($records as $record) {
1018 $i++;
1019 if ($i > $CFG->passwordreuselimit) {
1020 $DB->delete_records('user_password_history', array('id' => $record->id));
1026 * Was this password used before on change or reset password page?
1028 * The $CFG->passwordreuselimit setting determines
1029 * how many times different password needs to be used
1030 * before allowing previously used password again.
1032 * @param int $userid user id
1033 * @param string $password plaintext password
1034 * @return bool true if password reused
1036 function user_is_previously_used_password($userid, $password) {
1037 global $CFG, $DB;
1039 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1040 return false;
1043 $reused = false;
1045 $i = 0;
1046 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1047 foreach ($records as $record) {
1048 $i++;
1049 if ($i > $CFG->passwordreuselimit) {
1050 $DB->delete_records('user_password_history', array('id' => $record->id));
1051 continue;
1053 // NOTE: this is slow but we cannot compare the hashes directly any more.
1054 if (password_verify($password, $record->hash)) {
1055 $reused = true;
1059 return $reused;
1063 * Remove a user device from the Moodle database (for PUSH notifications usually).
1065 * @param string $uuid The device UUID.
1066 * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1067 * @return bool true if removed, false if the device didn't exists in the database
1068 * @since Moodle 2.9
1070 function user_remove_user_device($uuid, $appid = "") {
1071 global $DB, $USER;
1073 $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
1074 if (!empty($appid)) {
1075 $conditions['appid'] = $appid;
1078 if (!$DB->count_records('user_devices', $conditions)) {
1079 return false;
1082 $DB->delete_records('user_devices', $conditions);
1084 return true;
1088 * Trigger user_list_viewed event.
1090 * @param stdClass $course course object
1091 * @param stdClass $context course context object
1092 * @since Moodle 2.9
1094 function user_list_view($course, $context) {
1096 $event = \core\event\user_list_viewed::create(array(
1097 'objectid' => $course->id,
1098 'courseid' => $course->id,
1099 'context' => $context,
1100 'other' => array(
1101 'courseshortname' => $course->shortname,
1102 'coursefullname' => $course->fullname
1105 $event->trigger();
1109 * Returns the url to use for the "Grades" link in the user navigation.
1111 * @param int $userid The user's ID.
1112 * @param int $courseid The course ID if available.
1113 * @return mixed A URL to be directed to for "Grades".
1115 function user_mygrades_url($userid = null, $courseid = SITEID) {
1116 global $CFG, $USER;
1117 $url = null;
1118 if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
1119 if (isset($userid) && $USER->id != $userid) {
1120 // Send to the gradebook report.
1121 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
1122 array('id' => $courseid, 'userid' => $userid));
1123 } else {
1124 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
1126 } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
1127 && !empty($CFG->gradereport_mygradeurl)) {
1128 $url = $CFG->gradereport_mygradeurl;
1129 } else {
1130 $url = $CFG->wwwroot;
1132 return $url;
1136 * Check if the current user has permission to view details of the supplied user.
1138 * This function supports two modes:
1139 * If the optional $course param is omitted, then this function finds all shared courses and checks whether the current user has
1140 * permission in any of them, returning true if so.
1141 * If the $course param is provided, then this function checks permissions in ONLY that course.
1143 * @param object $user The other user's details.
1144 * @param object $course if provided, only check permissions in this course.
1145 * @param context $usercontext The user context if available.
1146 * @return bool true for ability to view this user, else false.
1148 function user_can_view_profile($user, $course = null, $usercontext = null) {
1149 global $USER, $CFG;
1151 if ($user->deleted) {
1152 return false;
1155 // Do we need to be logged in?
1156 if (empty($CFG->forceloginforprofiles)) {
1157 return true;
1158 } else {
1159 if (!isloggedin() || isguestuser()) {
1160 // User is not logged in and forceloginforprofile is set, we need to return now.
1161 return false;
1165 // Current user can always view their profile.
1166 if ($USER->id == $user->id) {
1167 return true;
1170 // Use callbacks so that (primarily) local plugins can prevent or allow profile access.
1171 $forceallow = false;
1172 $plugintypes = get_plugins_with_function('control_view_profile');
1173 foreach ($plugintypes as $plugins) {
1174 foreach ($plugins as $pluginfunction) {
1175 $result = $pluginfunction($user, $course, $usercontext);
1176 switch ($result) {
1177 case core_user::VIEWPROFILE_DO_NOT_PREVENT:
1178 // If the plugin doesn't stop access, just continue to next plugin or use
1179 // default behaviour.
1180 break;
1181 case core_user::VIEWPROFILE_FORCE_ALLOW:
1182 // Record that we are definitely going to allow it (unless another plugin
1183 // returns _PREVENT).
1184 $forceallow = true;
1185 break;
1186 case core_user::VIEWPROFILE_PREVENT:
1187 // If any plugin returns PREVENT then we return false, regardless of what
1188 // other plugins said.
1189 return false;
1193 if ($forceallow) {
1194 return true;
1197 // Course contacts have visible profiles always.
1198 if (has_coursecontact_role($user->id)) {
1199 return true;
1202 // If we're only checking the capabilities in the single provided course.
1203 if (isset($course)) {
1204 // Confirm that $user is enrolled in the $course we're checking.
1205 if (is_enrolled(context_course::instance($course->id), $user)) {
1206 $userscourses = array($course);
1208 } else {
1209 // Else we're checking whether the current user can view $user's profile anywhere, so check user context first.
1210 if (empty($usercontext)) {
1211 $usercontext = context_user::instance($user->id);
1213 if (has_capability('moodle/user:viewdetails', $usercontext) || has_capability('moodle/user:viewalldetails', $usercontext)) {
1214 return true;
1216 // This returns context information, so we can preload below.
1217 $userscourses = enrol_get_all_users_courses($user->id);
1220 if (empty($userscourses)) {
1221 return false;
1224 foreach ($userscourses as $userscourse) {
1225 context_helper::preload_from_record($userscourse);
1226 $coursecontext = context_course::instance($userscourse->id);
1227 if (has_capability('moodle/user:viewdetails', $coursecontext) ||
1228 has_capability('moodle/user:viewalldetails', $coursecontext)) {
1229 if (!groups_user_groups_visible($userscourse, $user->id)) {
1230 // Not a member of the same group.
1231 continue;
1233 return true;
1236 return false;
1240 * Returns users tagged with a specified tag.
1242 * @param core_tag_tag $tag
1243 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1244 * are displayed on the page and the per-page limit may be bigger
1245 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1246 * to display items in the same context first
1247 * @param int $ctx context id where to search for records
1248 * @param bool $rec search in subcontexts as well
1249 * @param int $page 0-based number of page being displayed
1250 * @return \core_tag\output\tagindex
1252 function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1253 global $PAGE;
1255 if ($ctx && $ctx != context_system::instance()->id) {
1256 $usercount = 0;
1257 } else {
1258 // Users can only be displayed in system context.
1259 $usercount = $tag->count_tagged_items('core', 'user',
1260 'it.deleted=:notdeleted', array('notdeleted' => 0));
1262 $perpage = $exclusivemode ? 24 : 5;
1263 $content = '';
1264 $totalpages = ceil($usercount / $perpage);
1266 if ($usercount) {
1267 $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage,
1268 'it.deleted=:notdeleted', array('notdeleted' => 0));
1269 $renderer = $PAGE->get_renderer('core', 'user');
1270 $content .= $renderer->user_list($userlist, $exclusivemode);
1273 return new core_tag\output\tagindex($tag, 'core', 'user', $content,
1274 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1278 * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access a course.
1280 * @param int $accesssince The unix timestamp to compare to users' last access
1281 * @param string $tableprefix
1282 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1283 * @return string
1285 function user_get_course_lastaccess_sql($accesssince = null, $tableprefix = 'ul', $haveaccessed = false) {
1286 return user_get_lastaccess_sql('timeaccess', $accesssince, $tableprefix, $haveaccessed);
1290 * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access the system.
1292 * @param int $accesssince The unix timestamp to compare to users' last access
1293 * @param string $tableprefix
1294 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1295 * @return string
1297 function user_get_user_lastaccess_sql($accesssince = null, $tableprefix = 'u', $haveaccessed = false) {
1298 return user_get_lastaccess_sql('lastaccess', $accesssince, $tableprefix, $haveaccessed);
1302 * Returns SQL that can be used to limit a query to a period where the user last accessed or
1303 * did not access something recorded by a given table.
1305 * @param string $columnname The name of the access column to check against
1306 * @param int $accesssince The unix timestamp to compare to users' last access
1307 * @param string $tableprefix The query prefix of the table to check
1308 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1309 * @return string
1311 function user_get_lastaccess_sql($columnname, $accesssince, $tableprefix, $haveaccessed = false) {
1312 if (empty($accesssince)) {
1313 return '';
1316 // Only users who have accessed since $accesssince.
1317 if ($haveaccessed) {
1318 if ($accesssince == -1) {
1319 // Include all users who have logged in at some point.
1320 $sql = "({$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0)";
1321 } else {
1322 // Users who have accessed since the specified time.
1323 $sql = "{$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0
1324 AND {$tableprefix}.{$columnname} >= {$accesssince}";
1326 } else {
1327 // Only users who have not accessed since $accesssince.
1329 if ($accesssince == -1) {
1330 // Users who have never accessed.
1331 $sql = "({$tableprefix}.{$columnname} IS NULL OR {$tableprefix}.{$columnname} = 0)";
1332 } else {
1333 // Users who have not accessed since the specified time.
1334 $sql = "({$tableprefix}.{$columnname} IS NULL
1335 OR ({$tableprefix}.{$columnname} != 0 AND {$tableprefix}.{$columnname} < {$accesssince}))";
1339 return $sql;
1343 * Callback for inplace editable API.
1345 * @param string $itemtype - Only user_roles is supported.
1346 * @param string $itemid - Courseid and userid separated by a :
1347 * @param string $newvalue - json encoded list of roleids.
1348 * @return \core\output\inplace_editable|null
1350 function core_user_inplace_editable($itemtype, $itemid, $newvalue) {
1351 if ($itemtype === 'user_roles') {
1352 return \core_user\output\user_roles_editable::update($itemid, $newvalue);
1357 * Map an internal field name to a valid purpose from: "https://www.w3.org/TR/WCAG21/#input-purposes"
1359 * @param integer $userid
1360 * @param string $fieldname
1361 * @return string $purpose (empty string if there is no mapping).
1363 function user_edit_map_field_purpose($userid, $fieldname) {
1364 global $USER;
1366 $currentuser = ($userid == $USER->id) && !\core\session\manager::is_loggedinas();
1367 // These are the fields considered valid to map and auto fill from a browser.
1368 // We do not include fields that are in a collapsed section by default because
1369 // the browser could auto-fill the field and cause a new value to be saved when
1370 // that field was never visible.
1371 $validmappings = array(
1372 'username' => 'username',
1373 'password' => 'current-password',
1374 'firstname' => 'given-name',
1375 'lastname' => 'family-name',
1376 'middlename' => 'additional-name',
1377 'email' => 'email',
1378 'country' => 'country',
1379 'lang' => 'language'
1382 $purpose = '';
1383 // Only set a purpose when editing your own user details.
1384 if ($currentuser && isset($validmappings[$fieldname])) {
1385 $purpose = ' autocomplete="' . $validmappings[$fieldname] . '" ';
1388 return $purpose;
1392 * Update the users public key for the specified device and app.
1394 * @param string $uuid The device UUID.
1395 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1396 * @param string $publickey The app generated public key.
1397 * @return bool
1398 * @since Moodle 4.2
1400 function user_update_device_public_key(string $uuid, string $appid, string $publickey): bool {
1401 global $USER, $DB;
1403 if (!$DB->get_record('user_devices',
1404 ['uuid' => $uuid, 'appid' => $appid, 'userid' => $USER->id]
1405 )) {
1406 return false;
1409 $DB->set_field('user_devices', 'publickey', $publickey,
1410 ['uuid' => $uuid, 'appid' => $appid, 'userid' => $USER->id]
1413 return true;