MDL-62459 database: remove unused table role_sortorder
[moodle.git] / user / lib.php
blobcb8e979d63ac0ba75161eedeccb8aa1c0e8ab3a5
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * External user API
20 * @package core_user
21 * @copyright 2009 Moodle Pty Ltd (http://moodle.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 define('USER_FILTER_ENROLMENT', 1);
26 define('USER_FILTER_GROUP', 2);
27 define('USER_FILTER_LAST_ACCESS', 3);
28 define('USER_FILTER_ROLE', 4);
29 define('USER_FILTER_STATUS', 5);
30 define('USER_FILTER_STRING', 6);
32 /**
33 * Creates a user
35 * @throws moodle_exception
36 * @param stdClass $user user to create
37 * @param bool $updatepassword if true, authentication plugin will update password.
38 * @param bool $triggerevent set false if user_created event should not be triggred.
39 * This will not affect user_password_updated event triggering.
40 * @return int id of the newly created user
42 function user_create_user($user, $updatepassword = true, $triggerevent = true) {
43 global $DB;
45 // Set the timecreate field to the current time.
46 if (!is_object($user)) {
47 $user = (object) $user;
50 // Check username.
51 if (trim($user->username) === '') {
52 throw new moodle_exception('invalidusernameblank');
55 if ($user->username !== core_text::strtolower($user->username)) {
56 throw new moodle_exception('usernamelowercase');
59 if ($user->username !== core_user::clean_field($user->username, 'username')) {
60 throw new moodle_exception('invalidusername');
63 // Save the password in a temp value for later.
64 if ($updatepassword && isset($user->password)) {
66 // Check password toward the password policy.
67 if (!check_password_policy($user->password, $errmsg)) {
68 throw new moodle_exception($errmsg);
71 $userpassword = $user->password;
72 unset($user->password);
75 // Apply default values for user preferences that are stored in users table.
76 if (!isset($user->calendartype)) {
77 $user->calendartype = core_user::get_property_default('calendartype');
79 if (!isset($user->maildisplay)) {
80 $user->maildisplay = core_user::get_property_default('maildisplay');
82 if (!isset($user->mailformat)) {
83 $user->mailformat = core_user::get_property_default('mailformat');
85 if (!isset($user->maildigest)) {
86 $user->maildigest = core_user::get_property_default('maildigest');
88 if (!isset($user->autosubscribe)) {
89 $user->autosubscribe = core_user::get_property_default('autosubscribe');
91 if (!isset($user->trackforums)) {
92 $user->trackforums = core_user::get_property_default('trackforums');
94 if (!isset($user->lang)) {
95 $user->lang = core_user::get_property_default('lang');
98 $user->timecreated = time();
99 $user->timemodified = $user->timecreated;
101 // Validate user data object.
102 $uservalidation = core_user::validate($user);
103 if ($uservalidation !== true) {
104 foreach ($uservalidation as $field => $message) {
105 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
106 $user->$field = core_user::clean_field($user->$field, $field);
110 // Insert the user into the database.
111 $newuserid = $DB->insert_record('user', $user);
113 // Create USER context for this user.
114 $usercontext = context_user::instance($newuserid);
116 // Update user password if necessary.
117 if (isset($userpassword)) {
118 // Get full database user row, in case auth is default.
119 $newuser = $DB->get_record('user', array('id' => $newuserid));
120 $authplugin = get_auth_plugin($newuser->auth);
121 $authplugin->user_update_password($newuser, $userpassword);
124 // Trigger event If required.
125 if ($triggerevent) {
126 \core\event\user_created::create_from_userid($newuserid)->trigger();
129 // Purge the associated caches for the current user only.
130 $presignupcache = \cache::make('core', 'presignup');
131 $presignupcache->purge_current_user();
133 return $newuserid;
137 * Update a user with a user object (will compare against the ID)
139 * @throws moodle_exception
140 * @param stdClass $user the user to update
141 * @param bool $updatepassword if true, authentication plugin will update password.
142 * @param bool $triggerevent set false if user_updated event should not be triggred.
143 * This will not affect user_password_updated event triggering.
145 function user_update_user($user, $updatepassword = true, $triggerevent = true) {
146 global $DB;
148 // Set the timecreate field to the current time.
149 if (!is_object($user)) {
150 $user = (object) $user;
153 // Check username.
154 if (isset($user->username)) {
155 if ($user->username !== core_text::strtolower($user->username)) {
156 throw new moodle_exception('usernamelowercase');
157 } else {
158 if ($user->username !== core_user::clean_field($user->username, 'username')) {
159 throw new moodle_exception('invalidusername');
164 // Unset password here, for updating later, if password update is required.
165 if ($updatepassword && isset($user->password)) {
167 // Check password toward the password policy.
168 if (!check_password_policy($user->password, $errmsg)) {
169 throw new moodle_exception($errmsg);
172 $passwd = $user->password;
173 unset($user->password);
176 // Make sure calendartype, if set, is valid.
177 if (empty($user->calendartype)) {
178 // Unset this variable, must be an empty string, which we do not want to update the calendartype to.
179 unset($user->calendartype);
182 $user->timemodified = time();
184 // Validate user data object.
185 $uservalidation = core_user::validate($user);
186 if ($uservalidation !== true) {
187 foreach ($uservalidation as $field => $message) {
188 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
189 $user->$field = core_user::clean_field($user->$field, $field);
193 $DB->update_record('user', $user);
195 if ($updatepassword) {
196 // Get full user record.
197 $updateduser = $DB->get_record('user', array('id' => $user->id));
199 // If password was set, then update its hash.
200 if (isset($passwd)) {
201 $authplugin = get_auth_plugin($updateduser->auth);
202 if ($authplugin->can_change_password()) {
203 $authplugin->user_update_password($updateduser, $passwd);
207 // Trigger event if required.
208 if ($triggerevent) {
209 \core\event\user_updated::create_from_userid($user->id)->trigger();
214 * Marks user deleted in internal user database and notifies the auth plugin.
215 * Also unenrols user from all roles and does other cleanup.
217 * @todo Decide if this transaction is really needed (look for internal TODO:)
218 * @param object $user Userobject before delete (without system magic quotes)
219 * @return boolean success
221 function user_delete_user($user) {
222 return delete_user($user);
226 * Get users by id
228 * @param array $userids id of users to retrieve
229 * @return array
231 function user_get_users_by_id($userids) {
232 global $DB;
233 return $DB->get_records_list('user', 'id', $userids);
237 * Returns the list of default 'displayable' fields
239 * Contains database field names but also names used to generate information, such as enrolledcourses
241 * @return array of user fields
243 function user_get_default_fields() {
244 return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
245 'address', 'phone1', 'phone2', 'icq', 'skype', 'yahoo', 'aim', 'msn', 'department',
246 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
247 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
248 'city', 'url', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
249 'groups', 'roles', 'preferences', 'enrolledcourses', 'suspended', 'lastcourseaccess'
255 * Give user record from mdl_user, build an array contains all user details.
257 * Warning: description file urls are 'webservice/pluginfile.php' is use.
258 * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
260 * @throws moodle_exception
261 * @param stdClass $user user record from mdl_user
262 * @param stdClass $course moodle course
263 * @param array $userfields required fields
264 * @return array|null
266 function user_get_user_details($user, $course = null, array $userfields = array()) {
267 global $USER, $DB, $CFG, $PAGE;
268 require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library.
269 require_once($CFG->dirroot . "/lib/filelib.php"); // File handling on description and friends.
271 $defaultfields = user_get_default_fields();
273 if (empty($userfields)) {
274 $userfields = $defaultfields;
277 foreach ($userfields as $thefield) {
278 if (!in_array($thefield, $defaultfields)) {
279 throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
283 // Make sure id and fullname are included.
284 if (!in_array('id', $userfields)) {
285 $userfields[] = 'id';
288 if (!in_array('fullname', $userfields)) {
289 $userfields[] = 'fullname';
292 if (!empty($course)) {
293 $context = context_course::instance($course->id);
294 $usercontext = context_user::instance($user->id);
295 $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext));
296 } else {
297 $context = context_user::instance($user->id);
298 $usercontext = $context;
299 $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
302 $currentuser = ($user->id == $USER->id);
303 $isadmin = is_siteadmin($USER);
305 $showuseridentityfields = get_extra_user_fields($context);
307 if (!empty($course)) {
308 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
309 } else {
310 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
312 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
313 if (!empty($course)) {
314 $canviewuseremail = has_capability('moodle/course:useremail', $context);
315 } else {
316 $canviewuseremail = false;
318 $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
319 if (!empty($course)) {
320 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
321 } else {
322 $canaccessallgroups = false;
325 if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
326 // Skip this user details.
327 return null;
330 $userdetails = array();
331 $userdetails['id'] = $user->id;
333 if (in_array('username', $userfields)) {
334 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
335 $userdetails['username'] = $user->username;
338 if ($isadmin or $canviewfullnames) {
339 if (in_array('firstname', $userfields)) {
340 $userdetails['firstname'] = $user->firstname;
342 if (in_array('lastname', $userfields)) {
343 $userdetails['lastname'] = $user->lastname;
346 $userdetails['fullname'] = fullname($user, $canviewfullnames);
348 if (in_array('customfields', $userfields)) {
349 $categories = profile_get_user_fields_with_data_by_category($user->id);
350 $userdetails['customfields'] = array();
351 foreach ($categories as $categoryid => $fields) {
352 foreach ($fields as $formfield) {
353 if ($formfield->is_visible() and !$formfield->is_empty()) {
355 // TODO: Part of MDL-50728, this conditional coding must be moved to
356 // proper profile fields API so they are self-contained.
357 // We only use display_data in fields that require text formatting.
358 if ($formfield->field->datatype == 'text' or $formfield->field->datatype == 'textarea') {
359 $fieldvalue = $formfield->display_data();
360 } else {
361 // Cases: datetime, checkbox and menu.
362 $fieldvalue = $formfield->data;
365 $userdetails['customfields'][] =
366 array('name' => $formfield->field->name, 'value' => $fieldvalue,
367 'type' => $formfield->field->datatype, 'shortname' => $formfield->field->shortname);
371 // Unset customfields if it's empty.
372 if (empty($userdetails['customfields'])) {
373 unset($userdetails['customfields']);
377 // Profile image.
378 if (in_array('profileimageurl', $userfields)) {
379 $userpicture = new user_picture($user);
380 $userpicture->size = 1; // Size f1.
381 $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
383 if (in_array('profileimageurlsmall', $userfields)) {
384 if (!isset($userpicture)) {
385 $userpicture = new user_picture($user);
387 $userpicture->size = 0; // Size f2.
388 $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
391 // Hidden user field.
392 if ($canviewhiddenuserfields) {
393 $hiddenfields = array();
394 // Address, phone1 and phone2 not appears in hidden fields list but require viewhiddenfields capability
395 // according to user/profile.php.
396 if (!empty($user->address) && in_array('address', $userfields)) {
397 $userdetails['address'] = $user->address;
399 } else {
400 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
403 if (!empty($user->phone1) && in_array('phone1', $userfields) &&
404 (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) {
405 $userdetails['phone1'] = $user->phone1;
407 if (!empty($user->phone2) && in_array('phone2', $userfields) &&
408 (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) {
409 $userdetails['phone2'] = $user->phone2;
412 if (isset($user->description) &&
413 ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
414 if (in_array('description', $userfields)) {
415 // Always return the descriptionformat if description is requested.
416 list($userdetails['description'], $userdetails['descriptionformat']) =
417 external_format_text($user->description, $user->descriptionformat,
418 $usercontext->id, 'user', 'profile', null);
422 if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
423 $userdetails['country'] = $user->country;
426 if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
427 $userdetails['city'] = $user->city;
430 if (in_array('url', $userfields) && $user->url && (!isset($hiddenfields['webpage']) or $isadmin)) {
431 $url = $user->url;
432 if (strpos($user->url, '://') === false) {
433 $url = 'http://'. $url;
435 $user->url = clean_param($user->url, PARAM_URL);
436 $userdetails['url'] = $user->url;
439 if (in_array('icq', $userfields) && $user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) {
440 $userdetails['icq'] = $user->icq;
443 if (in_array('skype', $userfields) && $user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) {
444 $userdetails['skype'] = $user->skype;
446 if (in_array('yahoo', $userfields) && $user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) {
447 $userdetails['yahoo'] = $user->yahoo;
449 if (in_array('aim', $userfields) && $user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) {
450 $userdetails['aim'] = $user->aim;
452 if (in_array('msn', $userfields) && $user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) {
453 $userdetails['msn'] = $user->msn;
455 if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) {
456 $userdetails['suspended'] = (bool)$user->suspended;
459 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
460 if ($user->firstaccess) {
461 $userdetails['firstaccess'] = $user->firstaccess;
462 } else {
463 $userdetails['firstaccess'] = 0;
466 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
467 if ($user->lastaccess) {
468 $userdetails['lastaccess'] = $user->lastaccess;
469 } else {
470 $userdetails['lastaccess'] = 0;
474 // Hidden fields restriction to lastaccess field applies to both site and course access time.
475 if (in_array('lastcourseaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
476 if (isset($user->lastcourseaccess)) {
477 $userdetails['lastcourseaccess'] = $user->lastcourseaccess;
478 } else {
479 $userdetails['lastcourseaccess'] = 0;
483 if (in_array('email', $userfields) && (
484 $currentuser
485 or (!isset($hiddenfields['email']) and (
486 $user->maildisplay == core_user::MAILDISPLAY_EVERYONE
487 or ($user->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY and enrol_sharing_course($user, $USER))
488 or $canviewuseremail // TODO: Deprecate/remove for MDL-37479.
490 or in_array('email', $showuseridentityfields)
491 )) {
492 $userdetails['email'] = $user->email;
495 if (in_array('interests', $userfields)) {
496 $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
497 if ($interests) {
498 $userdetails['interests'] = join(', ', $interests);
502 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
503 if (in_array('idnumber', $userfields) && $user->idnumber) {
504 if (in_array('idnumber', $showuseridentityfields) or $currentuser or
505 has_capability('moodle/user:viewalldetails', $context)) {
506 $userdetails['idnumber'] = $user->idnumber;
509 if (in_array('institution', $userfields) && $user->institution) {
510 if (in_array('institution', $showuseridentityfields) or $currentuser or
511 has_capability('moodle/user:viewalldetails', $context)) {
512 $userdetails['institution'] = $user->institution;
515 // Isset because it's ok to have department 0.
516 if (in_array('department', $userfields) && isset($user->department)) {
517 if (in_array('department', $showuseridentityfields) or $currentuser or
518 has_capability('moodle/user:viewalldetails', $context)) {
519 $userdetails['department'] = $user->department;
523 if (in_array('roles', $userfields) && !empty($course)) {
524 // Not a big secret.
525 $roles = get_user_roles($context, $user->id, false);
526 $userdetails['roles'] = array();
527 foreach ($roles as $role) {
528 $userdetails['roles'][] = array(
529 'roleid' => $role->roleid,
530 'name' => $role->name,
531 'shortname' => $role->shortname,
532 'sortorder' => $role->sortorder
537 // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
538 if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
539 $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid,
540 'g.id, g.name,g.description,g.descriptionformat');
541 $userdetails['groups'] = array();
542 foreach ($usergroups as $group) {
543 list($group->description, $group->descriptionformat) =
544 external_format_text($group->description, $group->descriptionformat,
545 $context->id, 'group', 'description', $group->id);
546 $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name,
547 'description' => $group->description, 'descriptionformat' => $group->descriptionformat);
550 // List of courses where the user is enrolled.
551 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
552 $enrolledcourses = array();
553 if ($mycourses = enrol_get_users_courses($user->id, true)) {
554 foreach ($mycourses as $mycourse) {
555 if ($mycourse->category) {
556 $coursecontext = context_course::instance($mycourse->id);
557 $enrolledcourse = array();
558 $enrolledcourse['id'] = $mycourse->id;
559 $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
560 $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
561 $enrolledcourses[] = $enrolledcourse;
564 $userdetails['enrolledcourses'] = $enrolledcourses;
568 // User preferences.
569 if (in_array('preferences', $userfields) && $currentuser) {
570 $preferences = array();
571 $userpreferences = get_user_preferences();
572 foreach ($userpreferences as $prefname => $prefvalue) {
573 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
575 $userdetails['preferences'] = $preferences;
578 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
579 $extrafields = ['auth', 'confirmed', 'lang', 'theme', 'timezone', 'mailformat'];
580 foreach ($extrafields as $extrafield) {
581 if (in_array($extrafield, $userfields) && isset($user->$extrafield)) {
582 $userdetails[$extrafield] = $user->$extrafield;
587 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
588 if (isset($userdetails['lang'])) {
589 $userdetails['lang'] = clean_param($userdetails['lang'], PARAM_LANG);
591 if (isset($userdetails['theme'])) {
592 $userdetails['theme'] = clean_param($userdetails['theme'], PARAM_THEME);
595 return $userdetails;
599 * Tries to obtain user details, either recurring directly to the user's system profile
600 * or through one of the user's course enrollments (course profile).
602 * @param stdClass $user The user.
603 * @return array if unsuccessful or the allowed user details.
605 function user_get_user_details_courses($user) {
606 global $USER;
607 $userdetails = null;
609 // Get the courses that the user is enrolled in (only active).
610 $courses = enrol_get_users_courses($user->id, true);
612 $systemprofile = false;
613 if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
614 $systemprofile = true;
617 // Try using system profile.
618 if ($systemprofile) {
619 $userdetails = user_get_user_details($user, null);
620 } else {
621 // Try through course profile.
622 foreach ($courses as $course) {
623 if (can_view_user_details_cap($user, $course) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
624 $userdetails = user_get_user_details($user, $course);
629 return $userdetails;
633 * Check if $USER have the necessary capabilities to obtain user details.
635 * @param stdClass $user
636 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
637 * @return bool true if $USER can view user details.
639 function can_view_user_details_cap($user, $course = null) {
640 // Check $USER has the capability to view the user details at user context.
641 $usercontext = context_user::instance($user->id);
642 $result = has_capability('moodle/user:viewdetails', $usercontext);
643 // Otherwise can $USER see them at course context.
644 if (!$result && !empty($course)) {
645 $context = context_course::instance($course->id);
646 $result = has_capability('moodle/user:viewdetails', $context);
648 return $result;
652 * Return a list of page types
653 * @param string $pagetype current page type
654 * @param stdClass $parentcontext Block's parent context
655 * @param stdClass $currentcontext Current context of block
656 * @return array
658 function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
659 return array('user-profile' => get_string('page-user-profile', 'pagetype'));
663 * Count the number of failed login attempts for the given user, since last successful login.
665 * @param int|stdclass $user user id or object.
666 * @param bool $reset Resets failed login count, if set to true.
668 * @return int number of failed login attempts since the last successful login.
670 function user_count_login_failures($user, $reset = true) {
671 global $DB;
673 if (!is_object($user)) {
674 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
676 if ($user->deleted) {
677 // Deleted user, nothing to do.
678 return 0;
680 $count = get_user_preferences('login_failed_count_since_success', 0, $user);
681 if ($reset) {
682 set_user_preference('login_failed_count_since_success', 0, $user);
684 return $count;
688 * Converts a string into a flat array of menu items, where each menu items is a
689 * stdClass with fields type, url, title, pix, and imgsrc.
691 * @param string $text the menu items definition
692 * @param moodle_page $page the current page
693 * @return array
695 function user_convert_text_to_menu_items($text, $page) {
696 global $OUTPUT, $CFG;
698 $lines = explode("\n", $text);
699 $items = array();
700 $lastchild = null;
701 $lastdepth = null;
702 $lastsort = 0;
703 $children = array();
704 foreach ($lines as $line) {
705 $line = trim($line);
706 $bits = explode('|', $line, 3);
707 $itemtype = 'link';
708 if (preg_match("/^#+$/", $line)) {
709 $itemtype = 'divider';
710 } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
711 // Every item must have a name to be valid.
712 continue;
713 } else {
714 $bits[0] = ltrim($bits[0], '-');
717 // Create the child.
718 $child = new stdClass();
719 $child->itemtype = $itemtype;
720 if ($itemtype === 'divider') {
721 // Add the divider to the list of children and skip link
722 // processing.
723 $children[] = $child;
724 continue;
727 // Name processing.
728 $namebits = explode(',', $bits[0], 2);
729 if (count($namebits) == 2) {
730 // Check the validity of the identifier part of the string.
731 if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
732 // Treat this as a language string.
733 $child->title = get_string($namebits[0], $namebits[1]);
734 $child->titleidentifier = implode(',', $namebits);
737 if (empty($child->title)) {
738 // Use it as is, don't even clean it.
739 $child->title = $bits[0];
740 $child->titleidentifier = str_replace(" ", "-", $bits[0]);
743 // URL processing.
744 if (!array_key_exists(1, $bits) or empty($bits[1])) {
745 // Set the url to null, and set the itemtype to invalid.
746 $bits[1] = null;
747 $child->itemtype = "invalid";
748 } else {
749 // Nasty hack to replace the grades with the direct url.
750 if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
751 $bits[1] = user_mygrades_url();
754 // Make sure the url is a moodle url.
755 $bits[1] = new moodle_url(trim($bits[1]));
757 $child->url = $bits[1];
759 // PIX processing.
760 $pixpath = "t/edit";
761 if (!array_key_exists(2, $bits) or empty($bits[2])) {
762 // Use the default.
763 $child->pix = $pixpath;
764 } else {
765 // Check for the specified image existing.
766 if (strpos($bits[2], '../') === 0) {
767 // The string starts with '../'.
768 // Strip off the first three characters - this should be the pix path.
769 $pixpath = substr($bits[2], 3);
770 } else if (strpos($bits[2], '/') === false) {
771 // There is no / in the path. Prefix it with 't/', which is the default path.
772 $pixpath = "t/{$bits[2]}";
773 } else {
774 // There is a '/' in the path - this is either a URL, or a standard pix path with no changes required.
775 $pixpath = $bits[2];
777 if ($page->theme->resolve_image_location($pixpath, 'moodle', true)) {
778 // Use the image.
779 $child->pix = $pixpath;
780 } else {
781 // Treat it like a URL.
782 $child->pix = null;
783 $child->imgsrc = $bits[2];
787 // Add this child to the list of children.
788 $children[] = $child;
790 return $children;
794 * Get a list of essential user navigation items.
796 * @param stdclass $user user object.
797 * @param moodle_page $page page object.
798 * @param array $options associative array.
799 * options are:
800 * - avatarsize=35 (size of avatar image)
801 * @return stdClass $returnobj navigation information object, where:
803 * $returnobj->navitems array array of links where each link is a
804 * stdClass with fields url, title, and
805 * pix
806 * $returnobj->metadata array array of useful user metadata to be
807 * used when constructing navigation;
808 * fields include:
810 * ROLE FIELDS
811 * asotherrole bool whether viewing as another role
812 * rolename string name of the role
814 * USER FIELDS
815 * These fields are for the currently-logged in user, or for
816 * the user that the real user is currently logged in as.
818 * userid int the id of the user in question
819 * userfullname string the user's full name
820 * userprofileurl moodle_url the url of the user's profile
821 * useravatar string a HTML fragment - the rendered
822 * user_picture for this user
823 * userloginfail string an error string denoting the number
824 * of login failures since last login
826 * "REAL USER" FIELDS
827 * These fields are for when asotheruser is true, and
828 * correspond to the underlying "real user".
830 * asotheruser bool whether viewing as another user
831 * realuserid int the id of the user in question
832 * realuserfullname string the user's full name
833 * realuserprofileurl moodle_url the url of the user's profile
834 * realuseravatar string a HTML fragment - the rendered
835 * user_picture for this user
837 * MNET PROVIDER FIELDS
838 * asmnetuser bool whether viewing as a user from an
839 * MNet provider
840 * mnetidprovidername string name of the MNet provider
841 * mnetidproviderwwwroot string URL of the MNet provider
843 function user_get_user_navigation_info($user, $page, $options = array()) {
844 global $OUTPUT, $DB, $SESSION, $CFG;
846 $returnobject = new stdClass();
847 $returnobject->navitems = array();
848 $returnobject->metadata = array();
850 $course = $page->course;
852 // Query the environment.
853 $context = context_course::instance($course->id);
855 // Get basic user metadata.
856 $returnobject->metadata['userid'] = $user->id;
857 $returnobject->metadata['userfullname'] = fullname($user, true);
858 $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
859 'id' => $user->id
862 $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
863 if (!empty($options['avatarsize'])) {
864 $avataroptions['size'] = $options['avatarsize'];
866 $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
867 $user, $avataroptions
869 // Build a list of items for a regular user.
871 // Query MNet status.
872 if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
873 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
874 $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
875 $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
878 // Did the user just log in?
879 if (isset($SESSION->justloggedin)) {
880 // Don't unset this flag as login_info still needs it.
881 if (!empty($CFG->displayloginfailures)) {
882 // Don't reset the count either, as login_info() still needs it too.
883 if ($count = user_count_login_failures($user, false)) {
885 // Get login failures string.
886 $a = new stdClass();
887 $a->attempts = html_writer::tag('span', $count, array('class' => 'value'));
888 $returnobject->metadata['userloginfail'] =
889 get_string('failedloginattempts', '', $a);
895 // Links: Dashboard.
896 $myhome = new stdClass();
897 $myhome->itemtype = 'link';
898 $myhome->url = new moodle_url('/my/');
899 $myhome->title = get_string('mymoodle', 'admin');
900 $myhome->titleidentifier = 'mymoodle,admin';
901 $myhome->pix = "i/dashboard";
902 $returnobject->navitems[] = $myhome;
904 // Links: My Profile.
905 $myprofile = new stdClass();
906 $myprofile->itemtype = 'link';
907 $myprofile->url = new moodle_url('/user/profile.php', array('id' => $user->id));
908 $myprofile->title = get_string('profile');
909 $myprofile->titleidentifier = 'profile,moodle';
910 $myprofile->pix = "i/user";
911 $returnobject->navitems[] = $myprofile;
913 $returnobject->metadata['asotherrole'] = false;
915 // Before we add the last items (usually a logout + switch role link), add any
916 // custom-defined items.
917 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
918 foreach ($customitems as $item) {
919 $returnobject->navitems[] = $item;
923 if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
924 $realuser = \core\session\manager::get_realuser();
926 // Save values for the real user, as $user will be full of data for the
927 // user the user is disguised as.
928 $returnobject->metadata['realuserid'] = $realuser->id;
929 $returnobject->metadata['realuserfullname'] = fullname($realuser, true);
930 $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', array(
931 'id' => $realuser->id
933 $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
935 // Build a user-revert link.
936 $userrevert = new stdClass();
937 $userrevert->itemtype = 'link';
938 $userrevert->url = new moodle_url('/course/loginas.php', array(
939 'id' => $course->id,
940 'sesskey' => sesskey()
942 $userrevert->pix = "a/logout";
943 $userrevert->title = get_string('logout');
944 $userrevert->titleidentifier = 'logout,moodle';
945 $returnobject->navitems[] = $userrevert;
947 } else {
949 // Build a logout link.
950 $logout = new stdClass();
951 $logout->itemtype = 'link';
952 $logout->url = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
953 $logout->pix = "a/logout";
954 $logout->title = get_string('logout');
955 $logout->titleidentifier = 'logout,moodle';
956 $returnobject->navitems[] = $logout;
959 if (is_role_switched($course->id)) {
960 if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
961 // Build role-return link instead of logout link.
962 $rolereturn = new stdClass();
963 $rolereturn->itemtype = 'link';
964 $rolereturn->url = new moodle_url('/course/switchrole.php', array(
965 'id' => $course->id,
966 'sesskey' => sesskey(),
967 'switchrole' => 0,
968 'returnurl' => $page->url->out_as_local_url(false)
970 $rolereturn->pix = "a/logout";
971 $rolereturn->title = get_string('switchrolereturn');
972 $rolereturn->titleidentifier = 'switchrolereturn,moodle';
973 $returnobject->navitems[] = $rolereturn;
975 $returnobject->metadata['asotherrole'] = true;
976 $returnobject->metadata['rolename'] = role_get_name($role, $context);
979 } else {
980 // Build switch role link.
981 $roles = get_switchable_roles($context);
982 if (is_array($roles) && (count($roles) > 0)) {
983 $switchrole = new stdClass();
984 $switchrole->itemtype = 'link';
985 $switchrole->url = new moodle_url('/course/switchrole.php', array(
986 'id' => $course->id,
987 'switchrole' => -1,
988 'returnurl' => $page->url->out_as_local_url(false)
990 $switchrole->pix = "i/switchrole";
991 $switchrole->title = get_string('switchroleto');
992 $switchrole->titleidentifier = 'switchroleto,moodle';
993 $returnobject->navitems[] = $switchrole;
997 return $returnobject;
1001 * Add password to the list of used hashes for this user.
1003 * This is supposed to be used from:
1004 * 1/ change own password form
1005 * 2/ password reset process
1006 * 3/ user signup in auth plugins if password changing supported
1008 * @param int $userid user id
1009 * @param string $password plaintext password
1010 * @return void
1012 function user_add_password_history($userid, $password) {
1013 global $CFG, $DB;
1015 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1016 return;
1019 // Note: this is using separate code form normal password hashing because
1020 // we need to have this under control in the future. Also the auth
1021 // plugin might not store the passwords locally at all.
1023 $record = new stdClass();
1024 $record->userid = $userid;
1025 $record->hash = password_hash($password, PASSWORD_DEFAULT);
1026 $record->timecreated = time();
1027 $DB->insert_record('user_password_history', $record);
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));
1040 * Was this password used before on change or reset password page?
1042 * The $CFG->passwordreuselimit setting determines
1043 * how many times different password needs to be used
1044 * before allowing previously used password again.
1046 * @param int $userid user id
1047 * @param string $password plaintext password
1048 * @return bool true if password reused
1050 function user_is_previously_used_password($userid, $password) {
1051 global $CFG, $DB;
1053 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1054 return false;
1057 $reused = false;
1059 $i = 0;
1060 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1061 foreach ($records as $record) {
1062 $i++;
1063 if ($i > $CFG->passwordreuselimit) {
1064 $DB->delete_records('user_password_history', array('id' => $record->id));
1065 continue;
1067 // NOTE: this is slow but we cannot compare the hashes directly any more.
1068 if (password_verify($password, $record->hash)) {
1069 $reused = true;
1073 return $reused;
1077 * Remove a user device from the Moodle database (for PUSH notifications usually).
1079 * @param string $uuid The device UUID.
1080 * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1081 * @return bool true if removed, false if the device didn't exists in the database
1082 * @since Moodle 2.9
1084 function user_remove_user_device($uuid, $appid = "") {
1085 global $DB, $USER;
1087 $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
1088 if (!empty($appid)) {
1089 $conditions['appid'] = $appid;
1092 if (!$DB->count_records('user_devices', $conditions)) {
1093 return false;
1096 $DB->delete_records('user_devices', $conditions);
1098 return true;
1102 * Trigger user_list_viewed event.
1104 * @param stdClass $course course object
1105 * @param stdClass $context course context object
1106 * @since Moodle 2.9
1108 function user_list_view($course, $context) {
1110 $event = \core\event\user_list_viewed::create(array(
1111 'objectid' => $course->id,
1112 'courseid' => $course->id,
1113 'context' => $context,
1114 'other' => array(
1115 'courseshortname' => $course->shortname,
1116 'coursefullname' => $course->fullname
1119 $event->trigger();
1123 * Returns the url to use for the "Grades" link in the user navigation.
1125 * @param int $userid The user's ID.
1126 * @param int $courseid The course ID if available.
1127 * @return mixed A URL to be directed to for "Grades".
1129 function user_mygrades_url($userid = null, $courseid = SITEID) {
1130 global $CFG, $USER;
1131 $url = null;
1132 if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
1133 if (isset($userid) && $USER->id != $userid) {
1134 // Send to the gradebook report.
1135 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
1136 array('id' => $courseid, 'userid' => $userid));
1137 } else {
1138 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
1140 } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
1141 && !empty($CFG->gradereport_mygradeurl)) {
1142 $url = $CFG->gradereport_mygradeurl;
1143 } else {
1144 $url = $CFG->wwwroot;
1146 return $url;
1150 * Check if the current user has permission to view details of the supplied user.
1152 * This function supports two modes:
1153 * If the optional $course param is omitted, then this function finds all shared courses and checks whether the current user has
1154 * permission in any of them, returning true if so.
1155 * If the $course param is provided, then this function checks permissions in ONLY that course.
1157 * @param object $user The other user's details.
1158 * @param object $course if provided, only check permissions in this course.
1159 * @param context $usercontext The user context if available.
1160 * @return bool true for ability to view this user, else false.
1162 function user_can_view_profile($user, $course = null, $usercontext = null) {
1163 global $USER, $CFG;
1165 if ($user->deleted) {
1166 return false;
1169 // Do we need to be logged in?
1170 if (empty($CFG->forceloginforprofiles)) {
1171 return true;
1172 } else {
1173 if (!isloggedin() || isguestuser()) {
1174 // User is not logged in and forceloginforprofile is set, we need to return now.
1175 return false;
1179 // Current user can always view their profile.
1180 if ($USER->id == $user->id) {
1181 return true;
1184 // Use callbacks so that (primarily) local plugins can prevent or allow profile access.
1185 $forceallow = false;
1186 $plugintypes = get_plugins_with_function('control_view_profile');
1187 foreach ($plugintypes as $plugins) {
1188 foreach ($plugins as $pluginfunction) {
1189 $result = $pluginfunction($user, $course, $usercontext);
1190 switch ($result) {
1191 case core_user::VIEWPROFILE_DO_NOT_PREVENT:
1192 // If the plugin doesn't stop access, just continue to next plugin or use
1193 // default behaviour.
1194 break;
1195 case core_user::VIEWPROFILE_FORCE_ALLOW:
1196 // Record that we are definitely going to allow it (unless another plugin
1197 // returns _PREVENT).
1198 $forceallow = true;
1199 break;
1200 case core_user::VIEWPROFILE_PREVENT:
1201 // If any plugin returns PREVENT then we return false, regardless of what
1202 // other plugins said.
1203 return false;
1207 if ($forceallow) {
1208 return true;
1211 // Course contacts have visible profiles always.
1212 if (has_coursecontact_role($user->id)) {
1213 return true;
1216 // If we're only checking the capabilities in the single provided course.
1217 if (isset($course)) {
1218 // Confirm that $user is enrolled in the $course we're checking.
1219 if (is_enrolled(context_course::instance($course->id), $user)) {
1220 $userscourses = array($course);
1222 } else {
1223 // Else we're checking whether the current user can view $user's profile anywhere, so check user context first.
1224 if (empty($usercontext)) {
1225 $usercontext = context_user::instance($user->id);
1227 if (has_capability('moodle/user:viewdetails', $usercontext) || has_capability('moodle/user:viewalldetails', $usercontext)) {
1228 return true;
1230 // This returns context information, so we can preload below.
1231 $userscourses = enrol_get_all_users_courses($user->id);
1234 if (empty($userscourses)) {
1235 return false;
1238 foreach ($userscourses as $userscourse) {
1239 context_helper::preload_from_record($userscourse);
1240 $coursecontext = context_course::instance($userscourse->id);
1241 if (has_capability('moodle/user:viewdetails', $coursecontext) ||
1242 has_capability('moodle/user:viewalldetails', $coursecontext)) {
1243 if (!groups_user_groups_visible($userscourse, $user->id)) {
1244 // Not a member of the same group.
1245 continue;
1247 return true;
1250 return false;
1254 * Returns users tagged with a specified tag.
1256 * @param core_tag_tag $tag
1257 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1258 * are displayed on the page and the per-page limit may be bigger
1259 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1260 * to display items in the same context first
1261 * @param int $ctx context id where to search for records
1262 * @param bool $rec search in subcontexts as well
1263 * @param int $page 0-based number of page being displayed
1264 * @return \core_tag\output\tagindex
1266 function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1267 global $PAGE;
1269 if ($ctx && $ctx != context_system::instance()->id) {
1270 $usercount = 0;
1271 } else {
1272 // Users can only be displayed in system context.
1273 $usercount = $tag->count_tagged_items('core', 'user',
1274 'it.deleted=:notdeleted', array('notdeleted' => 0));
1276 $perpage = $exclusivemode ? 24 : 5;
1277 $content = '';
1278 $totalpages = ceil($usercount / $perpage);
1280 if ($usercount) {
1281 $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage,
1282 'it.deleted=:notdeleted', array('notdeleted' => 0));
1283 $renderer = $PAGE->get_renderer('core', 'user');
1284 $content .= $renderer->user_list($userlist, $exclusivemode);
1287 return new core_tag\output\tagindex($tag, 'core', 'user', $content,
1288 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1292 * Returns the SQL used by the participants table.
1294 * @param int $courseid The course id
1295 * @param int $groupid The groupid, 0 means all groups and USERSWITHOUTGROUP no group
1296 * @param int $accesssince The time since last access, 0 means any time
1297 * @param int $roleid The role id, 0 means all roles
1298 * @param int $enrolid The enrolment id, 0 means all enrolment methods will be returned.
1299 * @param int $statusid The user enrolment status, -1 means all enrolments regardless of the status will be returned, if allowed.
1300 * @param string|array $search The search that was performed, empty means perform no search
1301 * @param string $additionalwhere Any additional SQL to add to where
1302 * @param array $additionalparams The additional params
1303 * @return array
1305 function user_get_participants_sql($courseid, $groupid = 0, $accesssince = 0, $roleid = 0, $enrolid = 0, $statusid = -1,
1306 $search = '', $additionalwhere = '', $additionalparams = array()) {
1307 global $DB, $USER, $CFG;
1309 // Get the context.
1310 $context = \context_course::instance($courseid, MUST_EXIST);
1312 $isfrontpage = ($courseid == SITEID);
1314 // Default filter settings. We only show active by default, especially if the user has no capability to review enrolments.
1315 $onlyactive = true;
1316 $onlysuspended = false;
1317 if (has_capability('moodle/course:enrolreview', $context)) {
1318 switch ($statusid) {
1319 case ENROL_USER_ACTIVE:
1320 // Nothing to do here.
1321 break;
1322 case ENROL_USER_SUSPENDED:
1323 $onlyactive = false;
1324 $onlysuspended = true;
1325 break;
1326 default:
1327 // If the user has capability to review user enrolments, but statusid is set to -1, set $onlyactive to false.
1328 $onlyactive = false;
1329 break;
1333 list($esql, $params) = get_enrolled_sql($context, null, $groupid, $onlyactive, $onlysuspended, $enrolid);
1335 $joins = array('FROM {user} u');
1336 $wheres = array();
1338 $userfields = get_extra_user_fields($context);
1339 $userfieldssql = user_picture::fields('u', $userfields);
1341 if ($isfrontpage) {
1342 $select = "SELECT $userfieldssql, u.lastaccess";
1343 $joins[] = "JOIN ($esql) e ON e.id = u.id"; // Everybody on the frontpage usually.
1344 if ($accesssince) {
1345 $wheres[] = user_get_user_lastaccess_sql($accesssince);
1347 } else {
1348 $select = "SELECT $userfieldssql, COALESCE(ul.timeaccess, 0) AS lastaccess";
1349 $joins[] = "JOIN ($esql) e ON e.id = u.id"; // Course enrolled users only.
1350 // Not everybody has accessed the course yet.
1351 $joins[] = 'LEFT JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = :courseid)';
1352 $params['courseid'] = $courseid;
1353 if ($accesssince) {
1354 $wheres[] = user_get_course_lastaccess_sql($accesssince);
1358 // Performance hacks - we preload user contexts together with accounts.
1359 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1360 $ccjoin = 'LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)';
1361 $params['contextlevel'] = CONTEXT_USER;
1362 $select .= $ccselect;
1363 $joins[] = $ccjoin;
1365 // Limit list to users with some role only.
1366 if ($roleid) {
1367 // We want to query both the current context and parent contexts.
1368 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true),
1369 SQL_PARAMS_NAMED, 'relatedctx');
1371 $wheres[] = "u.id IN (SELECT userid FROM {role_assignments} WHERE roleid = :roleid AND contextid $relatedctxsql)";
1372 $params = array_merge($params, array('roleid' => $roleid), $relatedctxparams);
1375 if (!empty($search)) {
1376 if (!is_array($search)) {
1377 $search = [$search];
1379 foreach ($search as $index => $keyword) {
1380 $searchkey1 = 'search' . $index . '1';
1381 $searchkey2 = 'search' . $index . '2';
1382 $searchkey3 = 'search' . $index . '3';
1383 $searchkey4 = 'search' . $index . '4';
1384 $searchkey5 = 'search' . $index . '5';
1385 $searchkey6 = 'search' . $index . '6';
1386 $searchkey7 = 'search' . $index . '7';
1388 $conditions = array();
1389 // Search by fullname.
1390 $fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
1391 $conditions[] = $DB->sql_like($fullname, ':' . $searchkey1, false, false);
1393 // Search by email.
1394 $email = $DB->sql_like('email', ':' . $searchkey2, false, false);
1395 if (!in_array('email', $userfields)) {
1396 $maildisplay = 'maildisplay' . $index;
1397 $userid1 = 'userid' . $index . '1';
1398 // Prevent users who hide their email address from being found by others
1399 // who aren't allowed to see hidden email addresses.
1400 $email = "(". $email ." AND (" .
1401 "u.maildisplay <> :$maildisplay " .
1402 "OR u.id = :$userid1". // User can always find himself.
1403 "))";
1404 $params[$maildisplay] = core_user::MAILDISPLAY_HIDE;
1405 $params[$userid1] = $USER->id;
1407 $conditions[] = $email;
1409 // Search by idnumber.
1410 $idnumber = $DB->sql_like('idnumber', ':' . $searchkey3, false, false);
1411 if (!in_array('idnumber', $userfields)) {
1412 $userid2 = 'userid' . $index . '2';
1413 // Users who aren't allowed to see idnumbers should at most find themselves
1414 // when searching for an idnumber.
1415 $idnumber = "(". $idnumber . " AND u.id = :$userid2)";
1416 $params[$userid2] = $USER->id;
1418 $conditions[] = $idnumber;
1420 if (!empty($CFG->showuseridentity)) {
1421 // Search all user identify fields.
1422 $extrasearchfields = explode(',', $CFG->showuseridentity);
1423 foreach ($extrasearchfields as $extrasearchfield) {
1424 if (in_array($extrasearchfield, ['email', 'idnumber', 'country'])) {
1425 // Already covered above. Search by country not supported.
1426 continue;
1428 $param = $searchkey3 . $extrasearchfield;
1429 $condition = $DB->sql_like($extrasearchfield, ':' . $param, false, false);
1430 $params[$param] = "%$keyword%";
1431 if (!in_array($extrasearchfield, $userfields)) {
1432 // User cannot see this field, but allow match if their own account.
1433 $userid3 = 'userid' . $index . '3' . $extrasearchfield;
1434 $condition = "(". $condition . " AND u.id = :$userid3)";
1435 $params[$userid3] = $USER->id;
1437 $conditions[] = $condition;
1441 // Search by middlename.
1442 $middlename = $DB->sql_like('middlename', ':' . $searchkey4, false, false);
1443 $conditions[] = $middlename;
1445 // Search by alternatename.
1446 $alternatename = $DB->sql_like('alternatename', ':' . $searchkey5, false, false);
1447 $conditions[] = $alternatename;
1449 // Search by firstnamephonetic.
1450 $firstnamephonetic = $DB->sql_like('firstnamephonetic', ':' . $searchkey6, false, false);
1451 $conditions[] = $firstnamephonetic;
1453 // Search by lastnamephonetic.
1454 $lastnamephonetic = $DB->sql_like('lastnamephonetic', ':' . $searchkey7, false, false);
1455 $conditions[] = $lastnamephonetic;
1457 $wheres[] = "(". implode(" OR ", $conditions) .") ";
1458 $params[$searchkey1] = "%$keyword%";
1459 $params[$searchkey2] = "%$keyword%";
1460 $params[$searchkey3] = "%$keyword%";
1461 $params[$searchkey4] = "%$keyword%";
1462 $params[$searchkey5] = "%$keyword%";
1463 $params[$searchkey6] = "%$keyword%";
1464 $params[$searchkey7] = "%$keyword%";
1468 if (!empty($additionalwhere)) {
1469 $wheres[] = $additionalwhere;
1470 $params = array_merge($params, $additionalparams);
1473 $from = implode("\n", $joins);
1474 if ($wheres) {
1475 $where = 'WHERE ' . implode(' AND ', $wheres);
1476 } else {
1477 $where = '';
1480 return array($select, $from, $where, $params);
1484 * Returns the total number of participants for a given course.
1486 * @param int $courseid The course id
1487 * @param int $groupid The groupid, 0 means all groups and USERSWITHOUTGROUP no group
1488 * @param int $accesssince The time since last access, 0 means any time
1489 * @param int $roleid The role id, 0 means all roles
1490 * @param int $enrolid The applied filter for the user enrolment ID.
1491 * @param int $status The applied filter for the user's enrolment status.
1492 * @param string|array $search The search that was performed, empty means perform no search
1493 * @param string $additionalwhere Any additional SQL to add to where
1494 * @param array $additionalparams The additional params
1495 * @return int
1497 function user_get_total_participants($courseid, $groupid = 0, $accesssince = 0, $roleid = 0, $enrolid = 0, $statusid = -1,
1498 $search = '', $additionalwhere = '', $additionalparams = array()) {
1499 global $DB;
1501 list($select, $from, $where, $params) = user_get_participants_sql($courseid, $groupid, $accesssince, $roleid, $enrolid,
1502 $statusid, $search, $additionalwhere, $additionalparams);
1504 return $DB->count_records_sql("SELECT COUNT(u.id) $from $where", $params);
1508 * Returns the participants for a given course.
1510 * @param int $courseid The course id
1511 * @param int $groupid The groupid, 0 means all groups and USERSWITHOUTGROUP no group
1512 * @param int $accesssince The time since last access
1513 * @param int $roleid The role id
1514 * @param int $enrolid The applied filter for the user enrolment ID.
1515 * @param int $status The applied filter for the user's enrolment status.
1516 * @param string $search The search that was performed
1517 * @param string $additionalwhere Any additional SQL to add to where
1518 * @param array $additionalparams The additional params
1519 * @param string $sort The SQL sort
1520 * @param int $limitfrom return a subset of records, starting at this point (optional).
1521 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1522 * @return moodle_recordset
1524 function user_get_participants($courseid, $groupid = 0, $accesssince, $roleid, $enrolid = 0, $statusid, $search,
1525 $additionalwhere = '', $additionalparams = array(), $sort = '', $limitfrom = 0, $limitnum = 0) {
1526 global $DB;
1528 list($select, $from, $where, $params) = user_get_participants_sql($courseid, $groupid, $accesssince, $roleid, $enrolid,
1529 $statusid, $search, $additionalwhere, $additionalparams);
1531 return $DB->get_recordset_sql("$select $from $where $sort", $params, $limitfrom, $limitnum);
1535 * Returns SQL that can be used to limit a query to a period where the user last accessed a course.
1537 * @param int $accesssince The time since last access
1538 * @param string $tableprefix
1539 * @return string
1541 function user_get_course_lastaccess_sql($accesssince = null, $tableprefix = 'ul') {
1542 if (empty($accesssince)) {
1543 return '';
1546 if ($accesssince == -1) { // Never.
1547 return $tableprefix . '.timeaccess = 0';
1548 } else {
1549 return $tableprefix . '.timeaccess != 0 AND ' . $tableprefix . '.timeaccess < ' . $accesssince;
1554 * Returns SQL that can be used to limit a query to a period where the user last accessed the system.
1556 * @param int $accesssince The time since last access
1557 * @param string $tableprefix
1558 * @return string
1560 function user_get_user_lastaccess_sql($accesssince = null, $tableprefix = 'u') {
1561 if (empty($accesssince)) {
1562 return '';
1565 if ($accesssince == -1) { // Never.
1566 return $tableprefix . '.lastaccess = 0';
1567 } else {
1568 return $tableprefix . '.lastaccess != 0 AND ' . $tableprefix . '.lastaccess < ' . $accesssince;
1573 * Callback for inplace editable API.
1575 * @param string $itemtype - Only user_roles is supported.
1576 * @param string $itemid - Courseid and userid separated by a :
1577 * @param string $newvalue - json encoded list of roleids.
1578 * @return \core\output\inplace_editable
1580 function core_user_inplace_editable($itemtype, $itemid, $newvalue) {
1581 if ($itemtype === 'user_roles') {
1582 return \core_user\output\user_roles_editable::update($itemid, $newvalue);
1587 * Map an internal field name to a valid purpose from: "https://www.w3.org/TR/WCAG21/#input-purposes"
1589 * @param integer $userid
1590 * @param string $fieldname
1591 * @return string $purpose (empty string if there is no mapping).
1593 function user_edit_map_field_purpose($userid, $fieldname) {
1594 global $USER;
1596 $currentuser = ($userid == $USER->id) && !\core\session\manager::is_loggedinas();
1597 // These are the fields considered valid to map and auto fill from a browser.
1598 // We do not include fields that are in a collapsed section by default because
1599 // the browser could auto-fill the field and cause a new value to be saved when
1600 // that field was never visible.
1601 $validmappings = array(
1602 'username' => 'username',
1603 'password' => 'current-password',
1604 'firstname' => 'given-name',
1605 'lastname' => 'family-name',
1606 'middlename' => 'additional-name',
1607 'email' => 'email',
1608 'country' => 'country',
1609 'lang' => 'language'
1612 $purpose = '';
1613 // Only set a purpose when editing your own user details.
1614 if ($currentuser && isset($validmappings[$fieldname])) {
1615 $purpose = ' autocomplete="' . $validmappings[$fieldname] . '" ';
1618 return $purpose;