Merge branch 'MDL-74172-master' of https://github.com/bmbrands/moodle
[moodle.git] / user / lib.php
bloba819b83ec938ed7d5beb55efd1fe9e7d18362060
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');
98 $user->timecreated = time();
99 $user->timemodified = $user->timecreated;
101 // Validate user data object.
102 $uservalidation = core_user::validate($user);
103 if ($uservalidation !== true) {
104 foreach ($uservalidation as $field => $message) {
105 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
106 $user->$field = core_user::clean_field($user->$field, $field);
110 // Insert the user into the database.
111 $newuserid = $DB->insert_record('user', $user);
113 // Create USER context for this user.
114 $usercontext = context_user::instance($newuserid);
116 // Update user password if necessary.
117 if (isset($userpassword)) {
118 // Get full database user row, in case auth is default.
119 $newuser = $DB->get_record('user', array('id' => $newuserid));
120 $authplugin = get_auth_plugin($newuser->auth);
121 $authplugin->user_update_password($newuser, $userpassword);
124 // Trigger event If required.
125 if ($triggerevent) {
126 \core\event\user_created::create_from_userid($newuserid)->trigger();
129 // Purge the associated caches for the current user only.
130 $presignupcache = \cache::make('core', 'presignup');
131 $presignupcache->purge_current_user();
133 return $newuserid;
137 * Update a user with a user object (will compare against the ID)
139 * @throws moodle_exception
140 * @param stdClass $user the user to update
141 * @param bool $updatepassword if true, authentication plugin will update password.
142 * @param bool $triggerevent set false if user_updated event should not be triggred.
143 * This will not affect user_password_updated event triggering.
145 function user_update_user($user, $updatepassword = true, $triggerevent = true) {
146 global $DB;
148 // Set the timecreate field to the current time.
149 if (!is_object($user)) {
150 $user = (object) $user;
153 // Check username.
154 if (isset($user->username)) {
155 if ($user->username !== core_text::strtolower($user->username)) {
156 throw new moodle_exception('usernamelowercase');
157 } else {
158 if ($user->username !== core_user::clean_field($user->username, 'username')) {
159 throw new moodle_exception('invalidusername');
164 // Unset password here, for updating later, if password update is required.
165 if ($updatepassword && isset($user->password)) {
167 // Check password toward the password policy.
168 if (!check_password_policy($user->password, $errmsg, $user)) {
169 throw new moodle_exception($errmsg);
172 $passwd = $user->password;
173 unset($user->password);
176 // Make sure calendartype, if set, is valid.
177 if (empty($user->calendartype)) {
178 // Unset this variable, must be an empty string, which we do not want to update the calendartype to.
179 unset($user->calendartype);
182 $user->timemodified = time();
184 // Validate user data object.
185 $uservalidation = core_user::validate($user);
186 if ($uservalidation !== true) {
187 foreach ($uservalidation as $field => $message) {
188 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
189 $user->$field = core_user::clean_field($user->$field, $field);
193 $DB->update_record('user', $user);
195 if ($updatepassword) {
196 // Get full user record.
197 $updateduser = $DB->get_record('user', array('id' => $user->id));
199 // If password was set, then update its hash.
200 if (isset($passwd)) {
201 $authplugin = get_auth_plugin($updateduser->auth);
202 if ($authplugin->can_change_password()) {
203 $authplugin->user_update_password($updateduser, $passwd);
207 // Trigger event if required.
208 if ($triggerevent) {
209 \core\event\user_updated::create_from_userid($user->id)->trigger();
214 * Marks user deleted in internal user database and notifies the auth plugin.
215 * Also unenrols user from all roles and does other cleanup.
217 * @todo Decide if this transaction is really needed (look for internal TODO:)
218 * @param object $user Userobject before delete (without system magic quotes)
219 * @return boolean success
221 function user_delete_user($user) {
222 return delete_user($user);
226 * Get users by id
228 * @param array $userids id of users to retrieve
229 * @return array
231 function user_get_users_by_id($userids) {
232 global $DB;
233 return $DB->get_records_list('user', 'id', $userids);
237 * Returns the list of default 'displayable' fields
239 * Contains database field names but also names used to generate information, such as enrolledcourses
241 * @return array of user fields
243 function user_get_default_fields() {
244 return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
245 'address', 'phone1', 'phone2', 'department',
246 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
247 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
248 'city', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
249 'groups', 'roles', 'preferences', 'enrolledcourses', 'suspended', 'lastcourseaccess'
255 * Give user record from mdl_user, build an array contains all user details.
257 * Warning: description file urls are 'webservice/pluginfile.php' is use.
258 * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
260 * @throws moodle_exception
261 * @param stdClass $user user record from mdl_user
262 * @param stdClass $course moodle course
263 * @param array $userfields required fields
264 * @return array|null
266 function user_get_user_details($user, $course = null, array $userfields = array()) {
267 global $USER, $DB, $CFG, $PAGE;
268 require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library.
269 require_once($CFG->dirroot . "/lib/filelib.php"); // File handling on description and friends.
271 $defaultfields = user_get_default_fields();
273 if (empty($userfields)) {
274 $userfields = $defaultfields;
277 foreach ($userfields as $thefield) {
278 if (!in_array($thefield, $defaultfields)) {
279 throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
283 // Make sure id and fullname are included.
284 if (!in_array('id', $userfields)) {
285 $userfields[] = 'id';
288 if (!in_array('fullname', $userfields)) {
289 $userfields[] = 'fullname';
292 if (!empty($course)) {
293 $context = context_course::instance($course->id);
294 $usercontext = context_user::instance($user->id);
295 $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext));
296 } else {
297 $context = context_user::instance($user->id);
298 $usercontext = $context;
299 $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
302 $currentuser = ($user->id == $USER->id);
303 $isadmin = is_siteadmin($USER);
305 // This does not need to include custom profile fields as it is only used to check specific
306 // fields below.
307 $showuseridentityfields = \core_user\fields::get_identity_fields($context, false);
309 if (!empty($course)) {
310 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
311 } else {
312 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
314 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
315 if (!empty($course)) {
316 $canviewuseremail = has_capability('moodle/course:useremail', $context);
317 } else {
318 $canviewuseremail = false;
320 $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
321 if (!empty($course)) {
322 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
323 } else {
324 $canaccessallgroups = false;
327 if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
328 // Skip this user details.
329 return null;
332 $userdetails = array();
333 $userdetails['id'] = $user->id;
335 if (in_array('username', $userfields)) {
336 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
337 $userdetails['username'] = $user->username;
340 if ($isadmin or $canviewfullnames) {
341 if (in_array('firstname', $userfields)) {
342 $userdetails['firstname'] = $user->firstname;
344 if (in_array('lastname', $userfields)) {
345 $userdetails['lastname'] = $user->lastname;
348 $userdetails['fullname'] = fullname($user, $canviewfullnames);
350 if (in_array('customfields', $userfields)) {
351 $categories = profile_get_user_fields_with_data_by_category($user->id);
352 $userdetails['customfields'] = array();
353 foreach ($categories as $categoryid => $fields) {
354 foreach ($fields as $formfield) {
355 if ($formfield->is_visible() and !$formfield->is_empty()) {
357 // TODO: Part of MDL-50728, this conditional coding must be moved to
358 // proper profile fields API so they are self-contained.
359 // We only use display_data in fields that require text formatting.
360 if ($formfield->field->datatype == 'text' or $formfield->field->datatype == 'textarea') {
361 $fieldvalue = $formfield->display_data();
362 } else {
363 // Cases: datetime, checkbox and menu.
364 $fieldvalue = $formfield->data;
367 $userdetails['customfields'][] =
368 array('name' => $formfield->field->name, 'value' => $fieldvalue,
369 'type' => $formfield->field->datatype, 'shortname' => $formfield->field->shortname);
373 // Unset customfields if it's empty.
374 if (empty($userdetails['customfields'])) {
375 unset($userdetails['customfields']);
379 // Profile image.
380 if (in_array('profileimageurl', $userfields)) {
381 $userpicture = new user_picture($user);
382 $userpicture->size = 1; // Size f1.
383 $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
385 if (in_array('profileimageurlsmall', $userfields)) {
386 if (!isset($userpicture)) {
387 $userpicture = new user_picture($user);
389 $userpicture->size = 0; // Size f2.
390 $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
393 // Hidden user field.
394 if ($canviewhiddenuserfields) {
395 $hiddenfields = array();
396 // Address, phone1 and phone2 not appears in hidden fields list but require viewhiddenfields capability
397 // according to user/profile.php.
398 if (!empty($user->address) && in_array('address', $userfields)) {
399 $userdetails['address'] = $user->address;
401 } else {
402 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
405 if (!empty($user->phone1) && in_array('phone1', $userfields) &&
406 (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) {
407 $userdetails['phone1'] = $user->phone1;
409 if (!empty($user->phone2) && in_array('phone2', $userfields) &&
410 (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) {
411 $userdetails['phone2'] = $user->phone2;
414 if (isset($user->description) &&
415 ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
416 if (in_array('description', $userfields)) {
417 // Always return the descriptionformat if description is requested.
418 list($userdetails['description'], $userdetails['descriptionformat']) =
419 external_format_text($user->description, $user->descriptionformat,
420 $usercontext->id, 'user', 'profile', null);
424 if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
425 $userdetails['country'] = $user->country;
428 if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
429 $userdetails['city'] = $user->city;
432 if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) {
433 $userdetails['suspended'] = (bool)$user->suspended;
436 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
437 if ($user->firstaccess) {
438 $userdetails['firstaccess'] = $user->firstaccess;
439 } else {
440 $userdetails['firstaccess'] = 0;
443 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
444 if ($user->lastaccess) {
445 $userdetails['lastaccess'] = $user->lastaccess;
446 } else {
447 $userdetails['lastaccess'] = 0;
451 // Hidden fields restriction to lastaccess field applies to both site and course access time.
452 if (in_array('lastcourseaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
453 if (isset($user->lastcourseaccess)) {
454 $userdetails['lastcourseaccess'] = $user->lastcourseaccess;
455 } else {
456 $userdetails['lastcourseaccess'] = 0;
460 if (in_array('email', $userfields) && (
461 $currentuser
462 or (!isset($hiddenfields['email']) and (
463 $user->maildisplay == core_user::MAILDISPLAY_EVERYONE
464 or ($user->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY and enrol_sharing_course($user, $USER))
465 or $canviewuseremail // TODO: Deprecate/remove for MDL-37479.
467 or in_array('email', $showuseridentityfields)
468 )) {
469 $userdetails['email'] = $user->email;
472 if (in_array('interests', $userfields)) {
473 $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
474 if ($interests) {
475 $userdetails['interests'] = join(', ', $interests);
479 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
480 if (in_array('idnumber', $userfields) && $user->idnumber) {
481 if (in_array('idnumber', $showuseridentityfields) or $currentuser or
482 has_capability('moodle/user:viewalldetails', $context)) {
483 $userdetails['idnumber'] = $user->idnumber;
486 if (in_array('institution', $userfields) && $user->institution) {
487 if (in_array('institution', $showuseridentityfields) or $currentuser or
488 has_capability('moodle/user:viewalldetails', $context)) {
489 $userdetails['institution'] = $user->institution;
492 // Isset because it's ok to have department 0.
493 if (in_array('department', $userfields) && isset($user->department)) {
494 if (in_array('department', $showuseridentityfields) or $currentuser or
495 has_capability('moodle/user:viewalldetails', $context)) {
496 $userdetails['department'] = $user->department;
500 if (in_array('roles', $userfields) && !empty($course)) {
501 // Not a big secret.
502 $roles = get_user_roles($context, $user->id, false);
503 $userdetails['roles'] = array();
504 foreach ($roles as $role) {
505 $userdetails['roles'][] = array(
506 'roleid' => $role->roleid,
507 'name' => $role->name,
508 'shortname' => $role->shortname,
509 'sortorder' => $role->sortorder
514 // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
515 if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
516 $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid,
517 'g.id, g.name,g.description,g.descriptionformat');
518 $userdetails['groups'] = array();
519 foreach ($usergroups as $group) {
520 list($group->description, $group->descriptionformat) =
521 external_format_text($group->description, $group->descriptionformat,
522 $context->id, 'group', 'description', $group->id);
523 $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name,
524 'description' => $group->description, 'descriptionformat' => $group->descriptionformat);
527 // List of courses where the user is enrolled.
528 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
529 $enrolledcourses = array();
530 if ($mycourses = enrol_get_users_courses($user->id, true)) {
531 foreach ($mycourses as $mycourse) {
532 if ($mycourse->category) {
533 $coursecontext = context_course::instance($mycourse->id);
534 $enrolledcourse = array();
535 $enrolledcourse['id'] = $mycourse->id;
536 $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
537 $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
538 $enrolledcourses[] = $enrolledcourse;
541 $userdetails['enrolledcourses'] = $enrolledcourses;
545 // User preferences.
546 if (in_array('preferences', $userfields) && $currentuser) {
547 $preferences = array();
548 $userpreferences = get_user_preferences();
549 foreach ($userpreferences as $prefname => $prefvalue) {
550 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
552 $userdetails['preferences'] = $preferences;
555 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
556 $extrafields = ['auth', 'confirmed', 'lang', 'theme', 'timezone', 'mailformat'];
557 foreach ($extrafields as $extrafield) {
558 if (in_array($extrafield, $userfields) && isset($user->$extrafield)) {
559 $userdetails[$extrafield] = $user->$extrafield;
564 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
565 if (isset($userdetails['lang'])) {
566 $userdetails['lang'] = clean_param($userdetails['lang'], PARAM_LANG);
568 if (isset($userdetails['theme'])) {
569 $userdetails['theme'] = clean_param($userdetails['theme'], PARAM_THEME);
572 return $userdetails;
576 * Tries to obtain user details, either recurring directly to the user's system profile
577 * or through one of the user's course enrollments (course profile).
579 * @param stdClass $user The user.
580 * @return array if unsuccessful or the allowed user details.
582 function user_get_user_details_courses($user) {
583 global $USER;
584 $userdetails = null;
586 $systemprofile = false;
587 if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
588 $systemprofile = true;
591 // Try using system profile.
592 if ($systemprofile) {
593 $userdetails = user_get_user_details($user, null);
594 } else {
595 // Try through course profile.
596 // Get the courses that the user is enrolled in (only active).
597 $courses = enrol_get_users_courses($user->id, true);
598 foreach ($courses as $course) {
599 if (user_can_view_profile($user, $course)) {
600 $userdetails = user_get_user_details($user, $course);
605 return $userdetails;
609 * Check if $USER have the necessary capabilities to obtain user details.
611 * @param stdClass $user
612 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
613 * @return bool true if $USER can view user details.
615 function can_view_user_details_cap($user, $course = null) {
616 // Check $USER has the capability to view the user details at user context.
617 $usercontext = context_user::instance($user->id);
618 $result = has_capability('moodle/user:viewdetails', $usercontext);
619 // Otherwise can $USER see them at course context.
620 if (!$result && !empty($course)) {
621 $context = context_course::instance($course->id);
622 $result = has_capability('moodle/user:viewdetails', $context);
624 return $result;
628 * Return a list of page types
629 * @param string $pagetype current page type
630 * @param stdClass $parentcontext Block's parent context
631 * @param stdClass $currentcontext Current context of block
632 * @return array
634 function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
635 return array('user-profile' => get_string('page-user-profile', 'pagetype'));
639 * Count the number of failed login attempts for the given user, since last successful login.
641 * @param int|stdclass $user user id or object.
642 * @param bool $reset Resets failed login count, if set to true.
644 * @return int number of failed login attempts since the last successful login.
646 function user_count_login_failures($user, $reset = true) {
647 global $DB;
649 if (!is_object($user)) {
650 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
652 if ($user->deleted) {
653 // Deleted user, nothing to do.
654 return 0;
656 $count = get_user_preferences('login_failed_count_since_success', 0, $user);
657 if ($reset) {
658 set_user_preference('login_failed_count_since_success', 0, $user);
660 return $count;
664 * Converts a string into a flat array of menu items, where each menu items is a
665 * stdClass with fields type, url, title.
667 * @param string $text the menu items definition
668 * @param moodle_page $page the current page
669 * @return array
671 function user_convert_text_to_menu_items($text, $page) {
672 global $OUTPUT, $CFG;
674 $lines = explode("\n", $text);
675 $items = array();
676 $lastchild = null;
677 $lastdepth = null;
678 $lastsort = 0;
679 $children = array();
680 foreach ($lines as $line) {
681 $line = trim($line);
682 $bits = explode('|', $line, 2);
683 $itemtype = 'link';
684 if (preg_match("/^#+$/", $line)) {
685 $itemtype = 'divider';
686 } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
687 // Every item must have a name to be valid.
688 continue;
689 } else {
690 $bits[0] = ltrim($bits[0], '-');
693 // Create the child.
694 $child = new stdClass();
695 $child->itemtype = $itemtype;
696 if ($itemtype === 'divider') {
697 // Add the divider to the list of children and skip link
698 // processing.
699 $children[] = $child;
700 continue;
703 // Name processing.
704 $namebits = explode(',', $bits[0], 2);
705 if (count($namebits) == 2) {
706 // Check the validity of the identifier part of the string.
707 if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
708 // Treat this as a language string.
709 $child->title = get_string($namebits[0], $namebits[1]);
710 $child->titleidentifier = implode(',', $namebits);
713 if (empty($child->title)) {
714 // Use it as is, don't even clean it.
715 $child->title = $bits[0];
716 $child->titleidentifier = str_replace(" ", "-", $bits[0]);
719 // URL processing.
720 if (!array_key_exists(1, $bits) or empty($bits[1])) {
721 // Set the url to null, and set the itemtype to invalid.
722 $bits[1] = null;
723 $child->itemtype = "invalid";
724 } else {
725 // Nasty hack to replace the grades with the direct url.
726 if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
727 $bits[1] = user_mygrades_url();
730 // Make sure the url is a moodle url.
731 $bits[1] = new moodle_url(trim($bits[1]));
733 $child->url = $bits[1];
735 // Add this child to the list of children.
736 $children[] = $child;
738 return $children;
742 * Get a list of essential user navigation items.
744 * @param stdclass $user user object.
745 * @param moodle_page $page page object.
746 * @param array $options associative array.
747 * options are:
748 * - avatarsize=35 (size of avatar image)
749 * @return stdClass $returnobj navigation information object, where:
751 * $returnobj->navitems array array of links where each link is a
752 * stdClass with fields url, title, and
753 * pix
754 * $returnobj->metadata array array of useful user metadata to be
755 * used when constructing navigation;
756 * fields include:
758 * ROLE FIELDS
759 * asotherrole bool whether viewing as another role
760 * rolename string name of the role
762 * USER FIELDS
763 * These fields are for the currently-logged in user, or for
764 * the user that the real user is currently logged in as.
766 * userid int the id of the user in question
767 * userfullname string the user's full name
768 * userprofileurl moodle_url the url of the user's profile
769 * useravatar string a HTML fragment - the rendered
770 * user_picture for this user
771 * userloginfail string an error string denoting the number
772 * of login failures since last login
774 * "REAL USER" FIELDS
775 * These fields are for when asotheruser is true, and
776 * correspond to the underlying "real user".
778 * asotheruser bool whether viewing as another user
779 * realuserid int the id of the user in question
780 * realuserfullname string the user's full name
781 * realuserprofileurl moodle_url the url of the user's profile
782 * realuseravatar string a HTML fragment - the rendered
783 * user_picture for this user
785 * MNET PROVIDER FIELDS
786 * asmnetuser bool whether viewing as a user from an
787 * MNet provider
788 * mnetidprovidername string name of the MNet provider
789 * mnetidproviderwwwroot string URL of the MNet provider
791 function user_get_user_navigation_info($user, $page, $options = array()) {
792 global $OUTPUT, $DB, $SESSION, $CFG;
794 $returnobject = new stdClass();
795 $returnobject->navitems = array();
796 $returnobject->metadata = array();
798 $guest = isguestuser();
799 if (!isloggedin() || $guest) {
800 $returnobject->unauthenticateduser = [
801 'guest' => $guest,
802 'content' => $guest ? 'loggedinasguest' : 'loggedinnot',
805 return $returnobject;
808 $course = $page->course;
810 // Query the environment.
811 $context = context_course::instance($course->id);
813 // Get basic user metadata.
814 $returnobject->metadata['userid'] = $user->id;
815 $returnobject->metadata['userfullname'] = fullname($user);
816 $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
817 'id' => $user->id
820 $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
821 if (!empty($options['avatarsize'])) {
822 $avataroptions['size'] = $options['avatarsize'];
824 $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
825 $user, $avataroptions
827 // Build a list of items for a regular user.
829 // Query MNet status.
830 if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
831 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
832 $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
833 $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
836 // Did the user just log in?
837 if (isset($SESSION->justloggedin)) {
838 // Don't unset this flag as login_info still needs it.
839 if (!empty($CFG->displayloginfailures)) {
840 // Don't reset the count either, as login_info() still needs it too.
841 if ($count = user_count_login_failures($user, false)) {
843 // Get login failures string.
844 $a = new stdClass();
845 $a->attempts = html_writer::tag('span', $count, array('class' => 'value mr-1 font-weight-bold'));
846 $returnobject->metadata['userloginfail'] =
847 get_string('failedloginattempts', '', $a);
853 $returnobject->metadata['asotherrole'] = false;
855 // Before we add the last items (usually a logout + switch role link), add any
856 // custom-defined items.
857 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
858 $custommenucount = 0;
859 foreach ($customitems as $item) {
860 $returnobject->navitems[] = $item;
861 if ($item->itemtype !== 'divider' && $item->itemtype !== 'invalid') {
862 $custommenucount++;
866 if ($custommenucount > 0) {
867 // Only add a divider if we have customusermenuitems.
868 $divider = new stdClass();
869 $divider->itemtype = 'divider';
870 $returnobject->navitems[] = $divider;
873 // Links: Preferences.
874 $preferences = new stdClass();
875 $preferences->itemtype = 'link';
876 $preferences->url = new moodle_url('/user/preferences.php');
877 $preferences->title = get_string('preferences');
878 $preferences->titleidentifier = 'preferences,moodle';
879 $returnobject->navitems[] = $preferences;
882 if (is_role_switched($course->id)) {
883 if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
884 // Build role-return link instead of logout link.
885 $rolereturn = new stdClass();
886 $rolereturn->itemtype = 'link';
887 $rolereturn->url = new moodle_url('/course/switchrole.php', array(
888 'id' => $course->id,
889 'sesskey' => sesskey(),
890 'switchrole' => 0,
891 'returnurl' => $page->url->out_as_local_url(false)
893 $rolereturn->title = get_string('switchrolereturn');
894 $rolereturn->titleidentifier = 'switchrolereturn,moodle';
895 $returnobject->navitems[] = $rolereturn;
897 $returnobject->metadata['asotherrole'] = true;
898 $returnobject->metadata['rolename'] = role_get_name($role, $context);
901 } else {
902 // Build switch role link.
903 $roles = get_switchable_roles($context);
904 if (is_array($roles) && (count($roles) > 0)) {
905 $switchrole = new stdClass();
906 $switchrole->itemtype = 'link';
907 $switchrole->url = new moodle_url('/course/switchrole.php', array(
908 'id' => $course->id,
909 'switchrole' => -1,
910 'returnurl' => $page->url->out_as_local_url(false)
912 $switchrole->title = get_string('switchroleto');
913 $switchrole->titleidentifier = 'switchroleto,moodle';
914 $returnobject->navitems[] = $switchrole;
918 if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
919 $realuser = \core\session\manager::get_realuser();
921 // Save values for the real user, as $user will be full of data for the
922 // user is disguised as.
923 $returnobject->metadata['realuserid'] = $realuser->id;
924 $returnobject->metadata['realuserfullname'] = fullname($realuser);
925 $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', [
926 'id' => $realuser->id
928 $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
930 // Build a user-revert link.
931 $userrevert = new stdClass();
932 $userrevert->itemtype = 'link';
933 $userrevert->url = new moodle_url('/course/loginas.php', [
934 'id' => $course->id,
935 'sesskey' => sesskey()
937 $userrevert->title = get_string('logout');
938 $userrevert->titleidentifier = 'logout,moodle';
939 $returnobject->navitems[] = $userrevert;
940 } else {
941 // Build a logout link.
942 $logout = new stdClass();
943 $logout->itemtype = 'link';
944 $logout->url = new moodle_url('/login/logout.php', ['sesskey' => sesskey()]);
945 $logout->title = get_string('logout');
946 $logout->titleidentifier = 'logout,moodle';
947 $returnobject->navitems[] = $logout;
950 return $returnobject;
954 * Add password to the list of used hashes for this user.
956 * This is supposed to be used from:
957 * 1/ change own password form
958 * 2/ password reset process
959 * 3/ user signup in auth plugins if password changing supported
961 * @param int $userid user id
962 * @param string $password plaintext password
963 * @return void
965 function user_add_password_history($userid, $password) {
966 global $CFG, $DB;
968 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
969 return;
972 // Note: this is using separate code form normal password hashing because
973 // we need to have this under control in the future. Also the auth
974 // plugin might not store the passwords locally at all.
976 $record = new stdClass();
977 $record->userid = $userid;
978 $record->hash = password_hash($password, PASSWORD_DEFAULT);
979 $record->timecreated = time();
980 $DB->insert_record('user_password_history', $record);
982 $i = 0;
983 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
984 foreach ($records as $record) {
985 $i++;
986 if ($i > $CFG->passwordreuselimit) {
987 $DB->delete_records('user_password_history', array('id' => $record->id));
993 * Was this password used before on change or reset password page?
995 * The $CFG->passwordreuselimit setting determines
996 * how many times different password needs to be used
997 * before allowing previously used password again.
999 * @param int $userid user id
1000 * @param string $password plaintext password
1001 * @return bool true if password reused
1003 function user_is_previously_used_password($userid, $password) {
1004 global $CFG, $DB;
1006 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1007 return false;
1010 $reused = false;
1012 $i = 0;
1013 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1014 foreach ($records as $record) {
1015 $i++;
1016 if ($i > $CFG->passwordreuselimit) {
1017 $DB->delete_records('user_password_history', array('id' => $record->id));
1018 continue;
1020 // NOTE: this is slow but we cannot compare the hashes directly any more.
1021 if (password_verify($password, $record->hash)) {
1022 $reused = true;
1026 return $reused;
1030 * Remove a user device from the Moodle database (for PUSH notifications usually).
1032 * @param string $uuid The device UUID.
1033 * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1034 * @return bool true if removed, false if the device didn't exists in the database
1035 * @since Moodle 2.9
1037 function user_remove_user_device($uuid, $appid = "") {
1038 global $DB, $USER;
1040 $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
1041 if (!empty($appid)) {
1042 $conditions['appid'] = $appid;
1045 if (!$DB->count_records('user_devices', $conditions)) {
1046 return false;
1049 $DB->delete_records('user_devices', $conditions);
1051 return true;
1055 * Trigger user_list_viewed event.
1057 * @param stdClass $course course object
1058 * @param stdClass $context course context object
1059 * @since Moodle 2.9
1061 function user_list_view($course, $context) {
1063 $event = \core\event\user_list_viewed::create(array(
1064 'objectid' => $course->id,
1065 'courseid' => $course->id,
1066 'context' => $context,
1067 'other' => array(
1068 'courseshortname' => $course->shortname,
1069 'coursefullname' => $course->fullname
1072 $event->trigger();
1076 * Returns the url to use for the "Grades" link in the user navigation.
1078 * @param int $userid The user's ID.
1079 * @param int $courseid The course ID if available.
1080 * @return mixed A URL to be directed to for "Grades".
1082 function user_mygrades_url($userid = null, $courseid = SITEID) {
1083 global $CFG, $USER;
1084 $url = null;
1085 if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
1086 if (isset($userid) && $USER->id != $userid) {
1087 // Send to the gradebook report.
1088 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
1089 array('id' => $courseid, 'userid' => $userid));
1090 } else {
1091 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
1093 } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
1094 && !empty($CFG->gradereport_mygradeurl)) {
1095 $url = $CFG->gradereport_mygradeurl;
1096 } else {
1097 $url = $CFG->wwwroot;
1099 return $url;
1103 * Check if the current user has permission to view details of the supplied user.
1105 * This function supports two modes:
1106 * If the optional $course param is omitted, then this function finds all shared courses and checks whether the current user has
1107 * permission in any of them, returning true if so.
1108 * If the $course param is provided, then this function checks permissions in ONLY that course.
1110 * @param object $user The other user's details.
1111 * @param object $course if provided, only check permissions in this course.
1112 * @param context $usercontext The user context if available.
1113 * @return bool true for ability to view this user, else false.
1115 function user_can_view_profile($user, $course = null, $usercontext = null) {
1116 global $USER, $CFG;
1118 if ($user->deleted) {
1119 return false;
1122 // Do we need to be logged in?
1123 if (empty($CFG->forceloginforprofiles)) {
1124 return true;
1125 } else {
1126 if (!isloggedin() || isguestuser()) {
1127 // User is not logged in and forceloginforprofile is set, we need to return now.
1128 return false;
1132 // Current user can always view their profile.
1133 if ($USER->id == $user->id) {
1134 return true;
1137 // Use callbacks so that (primarily) local plugins can prevent or allow profile access.
1138 $forceallow = false;
1139 $plugintypes = get_plugins_with_function('control_view_profile');
1140 foreach ($plugintypes as $plugins) {
1141 foreach ($plugins as $pluginfunction) {
1142 $result = $pluginfunction($user, $course, $usercontext);
1143 switch ($result) {
1144 case core_user::VIEWPROFILE_DO_NOT_PREVENT:
1145 // If the plugin doesn't stop access, just continue to next plugin or use
1146 // default behaviour.
1147 break;
1148 case core_user::VIEWPROFILE_FORCE_ALLOW:
1149 // Record that we are definitely going to allow it (unless another plugin
1150 // returns _PREVENT).
1151 $forceallow = true;
1152 break;
1153 case core_user::VIEWPROFILE_PREVENT:
1154 // If any plugin returns PREVENT then we return false, regardless of what
1155 // other plugins said.
1156 return false;
1160 if ($forceallow) {
1161 return true;
1164 // Course contacts have visible profiles always.
1165 if (has_coursecontact_role($user->id)) {
1166 return true;
1169 // If we're only checking the capabilities in the single provided course.
1170 if (isset($course)) {
1171 // Confirm that $user is enrolled in the $course we're checking.
1172 if (is_enrolled(context_course::instance($course->id), $user)) {
1173 $userscourses = array($course);
1175 } else {
1176 // Else we're checking whether the current user can view $user's profile anywhere, so check user context first.
1177 if (empty($usercontext)) {
1178 $usercontext = context_user::instance($user->id);
1180 if (has_capability('moodle/user:viewdetails', $usercontext) || has_capability('moodle/user:viewalldetails', $usercontext)) {
1181 return true;
1183 // This returns context information, so we can preload below.
1184 $userscourses = enrol_get_all_users_courses($user->id);
1187 if (empty($userscourses)) {
1188 return false;
1191 foreach ($userscourses as $userscourse) {
1192 context_helper::preload_from_record($userscourse);
1193 $coursecontext = context_course::instance($userscourse->id);
1194 if (has_capability('moodle/user:viewdetails', $coursecontext) ||
1195 has_capability('moodle/user:viewalldetails', $coursecontext)) {
1196 if (!groups_user_groups_visible($userscourse, $user->id)) {
1197 // Not a member of the same group.
1198 continue;
1200 return true;
1203 return false;
1207 * Returns users tagged with a specified tag.
1209 * @param core_tag_tag $tag
1210 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1211 * are displayed on the page and the per-page limit may be bigger
1212 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1213 * to display items in the same context first
1214 * @param int $ctx context id where to search for records
1215 * @param bool $rec search in subcontexts as well
1216 * @param int $page 0-based number of page being displayed
1217 * @return \core_tag\output\tagindex
1219 function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1220 global $PAGE;
1222 if ($ctx && $ctx != context_system::instance()->id) {
1223 $usercount = 0;
1224 } else {
1225 // Users can only be displayed in system context.
1226 $usercount = $tag->count_tagged_items('core', 'user',
1227 'it.deleted=:notdeleted', array('notdeleted' => 0));
1229 $perpage = $exclusivemode ? 24 : 5;
1230 $content = '';
1231 $totalpages = ceil($usercount / $perpage);
1233 if ($usercount) {
1234 $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage,
1235 'it.deleted=:notdeleted', array('notdeleted' => 0));
1236 $renderer = $PAGE->get_renderer('core', 'user');
1237 $content .= $renderer->user_list($userlist, $exclusivemode);
1240 return new core_tag\output\tagindex($tag, 'core', 'user', $content,
1241 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1245 * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access a course.
1247 * @param int $accesssince The unix timestamp to compare to users' last access
1248 * @param string $tableprefix
1249 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1250 * @return string
1252 function user_get_course_lastaccess_sql($accesssince = null, $tableprefix = 'ul', $haveaccessed = false) {
1253 return user_get_lastaccess_sql('timeaccess', $accesssince, $tableprefix, $haveaccessed);
1257 * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access the system.
1259 * @param int $accesssince The unix timestamp to compare to users' last access
1260 * @param string $tableprefix
1261 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1262 * @return string
1264 function user_get_user_lastaccess_sql($accesssince = null, $tableprefix = 'u', $haveaccessed = false) {
1265 return user_get_lastaccess_sql('lastaccess', $accesssince, $tableprefix, $haveaccessed);
1269 * Returns SQL that can be used to limit a query to a period where the user last accessed or
1270 * did not access something recorded by a given table.
1272 * @param string $columnname The name of the access column to check against
1273 * @param int $accesssince The unix timestamp to compare to users' last access
1274 * @param string $tableprefix The query prefix of the table to check
1275 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1276 * @return string
1278 function user_get_lastaccess_sql($columnname, $accesssince, $tableprefix, $haveaccessed = false) {
1279 if (empty($accesssince)) {
1280 return '';
1283 // Only users who have accessed since $accesssince.
1284 if ($haveaccessed) {
1285 if ($accesssince == -1) {
1286 // Include all users who have logged in at some point.
1287 $sql = "({$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0)";
1288 } else {
1289 // Users who have accessed since the specified time.
1290 $sql = "{$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0
1291 AND {$tableprefix}.{$columnname} >= {$accesssince}";
1293 } else {
1294 // Only users who have not accessed since $accesssince.
1296 if ($accesssince == -1) {
1297 // Users who have never accessed.
1298 $sql = "({$tableprefix}.{$columnname} IS NULL OR {$tableprefix}.{$columnname} = 0)";
1299 } else {
1300 // Users who have not accessed since the specified time.
1301 $sql = "({$tableprefix}.{$columnname} IS NULL
1302 OR ({$tableprefix}.{$columnname} != 0 AND {$tableprefix}.{$columnname} < {$accesssince}))";
1306 return $sql;
1310 * Callback for inplace editable API.
1312 * @param string $itemtype - Only user_roles is supported.
1313 * @param string $itemid - Courseid and userid separated by a :
1314 * @param string $newvalue - json encoded list of roleids.
1315 * @return \core\output\inplace_editable
1317 function core_user_inplace_editable($itemtype, $itemid, $newvalue) {
1318 if ($itemtype === 'user_roles') {
1319 return \core_user\output\user_roles_editable::update($itemid, $newvalue);
1324 * Map an internal field name to a valid purpose from: "https://www.w3.org/TR/WCAG21/#input-purposes"
1326 * @param integer $userid
1327 * @param string $fieldname
1328 * @return string $purpose (empty string if there is no mapping).
1330 function user_edit_map_field_purpose($userid, $fieldname) {
1331 global $USER;
1333 $currentuser = ($userid == $USER->id) && !\core\session\manager::is_loggedinas();
1334 // These are the fields considered valid to map and auto fill from a browser.
1335 // We do not include fields that are in a collapsed section by default because
1336 // the browser could auto-fill the field and cause a new value to be saved when
1337 // that field was never visible.
1338 $validmappings = array(
1339 'username' => 'username',
1340 'password' => 'current-password',
1341 'firstname' => 'given-name',
1342 'lastname' => 'family-name',
1343 'middlename' => 'additional-name',
1344 'email' => 'email',
1345 'country' => 'country',
1346 'lang' => 'language'
1349 $purpose = '';
1350 // Only set a purpose when editing your own user details.
1351 if ($currentuser && isset($validmappings[$fieldname])) {
1352 $purpose = ' autocomplete="' . $validmappings[$fieldname] . '" ';
1355 return $purpose;