MDL-61410 question: support course tags on export
[moodle.git] / user / lib.php
blobe99fd85ee347ae37eecea1f212f44de88432ffbb
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 ($user->username !== core_text::strtolower($user->username)) {
52 throw new moodle_exception('usernamelowercase');
53 } else {
54 if ($user->username !== core_user::clean_field($user->username, 'username')) {
55 throw new moodle_exception('invalidusername');
59 // Save the password in a temp value for later.
60 if ($updatepassword && isset($user->password)) {
62 // Check password toward the password policy.
63 if (!check_password_policy($user->password, $errmsg)) {
64 throw new moodle_exception($errmsg);
67 $userpassword = $user->password;
68 unset($user->password);
71 // Apply default values for user preferences that are stored in users table.
72 if (!isset($user->calendartype)) {
73 $user->calendartype = core_user::get_property_default('calendartype');
75 if (!isset($user->maildisplay)) {
76 $user->maildisplay = core_user::get_property_default('maildisplay');
78 if (!isset($user->mailformat)) {
79 $user->mailformat = core_user::get_property_default('mailformat');
81 if (!isset($user->maildigest)) {
82 $user->maildigest = core_user::get_property_default('maildigest');
84 if (!isset($user->autosubscribe)) {
85 $user->autosubscribe = core_user::get_property_default('autosubscribe');
87 if (!isset($user->trackforums)) {
88 $user->trackforums = core_user::get_property_default('trackforums');
90 if (!isset($user->lang)) {
91 $user->lang = core_user::get_property_default('lang');
94 $user->timecreated = time();
95 $user->timemodified = $user->timecreated;
97 // Validate user data object.
98 $uservalidation = core_user::validate($user);
99 if ($uservalidation !== true) {
100 foreach ($uservalidation as $field => $message) {
101 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
102 $user->$field = core_user::clean_field($user->$field, $field);
106 // Insert the user into the database.
107 $newuserid = $DB->insert_record('user', $user);
109 // Create USER context for this user.
110 $usercontext = context_user::instance($newuserid);
112 // Update user password if necessary.
113 if (isset($userpassword)) {
114 // Get full database user row, in case auth is default.
115 $newuser = $DB->get_record('user', array('id' => $newuserid));
116 $authplugin = get_auth_plugin($newuser->auth);
117 $authplugin->user_update_password($newuser, $userpassword);
120 // Trigger event If required.
121 if ($triggerevent) {
122 \core\event\user_created::create_from_userid($newuserid)->trigger();
125 return $newuserid;
129 * Update a user with a user object (will compare against the ID)
131 * @throws moodle_exception
132 * @param stdClass $user the user to update
133 * @param bool $updatepassword if true, authentication plugin will update password.
134 * @param bool $triggerevent set false if user_updated event should not be triggred.
135 * This will not affect user_password_updated event triggering.
137 function user_update_user($user, $updatepassword = true, $triggerevent = true) {
138 global $DB;
140 // Set the timecreate field to the current time.
141 if (!is_object($user)) {
142 $user = (object) $user;
145 // Check username.
146 if (isset($user->username)) {
147 if ($user->username !== core_text::strtolower($user->username)) {
148 throw new moodle_exception('usernamelowercase');
149 } else {
150 if ($user->username !== core_user::clean_field($user->username, 'username')) {
151 throw new moodle_exception('invalidusername');
156 // Unset password here, for updating later, if password update is required.
157 if ($updatepassword && isset($user->password)) {
159 // Check password toward the password policy.
160 if (!check_password_policy($user->password, $errmsg)) {
161 throw new moodle_exception($errmsg);
164 $passwd = $user->password;
165 unset($user->password);
168 // Make sure calendartype, if set, is valid.
169 if (empty($user->calendartype)) {
170 // Unset this variable, must be an empty string, which we do not want to update the calendartype to.
171 unset($user->calendartype);
174 $user->timemodified = time();
176 // Validate user data object.
177 $uservalidation = core_user::validate($user);
178 if ($uservalidation !== true) {
179 foreach ($uservalidation as $field => $message) {
180 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
181 $user->$field = core_user::clean_field($user->$field, $field);
185 $DB->update_record('user', $user);
187 if ($updatepassword) {
188 // Get full user record.
189 $updateduser = $DB->get_record('user', array('id' => $user->id));
191 // If password was set, then update its hash.
192 if (isset($passwd)) {
193 $authplugin = get_auth_plugin($updateduser->auth);
194 if ($authplugin->can_change_password()) {
195 $authplugin->user_update_password($updateduser, $passwd);
199 // Trigger event if required.
200 if ($triggerevent) {
201 \core\event\user_updated::create_from_userid($user->id)->trigger();
206 * Marks user deleted in internal user database and notifies the auth plugin.
207 * Also unenrols user from all roles and does other cleanup.
209 * @todo Decide if this transaction is really needed (look for internal TODO:)
210 * @param object $user Userobject before delete (without system magic quotes)
211 * @return boolean success
213 function user_delete_user($user) {
214 return delete_user($user);
218 * Get users by id
220 * @param array $userids id of users to retrieve
221 * @return array
223 function user_get_users_by_id($userids) {
224 global $DB;
225 return $DB->get_records_list('user', 'id', $userids);
229 * Returns the list of default 'displayable' fields
231 * Contains database field names but also names used to generate information, such as enrolledcourses
233 * @return array of user fields
235 function user_get_default_fields() {
236 return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
237 'address', 'phone1', 'phone2', 'icq', 'skype', 'yahoo', 'aim', 'msn', 'department',
238 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
239 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
240 'city', 'url', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
241 'groups', 'roles', 'preferences', 'enrolledcourses', 'suspended'
247 * Give user record from mdl_user, build an array contains all user details.
249 * Warning: description file urls are 'webservice/pluginfile.php' is use.
250 * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
252 * @throws moodle_exception
253 * @param stdClass $user user record from mdl_user
254 * @param stdClass $course moodle course
255 * @param array $userfields required fields
256 * @return array|null
258 function user_get_user_details($user, $course = null, array $userfields = array()) {
259 global $USER, $DB, $CFG, $PAGE;
260 require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library.
261 require_once($CFG->dirroot . "/lib/filelib.php"); // File handling on description and friends.
263 $defaultfields = user_get_default_fields();
265 if (empty($userfields)) {
266 $userfields = $defaultfields;
269 foreach ($userfields as $thefield) {
270 if (!in_array($thefield, $defaultfields)) {
271 throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
275 // Make sure id and fullname are included.
276 if (!in_array('id', $userfields)) {
277 $userfields[] = 'id';
280 if (!in_array('fullname', $userfields)) {
281 $userfields[] = 'fullname';
284 if (!empty($course)) {
285 $context = context_course::instance($course->id);
286 $usercontext = context_user::instance($user->id);
287 $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext));
288 } else {
289 $context = context_user::instance($user->id);
290 $usercontext = $context;
291 $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
294 $currentuser = ($user->id == $USER->id);
295 $isadmin = is_siteadmin($USER);
297 $showuseridentityfields = get_extra_user_fields($context);
299 if (!empty($course)) {
300 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
301 } else {
302 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
304 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
305 if (!empty($course)) {
306 $canviewuseremail = has_capability('moodle/course:useremail', $context);
307 } else {
308 $canviewuseremail = false;
310 $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
311 if (!empty($course)) {
312 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
313 } else {
314 $canaccessallgroups = false;
317 if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
318 // Skip this user details.
319 return null;
322 $userdetails = array();
323 $userdetails['id'] = $user->id;
325 if (in_array('username', $userfields)) {
326 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
327 $userdetails['username'] = $user->username;
330 if ($isadmin or $canviewfullnames) {
331 if (in_array('firstname', $userfields)) {
332 $userdetails['firstname'] = $user->firstname;
334 if (in_array('lastname', $userfields)) {
335 $userdetails['lastname'] = $user->lastname;
338 $userdetails['fullname'] = fullname($user);
340 if (in_array('customfields', $userfields)) {
341 $categories = profile_get_user_fields_with_data_by_category($user->id);
342 $userdetails['customfields'] = array();
343 foreach ($categories as $categoryid => $fields) {
344 foreach ($fields as $formfield) {
345 if ($formfield->is_visible() and !$formfield->is_empty()) {
347 // TODO: Part of MDL-50728, this conditional coding must be moved to
348 // proper profile fields API so they are self-contained.
349 // We only use display_data in fields that require text formatting.
350 if ($formfield->field->datatype == 'text' or $formfield->field->datatype == 'textarea') {
351 $fieldvalue = $formfield->display_data();
352 } else {
353 // Cases: datetime, checkbox and menu.
354 $fieldvalue = $formfield->data;
357 $userdetails['customfields'][] =
358 array('name' => $formfield->field->name, 'value' => $fieldvalue,
359 'type' => $formfield->field->datatype, 'shortname' => $formfield->field->shortname);
363 // Unset customfields if it's empty.
364 if (empty($userdetails['customfields'])) {
365 unset($userdetails['customfields']);
369 // Profile image.
370 if (in_array('profileimageurl', $userfields)) {
371 $userpicture = new user_picture($user);
372 $userpicture->size = 1; // Size f1.
373 $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
375 if (in_array('profileimageurlsmall', $userfields)) {
376 if (!isset($userpicture)) {
377 $userpicture = new user_picture($user);
379 $userpicture->size = 0; // Size f2.
380 $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
383 // Hidden user field.
384 if ($canviewhiddenuserfields) {
385 $hiddenfields = array();
386 // Address, phone1 and phone2 not appears in hidden fields list but require viewhiddenfields capability
387 // according to user/profile.php.
388 if (!empty($user->address) && in_array('address', $userfields)) {
389 $userdetails['address'] = $user->address;
391 } else {
392 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
395 if (!empty($user->phone1) && in_array('phone1', $userfields) &&
396 (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) {
397 $userdetails['phone1'] = $user->phone1;
399 if (!empty($user->phone2) && in_array('phone2', $userfields) &&
400 (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) {
401 $userdetails['phone2'] = $user->phone2;
404 if (isset($user->description) &&
405 ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
406 if (in_array('description', $userfields)) {
407 // Always return the descriptionformat if description is requested.
408 list($userdetails['description'], $userdetails['descriptionformat']) =
409 external_format_text($user->description, $user->descriptionformat,
410 $usercontext->id, 'user', 'profile', null);
414 if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
415 $userdetails['country'] = $user->country;
418 if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
419 $userdetails['city'] = $user->city;
422 if (in_array('url', $userfields) && $user->url && (!isset($hiddenfields['webpage']) or $isadmin)) {
423 $url = $user->url;
424 if (strpos($user->url, '://') === false) {
425 $url = 'http://'. $url;
427 $user->url = clean_param($user->url, PARAM_URL);
428 $userdetails['url'] = $user->url;
431 if (in_array('icq', $userfields) && $user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) {
432 $userdetails['icq'] = $user->icq;
435 if (in_array('skype', $userfields) && $user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) {
436 $userdetails['skype'] = $user->skype;
438 if (in_array('yahoo', $userfields) && $user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) {
439 $userdetails['yahoo'] = $user->yahoo;
441 if (in_array('aim', $userfields) && $user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) {
442 $userdetails['aim'] = $user->aim;
444 if (in_array('msn', $userfields) && $user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) {
445 $userdetails['msn'] = $user->msn;
447 if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) {
448 $userdetails['suspended'] = (bool)$user->suspended;
451 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
452 if ($user->firstaccess) {
453 $userdetails['firstaccess'] = $user->firstaccess;
454 } else {
455 $userdetails['firstaccess'] = 0;
458 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
459 if ($user->lastaccess) {
460 $userdetails['lastaccess'] = $user->lastaccess;
461 } else {
462 $userdetails['lastaccess'] = 0;
466 if (in_array('email', $userfields) && ($isadmin // The admin is allowed the users email.
467 or $currentuser // Of course the current user is as well.
468 or $canviewuseremail // This is a capability in course context, it will be false in usercontext.
469 or in_array('email', $showuseridentityfields)
470 or $user->maildisplay == 1
471 or ($user->maildisplay == 2 and enrol_sharing_course($user, $USER)))) {
472 $userdetails['email'] = $user->email;
475 if (in_array('interests', $userfields)) {
476 $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
477 if ($interests) {
478 $userdetails['interests'] = join(', ', $interests);
482 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
483 if (in_array('idnumber', $userfields) && $user->idnumber) {
484 if (in_array('idnumber', $showuseridentityfields) or $currentuser or
485 has_capability('moodle/user:viewalldetails', $context)) {
486 $userdetails['idnumber'] = $user->idnumber;
489 if (in_array('institution', $userfields) && $user->institution) {
490 if (in_array('institution', $showuseridentityfields) or $currentuser or
491 has_capability('moodle/user:viewalldetails', $context)) {
492 $userdetails['institution'] = $user->institution;
495 // Isset because it's ok to have department 0.
496 if (in_array('department', $userfields) && isset($user->department)) {
497 if (in_array('department', $showuseridentityfields) or $currentuser or
498 has_capability('moodle/user:viewalldetails', $context)) {
499 $userdetails['department'] = $user->department;
503 if (in_array('roles', $userfields) && !empty($course)) {
504 // Not a big secret.
505 $roles = get_user_roles($context, $user->id, false);
506 $userdetails['roles'] = array();
507 foreach ($roles as $role) {
508 $userdetails['roles'][] = array(
509 'roleid' => $role->roleid,
510 'name' => $role->name,
511 'shortname' => $role->shortname,
512 'sortorder' => $role->sortorder
517 // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
518 if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
519 $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid,
520 'g.id, g.name,g.description,g.descriptionformat');
521 $userdetails['groups'] = array();
522 foreach ($usergroups as $group) {
523 list($group->description, $group->descriptionformat) =
524 external_format_text($group->description, $group->descriptionformat,
525 $context->id, 'group', 'description', $group->id);
526 $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name,
527 'description' => $group->description, 'descriptionformat' => $group->descriptionformat);
530 // List of courses where the user is enrolled.
531 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
532 $enrolledcourses = array();
533 if ($mycourses = enrol_get_users_courses($user->id, true)) {
534 foreach ($mycourses as $mycourse) {
535 if ($mycourse->category) {
536 $coursecontext = context_course::instance($mycourse->id);
537 $enrolledcourse = array();
538 $enrolledcourse['id'] = $mycourse->id;
539 $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
540 $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
541 $enrolledcourses[] = $enrolledcourse;
544 $userdetails['enrolledcourses'] = $enrolledcourses;
548 // User preferences.
549 if (in_array('preferences', $userfields) && $currentuser) {
550 $preferences = array();
551 $userpreferences = get_user_preferences();
552 foreach ($userpreferences as $prefname => $prefvalue) {
553 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
555 $userdetails['preferences'] = $preferences;
558 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
559 $extrafields = ['auth', 'confirmed', 'lang', 'theme', 'timezone', 'mailformat'];
560 foreach ($extrafields as $extrafield) {
561 if (in_array($extrafield, $userfields) && isset($user->$extrafield)) {
562 $userdetails[$extrafield] = $user->$extrafield;
567 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
568 if (isset($userdetails['lang'])) {
569 $userdetails['lang'] = clean_param($userdetails['lang'], PARAM_LANG);
571 if (isset($userdetails['theme'])) {
572 $userdetails['theme'] = clean_param($userdetails['theme'], PARAM_THEME);
575 return $userdetails;
579 * Tries to obtain user details, either recurring directly to the user's system profile
580 * or through one of the user's course enrollments (course profile).
582 * @param stdClass $user The user.
583 * @return array if unsuccessful or the allowed user details.
585 function user_get_user_details_courses($user) {
586 global $USER;
587 $userdetails = null;
589 // Get the courses that the user is enrolled in (only active).
590 $courses = enrol_get_users_courses($user->id, true);
592 $systemprofile = false;
593 if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
594 $systemprofile = true;
597 // Try using system profile.
598 if ($systemprofile) {
599 $userdetails = user_get_user_details($user, null);
600 } else {
601 // Try through course profile.
602 foreach ($courses as $course) {
603 if (can_view_user_details_cap($user, $course) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
604 $userdetails = user_get_user_details($user, $course);
609 return $userdetails;
613 * Check if $USER have the necessary capabilities to obtain user details.
615 * @param stdClass $user
616 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
617 * @return bool true if $USER can view user details.
619 function can_view_user_details_cap($user, $course = null) {
620 // Check $USER has the capability to view the user details at user context.
621 $usercontext = context_user::instance($user->id);
622 $result = has_capability('moodle/user:viewdetails', $usercontext);
623 // Otherwise can $USER see them at course context.
624 if (!$result && !empty($course)) {
625 $context = context_course::instance($course->id);
626 $result = has_capability('moodle/user:viewdetails', $context);
628 return $result;
632 * Return a list of page types
633 * @param string $pagetype current page type
634 * @param stdClass $parentcontext Block's parent context
635 * @param stdClass $currentcontext Current context of block
636 * @return array
638 function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
639 return array('user-profile' => get_string('page-user-profile', 'pagetype'));
643 * Count the number of failed login attempts for the given user, since last successful login.
645 * @param int|stdclass $user user id or object.
646 * @param bool $reset Resets failed login count, if set to true.
648 * @return int number of failed login attempts since the last successful login.
650 function user_count_login_failures($user, $reset = true) {
651 global $DB;
653 if (!is_object($user)) {
654 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
656 if ($user->deleted) {
657 // Deleted user, nothing to do.
658 return 0;
660 $count = get_user_preferences('login_failed_count_since_success', 0, $user);
661 if ($reset) {
662 set_user_preference('login_failed_count_since_success', 0, $user);
664 return $count;
668 * Converts a string into a flat array of menu items, where each menu items is a
669 * stdClass with fields type, url, title, pix, and imgsrc.
671 * @param string $text the menu items definition
672 * @param moodle_page $page the current page
673 * @return array
675 function user_convert_text_to_menu_items($text, $page) {
676 global $OUTPUT, $CFG;
678 $lines = explode("\n", $text);
679 $items = array();
680 $lastchild = null;
681 $lastdepth = null;
682 $lastsort = 0;
683 $children = array();
684 foreach ($lines as $line) {
685 $line = trim($line);
686 $bits = explode('|', $line, 3);
687 $itemtype = 'link';
688 if (preg_match("/^#+$/", $line)) {
689 $itemtype = 'divider';
690 } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
691 // Every item must have a name to be valid.
692 continue;
693 } else {
694 $bits[0] = ltrim($bits[0], '-');
697 // Create the child.
698 $child = new stdClass();
699 $child->itemtype = $itemtype;
700 if ($itemtype === 'divider') {
701 // Add the divider to the list of children and skip link
702 // processing.
703 $children[] = $child;
704 continue;
707 // Name processing.
708 $namebits = explode(',', $bits[0], 2);
709 if (count($namebits) == 2) {
710 // Check the validity of the identifier part of the string.
711 if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
712 // Treat this as a language string.
713 $child->title = get_string($namebits[0], $namebits[1]);
714 $child->titleidentifier = implode(',', $namebits);
717 if (empty($child->title)) {
718 // Use it as is, don't even clean it.
719 $child->title = $bits[0];
720 $child->titleidentifier = str_replace(" ", "-", $bits[0]);
723 // URL processing.
724 if (!array_key_exists(1, $bits) or empty($bits[1])) {
725 // Set the url to null, and set the itemtype to invalid.
726 $bits[1] = null;
727 $child->itemtype = "invalid";
728 } else {
729 // Nasty hack to replace the grades with the direct url.
730 if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
731 $bits[1] = user_mygrades_url();
734 // Make sure the url is a moodle url.
735 $bits[1] = new moodle_url(trim($bits[1]));
737 $child->url = $bits[1];
739 // PIX processing.
740 $pixpath = "t/edit";
741 if (!array_key_exists(2, $bits) or empty($bits[2])) {
742 // Use the default.
743 $child->pix = $pixpath;
744 } else {
745 // Check for the specified image existing.
746 $pixpath = "t/" . $bits[2];
747 if ($page->theme->resolve_image_location($pixpath, 'moodle', true)) {
748 // Use the image.
749 $child->pix = $pixpath;
750 } else {
751 // Treat it like a URL.
752 $child->pix = null;
753 $child->imgsrc = $bits[2];
757 // Add this child to the list of children.
758 $children[] = $child;
760 return $children;
764 * Get a list of essential user navigation items.
766 * @param stdclass $user user object.
767 * @param moodle_page $page page object.
768 * @param array $options associative array.
769 * options are:
770 * - avatarsize=35 (size of avatar image)
771 * @return stdClass $returnobj navigation information object, where:
773 * $returnobj->navitems array array of links where each link is a
774 * stdClass with fields url, title, and
775 * pix
776 * $returnobj->metadata array array of useful user metadata to be
777 * used when constructing navigation;
778 * fields include:
780 * ROLE FIELDS
781 * asotherrole bool whether viewing as another role
782 * rolename string name of the role
784 * USER FIELDS
785 * These fields are for the currently-logged in user, or for
786 * the user that the real user is currently logged in as.
788 * userid int the id of the user in question
789 * userfullname string the user's full name
790 * userprofileurl moodle_url the url of the user's profile
791 * useravatar string a HTML fragment - the rendered
792 * user_picture for this user
793 * userloginfail string an error string denoting the number
794 * of login failures since last login
796 * "REAL USER" FIELDS
797 * These fields are for when asotheruser is true, and
798 * correspond to the underlying "real user".
800 * asotheruser bool whether viewing as another user
801 * realuserid int the id of the user in question
802 * realuserfullname string the user's full name
803 * realuserprofileurl moodle_url the url of the user's profile
804 * realuseravatar string a HTML fragment - the rendered
805 * user_picture for this user
807 * MNET PROVIDER FIELDS
808 * asmnetuser bool whether viewing as a user from an
809 * MNet provider
810 * mnetidprovidername string name of the MNet provider
811 * mnetidproviderwwwroot string URL of the MNet provider
813 function user_get_user_navigation_info($user, $page, $options = array()) {
814 global $OUTPUT, $DB, $SESSION, $CFG;
816 $returnobject = new stdClass();
817 $returnobject->navitems = array();
818 $returnobject->metadata = array();
820 $course = $page->course;
822 // Query the environment.
823 $context = context_course::instance($course->id);
825 // Get basic user metadata.
826 $returnobject->metadata['userid'] = $user->id;
827 $returnobject->metadata['userfullname'] = fullname($user, true);
828 $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
829 'id' => $user->id
832 $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
833 if (!empty($options['avatarsize'])) {
834 $avataroptions['size'] = $options['avatarsize'];
836 $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
837 $user, $avataroptions
839 // Build a list of items for a regular user.
841 // Query MNet status.
842 if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
843 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
844 $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
845 $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
848 // Did the user just log in?
849 if (isset($SESSION->justloggedin)) {
850 // Don't unset this flag as login_info still needs it.
851 if (!empty($CFG->displayloginfailures)) {
852 // Don't reset the count either, as login_info() still needs it too.
853 if ($count = user_count_login_failures($user, false)) {
855 // Get login failures string.
856 $a = new stdClass();
857 $a->attempts = html_writer::tag('span', $count, array('class' => 'value'));
858 $returnobject->metadata['userloginfail'] =
859 get_string('failedloginattempts', '', $a);
865 // Links: Dashboard.
866 $myhome = new stdClass();
867 $myhome->itemtype = 'link';
868 $myhome->url = new moodle_url('/my/');
869 $myhome->title = get_string('mymoodle', 'admin');
870 $myhome->titleidentifier = 'mymoodle,admin';
871 $myhome->pix = "i/dashboard";
872 $returnobject->navitems[] = $myhome;
874 // Links: My Profile.
875 $myprofile = new stdClass();
876 $myprofile->itemtype = 'link';
877 $myprofile->url = new moodle_url('/user/profile.php', array('id' => $user->id));
878 $myprofile->title = get_string('profile');
879 $myprofile->titleidentifier = 'profile,moodle';
880 $myprofile->pix = "i/user";
881 $returnobject->navitems[] = $myprofile;
883 $returnobject->metadata['asotherrole'] = false;
885 // Before we add the last items (usually a logout + switch role link), add any
886 // custom-defined items.
887 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
888 foreach ($customitems as $item) {
889 $returnobject->navitems[] = $item;
893 if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
894 $realuser = \core\session\manager::get_realuser();
896 // Save values for the real user, as $user will be full of data for the
897 // user the user is disguised as.
898 $returnobject->metadata['realuserid'] = $realuser->id;
899 $returnobject->metadata['realuserfullname'] = fullname($realuser, true);
900 $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', array(
901 'id' => $realuser->id
903 $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
905 // Build a user-revert link.
906 $userrevert = new stdClass();
907 $userrevert->itemtype = 'link';
908 $userrevert->url = new moodle_url('/course/loginas.php', array(
909 'id' => $course->id,
910 'sesskey' => sesskey()
912 $userrevert->pix = "a/logout";
913 $userrevert->title = get_string('logout');
914 $userrevert->titleidentifier = 'logout,moodle';
915 $returnobject->navitems[] = $userrevert;
917 } else {
919 // Build a logout link.
920 $logout = new stdClass();
921 $logout->itemtype = 'link';
922 $logout->url = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
923 $logout->pix = "a/logout";
924 $logout->title = get_string('logout');
925 $logout->titleidentifier = 'logout,moodle';
926 $returnobject->navitems[] = $logout;
929 if (is_role_switched($course->id)) {
930 if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
931 // Build role-return link instead of logout link.
932 $rolereturn = new stdClass();
933 $rolereturn->itemtype = 'link';
934 $rolereturn->url = new moodle_url('/course/switchrole.php', array(
935 'id' => $course->id,
936 'sesskey' => sesskey(),
937 'switchrole' => 0,
938 'returnurl' => $page->url->out_as_local_url(false)
940 $rolereturn->pix = "a/logout";
941 $rolereturn->title = get_string('switchrolereturn');
942 $rolereturn->titleidentifier = 'switchrolereturn,moodle';
943 $returnobject->navitems[] = $rolereturn;
945 $returnobject->metadata['asotherrole'] = true;
946 $returnobject->metadata['rolename'] = role_get_name($role, $context);
949 } else {
950 // Build switch role link.
951 $roles = get_switchable_roles($context);
952 if (is_array($roles) && (count($roles) > 0)) {
953 $switchrole = new stdClass();
954 $switchrole->itemtype = 'link';
955 $switchrole->url = new moodle_url('/course/switchrole.php', array(
956 'id' => $course->id,
957 'switchrole' => -1,
958 'returnurl' => $page->url->out_as_local_url(false)
960 $switchrole->pix = "i/switchrole";
961 $switchrole->title = get_string('switchroleto');
962 $switchrole->titleidentifier = 'switchroleto,moodle';
963 $returnobject->navitems[] = $switchrole;
967 return $returnobject;
971 * Add password to the list of used hashes for this user.
973 * This is supposed to be used from:
974 * 1/ change own password form
975 * 2/ password reset process
976 * 3/ user signup in auth plugins if password changing supported
978 * @param int $userid user id
979 * @param string $password plaintext password
980 * @return void
982 function user_add_password_history($userid, $password) {
983 global $CFG, $DB;
985 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
986 return;
989 // Note: this is using separate code form normal password hashing because
990 // we need to have this under control in the future. Also the auth
991 // plugin might not store the passwords locally at all.
993 $record = new stdClass();
994 $record->userid = $userid;
995 $record->hash = password_hash($password, PASSWORD_DEFAULT);
996 $record->timecreated = time();
997 $DB->insert_record('user_password_history', $record);
999 $i = 0;
1000 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1001 foreach ($records as $record) {
1002 $i++;
1003 if ($i > $CFG->passwordreuselimit) {
1004 $DB->delete_records('user_password_history', array('id' => $record->id));
1010 * Was this password used before on change or reset password page?
1012 * The $CFG->passwordreuselimit setting determines
1013 * how many times different password needs to be used
1014 * before allowing previously used password again.
1016 * @param int $userid user id
1017 * @param string $password plaintext password
1018 * @return bool true if password reused
1020 function user_is_previously_used_password($userid, $password) {
1021 global $CFG, $DB;
1023 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1024 return false;
1027 $reused = false;
1029 $i = 0;
1030 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1031 foreach ($records as $record) {
1032 $i++;
1033 if ($i > $CFG->passwordreuselimit) {
1034 $DB->delete_records('user_password_history', array('id' => $record->id));
1035 continue;
1037 // NOTE: this is slow but we cannot compare the hashes directly any more.
1038 if (password_verify($password, $record->hash)) {
1039 $reused = true;
1043 return $reused;
1047 * Remove a user device from the Moodle database (for PUSH notifications usually).
1049 * @param string $uuid The device UUID.
1050 * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1051 * @return bool true if removed, false if the device didn't exists in the database
1052 * @since Moodle 2.9
1054 function user_remove_user_device($uuid, $appid = "") {
1055 global $DB, $USER;
1057 $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
1058 if (!empty($appid)) {
1059 $conditions['appid'] = $appid;
1062 if (!$DB->count_records('user_devices', $conditions)) {
1063 return false;
1066 $DB->delete_records('user_devices', $conditions);
1068 return true;
1072 * Trigger user_list_viewed event.
1074 * @param stdClass $course course object
1075 * @param stdClass $context course context object
1076 * @since Moodle 2.9
1078 function user_list_view($course, $context) {
1080 $event = \core\event\user_list_viewed::create(array(
1081 'objectid' => $course->id,
1082 'courseid' => $course->id,
1083 'context' => $context,
1084 'other' => array(
1085 'courseshortname' => $course->shortname,
1086 'coursefullname' => $course->fullname
1089 $event->trigger();
1093 * Returns the url to use for the "Grades" link in the user navigation.
1095 * @param int $userid The user's ID.
1096 * @param int $courseid The course ID if available.
1097 * @return mixed A URL to be directed to for "Grades".
1099 function user_mygrades_url($userid = null, $courseid = SITEID) {
1100 global $CFG, $USER;
1101 $url = null;
1102 if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
1103 if (isset($userid) && $USER->id != $userid) {
1104 // Send to the gradebook report.
1105 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
1106 array('id' => $courseid, 'userid' => $userid));
1107 } else {
1108 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
1110 } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
1111 && !empty($CFG->gradereport_mygradeurl)) {
1112 $url = $CFG->gradereport_mygradeurl;
1113 } else {
1114 $url = $CFG->wwwroot;
1116 return $url;
1120 * Check if the current user has permission to view details of the supplied user.
1122 * This function supports two modes:
1123 * If the optional $course param is omitted, then this function finds all shared courses and checks whether the current user has
1124 * permission in any of them, returning true if so.
1125 * If the $course param is provided, then this function checks permissions in ONLY that course.
1127 * @param object $user The other user's details.
1128 * @param object $course if provided, only check permissions in this course.
1129 * @param context $usercontext The user context if available.
1130 * @return bool true for ability to view this user, else false.
1132 function user_can_view_profile($user, $course = null, $usercontext = null) {
1133 global $USER, $CFG;
1135 if ($user->deleted) {
1136 return false;
1139 // Do we need to be logged in?
1140 if (empty($CFG->forceloginforprofiles)) {
1141 return true;
1142 } else {
1143 if (!isloggedin() || isguestuser()) {
1144 // User is not logged in and forceloginforprofile is set, we need to return now.
1145 return false;
1149 // Current user can always view their profile.
1150 if ($USER->id == $user->id) {
1151 return true;
1154 // Course contacts have visible profiles always.
1155 if (has_coursecontact_role($user->id)) {
1156 return true;
1159 // If we're only checking the capabilities in the single provided course.
1160 if (isset($course)) {
1161 // Confirm that $user is enrolled in the $course we're checking.
1162 if (is_enrolled(context_course::instance($course->id), $user)) {
1163 $userscourses = array($course);
1165 } else {
1166 // Else we're checking whether the current user can view $user's profile anywhere, so check user context first.
1167 if (empty($usercontext)) {
1168 $usercontext = context_user::instance($user->id);
1170 if (has_capability('moodle/user:viewdetails', $usercontext) || has_capability('moodle/user:viewalldetails', $usercontext)) {
1171 return true;
1173 // This returns context information, so we can preload below.
1174 $userscourses = enrol_get_all_users_courses($user->id);
1177 if (empty($userscourses)) {
1178 return false;
1181 foreach ($userscourses as $userscourse) {
1182 context_helper::preload_from_record($userscourse);
1183 $coursecontext = context_course::instance($userscourse->id);
1184 if (has_capability('moodle/user:viewdetails', $coursecontext) ||
1185 has_capability('moodle/user:viewalldetails', $coursecontext)) {
1186 if (!groups_user_groups_visible($userscourse, $user->id)) {
1187 // Not a member of the same group.
1188 continue;
1190 return true;
1193 return false;
1197 * Returns users tagged with a specified tag.
1199 * @param core_tag_tag $tag
1200 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1201 * are displayed on the page and the per-page limit may be bigger
1202 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1203 * to display items in the same context first
1204 * @param int $ctx context id where to search for records
1205 * @param bool $rec search in subcontexts as well
1206 * @param int $page 0-based number of page being displayed
1207 * @return \core_tag\output\tagindex
1209 function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1210 global $PAGE;
1212 if ($ctx && $ctx != context_system::instance()->id) {
1213 $usercount = 0;
1214 } else {
1215 // Users can only be displayed in system context.
1216 $usercount = $tag->count_tagged_items('core', 'user',
1217 'it.deleted=:notdeleted', array('notdeleted' => 0));
1219 $perpage = $exclusivemode ? 24 : 5;
1220 $content = '';
1221 $totalpages = ceil($usercount / $perpage);
1223 if ($usercount) {
1224 $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage,
1225 'it.deleted=:notdeleted', array('notdeleted' => 0));
1226 $renderer = $PAGE->get_renderer('core', 'user');
1227 $content .= $renderer->user_list($userlist, $exclusivemode);
1230 return new core_tag\output\tagindex($tag, 'core', 'user', $content,
1231 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1235 * Returns the SQL used by the participants table.
1237 * @param int $courseid The course id
1238 * @param int $groupid The groupid, 0 means all groups
1239 * @param int $accesssince The time since last access, 0 means any time
1240 * @param int $roleid The role id, 0 means all roles
1241 * @param int $enrolid The enrolment id, 0 means all enrolment methods will be returned.
1242 * @param int $statusid The user enrolment status, -1 means all enrolments regardless of the status will be returned, if allowed.
1243 * @param string|array $search The search that was performed, empty means perform no search
1244 * @param string $additionalwhere Any additional SQL to add to where
1245 * @param array $additionalparams The additional params
1246 * @return array
1248 function user_get_participants_sql($courseid, $groupid = 0, $accesssince = 0, $roleid = 0, $enrolid = 0, $statusid = -1,
1249 $search = '', $additionalwhere = '', $additionalparams = array()) {
1250 global $DB, $USER;
1252 // Get the context.
1253 $context = \context_course::instance($courseid, MUST_EXIST);
1255 $isfrontpage = ($courseid == SITEID);
1257 // Default filter settings. We only show active by default, especially if the user has no capability to review enrolments.
1258 $onlyactive = true;
1259 $onlysuspended = false;
1260 if (has_capability('moodle/course:enrolreview', $context)) {
1261 switch ($statusid) {
1262 case ENROL_USER_ACTIVE:
1263 // Nothing to do here.
1264 break;
1265 case ENROL_USER_SUSPENDED:
1266 $onlyactive = false;
1267 $onlysuspended = true;
1268 break;
1269 default:
1270 // If the user has capability to review user enrolments, but statusid is set to -1, set $onlyactive to false.
1271 $onlyactive = false;
1272 break;
1276 list($esql, $params) = get_enrolled_sql($context, null, $groupid, $onlyactive, $onlysuspended, $enrolid);
1278 $joins = array('FROM {user} u');
1279 $wheres = array();
1281 $userfields = get_extra_user_fields($context);
1282 $userfieldssql = user_picture::fields('u', $userfields);
1284 if ($isfrontpage) {
1285 $select = "SELECT $userfieldssql, u.lastaccess";
1286 $joins[] = "JOIN ($esql) e ON e.id = u.id"; // Everybody on the frontpage usually.
1287 if ($accesssince) {
1288 $wheres[] = user_get_user_lastaccess_sql($accesssince);
1290 } else {
1291 $select = "SELECT $userfieldssql, COALESCE(ul.timeaccess, 0) AS lastaccess";
1292 $joins[] = "JOIN ($esql) e ON e.id = u.id"; // Course enrolled users only.
1293 // Not everybody has accessed the course yet.
1294 $joins[] = 'LEFT JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = :courseid)';
1295 $params['courseid'] = $courseid;
1296 if ($accesssince) {
1297 $wheres[] = user_get_course_lastaccess_sql($accesssince);
1301 // Performance hacks - we preload user contexts together with accounts.
1302 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1303 $ccjoin = 'LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)';
1304 $params['contextlevel'] = CONTEXT_USER;
1305 $select .= $ccselect;
1306 $joins[] = $ccjoin;
1308 // Limit list to users with some role only.
1309 if ($roleid) {
1310 // We want to query both the current context and parent contexts.
1311 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true),
1312 SQL_PARAMS_NAMED, 'relatedctx');
1314 $wheres[] = "u.id IN (SELECT userid FROM {role_assignments} WHERE roleid = :roleid AND contextid $relatedctxsql)";
1315 $params = array_merge($params, array('roleid' => $roleid), $relatedctxparams);
1318 if (!empty($search)) {
1319 if (!is_array($search)) {
1320 $search = [$search];
1322 foreach ($search as $index => $keyword) {
1323 $searchkey1 = 'search' . $index . '1';
1324 $searchkey2 = 'search' . $index . '2';
1325 $searchkey3 = 'search' . $index . '3';
1326 $searchkey4 = 'search' . $index . '4';
1327 $searchkey5 = 'search' . $index . '5';
1328 $searchkey6 = 'search' . $index . '6';
1329 $searchkey7 = 'search' . $index . '7';
1331 $conditions = array();
1332 // Search by fullname.
1333 $fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
1334 $conditions[] = $DB->sql_like($fullname, ':' . $searchkey1, false, false);
1336 // Search by email.
1337 $email = $DB->sql_like('email', ':' . $searchkey2, false, false);
1338 if (!in_array('email', $userfields)) {
1339 $maildisplay = 'maildisplay' . $index;
1340 $userid1 = 'userid' . $index . '1';
1341 // Prevent users who hide their email address from being found by others
1342 // who aren't allowed to see hidden email addresses.
1343 $email = "(". $email ." AND (" .
1344 "u.maildisplay <> :$maildisplay " .
1345 "OR u.id = :$userid1". // User can always find himself.
1346 "))";
1347 $params[$maildisplay] = core_user::MAILDISPLAY_HIDE;
1348 $params[$userid1] = $USER->id;
1350 $conditions[] = $email;
1352 // Search by idnumber.
1353 $idnumber = $DB->sql_like('idnumber', ':' . $searchkey3, false, false);
1354 if (!in_array('idnumber', $userfields)) {
1355 $userid2 = 'userid' . $index . '2';
1356 // Users who aren't allowed to see idnumbers should at most find themselves
1357 // when searching for an idnumber.
1358 $idnumber = "(". $idnumber . " AND u.id = :$userid2)";
1359 $params[$userid2] = $USER->id;
1361 $conditions[] = $idnumber;
1363 // Search by middlename.
1364 $middlename = $DB->sql_like('middlename', ':' . $searchkey4, false, false);
1365 $conditions[] = $middlename;
1367 // Search by alternatename.
1368 $alternatename = $DB->sql_like('alternatename', ':' . $searchkey5, false, false);
1369 $conditions[] = $alternatename;
1371 // Search by firstnamephonetic.
1372 $firstnamephonetic = $DB->sql_like('firstnamephonetic', ':' . $searchkey6, false, false);
1373 $conditions[] = $firstnamephonetic;
1375 // Search by lastnamephonetic.
1376 $lastnamephonetic = $DB->sql_like('lastnamephonetic', ':' . $searchkey7, false, false);
1377 $conditions[] = $lastnamephonetic;
1379 $wheres[] = "(". implode(" OR ", $conditions) .") ";
1380 $params[$searchkey1] = "%$keyword%";
1381 $params[$searchkey2] = "%$keyword%";
1382 $params[$searchkey3] = "%$keyword%";
1383 $params[$searchkey4] = "%$keyword%";
1384 $params[$searchkey5] = "%$keyword%";
1385 $params[$searchkey6] = "%$keyword%";
1386 $params[$searchkey7] = "%$keyword%";
1390 if (!empty($additionalwhere)) {
1391 $wheres[] = $additionalwhere;
1392 $params = array_merge($params, $additionalparams);
1395 $from = implode("\n", $joins);
1396 if ($wheres) {
1397 $where = 'WHERE ' . implode(' AND ', $wheres);
1398 } else {
1399 $where = '';
1402 return array($select, $from, $where, $params);
1406 * Returns the total number of participants for a given course.
1408 * @param int $courseid The course id
1409 * @param int $groupid The groupid, 0 means all groups
1410 * @param int $accesssince The time since last access, 0 means any time
1411 * @param int $roleid The role id, 0 means all roles
1412 * @param int $enrolid The applied filter for the user enrolment ID.
1413 * @param int $status The applied filter for the user's enrolment status.
1414 * @param string|array $search The search that was performed, empty means perform no search
1415 * @param string $additionalwhere Any additional SQL to add to where
1416 * @param array $additionalparams The additional params
1417 * @return int
1419 function user_get_total_participants($courseid, $groupid = 0, $accesssince = 0, $roleid = 0, $enrolid = 0, $statusid = -1,
1420 $search = '', $additionalwhere = '', $additionalparams = array()) {
1421 global $DB;
1423 list($select, $from, $where, $params) = user_get_participants_sql($courseid, $groupid, $accesssince, $roleid, $enrolid,
1424 $statusid, $search, $additionalwhere, $additionalparams);
1426 return $DB->count_records_sql("SELECT COUNT(u.id) $from $where", $params);
1430 * Returns the participants for a given course.
1432 * @param int $courseid The course id
1433 * @param int $groupid The group id
1434 * @param int $accesssince The time since last access
1435 * @param int $roleid The role id
1436 * @param int $enrolid The applied filter for the user enrolment ID.
1437 * @param int $status The applied filter for the user's enrolment status.
1438 * @param string $search The search that was performed
1439 * @param string $additionalwhere Any additional SQL to add to where
1440 * @param array $additionalparams The additional params
1441 * @param string $sort The SQL sort
1442 * @param int $limitfrom return a subset of records, starting at this point (optional).
1443 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1444 * @return moodle_recordset
1446 function user_get_participants($courseid, $groupid = 0, $accesssince, $roleid, $enrolid = 0, $statusid, $search,
1447 $additionalwhere = '', $additionalparams = array(), $sort = '', $limitfrom = 0, $limitnum = 0) {
1448 global $DB;
1450 list($select, $from, $where, $params) = user_get_participants_sql($courseid, $groupid, $accesssince, $roleid, $enrolid,
1451 $statusid, $search, $additionalwhere, $additionalparams);
1453 return $DB->get_recordset_sql("$select $from $where $sort", $params, $limitfrom, $limitnum);
1457 * Returns SQL that can be used to limit a query to a period where the user last accessed a course.
1459 * @param int $accesssince The time since last access
1460 * @param string $tableprefix
1461 * @return string
1463 function user_get_course_lastaccess_sql($accesssince = null, $tableprefix = 'ul') {
1464 if (empty($accesssince)) {
1465 return '';
1468 if ($accesssince == -1) { // Never.
1469 return $tableprefix . '.timeaccess = 0';
1470 } else {
1471 return $tableprefix . '.timeaccess != 0 AND ul.timeaccess < ' . $accesssince;
1476 * Returns SQL that can be used to limit a query to a period where the user last accessed the system.
1478 * @param int $accesssince The time since last access
1479 * @param string $tableprefix
1480 * @return string
1482 function user_get_user_lastaccess_sql($accesssince = null, $tableprefix = 'u') {
1483 if (empty($accesssince)) {
1484 return '';
1487 if ($accesssince == -1) { // Never.
1488 return $tableprefix . '.lastaccess = 0';
1489 } else {
1490 return $tableprefix . '.lastaccess != 0 AND u.lastaccess < ' . $accesssince;
1495 * Callback for inplace editable API.
1497 * @param string $itemtype - Only user_roles is supported.
1498 * @param string $itemid - Courseid and userid separated by a :
1499 * @param string $newvalue - json encoded list of roleids.
1500 * @return \core\output\inplace_editable
1502 function core_user_inplace_editable($itemtype, $itemid, $newvalue) {
1503 if ($itemtype === 'user_roles') {
1504 return \core_user\output\user_roles_editable::update($itemid, $newvalue);