Merge branch 'MDL-70099-311' of git://github.com/paulholden/moodle into MOODLE_311_STABLE
[moodle.git] / user / lib.php
blob3809b8170a37588c638aa2c1630a15dc719de5da
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', 'icq', 'skype', 'yahoo', 'aim', 'msn', 'department',
246 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
247 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
248 'city', 'url', '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('url', $userfields) && $user->url && (!isset($hiddenfields['webpage']) or $isadmin)) {
433 $url = $user->url;
434 if (strpos($user->url, '://') === false) {
435 $url = 'http://'. $url;
437 $user->url = clean_param($user->url, PARAM_URL);
438 $userdetails['url'] = $user->url;
441 if (in_array('icq', $userfields) && $user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) {
442 $userdetails['icq'] = $user->icq;
445 if (in_array('skype', $userfields) && $user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) {
446 $userdetails['skype'] = $user->skype;
448 if (in_array('yahoo', $userfields) && $user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) {
449 $userdetails['yahoo'] = $user->yahoo;
451 if (in_array('aim', $userfields) && $user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) {
452 $userdetails['aim'] = $user->aim;
454 if (in_array('msn', $userfields) && $user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) {
455 $userdetails['msn'] = $user->msn;
457 if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) {
458 $userdetails['suspended'] = (bool)$user->suspended;
461 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
462 if ($user->firstaccess) {
463 $userdetails['firstaccess'] = $user->firstaccess;
464 } else {
465 $userdetails['firstaccess'] = 0;
468 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
469 if ($user->lastaccess) {
470 $userdetails['lastaccess'] = $user->lastaccess;
471 } else {
472 $userdetails['lastaccess'] = 0;
476 // Hidden fields restriction to lastaccess field applies to both site and course access time.
477 if (in_array('lastcourseaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
478 if (isset($user->lastcourseaccess)) {
479 $userdetails['lastcourseaccess'] = $user->lastcourseaccess;
480 } else {
481 $userdetails['lastcourseaccess'] = 0;
485 if (in_array('email', $userfields) && (
486 $currentuser
487 or (!isset($hiddenfields['email']) and (
488 $user->maildisplay == core_user::MAILDISPLAY_EVERYONE
489 or ($user->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY and enrol_sharing_course($user, $USER))
490 or $canviewuseremail // TODO: Deprecate/remove for MDL-37479.
492 or in_array('email', $showuseridentityfields)
493 )) {
494 $userdetails['email'] = $user->email;
497 if (in_array('interests', $userfields)) {
498 $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
499 if ($interests) {
500 $userdetails['interests'] = join(', ', $interests);
504 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
505 if (in_array('idnumber', $userfields) && $user->idnumber) {
506 if (in_array('idnumber', $showuseridentityfields) or $currentuser or
507 has_capability('moodle/user:viewalldetails', $context)) {
508 $userdetails['idnumber'] = $user->idnumber;
511 if (in_array('institution', $userfields) && $user->institution) {
512 if (in_array('institution', $showuseridentityfields) or $currentuser or
513 has_capability('moodle/user:viewalldetails', $context)) {
514 $userdetails['institution'] = $user->institution;
517 // Isset because it's ok to have department 0.
518 if (in_array('department', $userfields) && isset($user->department)) {
519 if (in_array('department', $showuseridentityfields) or $currentuser or
520 has_capability('moodle/user:viewalldetails', $context)) {
521 $userdetails['department'] = $user->department;
525 if (in_array('roles', $userfields) && !empty($course)) {
526 // Not a big secret.
527 $roles = get_user_roles($context, $user->id, false);
528 $userdetails['roles'] = array();
529 foreach ($roles as $role) {
530 $userdetails['roles'][] = array(
531 'roleid' => $role->roleid,
532 'name' => $role->name,
533 'shortname' => $role->shortname,
534 'sortorder' => $role->sortorder
539 // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
540 if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
541 $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid,
542 'g.id, g.name,g.description,g.descriptionformat');
543 $userdetails['groups'] = array();
544 foreach ($usergroups as $group) {
545 list($group->description, $group->descriptionformat) =
546 external_format_text($group->description, $group->descriptionformat,
547 $context->id, 'group', 'description', $group->id);
548 $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name,
549 'description' => $group->description, 'descriptionformat' => $group->descriptionformat);
552 // List of courses where the user is enrolled.
553 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
554 $enrolledcourses = array();
555 if ($mycourses = enrol_get_users_courses($user->id, true)) {
556 foreach ($mycourses as $mycourse) {
557 if ($mycourse->category) {
558 $coursecontext = context_course::instance($mycourse->id);
559 $enrolledcourse = array();
560 $enrolledcourse['id'] = $mycourse->id;
561 $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
562 $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
563 $enrolledcourses[] = $enrolledcourse;
566 $userdetails['enrolledcourses'] = $enrolledcourses;
570 // User preferences.
571 if (in_array('preferences', $userfields) && $currentuser) {
572 $preferences = array();
573 $userpreferences = get_user_preferences();
574 foreach ($userpreferences as $prefname => $prefvalue) {
575 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
577 $userdetails['preferences'] = $preferences;
580 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
581 $extrafields = ['auth', 'confirmed', 'lang', 'theme', 'timezone', 'mailformat'];
582 foreach ($extrafields as $extrafield) {
583 if (in_array($extrafield, $userfields) && isset($user->$extrafield)) {
584 $userdetails[$extrafield] = $user->$extrafield;
589 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
590 if (isset($userdetails['lang'])) {
591 $userdetails['lang'] = clean_param($userdetails['lang'], PARAM_LANG);
593 if (isset($userdetails['theme'])) {
594 $userdetails['theme'] = clean_param($userdetails['theme'], PARAM_THEME);
597 return $userdetails;
601 * Tries to obtain user details, either recurring directly to the user's system profile
602 * or through one of the user's course enrollments (course profile).
604 * @param stdClass $user The user.
605 * @return array if unsuccessful or the allowed user details.
607 function user_get_user_details_courses($user) {
608 global $USER;
609 $userdetails = null;
611 $systemprofile = false;
612 if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
613 $systemprofile = true;
616 // Try using system profile.
617 if ($systemprofile) {
618 $userdetails = user_get_user_details($user, null);
619 } else {
620 // Try through course profile.
621 // Get the courses that the user is enrolled in (only active).
622 $courses = enrol_get_users_courses($user->id, true);
623 foreach ($courses as $course) {
624 if (user_can_view_profile($user, $course)) {
625 $userdetails = user_get_user_details($user, $course);
630 return $userdetails;
634 * Check if $USER have the necessary capabilities to obtain user details.
636 * @param stdClass $user
637 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
638 * @return bool true if $USER can view user details.
640 function can_view_user_details_cap($user, $course = null) {
641 // Check $USER has the capability to view the user details at user context.
642 $usercontext = context_user::instance($user->id);
643 $result = has_capability('moodle/user:viewdetails', $usercontext);
644 // Otherwise can $USER see them at course context.
645 if (!$result && !empty($course)) {
646 $context = context_course::instance($course->id);
647 $result = has_capability('moodle/user:viewdetails', $context);
649 return $result;
653 * Return a list of page types
654 * @param string $pagetype current page type
655 * @param stdClass $parentcontext Block's parent context
656 * @param stdClass $currentcontext Current context of block
657 * @return array
659 function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
660 return array('user-profile' => get_string('page-user-profile', 'pagetype'));
664 * Count the number of failed login attempts for the given user, since last successful login.
666 * @param int|stdclass $user user id or object.
667 * @param bool $reset Resets failed login count, if set to true.
669 * @return int number of failed login attempts since the last successful login.
671 function user_count_login_failures($user, $reset = true) {
672 global $DB;
674 if (!is_object($user)) {
675 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
677 if ($user->deleted) {
678 // Deleted user, nothing to do.
679 return 0;
681 $count = get_user_preferences('login_failed_count_since_success', 0, $user);
682 if ($reset) {
683 set_user_preference('login_failed_count_since_success', 0, $user);
685 return $count;
689 * Converts a string into a flat array of menu items, where each menu items is a
690 * stdClass with fields type, url, title, pix, and imgsrc.
692 * @param string $text the menu items definition
693 * @param moodle_page $page the current page
694 * @return array
696 function user_convert_text_to_menu_items($text, $page) {
697 global $OUTPUT, $CFG;
699 $lines = explode("\n", $text);
700 $items = array();
701 $lastchild = null;
702 $lastdepth = null;
703 $lastsort = 0;
704 $children = array();
705 foreach ($lines as $line) {
706 $line = trim($line);
707 $bits = explode('|', $line, 3);
708 $itemtype = 'link';
709 if (preg_match("/^#+$/", $line)) {
710 $itemtype = 'divider';
711 } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
712 // Every item must have a name to be valid.
713 continue;
714 } else {
715 $bits[0] = ltrim($bits[0], '-');
718 // Create the child.
719 $child = new stdClass();
720 $child->itemtype = $itemtype;
721 if ($itemtype === 'divider') {
722 // Add the divider to the list of children and skip link
723 // processing.
724 $children[] = $child;
725 continue;
728 // Name processing.
729 $namebits = explode(',', $bits[0], 2);
730 if (count($namebits) == 2) {
731 // Check the validity of the identifier part of the string.
732 if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
733 // Treat this as a language string.
734 $child->title = get_string($namebits[0], $namebits[1]);
735 $child->titleidentifier = implode(',', $namebits);
738 if (empty($child->title)) {
739 // Use it as is, don't even clean it.
740 $child->title = $bits[0];
741 $child->titleidentifier = str_replace(" ", "-", $bits[0]);
744 // URL processing.
745 if (!array_key_exists(1, $bits) or empty($bits[1])) {
746 // Set the url to null, and set the itemtype to invalid.
747 $bits[1] = null;
748 $child->itemtype = "invalid";
749 } else {
750 // Nasty hack to replace the grades with the direct url.
751 if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
752 $bits[1] = user_mygrades_url();
755 // Make sure the url is a moodle url.
756 $bits[1] = new moodle_url(trim($bits[1]));
758 $child->url = $bits[1];
760 // PIX processing.
761 $pixpath = "t/edit";
762 if (!array_key_exists(2, $bits) or empty($bits[2])) {
763 // Use the default.
764 $child->pix = $pixpath;
765 } else {
766 // Check for the specified image existing.
767 if (strpos($bits[2], '../') === 0) {
768 // The string starts with '../'.
769 // Strip off the first three characters - this should be the pix path.
770 $pixpath = substr($bits[2], 3);
771 } else if (strpos($bits[2], '/') === false) {
772 // There is no / in the path. Prefix it with 't/', which is the default path.
773 $pixpath = "t/{$bits[2]}";
774 } else {
775 // There is a '/' in the path - this is either a URL, or a standard pix path with no changes required.
776 $pixpath = $bits[2];
778 if ($page->theme->resolve_image_location($pixpath, 'moodle', true)) {
779 // Use the image.
780 $child->pix = $pixpath;
781 } else {
782 // Treat it like a URL.
783 $child->pix = null;
784 $child->imgsrc = $bits[2];
788 // Add this child to the list of children.
789 $children[] = $child;
791 return $children;
795 * Get a list of essential user navigation items.
797 * @param stdclass $user user object.
798 * @param moodle_page $page page object.
799 * @param array $options associative array.
800 * options are:
801 * - avatarsize=35 (size of avatar image)
802 * @return stdClass $returnobj navigation information object, where:
804 * $returnobj->navitems array array of links where each link is a
805 * stdClass with fields url, title, and
806 * pix
807 * $returnobj->metadata array array of useful user metadata to be
808 * used when constructing navigation;
809 * fields include:
811 * ROLE FIELDS
812 * asotherrole bool whether viewing as another role
813 * rolename string name of the role
815 * USER FIELDS
816 * These fields are for the currently-logged in user, or for
817 * the user that the real user is currently logged in as.
819 * userid int the id of the user in question
820 * userfullname string the user's full name
821 * userprofileurl moodle_url the url of the user's profile
822 * useravatar string a HTML fragment - the rendered
823 * user_picture for this user
824 * userloginfail string an error string denoting the number
825 * of login failures since last login
827 * "REAL USER" FIELDS
828 * These fields are for when asotheruser is true, and
829 * correspond to the underlying "real user".
831 * asotheruser bool whether viewing as another user
832 * realuserid int the id of the user in question
833 * realuserfullname string the user's full name
834 * realuserprofileurl moodle_url the url of the user's profile
835 * realuseravatar string a HTML fragment - the rendered
836 * user_picture for this user
838 * MNET PROVIDER FIELDS
839 * asmnetuser bool whether viewing as a user from an
840 * MNet provider
841 * mnetidprovidername string name of the MNet provider
842 * mnetidproviderwwwroot string URL of the MNet provider
844 function user_get_user_navigation_info($user, $page, $options = array()) {
845 global $OUTPUT, $DB, $SESSION, $CFG;
847 $returnobject = new stdClass();
848 $returnobject->navitems = array();
849 $returnobject->metadata = array();
851 $course = $page->course;
853 // Query the environment.
854 $context = context_course::instance($course->id);
856 // Get basic user metadata.
857 $returnobject->metadata['userid'] = $user->id;
858 $returnobject->metadata['userfullname'] = fullname($user);
859 $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
860 'id' => $user->id
863 $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
864 if (!empty($options['avatarsize'])) {
865 $avataroptions['size'] = $options['avatarsize'];
867 $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
868 $user, $avataroptions
870 // Build a list of items for a regular user.
872 // Query MNet status.
873 if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
874 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
875 $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
876 $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
879 // Did the user just log in?
880 if (isset($SESSION->justloggedin)) {
881 // Don't unset this flag as login_info still needs it.
882 if (!empty($CFG->displayloginfailures)) {
883 // Don't reset the count either, as login_info() still needs it too.
884 if ($count = user_count_login_failures($user, false)) {
886 // Get login failures string.
887 $a = new stdClass();
888 $a->attempts = html_writer::tag('span', $count, array('class' => 'value'));
889 $returnobject->metadata['userloginfail'] =
890 get_string('failedloginattempts', '', $a);
896 // Links: Dashboard.
897 $myhome = new stdClass();
898 $myhome->itemtype = 'link';
899 $myhome->url = new moodle_url('/my/');
900 $myhome->title = get_string('mymoodle', 'admin');
901 $myhome->titleidentifier = 'mymoodle,admin';
902 $myhome->pix = "i/dashboard";
903 $returnobject->navitems[] = $myhome;
905 // Links: My Profile.
906 $myprofile = new stdClass();
907 $myprofile->itemtype = 'link';
908 $myprofile->url = new moodle_url('/user/profile.php', array('id' => $user->id));
909 $myprofile->title = get_string('profile');
910 $myprofile->titleidentifier = 'profile,moodle';
911 $myprofile->pix = "i/user";
912 $returnobject->navitems[] = $myprofile;
914 $returnobject->metadata['asotherrole'] = false;
916 // Before we add the last items (usually a logout + switch role link), add any
917 // custom-defined items.
918 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
919 foreach ($customitems as $item) {
920 $returnobject->navitems[] = $item;
924 if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
925 $realuser = \core\session\manager::get_realuser();
927 // Save values for the real user, as $user will be full of data for the
928 // user the user is disguised as.
929 $returnobject->metadata['realuserid'] = $realuser->id;
930 $returnobject->metadata['realuserfullname'] = fullname($realuser);
931 $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', array(
932 'id' => $realuser->id
934 $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
936 // Build a user-revert link.
937 $userrevert = new stdClass();
938 $userrevert->itemtype = 'link';
939 $userrevert->url = new moodle_url('/course/loginas.php', array(
940 'id' => $course->id,
941 'sesskey' => sesskey()
943 $userrevert->pix = "a/logout";
944 $userrevert->title = get_string('logout');
945 $userrevert->titleidentifier = 'logout,moodle';
946 $returnobject->navitems[] = $userrevert;
948 } else {
950 // Build a logout link.
951 $logout = new stdClass();
952 $logout->itemtype = 'link';
953 $logout->url = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
954 $logout->pix = "a/logout";
955 $logout->title = get_string('logout');
956 $logout->titleidentifier = 'logout,moodle';
957 $returnobject->navitems[] = $logout;
960 if (is_role_switched($course->id)) {
961 if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
962 // Build role-return link instead of logout link.
963 $rolereturn = new stdClass();
964 $rolereturn->itemtype = 'link';
965 $rolereturn->url = new moodle_url('/course/switchrole.php', array(
966 'id' => $course->id,
967 'sesskey' => sesskey(),
968 'switchrole' => 0,
969 'returnurl' => $page->url->out_as_local_url(false)
971 $rolereturn->pix = "a/logout";
972 $rolereturn->title = get_string('switchrolereturn');
973 $rolereturn->titleidentifier = 'switchrolereturn,moodle';
974 $returnobject->navitems[] = $rolereturn;
976 $returnobject->metadata['asotherrole'] = true;
977 $returnobject->metadata['rolename'] = role_get_name($role, $context);
980 } else {
981 // Build switch role link.
982 $roles = get_switchable_roles($context);
983 if (is_array($roles) && (count($roles) > 0)) {
984 $switchrole = new stdClass();
985 $switchrole->itemtype = 'link';
986 $switchrole->url = new moodle_url('/course/switchrole.php', array(
987 'id' => $course->id,
988 'switchrole' => -1,
989 'returnurl' => $page->url->out_as_local_url(false)
991 $switchrole->pix = "i/switchrole";
992 $switchrole->title = get_string('switchroleto');
993 $switchrole->titleidentifier = 'switchroleto,moodle';
994 $returnobject->navitems[] = $switchrole;
998 return $returnobject;
1002 * Add password to the list of used hashes for this user.
1004 * This is supposed to be used from:
1005 * 1/ change own password form
1006 * 2/ password reset process
1007 * 3/ user signup in auth plugins if password changing supported
1009 * @param int $userid user id
1010 * @param string $password plaintext password
1011 * @return void
1013 function user_add_password_history($userid, $password) {
1014 global $CFG, $DB;
1016 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1017 return;
1020 // Note: this is using separate code form normal password hashing because
1021 // we need to have this under control in the future. Also the auth
1022 // plugin might not store the passwords locally at all.
1024 $record = new stdClass();
1025 $record->userid = $userid;
1026 $record->hash = password_hash($password, PASSWORD_DEFAULT);
1027 $record->timecreated = time();
1028 $DB->insert_record('user_password_history', $record);
1030 $i = 0;
1031 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1032 foreach ($records as $record) {
1033 $i++;
1034 if ($i > $CFG->passwordreuselimit) {
1035 $DB->delete_records('user_password_history', array('id' => $record->id));
1041 * Was this password used before on change or reset password page?
1043 * The $CFG->passwordreuselimit setting determines
1044 * how many times different password needs to be used
1045 * before allowing previously used password again.
1047 * @param int $userid user id
1048 * @param string $password plaintext password
1049 * @return bool true if password reused
1051 function user_is_previously_used_password($userid, $password) {
1052 global $CFG, $DB;
1054 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1055 return false;
1058 $reused = false;
1060 $i = 0;
1061 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1062 foreach ($records as $record) {
1063 $i++;
1064 if ($i > $CFG->passwordreuselimit) {
1065 $DB->delete_records('user_password_history', array('id' => $record->id));
1066 continue;
1068 // NOTE: this is slow but we cannot compare the hashes directly any more.
1069 if (password_verify($password, $record->hash)) {
1070 $reused = true;
1074 return $reused;
1078 * Remove a user device from the Moodle database (for PUSH notifications usually).
1080 * @param string $uuid The device UUID.
1081 * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1082 * @return bool true if removed, false if the device didn't exists in the database
1083 * @since Moodle 2.9
1085 function user_remove_user_device($uuid, $appid = "") {
1086 global $DB, $USER;
1088 $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
1089 if (!empty($appid)) {
1090 $conditions['appid'] = $appid;
1093 if (!$DB->count_records('user_devices', $conditions)) {
1094 return false;
1097 $DB->delete_records('user_devices', $conditions);
1099 return true;
1103 * Trigger user_list_viewed event.
1105 * @param stdClass $course course object
1106 * @param stdClass $context course context object
1107 * @since Moodle 2.9
1109 function user_list_view($course, $context) {
1111 $event = \core\event\user_list_viewed::create(array(
1112 'objectid' => $course->id,
1113 'courseid' => $course->id,
1114 'context' => $context,
1115 'other' => array(
1116 'courseshortname' => $course->shortname,
1117 'coursefullname' => $course->fullname
1120 $event->trigger();
1124 * Returns the url to use for the "Grades" link in the user navigation.
1126 * @param int $userid The user's ID.
1127 * @param int $courseid The course ID if available.
1128 * @return mixed A URL to be directed to for "Grades".
1130 function user_mygrades_url($userid = null, $courseid = SITEID) {
1131 global $CFG, $USER;
1132 $url = null;
1133 if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
1134 if (isset($userid) && $USER->id != $userid) {
1135 // Send to the gradebook report.
1136 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
1137 array('id' => $courseid, 'userid' => $userid));
1138 } else {
1139 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
1141 } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
1142 && !empty($CFG->gradereport_mygradeurl)) {
1143 $url = $CFG->gradereport_mygradeurl;
1144 } else {
1145 $url = $CFG->wwwroot;
1147 return $url;
1151 * Check if the current user has permission to view details of the supplied user.
1153 * This function supports two modes:
1154 * If the optional $course param is omitted, then this function finds all shared courses and checks whether the current user has
1155 * permission in any of them, returning true if so.
1156 * If the $course param is provided, then this function checks permissions in ONLY that course.
1158 * @param object $user The other user's details.
1159 * @param object $course if provided, only check permissions in this course.
1160 * @param context $usercontext The user context if available.
1161 * @return bool true for ability to view this user, else false.
1163 function user_can_view_profile($user, $course = null, $usercontext = null) {
1164 global $USER, $CFG;
1166 if ($user->deleted) {
1167 return false;
1170 // Do we need to be logged in?
1171 if (empty($CFG->forceloginforprofiles)) {
1172 return true;
1173 } else {
1174 if (!isloggedin() || isguestuser()) {
1175 // User is not logged in and forceloginforprofile is set, we need to return now.
1176 return false;
1180 // Current user can always view their profile.
1181 if ($USER->id == $user->id) {
1182 return true;
1185 // Use callbacks so that (primarily) local plugins can prevent or allow profile access.
1186 $forceallow = false;
1187 $plugintypes = get_plugins_with_function('control_view_profile');
1188 foreach ($plugintypes as $plugins) {
1189 foreach ($plugins as $pluginfunction) {
1190 $result = $pluginfunction($user, $course, $usercontext);
1191 switch ($result) {
1192 case core_user::VIEWPROFILE_DO_NOT_PREVENT:
1193 // If the plugin doesn't stop access, just continue to next plugin or use
1194 // default behaviour.
1195 break;
1196 case core_user::VIEWPROFILE_FORCE_ALLOW:
1197 // Record that we are definitely going to allow it (unless another plugin
1198 // returns _PREVENT).
1199 $forceallow = true;
1200 break;
1201 case core_user::VIEWPROFILE_PREVENT:
1202 // If any plugin returns PREVENT then we return false, regardless of what
1203 // other plugins said.
1204 return false;
1208 if ($forceallow) {
1209 return true;
1212 // Course contacts have visible profiles always.
1213 if (has_coursecontact_role($user->id)) {
1214 return true;
1217 // If we're only checking the capabilities in the single provided course.
1218 if (isset($course)) {
1219 // Confirm that $user is enrolled in the $course we're checking.
1220 if (is_enrolled(context_course::instance($course->id), $user)) {
1221 $userscourses = array($course);
1223 } else {
1224 // Else we're checking whether the current user can view $user's profile anywhere, so check user context first.
1225 if (empty($usercontext)) {
1226 $usercontext = context_user::instance($user->id);
1228 if (has_capability('moodle/user:viewdetails', $usercontext) || has_capability('moodle/user:viewalldetails', $usercontext)) {
1229 return true;
1231 // This returns context information, so we can preload below.
1232 $userscourses = enrol_get_all_users_courses($user->id);
1235 if (empty($userscourses)) {
1236 return false;
1239 foreach ($userscourses as $userscourse) {
1240 context_helper::preload_from_record($userscourse);
1241 $coursecontext = context_course::instance($userscourse->id);
1242 if (has_capability('moodle/user:viewdetails', $coursecontext) ||
1243 has_capability('moodle/user:viewalldetails', $coursecontext)) {
1244 if (!groups_user_groups_visible($userscourse, $user->id)) {
1245 // Not a member of the same group.
1246 continue;
1248 return true;
1251 return false;
1255 * Returns users tagged with a specified tag.
1257 * @param core_tag_tag $tag
1258 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1259 * are displayed on the page and the per-page limit may be bigger
1260 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1261 * to display items in the same context first
1262 * @param int $ctx context id where to search for records
1263 * @param bool $rec search in subcontexts as well
1264 * @param int $page 0-based number of page being displayed
1265 * @return \core_tag\output\tagindex
1267 function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1268 global $PAGE;
1270 if ($ctx && $ctx != context_system::instance()->id) {
1271 $usercount = 0;
1272 } else {
1273 // Users can only be displayed in system context.
1274 $usercount = $tag->count_tagged_items('core', 'user',
1275 'it.deleted=:notdeleted', array('notdeleted' => 0));
1277 $perpage = $exclusivemode ? 24 : 5;
1278 $content = '';
1279 $totalpages = ceil($usercount / $perpage);
1281 if ($usercount) {
1282 $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage,
1283 'it.deleted=:notdeleted', array('notdeleted' => 0));
1284 $renderer = $PAGE->get_renderer('core', 'user');
1285 $content .= $renderer->user_list($userlist, $exclusivemode);
1288 return new core_tag\output\tagindex($tag, 'core', 'user', $content,
1289 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1293 * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access a course.
1295 * @param int $accesssince The unix timestamp to compare to users' last access
1296 * @param string $tableprefix
1297 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1298 * @return string
1300 function user_get_course_lastaccess_sql($accesssince = null, $tableprefix = 'ul', $haveaccessed = false) {
1301 return user_get_lastaccess_sql('timeaccess', $accesssince, $tableprefix, $haveaccessed);
1305 * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access the system.
1307 * @param int $accesssince The unix timestamp to compare to users' last access
1308 * @param string $tableprefix
1309 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1310 * @return string
1312 function user_get_user_lastaccess_sql($accesssince = null, $tableprefix = 'u', $haveaccessed = false) {
1313 return user_get_lastaccess_sql('lastaccess', $accesssince, $tableprefix, $haveaccessed);
1317 * Returns SQL that can be used to limit a query to a period where the user last accessed or
1318 * did not access something recorded by a given table.
1320 * @param string $columnname The name of the access column to check against
1321 * @param int $accesssince The unix timestamp to compare to users' last access
1322 * @param string $tableprefix The query prefix of the table to check
1323 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1324 * @return string
1326 function user_get_lastaccess_sql($columnname, $accesssince, $tableprefix, $haveaccessed = false) {
1327 if (empty($accesssince)) {
1328 return '';
1331 // Only users who have accessed since $accesssince.
1332 if ($haveaccessed) {
1333 if ($accesssince == -1) {
1334 // Include all users who have logged in at some point.
1335 $sql = "({$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0)";
1336 } else {
1337 // Users who have accessed since the specified time.
1338 $sql = "{$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0
1339 AND {$tableprefix}.{$columnname} >= {$accesssince}";
1341 } else {
1342 // Only users who have not accessed since $accesssince.
1344 if ($accesssince == -1) {
1345 // Users who have never accessed.
1346 $sql = "({$tableprefix}.{$columnname} IS NULL OR {$tableprefix}.{$columnname} = 0)";
1347 } else {
1348 // Users who have not accessed since the specified time.
1349 $sql = "({$tableprefix}.{$columnname} IS NULL
1350 OR ({$tableprefix}.{$columnname} != 0 AND {$tableprefix}.{$columnname} < {$accesssince}))";
1354 return $sql;
1358 * Callback for inplace editable API.
1360 * @param string $itemtype - Only user_roles is supported.
1361 * @param string $itemid - Courseid and userid separated by a :
1362 * @param string $newvalue - json encoded list of roleids.
1363 * @return \core\output\inplace_editable
1365 function core_user_inplace_editable($itemtype, $itemid, $newvalue) {
1366 if ($itemtype === 'user_roles') {
1367 return \core_user\output\user_roles_editable::update($itemid, $newvalue);
1372 * Map an internal field name to a valid purpose from: "https://www.w3.org/TR/WCAG21/#input-purposes"
1374 * @param integer $userid
1375 * @param string $fieldname
1376 * @return string $purpose (empty string if there is no mapping).
1378 function user_edit_map_field_purpose($userid, $fieldname) {
1379 global $USER;
1381 $currentuser = ($userid == $USER->id) && !\core\session\manager::is_loggedinas();
1382 // These are the fields considered valid to map and auto fill from a browser.
1383 // We do not include fields that are in a collapsed section by default because
1384 // the browser could auto-fill the field and cause a new value to be saved when
1385 // that field was never visible.
1386 $validmappings = array(
1387 'username' => 'username',
1388 'password' => 'current-password',
1389 'firstname' => 'given-name',
1390 'lastname' => 'family-name',
1391 'middlename' => 'additional-name',
1392 'email' => 'email',
1393 'country' => 'country',
1394 'lang' => 'language'
1397 $purpose = '';
1398 // Only set a purpose when editing your own user details.
1399 if ($currentuser && isset($validmappings[$fieldname])) {
1400 $purpose = ' autocomplete="' . $validmappings[$fieldname] . '" ';
1403 return $purpose;