MDL-75012 js: Remove orphaned source maps
[moodle.git] / user / lib.php
blobcd2ba14d380f1b85862b7c68f3b4243ee8e66ca8
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 $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 $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 $user->timemodified = time();
191 // Validate user data object.
192 $uservalidation = core_user::validate($user);
193 if ($uservalidation !== true) {
194 foreach ($uservalidation as $field => $message) {
195 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
196 $user->$field = core_user::clean_field($user->$field, $field);
200 $DB->update_record('user', $user);
202 if ($updatepassword) {
203 // Get full user record.
204 $updateduser = $DB->get_record('user', array('id' => $user->id));
206 // If password was set, then update its hash.
207 if (isset($passwd)) {
208 $authplugin = get_auth_plugin($updateduser->auth);
209 if ($authplugin->can_change_password()) {
210 $authplugin->user_update_password($updateduser, $passwd);
214 // Trigger event if required.
215 if ($triggerevent) {
216 \core\event\user_updated::create_from_userid($user->id)->trigger();
221 * Marks user deleted in internal user database and notifies the auth plugin.
222 * Also unenrols user from all roles and does other cleanup.
224 * @todo Decide if this transaction is really needed (look for internal TODO:)
225 * @param object $user Userobject before delete (without system magic quotes)
226 * @return boolean success
228 function user_delete_user($user) {
229 return delete_user($user);
233 * Get users by id
235 * @param array $userids id of users to retrieve
236 * @return array
238 function user_get_users_by_id($userids) {
239 global $DB;
240 return $DB->get_records_list('user', 'id', $userids);
244 * Returns the list of default 'displayable' fields
246 * Contains database field names but also names used to generate information, such as enrolledcourses
248 * @return array of user fields
250 function user_get_default_fields() {
251 return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
252 'address', 'phone1', 'phone2', 'department',
253 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
254 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
255 'city', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
256 'groups', 'roles', 'preferences', 'enrolledcourses', 'suspended', 'lastcourseaccess'
262 * Give user record from mdl_user, build an array contains all user details.
264 * Warning: description file urls are 'webservice/pluginfile.php' is use.
265 * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
267 * @throws moodle_exception
268 * @param stdClass $user user record from mdl_user
269 * @param stdClass $course moodle course
270 * @param array $userfields required fields
271 * @return array|null
273 function user_get_user_details($user, $course = null, array $userfields = array()) {
274 global $USER, $DB, $CFG, $PAGE;
275 require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library.
276 require_once($CFG->dirroot . "/lib/filelib.php"); // File handling on description and friends.
278 $defaultfields = user_get_default_fields();
280 if (empty($userfields)) {
281 $userfields = $defaultfields;
284 foreach ($userfields as $thefield) {
285 if (!in_array($thefield, $defaultfields)) {
286 throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
290 // Make sure id and fullname are included.
291 if (!in_array('id', $userfields)) {
292 $userfields[] = 'id';
295 if (!in_array('fullname', $userfields)) {
296 $userfields[] = 'fullname';
299 if (!empty($course)) {
300 $context = context_course::instance($course->id);
301 $usercontext = context_user::instance($user->id);
302 $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext));
303 } else {
304 $context = context_user::instance($user->id);
305 $usercontext = $context;
306 $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
309 $currentuser = ($user->id == $USER->id);
310 $isadmin = is_siteadmin($USER);
312 // This does not need to include custom profile fields as it is only used to check specific
313 // fields below.
314 $showuseridentityfields = \core_user\fields::get_identity_fields($context, false);
316 if (!empty($course)) {
317 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
318 } else {
319 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
321 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
322 if (!empty($course)) {
323 $canviewuseremail = has_capability('moodle/course:useremail', $context);
324 } else {
325 $canviewuseremail = false;
327 $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
328 if (!empty($course)) {
329 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
330 } else {
331 $canaccessallgroups = false;
334 if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
335 // Skip this user details.
336 return null;
339 $userdetails = array();
340 $userdetails['id'] = $user->id;
342 if (in_array('username', $userfields)) {
343 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
344 $userdetails['username'] = $user->username;
347 if ($isadmin or $canviewfullnames) {
348 if (in_array('firstname', $userfields)) {
349 $userdetails['firstname'] = $user->firstname;
351 if (in_array('lastname', $userfields)) {
352 $userdetails['lastname'] = $user->lastname;
355 $userdetails['fullname'] = fullname($user, $canviewfullnames);
357 if (in_array('customfields', $userfields)) {
358 $categories = profile_get_user_fields_with_data_by_category($user->id);
359 $userdetails['customfields'] = array();
360 foreach ($categories as $categoryid => $fields) {
361 foreach ($fields as $formfield) {
362 if ($formfield->is_visible() and !$formfield->is_empty()) {
364 // TODO: Part of MDL-50728, this conditional coding must be moved to
365 // proper profile fields API so they are self-contained.
366 // We only use display_data in fields that require text formatting.
367 if ($formfield->field->datatype == 'text' or $formfield->field->datatype == 'textarea') {
368 $fieldvalue = $formfield->display_data();
369 } else {
370 // Cases: datetime, checkbox and menu.
371 $fieldvalue = $formfield->data;
374 $userdetails['customfields'][] =
375 array('name' => $formfield->field->name, 'value' => $fieldvalue,
376 'type' => $formfield->field->datatype, 'shortname' => $formfield->field->shortname);
380 // Unset customfields if it's empty.
381 if (empty($userdetails['customfields'])) {
382 unset($userdetails['customfields']);
386 // Profile image.
387 if (in_array('profileimageurl', $userfields)) {
388 $userpicture = new user_picture($user);
389 $userpicture->size = 1; // Size f1.
390 $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
392 if (in_array('profileimageurlsmall', $userfields)) {
393 if (!isset($userpicture)) {
394 $userpicture = new user_picture($user);
396 $userpicture->size = 0; // Size f2.
397 $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
400 // Hidden user field.
401 if ($canviewhiddenuserfields) {
402 $hiddenfields = array();
403 // Address, phone1 and phone2 not appears in hidden fields list but require viewhiddenfields capability
404 // according to user/profile.php.
405 if (!empty($user->address) && in_array('address', $userfields)) {
406 $userdetails['address'] = $user->address;
408 } else {
409 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
412 if (!empty($user->phone1) && in_array('phone1', $userfields) &&
413 (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) {
414 $userdetails['phone1'] = $user->phone1;
416 if (!empty($user->phone2) && in_array('phone2', $userfields) &&
417 (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) {
418 $userdetails['phone2'] = $user->phone2;
421 if (isset($user->description) &&
422 ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
423 if (in_array('description', $userfields)) {
424 // Always return the descriptionformat if description is requested.
425 list($userdetails['description'], $userdetails['descriptionformat']) =
426 external_format_text($user->description, $user->descriptionformat,
427 $usercontext->id, 'user', 'profile', null);
431 if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
432 $userdetails['country'] = $user->country;
435 if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
436 $userdetails['city'] = $user->city;
439 if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) {
440 $userdetails['suspended'] = (bool)$user->suspended;
443 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
444 if ($user->firstaccess) {
445 $userdetails['firstaccess'] = $user->firstaccess;
446 } else {
447 $userdetails['firstaccess'] = 0;
450 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
451 if ($user->lastaccess) {
452 $userdetails['lastaccess'] = $user->lastaccess;
453 } else {
454 $userdetails['lastaccess'] = 0;
458 // Hidden fields restriction to lastaccess field applies to both site and course access time.
459 if (in_array('lastcourseaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
460 if (isset($user->lastcourseaccess)) {
461 $userdetails['lastcourseaccess'] = $user->lastcourseaccess;
462 } else {
463 $userdetails['lastcourseaccess'] = 0;
467 if (in_array('email', $userfields) && (
468 $currentuser
469 or (!isset($hiddenfields['email']) and (
470 $user->maildisplay == core_user::MAILDISPLAY_EVERYONE
471 or ($user->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY and enrol_sharing_course($user, $USER))
472 or $canviewuseremail // TODO: Deprecate/remove for MDL-37479.
474 or in_array('email', $showuseridentityfields)
475 )) {
476 $userdetails['email'] = $user->email;
479 if (in_array('interests', $userfields)) {
480 $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
481 if ($interests) {
482 $userdetails['interests'] = join(', ', $interests);
486 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
487 if (in_array('idnumber', $userfields) && $user->idnumber) {
488 if (in_array('idnumber', $showuseridentityfields) or $currentuser or
489 has_capability('moodle/user:viewalldetails', $context)) {
490 $userdetails['idnumber'] = $user->idnumber;
493 if (in_array('institution', $userfields) && $user->institution) {
494 if (in_array('institution', $showuseridentityfields) or $currentuser or
495 has_capability('moodle/user:viewalldetails', $context)) {
496 $userdetails['institution'] = $user->institution;
499 // Isset because it's ok to have department 0.
500 if (in_array('department', $userfields) && isset($user->department)) {
501 if (in_array('department', $showuseridentityfields) or $currentuser or
502 has_capability('moodle/user:viewalldetails', $context)) {
503 $userdetails['department'] = $user->department;
507 if (in_array('roles', $userfields) && !empty($course)) {
508 // Not a big secret.
509 $roles = get_user_roles($context, $user->id, false);
510 $userdetails['roles'] = array();
511 foreach ($roles as $role) {
512 $userdetails['roles'][] = array(
513 'roleid' => $role->roleid,
514 'name' => $role->name,
515 'shortname' => $role->shortname,
516 'sortorder' => $role->sortorder
521 // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
522 if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
523 $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid,
524 'g.id, g.name,g.description,g.descriptionformat');
525 $userdetails['groups'] = array();
526 foreach ($usergroups as $group) {
527 list($group->description, $group->descriptionformat) =
528 external_format_text($group->description, $group->descriptionformat,
529 $context->id, 'group', 'description', $group->id);
530 $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name,
531 'description' => $group->description, 'descriptionformat' => $group->descriptionformat);
534 // List of courses where the user is enrolled.
535 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
536 $enrolledcourses = array();
537 if ($mycourses = enrol_get_users_courses($user->id, true)) {
538 foreach ($mycourses as $mycourse) {
539 if ($mycourse->category) {
540 $coursecontext = context_course::instance($mycourse->id);
541 $enrolledcourse = array();
542 $enrolledcourse['id'] = $mycourse->id;
543 $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
544 $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
545 $enrolledcourses[] = $enrolledcourse;
548 $userdetails['enrolledcourses'] = $enrolledcourses;
552 // User preferences.
553 if (in_array('preferences', $userfields) && $currentuser) {
554 $preferences = array();
555 $userpreferences = get_user_preferences();
556 foreach ($userpreferences as $prefname => $prefvalue) {
557 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
559 $userdetails['preferences'] = $preferences;
562 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
563 $extrafields = ['auth', 'confirmed', 'lang', 'theme', 'timezone', 'mailformat'];
564 foreach ($extrafields as $extrafield) {
565 if (in_array($extrafield, $userfields) && isset($user->$extrafield)) {
566 $userdetails[$extrafield] = $user->$extrafield;
571 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
572 if (isset($userdetails['lang'])) {
573 $userdetails['lang'] = clean_param($userdetails['lang'], PARAM_LANG);
575 if (isset($userdetails['theme'])) {
576 $userdetails['theme'] = clean_param($userdetails['theme'], PARAM_THEME);
579 return $userdetails;
583 * Tries to obtain user details, either recurring directly to the user's system profile
584 * or through one of the user's course enrollments (course profile).
586 * @param stdClass $user The user.
587 * @return array if unsuccessful or the allowed user details.
589 function user_get_user_details_courses($user) {
590 global $USER;
591 $userdetails = null;
593 $systemprofile = false;
594 if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
595 $systemprofile = true;
598 // Try using system profile.
599 if ($systemprofile) {
600 $userdetails = user_get_user_details($user, null);
601 } else {
602 // Try through course profile.
603 // Get the courses that the user is enrolled in (only active).
604 $courses = enrol_get_users_courses($user->id, true);
605 foreach ($courses as $course) {
606 if (user_can_view_profile($user, $course)) {
607 $userdetails = user_get_user_details($user, $course);
612 return $userdetails;
616 * Check if $USER have the necessary capabilities to obtain user details.
618 * @param stdClass $user
619 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
620 * @return bool true if $USER can view user details.
622 function can_view_user_details_cap($user, $course = null) {
623 // Check $USER has the capability to view the user details at user context.
624 $usercontext = context_user::instance($user->id);
625 $result = has_capability('moodle/user:viewdetails', $usercontext);
626 // Otherwise can $USER see them at course context.
627 if (!$result && !empty($course)) {
628 $context = context_course::instance($course->id);
629 $result = has_capability('moodle/user:viewdetails', $context);
631 return $result;
635 * Return a list of page types
636 * @param string $pagetype current page type
637 * @param stdClass $parentcontext Block's parent context
638 * @param stdClass $currentcontext Current context of block
639 * @return array
641 function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
642 return array('user-profile' => get_string('page-user-profile', 'pagetype'));
646 * Count the number of failed login attempts for the given user, since last successful login.
648 * @param int|stdclass $user user id or object.
649 * @param bool $reset Resets failed login count, if set to true.
651 * @return int number of failed login attempts since the last successful login.
653 function user_count_login_failures($user, $reset = true) {
654 global $DB;
656 if (!is_object($user)) {
657 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
659 if ($user->deleted) {
660 // Deleted user, nothing to do.
661 return 0;
663 $count = get_user_preferences('login_failed_count_since_success', 0, $user);
664 if ($reset) {
665 set_user_preference('login_failed_count_since_success', 0, $user);
667 return $count;
671 * Converts a string into a flat array of menu items, where each menu items is a
672 * stdClass with fields type, url, title.
674 * @param string $text the menu items definition
675 * @param moodle_page $page the current page
676 * @return array
678 function user_convert_text_to_menu_items($text, $page) {
679 global $OUTPUT, $CFG;
681 $lines = explode("\n", $text);
682 $items = array();
683 $lastchild = null;
684 $lastdepth = null;
685 $lastsort = 0;
686 $children = array();
687 foreach ($lines as $line) {
688 $line = trim($line);
689 $bits = explode('|', $line, 2);
690 $itemtype = 'link';
691 if (preg_match("/^#+$/", $line)) {
692 $itemtype = 'divider';
693 } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
694 // Every item must have a name to be valid.
695 continue;
696 } else {
697 $bits[0] = ltrim($bits[0], '-');
700 // Create the child.
701 $child = new stdClass();
702 $child->itemtype = $itemtype;
703 if ($itemtype === 'divider') {
704 // Add the divider to the list of children and skip link
705 // processing.
706 $children[] = $child;
707 continue;
710 // Name processing.
711 $namebits = explode(',', $bits[0], 2);
712 if (count($namebits) == 2) {
713 // Check the validity of the identifier part of the string.
714 if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
715 // Treat this as a language string.
716 $child->title = get_string($namebits[0], $namebits[1]);
717 $child->titleidentifier = implode(',', $namebits);
720 if (empty($child->title)) {
721 // Use it as is, don't even clean it.
722 $child->title = $bits[0];
723 $child->titleidentifier = str_replace(" ", "-", $bits[0]);
726 // URL processing.
727 if (!array_key_exists(1, $bits) or empty($bits[1])) {
728 // Set the url to null, and set the itemtype to invalid.
729 $bits[1] = null;
730 $child->itemtype = "invalid";
731 } else {
732 // Nasty hack to replace the grades with the direct url.
733 if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
734 $bits[1] = user_mygrades_url();
737 // Make sure the url is a moodle url.
738 $bits[1] = new moodle_url(trim($bits[1]));
740 $child->url = $bits[1];
742 // Add this child to the list of children.
743 $children[] = $child;
745 return $children;
749 * Get a list of essential user navigation items.
751 * @param stdclass $user user object.
752 * @param moodle_page $page page object.
753 * @param array $options associative array.
754 * options are:
755 * - avatarsize=35 (size of avatar image)
756 * @return stdClass $returnobj navigation information object, where:
758 * $returnobj->navitems array array of links where each link is a
759 * stdClass with fields url, title, and
760 * pix
761 * $returnobj->metadata array array of useful user metadata to be
762 * used when constructing navigation;
763 * fields include:
765 * ROLE FIELDS
766 * asotherrole bool whether viewing as another role
767 * rolename string name of the role
769 * USER FIELDS
770 * These fields are for the currently-logged in user, or for
771 * the user that the real user is currently logged in as.
773 * userid int the id of the user in question
774 * userfullname string the user's full name
775 * userprofileurl moodle_url the url of the user's profile
776 * useravatar string a HTML fragment - the rendered
777 * user_picture for this user
778 * userloginfail string an error string denoting the number
779 * of login failures since last login
781 * "REAL USER" FIELDS
782 * These fields are for when asotheruser is true, and
783 * correspond to the underlying "real user".
785 * asotheruser bool whether viewing as another user
786 * realuserid int the id of the user in question
787 * realuserfullname string the user's full name
788 * realuserprofileurl moodle_url the url of the user's profile
789 * realuseravatar string a HTML fragment - the rendered
790 * user_picture for this user
792 * MNET PROVIDER FIELDS
793 * asmnetuser bool whether viewing as a user from an
794 * MNet provider
795 * mnetidprovidername string name of the MNet provider
796 * mnetidproviderwwwroot string URL of the MNet provider
798 function user_get_user_navigation_info($user, $page, $options = array()) {
799 global $OUTPUT, $DB, $SESSION, $CFG;
801 $returnobject = new stdClass();
802 $returnobject->navitems = array();
803 $returnobject->metadata = array();
805 $guest = isguestuser();
806 if (!isloggedin() || $guest) {
807 $returnobject->unauthenticateduser = [
808 'guest' => $guest,
809 'content' => $guest ? 'loggedinasguest' : 'loggedinnot',
812 return $returnobject;
815 $course = $page->course;
817 // Query the environment.
818 $context = context_course::instance($course->id);
820 // Get basic user metadata.
821 $returnobject->metadata['userid'] = $user->id;
822 $returnobject->metadata['userfullname'] = fullname($user);
823 $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
824 'id' => $user->id
827 $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
828 if (!empty($options['avatarsize'])) {
829 $avataroptions['size'] = $options['avatarsize'];
831 $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
832 $user, $avataroptions
834 // Build a list of items for a regular user.
836 // Query MNet status.
837 if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
838 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
839 $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
840 $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
843 // Did the user just log in?
844 if (isset($SESSION->justloggedin)) {
845 // Don't unset this flag as login_info still needs it.
846 if (!empty($CFG->displayloginfailures)) {
847 // Don't reset the count either, as login_info() still needs it too.
848 if ($count = user_count_login_failures($user, false)) {
850 // Get login failures string.
851 $a = new stdClass();
852 $a->attempts = html_writer::tag('span', $count, array('class' => 'value mr-1 font-weight-bold'));
853 $returnobject->metadata['userloginfail'] =
854 get_string('failedloginattempts', '', $a);
860 $returnobject->metadata['asotherrole'] = false;
862 // Before we add the last items (usually a logout + switch role link), add any
863 // custom-defined items.
864 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
865 $custommenucount = 0;
866 foreach ($customitems as $item) {
867 $returnobject->navitems[] = $item;
868 if ($item->itemtype !== 'divider' && $item->itemtype !== 'invalid') {
869 $custommenucount++;
873 if ($custommenucount > 0) {
874 // Only add a divider if we have customusermenuitems.
875 $divider = new stdClass();
876 $divider->itemtype = 'divider';
877 $returnobject->navitems[] = $divider;
880 // Links: Preferences.
881 $preferences = new stdClass();
882 $preferences->itemtype = 'link';
883 $preferences->url = new moodle_url('/user/preferences.php');
884 $preferences->title = get_string('preferences');
885 $preferences->titleidentifier = 'preferences,moodle';
886 $returnobject->navitems[] = $preferences;
889 if (is_role_switched($course->id)) {
890 if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
891 // Build role-return link instead of logout link.
892 $rolereturn = new stdClass();
893 $rolereturn->itemtype = 'link';
894 $rolereturn->url = new moodle_url('/course/switchrole.php', array(
895 'id' => $course->id,
896 'sesskey' => sesskey(),
897 'switchrole' => 0,
898 'returnurl' => $page->url->out_as_local_url(false)
900 $rolereturn->title = get_string('switchrolereturn');
901 $rolereturn->titleidentifier = 'switchrolereturn,moodle';
902 $returnobject->navitems[] = $rolereturn;
904 $returnobject->metadata['asotherrole'] = true;
905 $returnobject->metadata['rolename'] = role_get_name($role, $context);
908 } else {
909 // Build switch role link.
910 $roles = get_switchable_roles($context);
911 if (is_array($roles) && (count($roles) > 0)) {
912 $switchrole = new stdClass();
913 $switchrole->itemtype = 'link';
914 $switchrole->url = new moodle_url('/course/switchrole.php', array(
915 'id' => $course->id,
916 'switchrole' => -1,
917 'returnurl' => $page->url->out_as_local_url(false)
919 $switchrole->title = get_string('switchroleto');
920 $switchrole->titleidentifier = 'switchroleto,moodle';
921 $returnobject->navitems[] = $switchrole;
925 if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
926 $realuser = \core\session\manager::get_realuser();
928 // Save values for the real user, as $user will be full of data for the
929 // user is disguised as.
930 $returnobject->metadata['realuserid'] = $realuser->id;
931 $returnobject->metadata['realuserfullname'] = fullname($realuser);
932 $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', [
933 'id' => $realuser->id
935 $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
937 // Build a user-revert link.
938 $userrevert = new stdClass();
939 $userrevert->itemtype = 'link';
940 $userrevert->url = new moodle_url('/course/loginas.php', [
941 'id' => $course->id,
942 'sesskey' => sesskey()
944 $userrevert->title = get_string('logout');
945 $userrevert->titleidentifier = 'logout,moodle';
946 $returnobject->navitems[] = $userrevert;
947 } else {
948 // Build a logout link.
949 $logout = new stdClass();
950 $logout->itemtype = 'link';
951 $logout->url = new moodle_url('/login/logout.php', ['sesskey' => sesskey()]);
952 $logout->title = get_string('logout');
953 $logout->titleidentifier = 'logout,moodle';
954 $returnobject->navitems[] = $logout;
957 return $returnobject;
961 * Add password to the list of used hashes for this user.
963 * This is supposed to be used from:
964 * 1/ change own password form
965 * 2/ password reset process
966 * 3/ user signup in auth plugins if password changing supported
968 * @param int $userid user id
969 * @param string $password plaintext password
970 * @return void
972 function user_add_password_history($userid, $password) {
973 global $CFG, $DB;
975 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
976 return;
979 // Note: this is using separate code form normal password hashing because
980 // we need to have this under control in the future. Also the auth
981 // plugin might not store the passwords locally at all.
983 $record = new stdClass();
984 $record->userid = $userid;
985 $record->hash = password_hash($password, PASSWORD_DEFAULT);
986 $record->timecreated = time();
987 $DB->insert_record('user_password_history', $record);
989 $i = 0;
990 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
991 foreach ($records as $record) {
992 $i++;
993 if ($i > $CFG->passwordreuselimit) {
994 $DB->delete_records('user_password_history', array('id' => $record->id));
1000 * Was this password used before on change or reset password page?
1002 * The $CFG->passwordreuselimit setting determines
1003 * how many times different password needs to be used
1004 * before allowing previously used password again.
1006 * @param int $userid user id
1007 * @param string $password plaintext password
1008 * @return bool true if password reused
1010 function user_is_previously_used_password($userid, $password) {
1011 global $CFG, $DB;
1013 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1014 return false;
1017 $reused = false;
1019 $i = 0;
1020 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1021 foreach ($records as $record) {
1022 $i++;
1023 if ($i > $CFG->passwordreuselimit) {
1024 $DB->delete_records('user_password_history', array('id' => $record->id));
1025 continue;
1027 // NOTE: this is slow but we cannot compare the hashes directly any more.
1028 if (password_verify($password, $record->hash)) {
1029 $reused = true;
1033 return $reused;
1037 * Remove a user device from the Moodle database (for PUSH notifications usually).
1039 * @param string $uuid The device UUID.
1040 * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1041 * @return bool true if removed, false if the device didn't exists in the database
1042 * @since Moodle 2.9
1044 function user_remove_user_device($uuid, $appid = "") {
1045 global $DB, $USER;
1047 $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
1048 if (!empty($appid)) {
1049 $conditions['appid'] = $appid;
1052 if (!$DB->count_records('user_devices', $conditions)) {
1053 return false;
1056 $DB->delete_records('user_devices', $conditions);
1058 return true;
1062 * Trigger user_list_viewed event.
1064 * @param stdClass $course course object
1065 * @param stdClass $context course context object
1066 * @since Moodle 2.9
1068 function user_list_view($course, $context) {
1070 $event = \core\event\user_list_viewed::create(array(
1071 'objectid' => $course->id,
1072 'courseid' => $course->id,
1073 'context' => $context,
1074 'other' => array(
1075 'courseshortname' => $course->shortname,
1076 'coursefullname' => $course->fullname
1079 $event->trigger();
1083 * Returns the url to use for the "Grades" link in the user navigation.
1085 * @param int $userid The user's ID.
1086 * @param int $courseid The course ID if available.
1087 * @return mixed A URL to be directed to for "Grades".
1089 function user_mygrades_url($userid = null, $courseid = SITEID) {
1090 global $CFG, $USER;
1091 $url = null;
1092 if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
1093 if (isset($userid) && $USER->id != $userid) {
1094 // Send to the gradebook report.
1095 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
1096 array('id' => $courseid, 'userid' => $userid));
1097 } else {
1098 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
1100 } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
1101 && !empty($CFG->gradereport_mygradeurl)) {
1102 $url = $CFG->gradereport_mygradeurl;
1103 } else {
1104 $url = $CFG->wwwroot;
1106 return $url;
1110 * Check if the current user has permission to view details of the supplied user.
1112 * This function supports two modes:
1113 * If the optional $course param is omitted, then this function finds all shared courses and checks whether the current user has
1114 * permission in any of them, returning true if so.
1115 * If the $course param is provided, then this function checks permissions in ONLY that course.
1117 * @param object $user The other user's details.
1118 * @param object $course if provided, only check permissions in this course.
1119 * @param context $usercontext The user context if available.
1120 * @return bool true for ability to view this user, else false.
1122 function user_can_view_profile($user, $course = null, $usercontext = null) {
1123 global $USER, $CFG;
1125 if ($user->deleted) {
1126 return false;
1129 // Do we need to be logged in?
1130 if (empty($CFG->forceloginforprofiles)) {
1131 return true;
1132 } else {
1133 if (!isloggedin() || isguestuser()) {
1134 // User is not logged in and forceloginforprofile is set, we need to return now.
1135 return false;
1139 // Current user can always view their profile.
1140 if ($USER->id == $user->id) {
1141 return true;
1144 // Use callbacks so that (primarily) local plugins can prevent or allow profile access.
1145 $forceallow = false;
1146 $plugintypes = get_plugins_with_function('control_view_profile');
1147 foreach ($plugintypes as $plugins) {
1148 foreach ($plugins as $pluginfunction) {
1149 $result = $pluginfunction($user, $course, $usercontext);
1150 switch ($result) {
1151 case core_user::VIEWPROFILE_DO_NOT_PREVENT:
1152 // If the plugin doesn't stop access, just continue to next plugin or use
1153 // default behaviour.
1154 break;
1155 case core_user::VIEWPROFILE_FORCE_ALLOW:
1156 // Record that we are definitely going to allow it (unless another plugin
1157 // returns _PREVENT).
1158 $forceallow = true;
1159 break;
1160 case core_user::VIEWPROFILE_PREVENT:
1161 // If any plugin returns PREVENT then we return false, regardless of what
1162 // other plugins said.
1163 return false;
1167 if ($forceallow) {
1168 return true;
1171 // Course contacts have visible profiles always.
1172 if (has_coursecontact_role($user->id)) {
1173 return true;
1176 // If we're only checking the capabilities in the single provided course.
1177 if (isset($course)) {
1178 // Confirm that $user is enrolled in the $course we're checking.
1179 if (is_enrolled(context_course::instance($course->id), $user)) {
1180 $userscourses = array($course);
1182 } else {
1183 // Else we're checking whether the current user can view $user's profile anywhere, so check user context first.
1184 if (empty($usercontext)) {
1185 $usercontext = context_user::instance($user->id);
1187 if (has_capability('moodle/user:viewdetails', $usercontext) || has_capability('moodle/user:viewalldetails', $usercontext)) {
1188 return true;
1190 // This returns context information, so we can preload below.
1191 $userscourses = enrol_get_all_users_courses($user->id);
1194 if (empty($userscourses)) {
1195 return false;
1198 foreach ($userscourses as $userscourse) {
1199 context_helper::preload_from_record($userscourse);
1200 $coursecontext = context_course::instance($userscourse->id);
1201 if (has_capability('moodle/user:viewdetails', $coursecontext) ||
1202 has_capability('moodle/user:viewalldetails', $coursecontext)) {
1203 if (!groups_user_groups_visible($userscourse, $user->id)) {
1204 // Not a member of the same group.
1205 continue;
1207 return true;
1210 return false;
1214 * Returns users tagged with a specified tag.
1216 * @param core_tag_tag $tag
1217 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1218 * are displayed on the page and the per-page limit may be bigger
1219 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1220 * to display items in the same context first
1221 * @param int $ctx context id where to search for records
1222 * @param bool $rec search in subcontexts as well
1223 * @param int $page 0-based number of page being displayed
1224 * @return \core_tag\output\tagindex
1226 function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1227 global $PAGE;
1229 if ($ctx && $ctx != context_system::instance()->id) {
1230 $usercount = 0;
1231 } else {
1232 // Users can only be displayed in system context.
1233 $usercount = $tag->count_tagged_items('core', 'user',
1234 'it.deleted=:notdeleted', array('notdeleted' => 0));
1236 $perpage = $exclusivemode ? 24 : 5;
1237 $content = '';
1238 $totalpages = ceil($usercount / $perpage);
1240 if ($usercount) {
1241 $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage,
1242 'it.deleted=:notdeleted', array('notdeleted' => 0));
1243 $renderer = $PAGE->get_renderer('core', 'user');
1244 $content .= $renderer->user_list($userlist, $exclusivemode);
1247 return new core_tag\output\tagindex($tag, 'core', 'user', $content,
1248 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1252 * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access a course.
1254 * @param int $accesssince The unix timestamp to compare to users' last access
1255 * @param string $tableprefix
1256 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1257 * @return string
1259 function user_get_course_lastaccess_sql($accesssince = null, $tableprefix = 'ul', $haveaccessed = false) {
1260 return user_get_lastaccess_sql('timeaccess', $accesssince, $tableprefix, $haveaccessed);
1264 * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access the system.
1266 * @param int $accesssince The unix timestamp to compare to users' last access
1267 * @param string $tableprefix
1268 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1269 * @return string
1271 function user_get_user_lastaccess_sql($accesssince = null, $tableprefix = 'u', $haveaccessed = false) {
1272 return user_get_lastaccess_sql('lastaccess', $accesssince, $tableprefix, $haveaccessed);
1276 * Returns SQL that can be used to limit a query to a period where the user last accessed or
1277 * did not access something recorded by a given table.
1279 * @param string $columnname The name of the access column to check against
1280 * @param int $accesssince The unix timestamp to compare to users' last access
1281 * @param string $tableprefix The query prefix of the table to check
1282 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1283 * @return string
1285 function user_get_lastaccess_sql($columnname, $accesssince, $tableprefix, $haveaccessed = false) {
1286 if (empty($accesssince)) {
1287 return '';
1290 // Only users who have accessed since $accesssince.
1291 if ($haveaccessed) {
1292 if ($accesssince == -1) {
1293 // Include all users who have logged in at some point.
1294 $sql = "({$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0)";
1295 } else {
1296 // Users who have accessed since the specified time.
1297 $sql = "{$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0
1298 AND {$tableprefix}.{$columnname} >= {$accesssince}";
1300 } else {
1301 // Only users who have not accessed since $accesssince.
1303 if ($accesssince == -1) {
1304 // Users who have never accessed.
1305 $sql = "({$tableprefix}.{$columnname} IS NULL OR {$tableprefix}.{$columnname} = 0)";
1306 } else {
1307 // Users who have not accessed since the specified time.
1308 $sql = "({$tableprefix}.{$columnname} IS NULL
1309 OR ({$tableprefix}.{$columnname} != 0 AND {$tableprefix}.{$columnname} < {$accesssince}))";
1313 return $sql;
1317 * Callback for inplace editable API.
1319 * @param string $itemtype - Only user_roles is supported.
1320 * @param string $itemid - Courseid and userid separated by a :
1321 * @param string $newvalue - json encoded list of roleids.
1322 * @return \core\output\inplace_editable
1324 function core_user_inplace_editable($itemtype, $itemid, $newvalue) {
1325 if ($itemtype === 'user_roles') {
1326 return \core_user\output\user_roles_editable::update($itemid, $newvalue);
1331 * Map an internal field name to a valid purpose from: "https://www.w3.org/TR/WCAG21/#input-purposes"
1333 * @param integer $userid
1334 * @param string $fieldname
1335 * @return string $purpose (empty string if there is no mapping).
1337 function user_edit_map_field_purpose($userid, $fieldname) {
1338 global $USER;
1340 $currentuser = ($userid == $USER->id) && !\core\session\manager::is_loggedinas();
1341 // These are the fields considered valid to map and auto fill from a browser.
1342 // We do not include fields that are in a collapsed section by default because
1343 // the browser could auto-fill the field and cause a new value to be saved when
1344 // that field was never visible.
1345 $validmappings = array(
1346 'username' => 'username',
1347 'password' => 'current-password',
1348 'firstname' => 'given-name',
1349 'lastname' => 'family-name',
1350 'middlename' => 'additional-name',
1351 'email' => 'email',
1352 'country' => 'country',
1353 'lang' => 'language'
1356 $purpose = '';
1357 // Only set a purpose when editing your own user details.
1358 if ($currentuser && isset($validmappings[$fieldname])) {
1359 $purpose = ' autocomplete="' . $validmappings[$fieldname] . '" ';
1362 return $purpose;