Merge branch 'MDL-78811-Master' of https://github.com/aydevworks/moodle
[moodle.git] / user / lib.php
blobcbe2691acc6c49d37dfee34d6d173ea3f6890578
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, $CFG;
155 // Set the timecreate field to the current time.
156 if (!is_object($user)) {
157 $user = (object) $user;
160 // Communication api update for user.
161 if (core_communication\api::is_available()) {
162 $usercourses = enrol_get_users_courses($user->id);
163 $currentrecord = $DB->get_record('user', ['id' => $user->id]);
164 if (!empty($currentrecord) && isset($user->suspended) && $currentrecord->suspended !== $user->suspended) {
165 foreach ($usercourses as $usercourse) {
166 $communication = \core_communication\api::load_by_instance(
167 'core_course',
168 'coursecommunication',
169 $usercourse->id
171 // If the record updated the suspended for a user.
172 if ($user->suspended === 0) {
173 $communication->add_members_to_room([$user->id]);
174 } else if ($user->suspended === 1) {
175 $communication->remove_members_from_room([$user->id]);
181 // Check username.
182 if (isset($user->username)) {
183 if ($user->username !== core_text::strtolower($user->username)) {
184 throw new moodle_exception('usernamelowercase');
185 } else {
186 if ($user->username !== core_user::clean_field($user->username, 'username')) {
187 throw new moodle_exception('invalidusername');
192 // Unset password here, for updating later, if password update is required.
193 if ($updatepassword && isset($user->password)) {
195 // Check password toward the password policy.
196 if (!check_password_policy($user->password, $errmsg, $user)) {
197 throw new moodle_exception($errmsg);
200 $passwd = $user->password;
201 unset($user->password);
204 // Make sure calendartype, if set, is valid.
205 if (empty($user->calendartype)) {
206 // Unset this variable, must be an empty string, which we do not want to update the calendartype to.
207 unset($user->calendartype);
210 $user->timemodified = time();
212 // Validate user data object.
213 $uservalidation = core_user::validate($user);
214 if ($uservalidation !== true) {
215 foreach ($uservalidation as $field => $message) {
216 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
217 $user->$field = core_user::clean_field($user->$field, $field);
221 $DB->update_record('user', $user);
223 if ($updatepassword) {
224 // Get full user record.
225 $updateduser = $DB->get_record('user', array('id' => $user->id));
227 // If password was set, then update its hash.
228 if (isset($passwd)) {
229 $authplugin = get_auth_plugin($updateduser->auth);
230 if ($authplugin->can_change_password()) {
231 $authplugin->user_update_password($updateduser, $passwd);
235 // Trigger event if required.
236 if ($triggerevent) {
237 \core\event\user_updated::create_from_userid($user->id)->trigger();
242 * Marks user deleted in internal user database and notifies the auth plugin.
243 * Also unenrols user from all roles and does other cleanup.
245 * @todo Decide if this transaction is really needed (look for internal TODO:)
246 * @param object $user Userobject before delete (without system magic quotes)
247 * @return boolean success
249 function user_delete_user($user) {
250 return delete_user($user);
254 * Get users by id
256 * @param array $userids id of users to retrieve
257 * @return array
259 function user_get_users_by_id($userids) {
260 global $DB;
261 return $DB->get_records_list('user', 'id', $userids);
265 * Returns the list of default 'displayable' fields
267 * Contains database field names but also names used to generate information, such as enrolledcourses
269 * @return array of user fields
271 function user_get_default_fields() {
272 return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
273 'address', 'phone1', 'phone2', 'department',
274 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
275 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
276 'city', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
277 'groups', 'roles', 'preferences', 'enrolledcourses', 'suspended', 'lastcourseaccess'
283 * Give user record from mdl_user, build an array contains all user details.
285 * Warning: description file urls are 'webservice/pluginfile.php' is use.
286 * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
288 * @throws moodle_exception
289 * @param stdClass $user user record from mdl_user
290 * @param stdClass $course moodle course
291 * @param array $userfields required fields
292 * @return array|null
294 function user_get_user_details($user, $course = null, array $userfields = array()) {
295 global $USER, $DB, $CFG, $PAGE;
296 require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library.
297 require_once($CFG->dirroot . "/lib/filelib.php"); // File handling on description and friends.
299 $defaultfields = user_get_default_fields();
301 if (empty($userfields)) {
302 $userfields = $defaultfields;
305 foreach ($userfields as $thefield) {
306 if (!in_array($thefield, $defaultfields)) {
307 throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
311 // Make sure id and fullname are included.
312 if (!in_array('id', $userfields)) {
313 $userfields[] = 'id';
316 if (!in_array('fullname', $userfields)) {
317 $userfields[] = 'fullname';
320 if (!empty($course)) {
321 $context = context_course::instance($course->id);
322 $usercontext = context_user::instance($user->id);
323 $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext));
324 } else {
325 $context = context_user::instance($user->id);
326 $usercontext = $context;
327 $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
330 $currentuser = ($user->id == $USER->id);
331 $isadmin = is_siteadmin($USER);
333 // This does not need to include custom profile fields as it is only used to check specific
334 // fields below.
335 $showuseridentityfields = \core_user\fields::get_identity_fields($context, false);
337 if (!empty($course)) {
338 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
339 } else {
340 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
342 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
343 if (!empty($course)) {
344 $canviewuseremail = has_capability('moodle/course:useremail', $context);
345 } else {
346 $canviewuseremail = false;
348 $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
349 if (!empty($course)) {
350 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
351 } else {
352 $canaccessallgroups = false;
355 if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
356 // Skip this user details.
357 return null;
360 $userdetails = array();
361 $userdetails['id'] = $user->id;
363 if (in_array('username', $userfields)) {
364 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
365 $userdetails['username'] = $user->username;
368 if ($isadmin or $canviewfullnames) {
369 if (in_array('firstname', $userfields)) {
370 $userdetails['firstname'] = $user->firstname;
372 if (in_array('lastname', $userfields)) {
373 $userdetails['lastname'] = $user->lastname;
376 $userdetails['fullname'] = fullname($user, $canviewfullnames);
378 if (in_array('customfields', $userfields)) {
379 $categories = profile_get_user_fields_with_data_by_category($user->id);
380 $userdetails['customfields'] = array();
381 foreach ($categories as $categoryid => $fields) {
382 foreach ($fields as $formfield) {
383 if ($formfield->is_visible() and !$formfield->is_empty()) {
385 $userdetails['customfields'][] = [
386 'name' => $formfield->field->name,
387 'value' => $formfield->data,
388 'displayvalue' => $formfield->display_data(),
389 'type' => $formfield->field->datatype,
390 'shortname' => $formfield->field->shortname
395 // Unset customfields if it's empty.
396 if (empty($userdetails['customfields'])) {
397 unset($userdetails['customfields']);
401 // Profile image.
402 if (in_array('profileimageurl', $userfields)) {
403 $userpicture = new user_picture($user);
404 $userpicture->size = 1; // Size f1.
405 $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
407 if (in_array('profileimageurlsmall', $userfields)) {
408 if (!isset($userpicture)) {
409 $userpicture = new user_picture($user);
411 $userpicture->size = 0; // Size f2.
412 $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
415 // Hidden user field.
416 if ($canviewhiddenuserfields) {
417 $hiddenfields = array();
418 } else {
419 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
423 if (!empty($user->address) && (in_array('address', $userfields)
424 && in_array('address', $showuseridentityfields) || $isadmin)) {
425 $userdetails['address'] = $user->address;
427 if (!empty($user->phone1) && (in_array('phone1', $userfields)
428 && in_array('phone1', $showuseridentityfields) || $isadmin)) {
429 $userdetails['phone1'] = $user->phone1;
431 if (!empty($user->phone2) && (in_array('phone2', $userfields)
432 && in_array('phone2', $showuseridentityfields) || $isadmin)) {
433 $userdetails['phone2'] = $user->phone2;
436 if (isset($user->description) &&
437 ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
438 if (in_array('description', $userfields)) {
439 // Always return the descriptionformat if description is requested.
440 list($userdetails['description'], $userdetails['descriptionformat']) =
441 \core_external\util::format_text($user->description, $user->descriptionformat,
442 $usercontext, 'user', 'profile', null);
446 if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
447 $userdetails['country'] = $user->country;
450 if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
451 $userdetails['city'] = $user->city;
454 if (in_array('timezone', $userfields) && (!isset($hiddenfields['timezone']) || $isadmin) && $user->timezone) {
455 $userdetails['timezone'] = $user->timezone;
458 if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) {
459 $userdetails['suspended'] = (bool)$user->suspended;
462 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
463 if ($user->firstaccess) {
464 $userdetails['firstaccess'] = $user->firstaccess;
465 } else {
466 $userdetails['firstaccess'] = 0;
469 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
470 if ($user->lastaccess) {
471 $userdetails['lastaccess'] = $user->lastaccess;
472 } else {
473 $userdetails['lastaccess'] = 0;
477 // Hidden fields restriction to lastaccess field applies to both site and course access time.
478 if (in_array('lastcourseaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
479 if (isset($user->lastcourseaccess)) {
480 $userdetails['lastcourseaccess'] = $user->lastcourseaccess;
481 } else {
482 $userdetails['lastcourseaccess'] = 0;
486 if (in_array('email', $userfields) && (
487 $currentuser
488 or (!isset($hiddenfields['email']) and (
489 $user->maildisplay == core_user::MAILDISPLAY_EVERYONE
490 or ($user->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY and enrol_sharing_course($user, $USER))
491 or $canviewuseremail // TODO: Deprecate/remove for MDL-37479.
493 or in_array('email', $showuseridentityfields)
494 )) {
495 $userdetails['email'] = $user->email;
498 if (in_array('interests', $userfields)) {
499 $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
500 if ($interests) {
501 $userdetails['interests'] = join(', ', $interests);
505 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
506 if (in_array('idnumber', $userfields) && $user->idnumber) {
507 if (in_array('idnumber', $showuseridentityfields) or $currentuser or
508 has_capability('moodle/user:viewalldetails', $context)) {
509 $userdetails['idnumber'] = $user->idnumber;
512 if (in_array('institution', $userfields) && $user->institution) {
513 if (in_array('institution', $showuseridentityfields) or $currentuser or
514 has_capability('moodle/user:viewalldetails', $context)) {
515 $userdetails['institution'] = $user->institution;
518 // Isset because it's ok to have department 0.
519 if (in_array('department', $userfields) && isset($user->department)) {
520 if (in_array('department', $showuseridentityfields) or $currentuser or
521 has_capability('moodle/user:viewalldetails', $context)) {
522 $userdetails['department'] = $user->department;
526 if (in_array('roles', $userfields) && !empty($course)) {
527 // Not a big secret.
528 $roles = get_user_roles($context, $user->id, false);
529 $userdetails['roles'] = array();
530 foreach ($roles as $role) {
531 $userdetails['roles'][] = array(
532 'roleid' => $role->roleid,
533 'name' => $role->name,
534 'shortname' => $role->shortname,
535 'sortorder' => $role->sortorder
540 // Return user groups.
541 if (in_array('groups', $userfields) && !empty($course)) {
542 if ($usergroups = groups_get_all_groups($course->id, $user->id)) {
543 $userdetails['groups'] = [];
544 foreach ($usergroups as $group) {
545 if ($course->groupmode == SEPARATEGROUPS && !$canaccessallgroups && $user->id != $USER->id) {
546 // In separate groups, I only have to see the groups shared between both users.
547 if (!groups_is_member($group->id, $USER->id)) {
548 continue;
552 $userdetails['groups'][] = [
553 'id' => $group->id,
554 'name' => format_string($group->name),
555 'description' => format_text($group->description, $group->descriptionformat, ['context' => $context]),
556 'descriptionformat' => $group->descriptionformat
561 // List of courses where the user is enrolled.
562 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
563 $enrolledcourses = array();
564 if ($mycourses = enrol_get_users_courses($user->id, true)) {
565 foreach ($mycourses as $mycourse) {
566 if ($mycourse->category) {
567 $coursecontext = context_course::instance($mycourse->id);
568 $enrolledcourse = array();
569 $enrolledcourse['id'] = $mycourse->id;
570 $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
571 $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
572 $enrolledcourses[] = $enrolledcourse;
575 $userdetails['enrolledcourses'] = $enrolledcourses;
579 // User preferences.
580 if (in_array('preferences', $userfields) && $currentuser) {
581 $preferences = array();
582 $userpreferences = get_user_preferences();
583 foreach ($userpreferences as $prefname => $prefvalue) {
584 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
586 $userdetails['preferences'] = $preferences;
589 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
590 $extrafields = ['auth', 'confirmed', 'lang', 'theme', 'mailformat'];
591 foreach ($extrafields as $extrafield) {
592 if (in_array($extrafield, $userfields) && isset($user->$extrafield)) {
593 $userdetails[$extrafield] = $user->$extrafield;
598 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
599 if (isset($userdetails['lang'])) {
600 $userdetails['lang'] = clean_param($userdetails['lang'], PARAM_LANG);
602 if (isset($userdetails['theme'])) {
603 $userdetails['theme'] = clean_param($userdetails['theme'], PARAM_THEME);
606 return $userdetails;
610 * Tries to obtain user details, either recurring directly to the user's system profile
611 * or through one of the user's course enrollments (course profile).
613 * You can use the $userfields parameter to reduce the amount of a user record that is required by the method.
614 * The minimum user fields are:
615 * * id
616 * * deleted
617 * * all potential fullname fields
619 * @param stdClass $user The user.
620 * @param array $userfields An array of userfields to be returned, the values must be a
621 * subset of user_get_default_fields (optional)
622 * @return array if unsuccessful or the allowed user details.
624 function user_get_user_details_courses($user, array $userfields = []) {
625 global $USER;
626 $userdetails = null;
628 $systemprofile = false;
629 if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
630 $systemprofile = true;
633 // Try using system profile.
634 if ($systemprofile) {
635 $userdetails = user_get_user_details($user, null, $userfields);
636 } else {
637 // Try through course profile.
638 // Get the courses that the user is enrolled in (only active).
639 $courses = enrol_get_users_courses($user->id, true);
640 foreach ($courses as $course) {
641 if (user_can_view_profile($user, $course)) {
642 $userdetails = user_get_user_details($user, $course, $userfields);
647 return $userdetails;
651 * Check if $USER have the necessary capabilities to obtain user details.
653 * @param stdClass $user
654 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
655 * @return bool true if $USER can view user details.
657 function can_view_user_details_cap($user, $course = null) {
658 // Check $USER has the capability to view the user details at user context.
659 $usercontext = context_user::instance($user->id);
660 $result = has_capability('moodle/user:viewdetails', $usercontext);
661 // Otherwise can $USER see them at course context.
662 if (!$result && !empty($course)) {
663 $context = context_course::instance($course->id);
664 $result = has_capability('moodle/user:viewdetails', $context);
666 return $result;
670 * Return a list of page types
671 * @param string $pagetype current page type
672 * @param stdClass $parentcontext Block's parent context
673 * @param stdClass $currentcontext Current context of block
674 * @return array
676 function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
677 return array('user-profile' => get_string('page-user-profile', 'pagetype'));
681 * Count the number of failed login attempts for the given user, since last successful login.
683 * @param int|stdclass $user user id or object.
684 * @param bool $reset Resets failed login count, if set to true.
686 * @return int number of failed login attempts since the last successful login.
688 function user_count_login_failures($user, $reset = true) {
689 global $DB;
691 if (!is_object($user)) {
692 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
694 if ($user->deleted) {
695 // Deleted user, nothing to do.
696 return 0;
698 $count = get_user_preferences('login_failed_count_since_success', 0, $user);
699 if ($reset) {
700 set_user_preference('login_failed_count_since_success', 0, $user);
702 return $count;
706 * Converts a string into a flat array of menu items, where each menu items is a
707 * stdClass with fields type, url, title.
709 * @param string $text the menu items definition
710 * @param moodle_page $page the current page
711 * @return array
713 function user_convert_text_to_menu_items($text, $page) {
714 global $OUTPUT, $CFG;
716 $lines = explode("\n", $text);
717 $items = array();
718 $lastchild = null;
719 $lastdepth = null;
720 $lastsort = 0;
721 $children = array();
722 foreach ($lines as $line) {
723 $line = trim($line);
724 $bits = explode('|', $line, 2);
725 $itemtype = 'link';
726 if (preg_match("/^#+$/", $line)) {
727 $itemtype = 'divider';
728 } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
729 // Every item must have a name to be valid.
730 continue;
731 } else {
732 $bits[0] = ltrim($bits[0], '-');
735 // Create the child.
736 $child = new stdClass();
737 $child->itemtype = $itemtype;
738 if ($itemtype === 'divider') {
739 // Add the divider to the list of children and skip link
740 // processing.
741 $children[] = $child;
742 continue;
745 // Name processing.
746 $namebits = explode(',', $bits[0], 2);
747 if (count($namebits) == 2) {
748 // Check the validity of the identifier part of the string.
749 if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
750 // Treat this as a language string.
751 $child->title = get_string($namebits[0], $namebits[1]);
752 $child->titleidentifier = implode(',', $namebits);
755 if (empty($child->title)) {
756 // Use it as is, don't even clean it.
757 $child->title = $bits[0];
758 $child->titleidentifier = str_replace(" ", "-", $bits[0]);
761 // URL processing.
762 if (!array_key_exists(1, $bits) or empty($bits[1])) {
763 // Set the url to null, and set the itemtype to invalid.
764 $bits[1] = null;
765 $child->itemtype = "invalid";
766 } else {
767 // Nasty hack to replace the grades with the direct url.
768 if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
769 $bits[1] = user_mygrades_url();
772 // Make sure the url is a moodle url.
773 $bits[1] = new moodle_url(trim($bits[1]));
775 $child->url = $bits[1];
777 // Add this child to the list of children.
778 $children[] = $child;
780 return $children;
784 * Get a list of essential user navigation items.
786 * @param stdclass $user user object.
787 * @param moodle_page $page page object.
788 * @param array $options associative array.
789 * options are:
790 * - avatarsize=35 (size of avatar image)
791 * @return stdClass $returnobj navigation information object, where:
793 * $returnobj->navitems array array of links where each link is a
794 * stdClass with fields url, title, and
795 * pix
796 * $returnobj->metadata array array of useful user metadata to be
797 * used when constructing navigation;
798 * fields include:
800 * ROLE FIELDS
801 * asotherrole bool whether viewing as another role
802 * rolename string name of the role
804 * USER FIELDS
805 * These fields are for the currently-logged in user, or for
806 * the user that the real user is currently logged in as.
808 * userid int the id of the user in question
809 * userfullname string the user's full name
810 * userprofileurl moodle_url the url of the user's profile
811 * useravatar string a HTML fragment - the rendered
812 * user_picture for this user
813 * userloginfail string an error string denoting the number
814 * of login failures since last login
816 * "REAL USER" FIELDS
817 * These fields are for when asotheruser is true, and
818 * correspond to the underlying "real user".
820 * asotheruser bool whether viewing as another user
821 * realuserid int the id of the user in question
822 * realuserfullname string the user's full name
823 * realuserprofileurl moodle_url the url of the user's profile
824 * realuseravatar string a HTML fragment - the rendered
825 * user_picture for this user
827 * MNET PROVIDER FIELDS
828 * asmnetuser bool whether viewing as a user from an
829 * MNet provider
830 * mnetidprovidername string name of the MNet provider
831 * mnetidproviderwwwroot string URL of the MNet provider
833 function user_get_user_navigation_info($user, $page, $options = array()) {
834 global $OUTPUT, $DB, $SESSION, $CFG;
836 $returnobject = new stdClass();
837 $returnobject->navitems = array();
838 $returnobject->metadata = array();
840 $guest = isguestuser();
841 if (!isloggedin() || $guest) {
842 $returnobject->unauthenticateduser = [
843 'guest' => $guest,
844 'content' => $guest ? 'loggedinasguest' : 'loggedinnot',
847 return $returnobject;
850 $course = $page->course;
852 // Query the environment.
853 $context = context_course::instance($course->id);
855 // Get basic user metadata.
856 $returnobject->metadata['userid'] = $user->id;
857 $returnobject->metadata['userfullname'] = fullname($user);
858 $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
859 'id' => $user->id
862 $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
863 if (!empty($options['avatarsize'])) {
864 $avataroptions['size'] = $options['avatarsize'];
866 $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
867 $user, $avataroptions
869 // Build a list of items for a regular user.
871 // Query MNet status.
872 if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
873 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
874 $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
875 $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
878 // Did the user just log in?
879 if (isset($SESSION->justloggedin)) {
880 // Don't unset this flag as login_info still needs it.
881 if (!empty($CFG->displayloginfailures)) {
882 // Don't reset the count either, as login_info() still needs it too.
883 if ($count = user_count_login_failures($user, false)) {
885 // Get login failures string.
886 $a = new stdClass();
887 $a->attempts = html_writer::tag('span', $count, array('class' => 'value mr-1 font-weight-bold'));
888 $returnobject->metadata['userloginfail'] =
889 get_string('failedloginattempts', '', $a);
895 $returnobject->metadata['asotherrole'] = false;
897 // Before we add the last items (usually a logout + switch role link), add any
898 // custom-defined items.
899 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
900 $custommenucount = 0;
901 foreach ($customitems as $item) {
902 $returnobject->navitems[] = $item;
903 if ($item->itemtype !== 'divider' && $item->itemtype !== 'invalid') {
904 $custommenucount++;
908 if ($custommenucount > 0) {
909 // Only add a divider if we have customusermenuitems.
910 $divider = new stdClass();
911 $divider->itemtype = 'divider';
912 $returnobject->navitems[] = $divider;
915 // Links: Preferences.
916 $preferences = new stdClass();
917 $preferences->itemtype = 'link';
918 $preferences->url = new moodle_url('/user/preferences.php');
919 $preferences->title = get_string('preferences');
920 $preferences->titleidentifier = 'preferences,moodle';
921 $returnobject->navitems[] = $preferences;
924 if (is_role_switched($course->id)) {
925 if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
926 // Build role-return link instead of logout link.
927 $rolereturn = new stdClass();
928 $rolereturn->itemtype = 'link';
929 $rolereturn->url = new moodle_url('/course/switchrole.php', array(
930 'id' => $course->id,
931 'sesskey' => sesskey(),
932 'switchrole' => 0,
933 'returnurl' => $page->url->out_as_local_url(false)
935 $rolereturn->title = get_string('switchrolereturn');
936 $rolereturn->titleidentifier = 'switchrolereturn,moodle';
937 $returnobject->navitems[] = $rolereturn;
939 $returnobject->metadata['asotherrole'] = true;
940 $returnobject->metadata['rolename'] = role_get_name($role, $context);
943 } else {
944 // Build switch role link.
945 $roles = get_switchable_roles($context);
946 if (is_array($roles) && (count($roles) > 0)) {
947 $switchrole = new stdClass();
948 $switchrole->itemtype = 'link';
949 $switchrole->url = new moodle_url('/course/switchrole.php', array(
950 'id' => $course->id,
951 'switchrole' => -1,
952 'returnurl' => $page->url->out_as_local_url(false)
954 $switchrole->title = get_string('switchroleto');
955 $switchrole->titleidentifier = 'switchroleto,moodle';
956 $returnobject->navitems[] = $switchrole;
960 if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
961 $realuser = \core\session\manager::get_realuser();
963 // Save values for the real user, as $user will be full of data for the
964 // user is disguised as.
965 $returnobject->metadata['realuserid'] = $realuser->id;
966 $returnobject->metadata['realuserfullname'] = fullname($realuser);
967 $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', [
968 'id' => $realuser->id
970 $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
972 // Build a user-revert link.
973 $userrevert = new stdClass();
974 $userrevert->itemtype = 'link';
975 $userrevert->url = new moodle_url('/course/loginas.php', [
976 'id' => $course->id,
977 'sesskey' => sesskey()
979 $userrevert->title = get_string('logout');
980 $userrevert->titleidentifier = 'logout,moodle';
981 $returnobject->navitems[] = $userrevert;
982 } else {
983 // Build a logout link.
984 $logout = new stdClass();
985 $logout->itemtype = 'link';
986 $logout->url = new moodle_url('/login/logout.php', ['sesskey' => sesskey()]);
987 $logout->title = get_string('logout');
988 $logout->titleidentifier = 'logout,moodle';
989 $returnobject->navitems[] = $logout;
992 return $returnobject;
996 * Add password to the list of used hashes for this user.
998 * This is supposed to be used from:
999 * 1/ change own password form
1000 * 2/ password reset process
1001 * 3/ user signup in auth plugins if password changing supported
1003 * @param int $userid user id
1004 * @param string $password plaintext password
1005 * @return void
1007 function user_add_password_history($userid, $password) {
1008 global $CFG, $DB;
1010 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1011 return;
1014 // Note: this is using separate code form normal password hashing because
1015 // we need to have this under control in the future. Also the auth
1016 // plugin might not store the passwords locally at all.
1018 $record = new stdClass();
1019 $record->userid = $userid;
1020 $record->hash = password_hash($password, PASSWORD_DEFAULT);
1021 $record->timecreated = time();
1022 $DB->insert_record('user_password_history', $record);
1024 $i = 0;
1025 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1026 foreach ($records as $record) {
1027 $i++;
1028 if ($i > $CFG->passwordreuselimit) {
1029 $DB->delete_records('user_password_history', array('id' => $record->id));
1035 * Was this password used before on change or reset password page?
1037 * The $CFG->passwordreuselimit setting determines
1038 * how many times different password needs to be used
1039 * before allowing previously used password again.
1041 * @param int $userid user id
1042 * @param string $password plaintext password
1043 * @return bool true if password reused
1045 function user_is_previously_used_password($userid, $password) {
1046 global $CFG, $DB;
1048 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1049 return false;
1052 $reused = false;
1054 $i = 0;
1055 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1056 foreach ($records as $record) {
1057 $i++;
1058 if ($i > $CFG->passwordreuselimit) {
1059 $DB->delete_records('user_password_history', array('id' => $record->id));
1060 continue;
1062 // NOTE: this is slow but we cannot compare the hashes directly any more.
1063 if (password_verify($password, $record->hash)) {
1064 $reused = true;
1068 return $reused;
1072 * Remove a user device from the Moodle database (for PUSH notifications usually).
1074 * @param string $uuid The device UUID.
1075 * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1076 * @return bool true if removed, false if the device didn't exists in the database
1077 * @since Moodle 2.9
1079 function user_remove_user_device($uuid, $appid = "") {
1080 global $DB, $USER;
1082 $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
1083 if (!empty($appid)) {
1084 $conditions['appid'] = $appid;
1087 if (!$DB->count_records('user_devices', $conditions)) {
1088 return false;
1091 $DB->delete_records('user_devices', $conditions);
1093 return true;
1097 * Trigger user_list_viewed event.
1099 * @param stdClass $course course object
1100 * @param stdClass $context course context object
1101 * @since Moodle 2.9
1103 function user_list_view($course, $context) {
1105 $event = \core\event\user_list_viewed::create(array(
1106 'objectid' => $course->id,
1107 'courseid' => $course->id,
1108 'context' => $context,
1109 'other' => array(
1110 'courseshortname' => $course->shortname,
1111 'coursefullname' => $course->fullname
1114 $event->trigger();
1118 * Returns the url to use for the "Grades" link in the user navigation.
1120 * @param int $userid The user's ID.
1121 * @param int $courseid The course ID if available.
1122 * @return mixed A URL to be directed to for "Grades".
1124 function user_mygrades_url($userid = null, $courseid = SITEID) {
1125 global $CFG, $USER;
1126 $url = null;
1127 if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
1128 if (isset($userid) && $USER->id != $userid) {
1129 // Send to the gradebook report.
1130 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
1131 array('id' => $courseid, 'userid' => $userid));
1132 } else {
1133 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
1135 } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
1136 && !empty($CFG->gradereport_mygradeurl)) {
1137 $url = $CFG->gradereport_mygradeurl;
1138 } else {
1139 $url = $CFG->wwwroot;
1141 return $url;
1145 * Check if the current user has permission to view details of the supplied user.
1147 * This function supports two modes:
1148 * If the optional $course param is omitted, then this function finds all shared courses and checks whether the current user has
1149 * permission in any of them, returning true if so.
1150 * If the $course param is provided, then this function checks permissions in ONLY that course.
1152 * @param object $user The other user's details.
1153 * @param object $course if provided, only check permissions in this course.
1154 * @param context $usercontext The user context if available.
1155 * @return bool true for ability to view this user, else false.
1157 function user_can_view_profile($user, $course = null, $usercontext = null) {
1158 global $USER, $CFG;
1160 if ($user->deleted) {
1161 return false;
1164 // Do we need to be logged in?
1165 if (empty($CFG->forceloginforprofiles)) {
1166 return true;
1167 } else {
1168 if (!isloggedin() || isguestuser()) {
1169 // User is not logged in and forceloginforprofile is set, we need to return now.
1170 return false;
1174 // Current user can always view their profile.
1175 if ($USER->id == $user->id) {
1176 return true;
1179 // Use callbacks so that (primarily) local plugins can prevent or allow profile access.
1180 $forceallow = false;
1181 $plugintypes = get_plugins_with_function('control_view_profile');
1182 foreach ($plugintypes as $plugins) {
1183 foreach ($plugins as $pluginfunction) {
1184 $result = $pluginfunction($user, $course, $usercontext);
1185 switch ($result) {
1186 case core_user::VIEWPROFILE_DO_NOT_PREVENT:
1187 // If the plugin doesn't stop access, just continue to next plugin or use
1188 // default behaviour.
1189 break;
1190 case core_user::VIEWPROFILE_FORCE_ALLOW:
1191 // Record that we are definitely going to allow it (unless another plugin
1192 // returns _PREVENT).
1193 $forceallow = true;
1194 break;
1195 case core_user::VIEWPROFILE_PREVENT:
1196 // If any plugin returns PREVENT then we return false, regardless of what
1197 // other plugins said.
1198 return false;
1202 if ($forceallow) {
1203 return true;
1206 // Course contacts have visible profiles always.
1207 if (has_coursecontact_role($user->id)) {
1208 return true;
1211 // If we're only checking the capabilities in the single provided course.
1212 if (isset($course)) {
1213 // Confirm that $user is enrolled in the $course we're checking.
1214 if (is_enrolled(context_course::instance($course->id), $user)) {
1215 $userscourses = array($course);
1217 } else {
1218 // Else we're checking whether the current user can view $user's profile anywhere, so check user context first.
1219 if (empty($usercontext)) {
1220 $usercontext = context_user::instance($user->id);
1222 if (has_capability('moodle/user:viewdetails', $usercontext) || has_capability('moodle/user:viewalldetails', $usercontext)) {
1223 return true;
1225 // This returns context information, so we can preload below.
1226 $userscourses = enrol_get_all_users_courses($user->id);
1229 if (empty($userscourses)) {
1230 return false;
1233 foreach ($userscourses as $userscourse) {
1234 context_helper::preload_from_record($userscourse);
1235 $coursecontext = context_course::instance($userscourse->id);
1236 if (has_capability('moodle/user:viewdetails', $coursecontext) ||
1237 has_capability('moodle/user:viewalldetails', $coursecontext)) {
1238 if (!groups_user_groups_visible($userscourse, $user->id)) {
1239 // Not a member of the same group.
1240 continue;
1242 return true;
1245 return false;
1249 * Returns users tagged with a specified tag.
1251 * @param core_tag_tag $tag
1252 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1253 * are displayed on the page and the per-page limit may be bigger
1254 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1255 * to display items in the same context first
1256 * @param int $ctx context id where to search for records
1257 * @param bool $rec search in subcontexts as well
1258 * @param int $page 0-based number of page being displayed
1259 * @return \core_tag\output\tagindex
1261 function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1262 global $PAGE;
1264 if ($ctx && $ctx != context_system::instance()->id) {
1265 $usercount = 0;
1266 } else {
1267 // Users can only be displayed in system context.
1268 $usercount = $tag->count_tagged_items('core', 'user',
1269 'it.deleted=:notdeleted', array('notdeleted' => 0));
1271 $perpage = $exclusivemode ? 24 : 5;
1272 $content = '';
1273 $totalpages = ceil($usercount / $perpage);
1275 if ($usercount) {
1276 $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage,
1277 'it.deleted=:notdeleted', array('notdeleted' => 0));
1278 $renderer = $PAGE->get_renderer('core', 'user');
1279 $content .= $renderer->user_list($userlist, $exclusivemode);
1282 return new core_tag\output\tagindex($tag, 'core', 'user', $content,
1283 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1287 * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access a course.
1289 * @param int $accesssince The unix timestamp to compare to users' last access
1290 * @param string $tableprefix
1291 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1292 * @return string
1294 function user_get_course_lastaccess_sql($accesssince = null, $tableprefix = 'ul', $haveaccessed = false) {
1295 return user_get_lastaccess_sql('timeaccess', $accesssince, $tableprefix, $haveaccessed);
1299 * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access the system.
1301 * @param int $accesssince The unix timestamp to compare to users' last access
1302 * @param string $tableprefix
1303 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1304 * @return string
1306 function user_get_user_lastaccess_sql($accesssince = null, $tableprefix = 'u', $haveaccessed = false) {
1307 return user_get_lastaccess_sql('lastaccess', $accesssince, $tableprefix, $haveaccessed);
1311 * Returns SQL that can be used to limit a query to a period where the user last accessed or
1312 * did not access something recorded by a given table.
1314 * @param string $columnname The name of the access column to check against
1315 * @param int $accesssince The unix timestamp to compare to users' last access
1316 * @param string $tableprefix The query prefix of the table to check
1317 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1318 * @return string
1320 function user_get_lastaccess_sql($columnname, $accesssince, $tableprefix, $haveaccessed = false) {
1321 if (empty($accesssince)) {
1322 return '';
1325 // Only users who have accessed since $accesssince.
1326 if ($haveaccessed) {
1327 if ($accesssince == -1) {
1328 // Include all users who have logged in at some point.
1329 $sql = "({$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0)";
1330 } else {
1331 // Users who have accessed since the specified time.
1332 $sql = "{$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0
1333 AND {$tableprefix}.{$columnname} >= {$accesssince}";
1335 } else {
1336 // Only users who have not accessed since $accesssince.
1338 if ($accesssince == -1) {
1339 // Users who have never accessed.
1340 $sql = "({$tableprefix}.{$columnname} IS NULL OR {$tableprefix}.{$columnname} = 0)";
1341 } else {
1342 // Users who have not accessed since the specified time.
1343 $sql = "({$tableprefix}.{$columnname} IS NULL
1344 OR ({$tableprefix}.{$columnname} != 0 AND {$tableprefix}.{$columnname} < {$accesssince}))";
1348 return $sql;
1352 * Callback for inplace editable API.
1354 * @param string $itemtype - Only user_roles is supported.
1355 * @param string $itemid - Courseid and userid separated by a :
1356 * @param string $newvalue - json encoded list of roleids.
1357 * @return \core\output\inplace_editable|null
1359 function core_user_inplace_editable($itemtype, $itemid, $newvalue) {
1360 if ($itemtype === 'user_roles') {
1361 return \core_user\output\user_roles_editable::update($itemid, $newvalue);
1366 * Map an internal field name to a valid purpose from: "https://www.w3.org/TR/WCAG21/#input-purposes"
1368 * @param integer $userid
1369 * @param string $fieldname
1370 * @return string $purpose (empty string if there is no mapping).
1372 function user_edit_map_field_purpose($userid, $fieldname) {
1373 global $USER;
1375 $currentuser = ($userid == $USER->id) && !\core\session\manager::is_loggedinas();
1376 // These are the fields considered valid to map and auto fill from a browser.
1377 // We do not include fields that are in a collapsed section by default because
1378 // the browser could auto-fill the field and cause a new value to be saved when
1379 // that field was never visible.
1380 $validmappings = array(
1381 'username' => 'username',
1382 'password' => 'current-password',
1383 'firstname' => 'given-name',
1384 'lastname' => 'family-name',
1385 'middlename' => 'additional-name',
1386 'email' => 'email',
1387 'country' => 'country',
1388 'lang' => 'language'
1391 $purpose = '';
1392 // Only set a purpose when editing your own user details.
1393 if ($currentuser && isset($validmappings[$fieldname])) {
1394 $purpose = ' autocomplete="' . $validmappings[$fieldname] . '" ';
1397 return $purpose;
1401 * Update the users public key for the specified device and app.
1403 * @param string $uuid The device UUID.
1404 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1405 * @param string $publickey The app generated public key.
1406 * @return bool
1407 * @since Moodle 4.2
1409 function user_update_device_public_key(string $uuid, string $appid, string $publickey): bool {
1410 global $USER, $DB;
1412 if (!$DB->get_record('user_devices',
1413 ['uuid' => $uuid, 'appid' => $appid, 'userid' => $USER->id]
1414 )) {
1415 return false;
1418 $DB->set_field('user_devices', 'publickey', $publickey,
1419 ['uuid' => $uuid, 'appid' => $appid, 'userid' => $USER->id]
1422 return true;