MDL-60655 tool_httpsreplace: Use appropriate classes for PHPDocs params
[moodle.git] / user / lib.php
bloba7f9942eedf428aaa55ad9f99cd989c88d141cd0
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 /**
26 * Creates a user
28 * @throws moodle_exception
29 * @param stdClass $user user to create
30 * @param bool $updatepassword if true, authentication plugin will update password.
31 * @param bool $triggerevent set false if user_created event should not be triggred.
32 * This will not affect user_password_updated event triggering.
33 * @return int id of the newly created user
35 function user_create_user($user, $updatepassword = true, $triggerevent = true) {
36 global $DB;
38 // Set the timecreate field to the current time.
39 if (!is_object($user)) {
40 $user = (object) $user;
43 // Check username.
44 if ($user->username !== core_text::strtolower($user->username)) {
45 throw new moodle_exception('usernamelowercase');
46 } else {
47 if ($user->username !== core_user::clean_field($user->username, 'username')) {
48 throw new moodle_exception('invalidusername');
52 // Save the password in a temp value for later.
53 if ($updatepassword && isset($user->password)) {
55 // Check password toward the password policy.
56 if (!check_password_policy($user->password, $errmsg)) {
57 throw new moodle_exception($errmsg);
60 $userpassword = $user->password;
61 unset($user->password);
64 // Apply default values for user preferences that are stored in users table.
65 if (!isset($user->calendartype)) {
66 $user->calendartype = core_user::get_property_default('calendartype');
68 if (!isset($user->maildisplay)) {
69 $user->maildisplay = core_user::get_property_default('maildisplay');
71 if (!isset($user->mailformat)) {
72 $user->mailformat = core_user::get_property_default('mailformat');
74 if (!isset($user->maildigest)) {
75 $user->maildigest = core_user::get_property_default('maildigest');
77 if (!isset($user->autosubscribe)) {
78 $user->autosubscribe = core_user::get_property_default('autosubscribe');
80 if (!isset($user->trackforums)) {
81 $user->trackforums = core_user::get_property_default('trackforums');
83 if (!isset($user->lang)) {
84 $user->lang = core_user::get_property_default('lang');
87 $user->timecreated = time();
88 $user->timemodified = $user->timecreated;
90 // Validate user data object.
91 $uservalidation = core_user::validate($user);
92 if ($uservalidation !== true) {
93 foreach ($uservalidation as $field => $message) {
94 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
95 $user->$field = core_user::clean_field($user->$field, $field);
99 // Insert the user into the database.
100 $newuserid = $DB->insert_record('user', $user);
102 // Create USER context for this user.
103 $usercontext = context_user::instance($newuserid);
105 // Update user password if necessary.
106 if (isset($userpassword)) {
107 // Get full database user row, in case auth is default.
108 $newuser = $DB->get_record('user', array('id' => $newuserid));
109 $authplugin = get_auth_plugin($newuser->auth);
110 $authplugin->user_update_password($newuser, $userpassword);
113 // Trigger event If required.
114 if ($triggerevent) {
115 \core\event\user_created::create_from_userid($newuserid)->trigger();
118 return $newuserid;
122 * Update a user with a user object (will compare against the ID)
124 * @throws moodle_exception
125 * @param stdClass $user the user to update
126 * @param bool $updatepassword if true, authentication plugin will update password.
127 * @param bool $triggerevent set false if user_updated event should not be triggred.
128 * This will not affect user_password_updated event triggering.
130 function user_update_user($user, $updatepassword = true, $triggerevent = true) {
131 global $DB;
133 // Set the timecreate field to the current time.
134 if (!is_object($user)) {
135 $user = (object) $user;
138 // Check username.
139 if (isset($user->username)) {
140 if ($user->username !== core_text::strtolower($user->username)) {
141 throw new moodle_exception('usernamelowercase');
142 } else {
143 if ($user->username !== core_user::clean_field($user->username, 'username')) {
144 throw new moodle_exception('invalidusername');
149 // Unset password here, for updating later, if password update is required.
150 if ($updatepassword && isset($user->password)) {
152 // Check password toward the password policy.
153 if (!check_password_policy($user->password, $errmsg)) {
154 throw new moodle_exception($errmsg);
157 $passwd = $user->password;
158 unset($user->password);
161 // Make sure calendartype, if set, is valid.
162 if (empty($user->calendartype)) {
163 // Unset this variable, must be an empty string, which we do not want to update the calendartype to.
164 unset($user->calendartype);
167 $user->timemodified = time();
169 // Validate user data object.
170 $uservalidation = core_user::validate($user);
171 if ($uservalidation !== true) {
172 foreach ($uservalidation as $field => $message) {
173 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
174 $user->$field = core_user::clean_field($user->$field, $field);
178 $DB->update_record('user', $user);
180 if ($updatepassword) {
181 // Get full user record.
182 $updateduser = $DB->get_record('user', array('id' => $user->id));
184 // If password was set, then update its hash.
185 if (isset($passwd)) {
186 $authplugin = get_auth_plugin($updateduser->auth);
187 if ($authplugin->can_change_password()) {
188 $authplugin->user_update_password($updateduser, $passwd);
192 // Trigger event if required.
193 if ($triggerevent) {
194 \core\event\user_updated::create_from_userid($user->id)->trigger();
199 * Marks user deleted in internal user database and notifies the auth plugin.
200 * Also unenrols user from all roles and does other cleanup.
202 * @todo Decide if this transaction is really needed (look for internal TODO:)
203 * @param object $user Userobject before delete (without system magic quotes)
204 * @return boolean success
206 function user_delete_user($user) {
207 return delete_user($user);
211 * Get users by id
213 * @param array $userids id of users to retrieve
214 * @return array
216 function user_get_users_by_id($userids) {
217 global $DB;
218 return $DB->get_records_list('user', 'id', $userids);
222 * Returns the list of default 'displayable' fields
224 * Contains database field names but also names used to generate information, such as enrolledcourses
226 * @return array of user fields
228 function user_get_default_fields() {
229 return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
230 'address', 'phone1', 'phone2', 'icq', 'skype', 'yahoo', 'aim', 'msn', 'department',
231 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
232 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
233 'city', 'url', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
234 'groups', 'roles', 'preferences', 'enrolledcourses', 'suspended'
240 * Give user record from mdl_user, build an array contains all user details.
242 * Warning: description file urls are 'webservice/pluginfile.php' is use.
243 * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
245 * @throws moodle_exception
246 * @param stdClass $user user record from mdl_user
247 * @param stdClass $course moodle course
248 * @param array $userfields required fields
249 * @return array|null
251 function user_get_user_details($user, $course = null, array $userfields = array()) {
252 global $USER, $DB, $CFG, $PAGE;
253 require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library.
254 require_once($CFG->dirroot . "/lib/filelib.php"); // File handling on description and friends.
256 $defaultfields = user_get_default_fields();
258 if (empty($userfields)) {
259 $userfields = $defaultfields;
262 foreach ($userfields as $thefield) {
263 if (!in_array($thefield, $defaultfields)) {
264 throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
268 // Make sure id and fullname are included.
269 if (!in_array('id', $userfields)) {
270 $userfields[] = 'id';
273 if (!in_array('fullname', $userfields)) {
274 $userfields[] = 'fullname';
277 if (!empty($course)) {
278 $context = context_course::instance($course->id);
279 $usercontext = context_user::instance($user->id);
280 $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext));
281 } else {
282 $context = context_user::instance($user->id);
283 $usercontext = $context;
284 $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
287 $currentuser = ($user->id == $USER->id);
288 $isadmin = is_siteadmin($USER);
290 $showuseridentityfields = get_extra_user_fields($context);
292 if (!empty($course)) {
293 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
294 } else {
295 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
297 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
298 if (!empty($course)) {
299 $canviewuseremail = has_capability('moodle/course:useremail', $context);
300 } else {
301 $canviewuseremail = false;
303 $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
304 if (!empty($course)) {
305 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
306 } else {
307 $canaccessallgroups = false;
310 if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
311 // Skip this user details.
312 return null;
315 $userdetails = array();
316 $userdetails['id'] = $user->id;
318 if (in_array('username', $userfields)) {
319 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
320 $userdetails['username'] = $user->username;
323 if ($isadmin or $canviewfullnames) {
324 if (in_array('firstname', $userfields)) {
325 $userdetails['firstname'] = $user->firstname;
327 if (in_array('lastname', $userfields)) {
328 $userdetails['lastname'] = $user->lastname;
331 $userdetails['fullname'] = fullname($user);
333 if (in_array('customfields', $userfields)) {
334 $categories = profile_get_user_fields_with_data_by_category($user->id);
335 $userdetails['customfields'] = array();
336 foreach ($categories as $categoryid => $fields) {
337 foreach ($fields as $formfield) {
338 if ($formfield->is_visible() and !$formfield->is_empty()) {
340 // TODO: Part of MDL-50728, this conditional coding must be moved to
341 // proper profile fields API so they are self-contained.
342 // We only use display_data in fields that require text formatting.
343 if ($formfield->field->datatype == 'text' or $formfield->field->datatype == 'textarea') {
344 $fieldvalue = $formfield->display_data();
345 } else {
346 // Cases: datetime, checkbox and menu.
347 $fieldvalue = $formfield->data;
350 $userdetails['customfields'][] =
351 array('name' => $formfield->field->name, 'value' => $fieldvalue,
352 'type' => $formfield->field->datatype, 'shortname' => $formfield->field->shortname);
356 // Unset customfields if it's empty.
357 if (empty($userdetails['customfields'])) {
358 unset($userdetails['customfields']);
362 // Profile image.
363 if (in_array('profileimageurl', $userfields)) {
364 $userpicture = new user_picture($user);
365 $userpicture->size = 1; // Size f1.
366 $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
368 if (in_array('profileimageurlsmall', $userfields)) {
369 if (!isset($userpicture)) {
370 $userpicture = new user_picture($user);
372 $userpicture->size = 0; // Size f2.
373 $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
376 // Hidden user field.
377 if ($canviewhiddenuserfields) {
378 $hiddenfields = array();
379 // Address, phone1 and phone2 not appears in hidden fields list but require viewhiddenfields capability
380 // according to user/profile.php.
381 if (!empty($user->address) && in_array('address', $userfields)) {
382 $userdetails['address'] = $user->address;
384 } else {
385 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
388 if (!empty($user->phone1) && in_array('phone1', $userfields) &&
389 (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) {
390 $userdetails['phone1'] = $user->phone1;
392 if (!empty($user->phone2) && in_array('phone2', $userfields) &&
393 (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) {
394 $userdetails['phone2'] = $user->phone2;
397 if (isset($user->description) &&
398 ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
399 if (in_array('description', $userfields)) {
400 // Always return the descriptionformat if description is requested.
401 list($userdetails['description'], $userdetails['descriptionformat']) =
402 external_format_text($user->description, $user->descriptionformat,
403 $usercontext->id, 'user', 'profile', null);
407 if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
408 $userdetails['country'] = $user->country;
411 if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
412 $userdetails['city'] = $user->city;
415 if (in_array('url', $userfields) && $user->url && (!isset($hiddenfields['webpage']) or $isadmin)) {
416 $url = $user->url;
417 if (strpos($user->url, '://') === false) {
418 $url = 'http://'. $url;
420 $user->url = clean_param($user->url, PARAM_URL);
421 $userdetails['url'] = $user->url;
424 if (in_array('icq', $userfields) && $user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) {
425 $userdetails['icq'] = $user->icq;
428 if (in_array('skype', $userfields) && $user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) {
429 $userdetails['skype'] = $user->skype;
431 if (in_array('yahoo', $userfields) && $user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) {
432 $userdetails['yahoo'] = $user->yahoo;
434 if (in_array('aim', $userfields) && $user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) {
435 $userdetails['aim'] = $user->aim;
437 if (in_array('msn', $userfields) && $user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) {
438 $userdetails['msn'] = $user->msn;
440 if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) {
441 $userdetails['suspended'] = (bool)$user->suspended;
444 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
445 if ($user->firstaccess) {
446 $userdetails['firstaccess'] = $user->firstaccess;
447 } else {
448 $userdetails['firstaccess'] = 0;
451 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
452 if ($user->lastaccess) {
453 $userdetails['lastaccess'] = $user->lastaccess;
454 } else {
455 $userdetails['lastaccess'] = 0;
459 if (in_array('email', $userfields) && ($isadmin // The admin is allowed the users email.
460 or $currentuser // Of course the current user is as well.
461 or $canviewuseremail // This is a capability in course context, it will be false in usercontext.
462 or in_array('email', $showuseridentityfields)
463 or $user->maildisplay == 1
464 or ($user->maildisplay == 2 and enrol_sharing_course($user, $USER)))) {
465 $userdetails['email'] = $user->email;
468 if (in_array('interests', $userfields)) {
469 $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
470 if ($interests) {
471 $userdetails['interests'] = join(', ', $interests);
475 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
476 if (in_array('idnumber', $userfields) && $user->idnumber) {
477 if (in_array('idnumber', $showuseridentityfields) or $currentuser or
478 has_capability('moodle/user:viewalldetails', $context)) {
479 $userdetails['idnumber'] = $user->idnumber;
482 if (in_array('institution', $userfields) && $user->institution) {
483 if (in_array('institution', $showuseridentityfields) or $currentuser or
484 has_capability('moodle/user:viewalldetails', $context)) {
485 $userdetails['institution'] = $user->institution;
488 // Isset because it's ok to have department 0.
489 if (in_array('department', $userfields) && isset($user->department)) {
490 if (in_array('department', $showuseridentityfields) or $currentuser or
491 has_capability('moodle/user:viewalldetails', $context)) {
492 $userdetails['department'] = $user->department;
496 if (in_array('roles', $userfields) && !empty($course)) {
497 // Not a big secret.
498 $roles = get_user_roles($context, $user->id, false);
499 $userdetails['roles'] = array();
500 foreach ($roles as $role) {
501 $userdetails['roles'][] = array(
502 'roleid' => $role->roleid,
503 'name' => $role->name,
504 'shortname' => $role->shortname,
505 'sortorder' => $role->sortorder
510 // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
511 if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
512 $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid,
513 'g.id, g.name,g.description,g.descriptionformat');
514 $userdetails['groups'] = array();
515 foreach ($usergroups as $group) {
516 list($group->description, $group->descriptionformat) =
517 external_format_text($group->description, $group->descriptionformat,
518 $context->id, 'group', 'description', $group->id);
519 $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name,
520 'description' => $group->description, 'descriptionformat' => $group->descriptionformat);
523 // List of courses where the user is enrolled.
524 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
525 $enrolledcourses = array();
526 if ($mycourses = enrol_get_users_courses($user->id, true)) {
527 foreach ($mycourses as $mycourse) {
528 if ($mycourse->category) {
529 $coursecontext = context_course::instance($mycourse->id);
530 $enrolledcourse = array();
531 $enrolledcourse['id'] = $mycourse->id;
532 $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
533 $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
534 $enrolledcourses[] = $enrolledcourse;
537 $userdetails['enrolledcourses'] = $enrolledcourses;
541 // User preferences.
542 if (in_array('preferences', $userfields) && $currentuser) {
543 $preferences = array();
544 $userpreferences = get_user_preferences();
545 foreach ($userpreferences as $prefname => $prefvalue) {
546 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
548 $userdetails['preferences'] = $preferences;
551 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
552 $extrafields = ['auth', 'confirmed', 'lang', 'theme', 'timezone', 'mailformat'];
553 foreach ($extrafields as $extrafield) {
554 if (in_array($extrafield, $userfields) && isset($user->$extrafield)) {
555 $userdetails[$extrafield] = $user->$extrafield;
560 return $userdetails;
564 * Tries to obtain user details, either recurring directly to the user's system profile
565 * or through one of the user's course enrollments (course profile).
567 * @param stdClass $user The user.
568 * @return array if unsuccessful or the allowed user details.
570 function user_get_user_details_courses($user) {
571 global $USER;
572 $userdetails = null;
574 // Get the courses that the user is enrolled in (only active).
575 $courses = enrol_get_users_courses($user->id, true);
577 $systemprofile = false;
578 if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
579 $systemprofile = true;
582 // Try using system profile.
583 if ($systemprofile) {
584 $userdetails = user_get_user_details($user, null);
585 } else {
586 // Try through course profile.
587 foreach ($courses as $course) {
588 if (can_view_user_details_cap($user, $course) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
589 $userdetails = user_get_user_details($user, $course);
594 return $userdetails;
598 * Check if $USER have the necessary capabilities to obtain user details.
600 * @param stdClass $user
601 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
602 * @return bool true if $USER can view user details.
604 function can_view_user_details_cap($user, $course = null) {
605 // Check $USER has the capability to view the user details at user context.
606 $usercontext = context_user::instance($user->id);
607 $result = has_capability('moodle/user:viewdetails', $usercontext);
608 // Otherwise can $USER see them at course context.
609 if (!$result && !empty($course)) {
610 $context = context_course::instance($course->id);
611 $result = has_capability('moodle/user:viewdetails', $context);
613 return $result;
617 * Return a list of page types
618 * @param string $pagetype current page type
619 * @param stdClass $parentcontext Block's parent context
620 * @param stdClass $currentcontext Current context of block
621 * @return array
623 function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
624 return array('user-profile' => get_string('page-user-profile', 'pagetype'));
628 * Count the number of failed login attempts for the given user, since last successful login.
630 * @param int|stdclass $user user id or object.
631 * @param bool $reset Resets failed login count, if set to true.
633 * @return int number of failed login attempts since the last successful login.
635 function user_count_login_failures($user, $reset = true) {
636 global $DB;
638 if (!is_object($user)) {
639 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
641 if ($user->deleted) {
642 // Deleted user, nothing to do.
643 return 0;
645 $count = get_user_preferences('login_failed_count_since_success', 0, $user);
646 if ($reset) {
647 set_user_preference('login_failed_count_since_success', 0, $user);
649 return $count;
653 * Converts a string into a flat array of menu items, where each menu items is a
654 * stdClass with fields type, url, title, pix, and imgsrc.
656 * @param string $text the menu items definition
657 * @param moodle_page $page the current page
658 * @return array
660 function user_convert_text_to_menu_items($text, $page) {
661 global $OUTPUT, $CFG;
663 $lines = explode("\n", $text);
664 $items = array();
665 $lastchild = null;
666 $lastdepth = null;
667 $lastsort = 0;
668 $children = array();
669 foreach ($lines as $line) {
670 $line = trim($line);
671 $bits = explode('|', $line, 3);
672 $itemtype = 'link';
673 if (preg_match("/^#+$/", $line)) {
674 $itemtype = 'divider';
675 } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
676 // Every item must have a name to be valid.
677 continue;
678 } else {
679 $bits[0] = ltrim($bits[0], '-');
682 // Create the child.
683 $child = new stdClass();
684 $child->itemtype = $itemtype;
685 if ($itemtype === 'divider') {
686 // Add the divider to the list of children and skip link
687 // processing.
688 $children[] = $child;
689 continue;
692 // Name processing.
693 $namebits = explode(',', $bits[0], 2);
694 if (count($namebits) == 2) {
695 // Check the validity of the identifier part of the string.
696 if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
697 // Treat this as a language string.
698 $child->title = get_string($namebits[0], $namebits[1]);
699 $child->titleidentifier = implode(',', $namebits);
702 if (empty($child->title)) {
703 // Use it as is, don't even clean it.
704 $child->title = $bits[0];
705 $child->titleidentifier = str_replace(" ", "-", $bits[0]);
708 // URL processing.
709 if (!array_key_exists(1, $bits) or empty($bits[1])) {
710 // Set the url to null, and set the itemtype to invalid.
711 $bits[1] = null;
712 $child->itemtype = "invalid";
713 } else {
714 // Nasty hack to replace the grades with the direct url.
715 if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
716 $bits[1] = user_mygrades_url();
719 // Make sure the url is a moodle url.
720 $bits[1] = new moodle_url(trim($bits[1]));
722 $child->url = $bits[1];
724 // PIX processing.
725 $pixpath = "t/edit";
726 if (!array_key_exists(2, $bits) or empty($bits[2])) {
727 // Use the default.
728 $child->pix = $pixpath;
729 } else {
730 // Check for the specified image existing.
731 $pixpath = "t/" . $bits[2];
732 if ($page->theme->resolve_image_location($pixpath, 'moodle', true)) {
733 // Use the image.
734 $child->pix = $pixpath;
735 } else {
736 // Treat it like a URL.
737 $child->pix = null;
738 $child->imgsrc = $bits[2];
742 // Add this child to the list of children.
743 $children[] = $child;
745 return $children;
749 * Get a list of essential user navigation items.
751 * @param stdclass $user user object.
752 * @param moodle_page $page page object.
753 * @param array $options associative array.
754 * options are:
755 * - avatarsize=35 (size of avatar image)
756 * @return stdClass $returnobj navigation information object, where:
758 * $returnobj->navitems array array of links where each link is a
759 * stdClass with fields url, title, and
760 * pix
761 * $returnobj->metadata array array of useful user metadata to be
762 * used when constructing navigation;
763 * fields include:
765 * ROLE FIELDS
766 * asotherrole bool whether viewing as another role
767 * rolename string name of the role
769 * USER FIELDS
770 * These fields are for the currently-logged in user, or for
771 * the user that the real user is currently logged in as.
773 * userid int the id of the user in question
774 * userfullname string the user's full name
775 * userprofileurl moodle_url the url of the user's profile
776 * useravatar string a HTML fragment - the rendered
777 * user_picture for this user
778 * userloginfail string an error string denoting the number
779 * of login failures since last login
781 * "REAL USER" FIELDS
782 * These fields are for when asotheruser is true, and
783 * correspond to the underlying "real user".
785 * asotheruser bool whether viewing as another user
786 * realuserid int the id of the user in question
787 * realuserfullname string the user's full name
788 * realuserprofileurl moodle_url the url of the user's profile
789 * realuseravatar string a HTML fragment - the rendered
790 * user_picture for this user
792 * MNET PROVIDER FIELDS
793 * asmnetuser bool whether viewing as a user from an
794 * MNet provider
795 * mnetidprovidername string name of the MNet provider
796 * mnetidproviderwwwroot string URL of the MNet provider
798 function user_get_user_navigation_info($user, $page, $options = array()) {
799 global $OUTPUT, $DB, $SESSION, $CFG;
801 $returnobject = new stdClass();
802 $returnobject->navitems = array();
803 $returnobject->metadata = array();
805 $course = $page->course;
807 // Query the environment.
808 $context = context_course::instance($course->id);
810 // Get basic user metadata.
811 $returnobject->metadata['userid'] = $user->id;
812 $returnobject->metadata['userfullname'] = fullname($user, true);
813 $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
814 'id' => $user->id
817 $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
818 if (!empty($options['avatarsize'])) {
819 $avataroptions['size'] = $options['avatarsize'];
821 $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
822 $user, $avataroptions
824 // Build a list of items for a regular user.
826 // Query MNet status.
827 if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
828 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
829 $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
830 $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
833 // Did the user just log in?
834 if (isset($SESSION->justloggedin)) {
835 // Don't unset this flag as login_info still needs it.
836 if (!empty($CFG->displayloginfailures)) {
837 // Don't reset the count either, as login_info() still needs it too.
838 if ($count = user_count_login_failures($user, false)) {
840 // Get login failures string.
841 $a = new stdClass();
842 $a->attempts = html_writer::tag('span', $count, array('class' => 'value'));
843 $returnobject->metadata['userloginfail'] =
844 get_string('failedloginattempts', '', $a);
850 // Links: Dashboard.
851 $myhome = new stdClass();
852 $myhome->itemtype = 'link';
853 $myhome->url = new moodle_url('/my/');
854 $myhome->title = get_string('mymoodle', 'admin');
855 $myhome->titleidentifier = 'mymoodle,admin';
856 $myhome->pix = "i/dashboard";
857 $returnobject->navitems[] = $myhome;
859 // Links: My Profile.
860 $myprofile = new stdClass();
861 $myprofile->itemtype = 'link';
862 $myprofile->url = new moodle_url('/user/profile.php', array('id' => $user->id));
863 $myprofile->title = get_string('profile');
864 $myprofile->titleidentifier = 'profile,moodle';
865 $myprofile->pix = "i/user";
866 $returnobject->navitems[] = $myprofile;
868 $returnobject->metadata['asotherrole'] = false;
870 // Before we add the last items (usually a logout + switch role link), add any
871 // custom-defined items.
872 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
873 foreach ($customitems as $item) {
874 $returnobject->navitems[] = $item;
878 if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
879 $realuser = \core\session\manager::get_realuser();
881 // Save values for the real user, as $user will be full of data for the
882 // user the user is disguised as.
883 $returnobject->metadata['realuserid'] = $realuser->id;
884 $returnobject->metadata['realuserfullname'] = fullname($realuser, true);
885 $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', array(
886 'id' => $realuser->id
888 $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
890 // Build a user-revert link.
891 $userrevert = new stdClass();
892 $userrevert->itemtype = 'link';
893 $userrevert->url = new moodle_url('/course/loginas.php', array(
894 'id' => $course->id,
895 'sesskey' => sesskey()
897 $userrevert->pix = "a/logout";
898 $userrevert->title = get_string('logout');
899 $userrevert->titleidentifier = 'logout,moodle';
900 $returnobject->navitems[] = $userrevert;
902 } else {
904 // Build a logout link.
905 $logout = new stdClass();
906 $logout->itemtype = 'link';
907 $logout->url = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
908 $logout->pix = "a/logout";
909 $logout->title = get_string('logout');
910 $logout->titleidentifier = 'logout,moodle';
911 $returnobject->navitems[] = $logout;
914 if (is_role_switched($course->id)) {
915 if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
916 // Build role-return link instead of logout link.
917 $rolereturn = new stdClass();
918 $rolereturn->itemtype = 'link';
919 $rolereturn->url = new moodle_url('/course/switchrole.php', array(
920 'id' => $course->id,
921 'sesskey' => sesskey(),
922 'switchrole' => 0,
923 'returnurl' => $page->url->out_as_local_url(false)
925 $rolereturn->pix = "a/logout";
926 $rolereturn->title = get_string('switchrolereturn');
927 $rolereturn->titleidentifier = 'switchrolereturn,moodle';
928 $returnobject->navitems[] = $rolereturn;
930 $returnobject->metadata['asotherrole'] = true;
931 $returnobject->metadata['rolename'] = role_get_name($role, $context);
934 } else {
935 // Build switch role link.
936 $roles = get_switchable_roles($context);
937 if (is_array($roles) && (count($roles) > 0)) {
938 $switchrole = new stdClass();
939 $switchrole->itemtype = 'link';
940 $switchrole->url = new moodle_url('/course/switchrole.php', array(
941 'id' => $course->id,
942 'switchrole' => -1,
943 'returnurl' => $page->url->out_as_local_url(false)
945 $switchrole->pix = "i/switchrole";
946 $switchrole->title = get_string('switchroleto');
947 $switchrole->titleidentifier = 'switchroleto,moodle';
948 $returnobject->navitems[] = $switchrole;
952 return $returnobject;
956 * Add password to the list of used hashes for this user.
958 * This is supposed to be used from:
959 * 1/ change own password form
960 * 2/ password reset process
961 * 3/ user signup in auth plugins if password changing supported
963 * @param int $userid user id
964 * @param string $password plaintext password
965 * @return void
967 function user_add_password_history($userid, $password) {
968 global $CFG, $DB;
970 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
971 return;
974 // Note: this is using separate code form normal password hashing because
975 // we need to have this under control in the future. Also the auth
976 // plugin might not store the passwords locally at all.
978 $record = new stdClass();
979 $record->userid = $userid;
980 $record->hash = password_hash($password, PASSWORD_DEFAULT);
981 $record->timecreated = time();
982 $DB->insert_record('user_password_history', $record);
984 $i = 0;
985 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
986 foreach ($records as $record) {
987 $i++;
988 if ($i > $CFG->passwordreuselimit) {
989 $DB->delete_records('user_password_history', array('id' => $record->id));
995 * Was this password used before on change or reset password page?
997 * The $CFG->passwordreuselimit setting determines
998 * how many times different password needs to be used
999 * before allowing previously used password again.
1001 * @param int $userid user id
1002 * @param string $password plaintext password
1003 * @return bool true if password reused
1005 function user_is_previously_used_password($userid, $password) {
1006 global $CFG, $DB;
1008 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1009 return false;
1012 $reused = false;
1014 $i = 0;
1015 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1016 foreach ($records as $record) {
1017 $i++;
1018 if ($i > $CFG->passwordreuselimit) {
1019 $DB->delete_records('user_password_history', array('id' => $record->id));
1020 continue;
1022 // NOTE: this is slow but we cannot compare the hashes directly any more.
1023 if (password_verify($password, $record->hash)) {
1024 $reused = true;
1028 return $reused;
1032 * Remove a user device from the Moodle database (for PUSH notifications usually).
1034 * @param string $uuid The device UUID.
1035 * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1036 * @return bool true if removed, false if the device didn't exists in the database
1037 * @since Moodle 2.9
1039 function user_remove_user_device($uuid, $appid = "") {
1040 global $DB, $USER;
1042 $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
1043 if (!empty($appid)) {
1044 $conditions['appid'] = $appid;
1047 if (!$DB->count_records('user_devices', $conditions)) {
1048 return false;
1051 $DB->delete_records('user_devices', $conditions);
1053 return true;
1057 * Trigger user_list_viewed event.
1059 * @param stdClass $course course object
1060 * @param stdClass $context course context object
1061 * @since Moodle 2.9
1063 function user_list_view($course, $context) {
1065 $event = \core\event\user_list_viewed::create(array(
1066 'objectid' => $course->id,
1067 'courseid' => $course->id,
1068 'context' => $context,
1069 'other' => array(
1070 'courseshortname' => $course->shortname,
1071 'coursefullname' => $course->fullname
1074 $event->trigger();
1078 * Returns the url to use for the "Grades" link in the user navigation.
1080 * @param int $userid The user's ID.
1081 * @param int $courseid The course ID if available.
1082 * @return mixed A URL to be directed to for "Grades".
1084 function user_mygrades_url($userid = null, $courseid = SITEID) {
1085 global $CFG, $USER;
1086 $url = null;
1087 if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
1088 if (isset($userid) && $USER->id != $userid) {
1089 // Send to the gradebook report.
1090 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
1091 array('id' => $courseid, 'userid' => $userid));
1092 } else {
1093 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
1095 } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
1096 && !empty($CFG->gradereport_mygradeurl)) {
1097 $url = $CFG->gradereport_mygradeurl;
1098 } else {
1099 $url = $CFG->wwwroot;
1101 return $url;
1105 * Check if the current user has permission to view details of the supplied user.
1107 * This function supports two modes:
1108 * If the optional $course param is omitted, then this function finds all shared courses and checks whether the current user has
1109 * permission in any of them, returning true if so.
1110 * If the $course param is provided, then this function checks permissions in ONLY that course.
1112 * @param object $user The other user's details.
1113 * @param object $course if provided, only check permissions in this course.
1114 * @param context $usercontext The user context if available.
1115 * @return bool true for ability to view this user, else false.
1117 function user_can_view_profile($user, $course = null, $usercontext = null) {
1118 global $USER, $CFG;
1120 if ($user->deleted) {
1121 return false;
1124 // Do we need to be logged in?
1125 if (empty($CFG->forceloginforprofiles)) {
1126 return true;
1127 } else {
1128 if (!isloggedin() || isguestuser()) {
1129 // User is not logged in and forceloginforprofile is set, we need to return now.
1130 return false;
1134 // Current user can always view their profile.
1135 if ($USER->id == $user->id) {
1136 return true;
1139 // Course contacts have visible profiles always.
1140 if (has_coursecontact_role($user->id)) {
1141 return true;
1144 // If we're only checking the capabilities in the single provided course.
1145 if (isset($course)) {
1146 // Confirm that $user is enrolled in the $course we're checking.
1147 if (is_enrolled(context_course::instance($course->id), $user)) {
1148 $userscourses = array($course);
1150 } else {
1151 // Else we're checking whether the current user can view $user's profile anywhere, so check user context first.
1152 if (empty($usercontext)) {
1153 $usercontext = context_user::instance($user->id);
1155 if (has_capability('moodle/user:viewdetails', $usercontext) || has_capability('moodle/user:viewalldetails', $usercontext)) {
1156 return true;
1158 // This returns context information, so we can preload below.
1159 $userscourses = enrol_get_all_users_courses($user->id);
1162 if (empty($userscourses)) {
1163 return false;
1166 foreach ($userscourses as $userscourse) {
1167 context_helper::preload_from_record($userscourse);
1168 $coursecontext = context_course::instance($userscourse->id);
1169 if (has_capability('moodle/user:viewdetails', $coursecontext) ||
1170 has_capability('moodle/user:viewalldetails', $coursecontext)) {
1171 if (!groups_user_groups_visible($userscourse, $user->id)) {
1172 // Not a member of the same group.
1173 continue;
1175 return true;
1178 return false;
1182 * Returns users tagged with a specified tag.
1184 * @param core_tag_tag $tag
1185 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1186 * are displayed on the page and the per-page limit may be bigger
1187 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1188 * to display items in the same context first
1189 * @param int $ctx context id where to search for records
1190 * @param bool $rec search in subcontexts as well
1191 * @param int $page 0-based number of page being displayed
1192 * @return \core_tag\output\tagindex
1194 function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1195 global $PAGE;
1197 if ($ctx && $ctx != context_system::instance()->id) {
1198 $usercount = 0;
1199 } else {
1200 // Users can only be displayed in system context.
1201 $usercount = $tag->count_tagged_items('core', 'user',
1202 'it.deleted=:notdeleted', array('notdeleted' => 0));
1204 $perpage = $exclusivemode ? 24 : 5;
1205 $content = '';
1206 $totalpages = ceil($usercount / $perpage);
1208 if ($usercount) {
1209 $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage,
1210 'it.deleted=:notdeleted', array('notdeleted' => 0));
1211 $renderer = $PAGE->get_renderer('core', 'user');
1212 $content .= $renderer->user_list($userlist, $exclusivemode);
1215 return new core_tag\output\tagindex($tag, 'core', 'user', $content,
1216 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1220 * Returns the SQL used by the participants table.
1222 * @param int $courseid The course id
1223 * @param int $groupid The groupid, 0 means all groups
1224 * @param int $accesssince The time since last access, 0 means any time
1225 * @param int $roleid The role id, 0 means all roles
1226 * @param int $enrolid The enrolment id, 0 means all enrolment methods will be returned.
1227 * @param int $statusid The user enrolment status, -1 means all enrolments regardless of the status will be returned, if allowed.
1228 * @param string|array $search The search that was performed, empty means perform no search
1229 * @param string $additionalwhere Any additional SQL to add to where
1230 * @param array $additionalparams The additional params
1231 * @return array
1233 function user_get_participants_sql($courseid, $groupid = 0, $accesssince = 0, $roleid = 0, $enrolid = 0, $statusid = -1,
1234 $search = '', $additionalwhere = '', $additionalparams = array()) {
1235 global $DB;
1237 // Get the context.
1238 $context = \context_course::instance($courseid, MUST_EXIST);
1240 $isfrontpage = ($courseid == SITEID);
1242 // Default filter settings. We only show active by default, especially if the user has no capability to review enrolments.
1243 $onlyactive = true;
1244 $onlysuspended = false;
1245 if (has_capability('moodle/course:enrolreview', $context)) {
1246 switch ($statusid) {
1247 case ENROL_USER_ACTIVE:
1248 // Nothing to do here.
1249 break;
1250 case ENROL_USER_SUSPENDED:
1251 $onlyactive = false;
1252 $onlysuspended = true;
1253 break;
1254 default:
1255 // If the user has capability to review user enrolments, but statusid is set to -1, set $onlyactive to false.
1256 $onlyactive = false;
1257 break;
1261 list($esql, $params) = get_enrolled_sql($context, null, $groupid, $onlyactive, $onlysuspended, $enrolid);
1263 $joins = array('FROM {user} u');
1264 $wheres = array();
1266 $userfields = get_extra_user_fields($context, array('username', 'lang', 'timezone', 'maildisplay'));
1267 $userfieldssql = user_picture::fields('u', $userfields);
1269 if ($isfrontpage) {
1270 $select = "SELECT $userfieldssql, u.lastaccess";
1271 $joins[] = "JOIN ($esql) e ON e.id = u.id"; // Everybody on the frontpage usually.
1272 if ($accesssince) {
1273 $wheres[] = user_get_user_lastaccess_sql($accesssince);
1275 } else {
1276 $select = "SELECT $userfieldssql, COALESCE(ul.timeaccess, 0) AS lastaccess";
1277 $joins[] = "JOIN ($esql) e ON e.id = u.id"; // Course enrolled users only.
1278 // Not everybody has accessed the course yet.
1279 $joins[] = 'LEFT JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = :courseid)';
1280 $params['courseid'] = $courseid;
1281 if ($accesssince) {
1282 $wheres[] = user_get_course_lastaccess_sql($accesssince);
1286 // Performance hacks - we preload user contexts together with accounts.
1287 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1288 $ccjoin = 'LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)';
1289 $params['contextlevel'] = CONTEXT_USER;
1290 $select .= $ccselect;
1291 $joins[] = $ccjoin;
1293 // Limit list to users with some role only.
1294 if ($roleid) {
1295 // We want to query both the current context and parent contexts.
1296 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true),
1297 SQL_PARAMS_NAMED, 'relatedctx');
1299 $wheres[] = "u.id IN (SELECT userid FROM {role_assignments} WHERE roleid = :roleid AND contextid $relatedctxsql)";
1300 $params = array_merge($params, array('roleid' => $roleid), $relatedctxparams);
1303 if (!empty($search)) {
1304 if (!is_array($search)) {
1305 $search = [$search];
1307 foreach ($search as $index => $keyword) {
1308 $searchkey1 = 'search' . $index . '1';
1309 $searchkey2 = 'search' . $index . '2';
1310 $searchkey3 = 'search' . $index . '3';
1311 $fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
1312 $wheres[] = '(' . $DB->sql_like($fullname, ':' . $searchkey1, false, false) .
1313 ' OR ' . $DB->sql_like('email', ':' . $searchkey2, false, false) .
1314 ' OR ' . $DB->sql_like('idnumber', ':' . $searchkey3, false, false) . ') ';
1315 $params[$searchkey1] = "%$keyword%";
1316 $params[$searchkey2] = "%$keyword%";
1317 $params[$searchkey3] = "%$keyword%";
1321 if (!empty($additionalwhere)) {
1322 $wheres[] = $additionalwhere;
1323 $params = array_merge($params, $additionalparams);
1326 $from = implode("\n", $joins);
1327 if ($wheres) {
1328 $where = 'WHERE ' . implode(' AND ', $wheres);
1329 } else {
1330 $where = '';
1333 return array($select, $from, $where, $params);
1337 * Returns the total number of participants for a given course.
1339 * @param int $courseid The course id
1340 * @param int $groupid The groupid, 0 means all groups
1341 * @param int $accesssince The time since last access, 0 means any time
1342 * @param int $roleid The role id, 0 means all roles
1343 * @param int $enrolid The applied filter for the user enrolment ID.
1344 * @param int $status The applied filter for the user's enrolment status.
1345 * @param string|array $search The search that was performed, empty means perform no search
1346 * @param string $additionalwhere Any additional SQL to add to where
1347 * @param array $additionalparams The additional params
1348 * @return int
1350 function user_get_total_participants($courseid, $groupid = 0, $accesssince = 0, $roleid = 0, $enrolid = 0, $statusid = -1,
1351 $search = '', $additionalwhere = '', $additionalparams = array()) {
1352 global $DB;
1354 list($select, $from, $where, $params) = user_get_participants_sql($courseid, $groupid, $accesssince, $roleid, $enrolid,
1355 $statusid, $search, $additionalwhere, $additionalparams);
1357 return $DB->count_records_sql("SELECT COUNT(u.id) $from $where", $params);
1361 * Returns the participants for a given course.
1363 * @param int $courseid The course id
1364 * @param int $groupid The group id
1365 * @param int $accesssince The time since last access
1366 * @param int $roleid The role id
1367 * @param int $enrolid The applied filter for the user enrolment ID.
1368 * @param int $status The applied filter for the user's enrolment status.
1369 * @param string $search The search that was performed
1370 * @param string $additionalwhere Any additional SQL to add to where
1371 * @param array $additionalparams The additional params
1372 * @param string $sort The SQL sort
1373 * @param int $limitfrom return a subset of records, starting at this point (optional).
1374 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1375 * @return moodle_recordset
1377 function user_get_participants($courseid, $groupid = 0, $accesssince, $roleid, $enrolid = 0, $statusid, $search,
1378 $additionalwhere = '', $additionalparams = array(), $sort = '', $limitfrom = 0, $limitnum = 0) {
1379 global $DB;
1381 list($select, $from, $where, $params) = user_get_participants_sql($courseid, $groupid, $accesssince, $roleid, $enrolid,
1382 $statusid, $search, $additionalwhere, $additionalparams);
1384 return $DB->get_recordset_sql("$select $from $where $sort", $params, $limitfrom, $limitnum);
1388 * Returns SQL that can be used to limit a query to a period where the user last accessed a course.
1390 * @param int $accesssince The time since last access
1391 * @param string $tableprefix
1392 * @return string
1394 function user_get_course_lastaccess_sql($accesssince = null, $tableprefix = 'ul') {
1395 if (empty($accesssince)) {
1396 return '';
1399 if ($accesssince == -1) { // Never.
1400 return $tableprefix . '.timeaccess = 0';
1401 } else {
1402 return $tableprefix . '.timeaccess != 0 AND ul.timeaccess < ' . $accesssince;
1407 * Returns SQL that can be used to limit a query to a period where the user last accessed the system.
1409 * @param int $accesssince The time since last access
1410 * @param string $tableprefix
1411 * @return string
1413 function user_get_user_lastaccess_sql($accesssince = null, $tableprefix = 'u') {
1414 if (empty($accesssince)) {
1415 return '';
1418 if ($accesssince == -1) { // Never.
1419 return $tableprefix . '.lastaccess = 0';
1420 } else {
1421 return $tableprefix . '.lastaccess != 0 AND u.lastaccess < ' . $accesssince;
1426 * Callback for inplace editable API.
1428 * @param string $itemtype - Only user_roles is supported.
1429 * @param string $itemid - Courseid and userid separated by a :
1430 * @param string $newvalue - json encoded list of roleids.
1431 * @return \core\output\inplace_editable
1433 function core_user_inplace_editable($itemtype, $itemid, $newvalue) {
1434 if ($itemtype === 'user_roles') {
1435 return \core_user\output\user_roles_editable::update($itemid, $newvalue);