NOBUG: Fix white space issue due to history rewrite.
[moodle.git] / user / lib.php
blob97303aa47823ee519b6bdc5f9d2613fbbcba058c
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 // All new users must have a starred self-conversation.
130 $selfconversation = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_SELF, [$newuserid]);
131 \core_message\api::set_favourite_conversation($selfconversation->id, $newuserid);
133 // Purge the associated caches for the current user only.
134 $presignupcache = \cache::make('core', 'presignup');
135 $presignupcache->purge_current_user();
137 return $newuserid;
141 * Update a user with a user object (will compare against the ID)
143 * @throws moodle_exception
144 * @param stdClass $user the user to update
145 * @param bool $updatepassword if true, authentication plugin will update password.
146 * @param bool $triggerevent set false if user_updated event should not be triggred.
147 * This will not affect user_password_updated event triggering.
149 function user_update_user($user, $updatepassword = true, $triggerevent = true) {
150 global $DB;
152 // Set the timecreate field to the current time.
153 if (!is_object($user)) {
154 $user = (object) $user;
157 // Check username.
158 if (isset($user->username)) {
159 if ($user->username !== core_text::strtolower($user->username)) {
160 throw new moodle_exception('usernamelowercase');
161 } else {
162 if ($user->username !== core_user::clean_field($user->username, 'username')) {
163 throw new moodle_exception('invalidusername');
168 // Unset password here, for updating later, if password update is required.
169 if ($updatepassword && isset($user->password)) {
171 // Check password toward the password policy.
172 if (!check_password_policy($user->password, $errmsg)) {
173 throw new moodle_exception($errmsg);
176 $passwd = $user->password;
177 unset($user->password);
180 // Make sure calendartype, if set, is valid.
181 if (empty($user->calendartype)) {
182 // Unset this variable, must be an empty string, which we do not want to update the calendartype to.
183 unset($user->calendartype);
186 $user->timemodified = time();
188 // Validate user data object.
189 $uservalidation = core_user::validate($user);
190 if ($uservalidation !== true) {
191 foreach ($uservalidation as $field => $message) {
192 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
193 $user->$field = core_user::clean_field($user->$field, $field);
197 $DB->update_record('user', $user);
199 if ($updatepassword) {
200 // Get full user record.
201 $updateduser = $DB->get_record('user', array('id' => $user->id));
203 // If password was set, then update its hash.
204 if (isset($passwd)) {
205 $authplugin = get_auth_plugin($updateduser->auth);
206 if ($authplugin->can_change_password()) {
207 $authplugin->user_update_password($updateduser, $passwd);
211 // Trigger event if required.
212 if ($triggerevent) {
213 \core\event\user_updated::create_from_userid($user->id)->trigger();
218 * Marks user deleted in internal user database and notifies the auth plugin.
219 * Also unenrols user from all roles and does other cleanup.
221 * @todo Decide if this transaction is really needed (look for internal TODO:)
222 * @param object $user Userobject before delete (without system magic quotes)
223 * @return boolean success
225 function user_delete_user($user) {
226 return delete_user($user);
230 * Get users by id
232 * @param array $userids id of users to retrieve
233 * @return array
235 function user_get_users_by_id($userids) {
236 global $DB;
237 return $DB->get_records_list('user', 'id', $userids);
241 * Returns the list of default 'displayable' fields
243 * Contains database field names but also names used to generate information, such as enrolledcourses
245 * @return array of user fields
247 function user_get_default_fields() {
248 return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
249 'address', 'phone1', 'phone2', 'icq', 'skype', 'yahoo', 'aim', 'msn', 'department',
250 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
251 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
252 'city', 'url', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
253 'groups', 'roles', 'preferences', 'enrolledcourses', 'suspended', 'lastcourseaccess'
259 * Give user record from mdl_user, build an array contains all user details.
261 * Warning: description file urls are 'webservice/pluginfile.php' is use.
262 * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
264 * @throws moodle_exception
265 * @param stdClass $user user record from mdl_user
266 * @param stdClass $course moodle course
267 * @param array $userfields required fields
268 * @return array|null
270 function user_get_user_details($user, $course = null, array $userfields = array()) {
271 global $USER, $DB, $CFG, $PAGE;
272 require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library.
273 require_once($CFG->dirroot . "/lib/filelib.php"); // File handling on description and friends.
275 $defaultfields = user_get_default_fields();
277 if (empty($userfields)) {
278 $userfields = $defaultfields;
281 foreach ($userfields as $thefield) {
282 if (!in_array($thefield, $defaultfields)) {
283 throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
287 // Make sure id and fullname are included.
288 if (!in_array('id', $userfields)) {
289 $userfields[] = 'id';
292 if (!in_array('fullname', $userfields)) {
293 $userfields[] = 'fullname';
296 if (!empty($course)) {
297 $context = context_course::instance($course->id);
298 $usercontext = context_user::instance($user->id);
299 $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext));
300 } else {
301 $context = context_user::instance($user->id);
302 $usercontext = $context;
303 $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
306 $currentuser = ($user->id == $USER->id);
307 $isadmin = is_siteadmin($USER);
309 $showuseridentityfields = get_extra_user_fields($context);
311 if (!empty($course)) {
312 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
313 } else {
314 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
316 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
317 if (!empty($course)) {
318 $canviewuseremail = has_capability('moodle/course:useremail', $context);
319 } else {
320 $canviewuseremail = false;
322 $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
323 if (!empty($course)) {
324 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
325 } else {
326 $canaccessallgroups = false;
329 if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
330 // Skip this user details.
331 return null;
334 $userdetails = array();
335 $userdetails['id'] = $user->id;
337 if (in_array('username', $userfields)) {
338 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
339 $userdetails['username'] = $user->username;
342 if ($isadmin or $canviewfullnames) {
343 if (in_array('firstname', $userfields)) {
344 $userdetails['firstname'] = $user->firstname;
346 if (in_array('lastname', $userfields)) {
347 $userdetails['lastname'] = $user->lastname;
350 $userdetails['fullname'] = fullname($user, $canviewfullnames);
352 if (in_array('customfields', $userfields)) {
353 $categories = profile_get_user_fields_with_data_by_category($user->id);
354 $userdetails['customfields'] = array();
355 foreach ($categories as $categoryid => $fields) {
356 foreach ($fields as $formfield) {
357 if ($formfield->is_visible() and !$formfield->is_empty()) {
359 // TODO: Part of MDL-50728, this conditional coding must be moved to
360 // proper profile fields API so they are self-contained.
361 // We only use display_data in fields that require text formatting.
362 if ($formfield->field->datatype == 'text' or $formfield->field->datatype == 'textarea') {
363 $fieldvalue = $formfield->display_data();
364 } else {
365 // Cases: datetime, checkbox and menu.
366 $fieldvalue = $formfield->data;
369 $userdetails['customfields'][] =
370 array('name' => $formfield->field->name, 'value' => $fieldvalue,
371 'type' => $formfield->field->datatype, 'shortname' => $formfield->field->shortname);
375 // Unset customfields if it's empty.
376 if (empty($userdetails['customfields'])) {
377 unset($userdetails['customfields']);
381 // Profile image.
382 if (in_array('profileimageurl', $userfields)) {
383 $userpicture = new user_picture($user);
384 $userpicture->size = 1; // Size f1.
385 $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
387 if (in_array('profileimageurlsmall', $userfields)) {
388 if (!isset($userpicture)) {
389 $userpicture = new user_picture($user);
391 $userpicture->size = 0; // Size f2.
392 $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
395 // Hidden user field.
396 if ($canviewhiddenuserfields) {
397 $hiddenfields = array();
398 // Address, phone1 and phone2 not appears in hidden fields list but require viewhiddenfields capability
399 // according to user/profile.php.
400 if (!empty($user->address) && in_array('address', $userfields)) {
401 $userdetails['address'] = $user->address;
403 } else {
404 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
407 if (!empty($user->phone1) && in_array('phone1', $userfields) &&
408 (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) {
409 $userdetails['phone1'] = $user->phone1;
411 if (!empty($user->phone2) && in_array('phone2', $userfields) &&
412 (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) {
413 $userdetails['phone2'] = $user->phone2;
416 if (isset($user->description) &&
417 ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
418 if (in_array('description', $userfields)) {
419 // Always return the descriptionformat if description is requested.
420 list($userdetails['description'], $userdetails['descriptionformat']) =
421 external_format_text($user->description, $user->descriptionformat,
422 $usercontext->id, 'user', 'profile', null);
426 if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
427 $userdetails['country'] = $user->country;
430 if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
431 $userdetails['city'] = $user->city;
434 if (in_array('url', $userfields) && $user->url && (!isset($hiddenfields['webpage']) or $isadmin)) {
435 $url = $user->url;
436 if (strpos($user->url, '://') === false) {
437 $url = 'http://'. $url;
439 $user->url = clean_param($user->url, PARAM_URL);
440 $userdetails['url'] = $user->url;
443 if (in_array('icq', $userfields) && $user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) {
444 $userdetails['icq'] = $user->icq;
447 if (in_array('skype', $userfields) && $user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) {
448 $userdetails['skype'] = $user->skype;
450 if (in_array('yahoo', $userfields) && $user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) {
451 $userdetails['yahoo'] = $user->yahoo;
453 if (in_array('aim', $userfields) && $user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) {
454 $userdetails['aim'] = $user->aim;
456 if (in_array('msn', $userfields) && $user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) {
457 $userdetails['msn'] = $user->msn;
459 if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) {
460 $userdetails['suspended'] = (bool)$user->suspended;
463 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
464 if ($user->firstaccess) {
465 $userdetails['firstaccess'] = $user->firstaccess;
466 } else {
467 $userdetails['firstaccess'] = 0;
470 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
471 if ($user->lastaccess) {
472 $userdetails['lastaccess'] = $user->lastaccess;
473 } else {
474 $userdetails['lastaccess'] = 0;
478 // Hidden fields restriction to lastaccess field applies to both site and course access time.
479 if (in_array('lastcourseaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
480 if (isset($user->lastcourseaccess)) {
481 $userdetails['lastcourseaccess'] = $user->lastcourseaccess;
482 } else {
483 $userdetails['lastcourseaccess'] = 0;
487 if (in_array('email', $userfields) && (
488 $currentuser
489 or (!isset($hiddenfields['email']) and (
490 $user->maildisplay == core_user::MAILDISPLAY_EVERYONE
491 or ($user->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY and enrol_sharing_course($user, $USER))
492 or $canviewuseremail // TODO: Deprecate/remove for MDL-37479.
494 or in_array('email', $showuseridentityfields)
495 )) {
496 $userdetails['email'] = $user->email;
499 if (in_array('interests', $userfields)) {
500 $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
501 if ($interests) {
502 $userdetails['interests'] = join(', ', $interests);
506 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
507 if (in_array('idnumber', $userfields) && $user->idnumber) {
508 if (in_array('idnumber', $showuseridentityfields) or $currentuser or
509 has_capability('moodle/user:viewalldetails', $context)) {
510 $userdetails['idnumber'] = $user->idnumber;
513 if (in_array('institution', $userfields) && $user->institution) {
514 if (in_array('institution', $showuseridentityfields) or $currentuser or
515 has_capability('moodle/user:viewalldetails', $context)) {
516 $userdetails['institution'] = $user->institution;
519 // Isset because it's ok to have department 0.
520 if (in_array('department', $userfields) && isset($user->department)) {
521 if (in_array('department', $showuseridentityfields) or $currentuser or
522 has_capability('moodle/user:viewalldetails', $context)) {
523 $userdetails['department'] = $user->department;
527 if (in_array('roles', $userfields) && !empty($course)) {
528 // Not a big secret.
529 $roles = get_user_roles($context, $user->id, false);
530 $userdetails['roles'] = array();
531 foreach ($roles as $role) {
532 $userdetails['roles'][] = array(
533 'roleid' => $role->roleid,
534 'name' => $role->name,
535 'shortname' => $role->shortname,
536 'sortorder' => $role->sortorder
541 // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
542 if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
543 $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid,
544 'g.id, g.name,g.description,g.descriptionformat');
545 $userdetails['groups'] = array();
546 foreach ($usergroups as $group) {
547 list($group->description, $group->descriptionformat) =
548 external_format_text($group->description, $group->descriptionformat,
549 $context->id, 'group', 'description', $group->id);
550 $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name,
551 'description' => $group->description, 'descriptionformat' => $group->descriptionformat);
554 // List of courses where the user is enrolled.
555 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
556 $enrolledcourses = array();
557 if ($mycourses = enrol_get_users_courses($user->id, true)) {
558 foreach ($mycourses as $mycourse) {
559 if ($mycourse->category) {
560 $coursecontext = context_course::instance($mycourse->id);
561 $enrolledcourse = array();
562 $enrolledcourse['id'] = $mycourse->id;
563 $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
564 $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
565 $enrolledcourses[] = $enrolledcourse;
568 $userdetails['enrolledcourses'] = $enrolledcourses;
572 // User preferences.
573 if (in_array('preferences', $userfields) && $currentuser) {
574 $preferences = array();
575 $userpreferences = get_user_preferences();
576 foreach ($userpreferences as $prefname => $prefvalue) {
577 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
579 $userdetails['preferences'] = $preferences;
582 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
583 $extrafields = ['auth', 'confirmed', 'lang', 'theme', 'timezone', 'mailformat'];
584 foreach ($extrafields as $extrafield) {
585 if (in_array($extrafield, $userfields) && isset($user->$extrafield)) {
586 $userdetails[$extrafield] = $user->$extrafield;
591 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
592 if (isset($userdetails['lang'])) {
593 $userdetails['lang'] = clean_param($userdetails['lang'], PARAM_LANG);
595 if (isset($userdetails['theme'])) {
596 $userdetails['theme'] = clean_param($userdetails['theme'], PARAM_THEME);
599 return $userdetails;
603 * Tries to obtain user details, either recurring directly to the user's system profile
604 * or through one of the user's course enrollments (course profile).
606 * @param stdClass $user The user.
607 * @return array if unsuccessful or the allowed user details.
609 function user_get_user_details_courses($user) {
610 global $USER;
611 $userdetails = null;
613 $systemprofile = false;
614 if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
615 $systemprofile = true;
618 // Try using system profile.
619 if ($systemprofile) {
620 $userdetails = user_get_user_details($user, null);
621 } else {
622 // Try through course profile.
623 // Get the courses that the user is enrolled in (only active).
624 $courses = enrol_get_users_courses($user->id, true);
625 foreach ($courses as $course) {
626 if (user_can_view_profile($user, $course)) {
627 $userdetails = user_get_user_details($user, $course);
632 return $userdetails;
636 * Check if $USER have the necessary capabilities to obtain user details.
638 * @param stdClass $user
639 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
640 * @return bool true if $USER can view user details.
642 function can_view_user_details_cap($user, $course = null) {
643 // Check $USER has the capability to view the user details at user context.
644 $usercontext = context_user::instance($user->id);
645 $result = has_capability('moodle/user:viewdetails', $usercontext);
646 // Otherwise can $USER see them at course context.
647 if (!$result && !empty($course)) {
648 $context = context_course::instance($course->id);
649 $result = has_capability('moodle/user:viewdetails', $context);
651 return $result;
655 * Return a list of page types
656 * @param string $pagetype current page type
657 * @param stdClass $parentcontext Block's parent context
658 * @param stdClass $currentcontext Current context of block
659 * @return array
661 function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
662 return array('user-profile' => get_string('page-user-profile', 'pagetype'));
666 * Count the number of failed login attempts for the given user, since last successful login.
668 * @param int|stdclass $user user id or object.
669 * @param bool $reset Resets failed login count, if set to true.
671 * @return int number of failed login attempts since the last successful login.
673 function user_count_login_failures($user, $reset = true) {
674 global $DB;
676 if (!is_object($user)) {
677 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
679 if ($user->deleted) {
680 // Deleted user, nothing to do.
681 return 0;
683 $count = get_user_preferences('login_failed_count_since_success', 0, $user);
684 if ($reset) {
685 set_user_preference('login_failed_count_since_success', 0, $user);
687 return $count;
691 * Converts a string into a flat array of menu items, where each menu items is a
692 * stdClass with fields type, url, title, pix, and imgsrc.
694 * @param string $text the menu items definition
695 * @param moodle_page $page the current page
696 * @return array
698 function user_convert_text_to_menu_items($text, $page) {
699 global $OUTPUT, $CFG;
701 $lines = explode("\n", $text);
702 $items = array();
703 $lastchild = null;
704 $lastdepth = null;
705 $lastsort = 0;
706 $children = array();
707 foreach ($lines as $line) {
708 $line = trim($line);
709 $bits = explode('|', $line, 3);
710 $itemtype = 'link';
711 if (preg_match("/^#+$/", $line)) {
712 $itemtype = 'divider';
713 } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
714 // Every item must have a name to be valid.
715 continue;
716 } else {
717 $bits[0] = ltrim($bits[0], '-');
720 // Create the child.
721 $child = new stdClass();
722 $child->itemtype = $itemtype;
723 if ($itemtype === 'divider') {
724 // Add the divider to the list of children and skip link
725 // processing.
726 $children[] = $child;
727 continue;
730 // Name processing.
731 $namebits = explode(',', $bits[0], 2);
732 if (count($namebits) == 2) {
733 // Check the validity of the identifier part of the string.
734 if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
735 // Treat this as a language string.
736 $child->title = get_string($namebits[0], $namebits[1]);
737 $child->titleidentifier = implode(',', $namebits);
740 if (empty($child->title)) {
741 // Use it as is, don't even clean it.
742 $child->title = $bits[0];
743 $child->titleidentifier = str_replace(" ", "-", $bits[0]);
746 // URL processing.
747 if (!array_key_exists(1, $bits) or empty($bits[1])) {
748 // Set the url to null, and set the itemtype to invalid.
749 $bits[1] = null;
750 $child->itemtype = "invalid";
751 } else {
752 // Nasty hack to replace the grades with the direct url.
753 if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
754 $bits[1] = user_mygrades_url();
757 // Make sure the url is a moodle url.
758 $bits[1] = new moodle_url(trim($bits[1]));
760 $child->url = $bits[1];
762 // PIX processing.
763 $pixpath = "t/edit";
764 if (!array_key_exists(2, $bits) or empty($bits[2])) {
765 // Use the default.
766 $child->pix = $pixpath;
767 } else {
768 // Check for the specified image existing.
769 if (strpos($bits[2], '../') === 0) {
770 // The string starts with '../'.
771 // Strip off the first three characters - this should be the pix path.
772 $pixpath = substr($bits[2], 3);
773 } else if (strpos($bits[2], '/') === false) {
774 // There is no / in the path. Prefix it with 't/', which is the default path.
775 $pixpath = "t/{$bits[2]}";
776 } else {
777 // There is a '/' in the path - this is either a URL, or a standard pix path with no changes required.
778 $pixpath = $bits[2];
780 if ($page->theme->resolve_image_location($pixpath, 'moodle', true)) {
781 // Use the image.
782 $child->pix = $pixpath;
783 } else {
784 // Treat it like a URL.
785 $child->pix = null;
786 $child->imgsrc = $bits[2];
790 // Add this child to the list of children.
791 $children[] = $child;
793 return $children;
797 * Get a list of essential user navigation items.
799 * @param stdclass $user user object.
800 * @param moodle_page $page page object.
801 * @param array $options associative array.
802 * options are:
803 * - avatarsize=35 (size of avatar image)
804 * @return stdClass $returnobj navigation information object, where:
806 * $returnobj->navitems array array of links where each link is a
807 * stdClass with fields url, title, and
808 * pix
809 * $returnobj->metadata array array of useful user metadata to be
810 * used when constructing navigation;
811 * fields include:
813 * ROLE FIELDS
814 * asotherrole bool whether viewing as another role
815 * rolename string name of the role
817 * USER FIELDS
818 * These fields are for the currently-logged in user, or for
819 * the user that the real user is currently logged in as.
821 * userid int the id of the user in question
822 * userfullname string the user's full name
823 * userprofileurl moodle_url the url of the user's profile
824 * useravatar string a HTML fragment - the rendered
825 * user_picture for this user
826 * userloginfail string an error string denoting the number
827 * of login failures since last login
829 * "REAL USER" FIELDS
830 * These fields are for when asotheruser is true, and
831 * correspond to the underlying "real user".
833 * asotheruser bool whether viewing as another user
834 * realuserid int the id of the user in question
835 * realuserfullname string the user's full name
836 * realuserprofileurl moodle_url the url of the user's profile
837 * realuseravatar string a HTML fragment - the rendered
838 * user_picture for this user
840 * MNET PROVIDER FIELDS
841 * asmnetuser bool whether viewing as a user from an
842 * MNet provider
843 * mnetidprovidername string name of the MNet provider
844 * mnetidproviderwwwroot string URL of the MNet provider
846 function user_get_user_navigation_info($user, $page, $options = array()) {
847 global $OUTPUT, $DB, $SESSION, $CFG;
849 $returnobject = new stdClass();
850 $returnobject->navitems = array();
851 $returnobject->metadata = array();
853 $course = $page->course;
855 // Query the environment.
856 $context = context_course::instance($course->id);
858 // Get basic user metadata.
859 $returnobject->metadata['userid'] = $user->id;
860 $returnobject->metadata['userfullname'] = fullname($user, true);
861 $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
862 'id' => $user->id
865 $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
866 if (!empty($options['avatarsize'])) {
867 $avataroptions['size'] = $options['avatarsize'];
869 $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
870 $user, $avataroptions
872 // Build a list of items for a regular user.
874 // Query MNet status.
875 if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
876 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
877 $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
878 $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
881 // Did the user just log in?
882 if (isset($SESSION->justloggedin)) {
883 // Don't unset this flag as login_info still needs it.
884 if (!empty($CFG->displayloginfailures)) {
885 // Don't reset the count either, as login_info() still needs it too.
886 if ($count = user_count_login_failures($user, false)) {
888 // Get login failures string.
889 $a = new stdClass();
890 $a->attempts = html_writer::tag('span', $count, array('class' => 'value'));
891 $returnobject->metadata['userloginfail'] =
892 get_string('failedloginattempts', '', $a);
898 // Links: Dashboard.
899 $myhome = new stdClass();
900 $myhome->itemtype = 'link';
901 $myhome->url = new moodle_url('/my/');
902 $myhome->title = get_string('mymoodle', 'admin');
903 $myhome->titleidentifier = 'mymoodle,admin';
904 $myhome->pix = "i/dashboard";
905 $returnobject->navitems[] = $myhome;
907 // Links: My Profile.
908 $myprofile = new stdClass();
909 $myprofile->itemtype = 'link';
910 $myprofile->url = new moodle_url('/user/profile.php', array('id' => $user->id));
911 $myprofile->title = get_string('profile');
912 $myprofile->titleidentifier = 'profile,moodle';
913 $myprofile->pix = "i/user";
914 $returnobject->navitems[] = $myprofile;
916 $returnobject->metadata['asotherrole'] = false;
918 // Before we add the last items (usually a logout + switch role link), add any
919 // custom-defined items.
920 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
921 foreach ($customitems as $item) {
922 $returnobject->navitems[] = $item;
926 if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
927 $realuser = \core\session\manager::get_realuser();
929 // Save values for the real user, as $user will be full of data for the
930 // user the user is disguised as.
931 $returnobject->metadata['realuserid'] = $realuser->id;
932 $returnobject->metadata['realuserfullname'] = fullname($realuser, true);
933 $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', array(
934 'id' => $realuser->id
936 $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
938 // Build a user-revert link.
939 $userrevert = new stdClass();
940 $userrevert->itemtype = 'link';
941 $userrevert->url = new moodle_url('/course/loginas.php', array(
942 'id' => $course->id,
943 'sesskey' => sesskey()
945 $userrevert->pix = "a/logout";
946 $userrevert->title = get_string('logout');
947 $userrevert->titleidentifier = 'logout,moodle';
948 $returnobject->navitems[] = $userrevert;
950 } else {
952 // Build a logout link.
953 $logout = new stdClass();
954 $logout->itemtype = 'link';
955 $logout->url = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
956 $logout->pix = "a/logout";
957 $logout->title = get_string('logout');
958 $logout->titleidentifier = 'logout,moodle';
959 $returnobject->navitems[] = $logout;
962 if (is_role_switched($course->id)) {
963 if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
964 // Build role-return link instead of logout link.
965 $rolereturn = new stdClass();
966 $rolereturn->itemtype = 'link';
967 $rolereturn->url = new moodle_url('/course/switchrole.php', array(
968 'id' => $course->id,
969 'sesskey' => sesskey(),
970 'switchrole' => 0,
971 'returnurl' => $page->url->out_as_local_url(false)
973 $rolereturn->pix = "a/logout";
974 $rolereturn->title = get_string('switchrolereturn');
975 $rolereturn->titleidentifier = 'switchrolereturn,moodle';
976 $returnobject->navitems[] = $rolereturn;
978 $returnobject->metadata['asotherrole'] = true;
979 $returnobject->metadata['rolename'] = role_get_name($role, $context);
982 } else {
983 // Build switch role link.
984 $roles = get_switchable_roles($context);
985 if (is_array($roles) && (count($roles) > 0)) {
986 $switchrole = new stdClass();
987 $switchrole->itemtype = 'link';
988 $switchrole->url = new moodle_url('/course/switchrole.php', array(
989 'id' => $course->id,
990 'switchrole' => -1,
991 'returnurl' => $page->url->out_as_local_url(false)
993 $switchrole->pix = "i/switchrole";
994 $switchrole->title = get_string('switchroleto');
995 $switchrole->titleidentifier = 'switchroleto,moodle';
996 $returnobject->navitems[] = $switchrole;
1000 return $returnobject;
1004 * Add password to the list of used hashes for this user.
1006 * This is supposed to be used from:
1007 * 1/ change own password form
1008 * 2/ password reset process
1009 * 3/ user signup in auth plugins if password changing supported
1011 * @param int $userid user id
1012 * @param string $password plaintext password
1013 * @return void
1015 function user_add_password_history($userid, $password) {
1016 global $CFG, $DB;
1018 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1019 return;
1022 // Note: this is using separate code form normal password hashing because
1023 // we need to have this under control in the future. Also the auth
1024 // plugin might not store the passwords locally at all.
1026 $record = new stdClass();
1027 $record->userid = $userid;
1028 $record->hash = password_hash($password, PASSWORD_DEFAULT);
1029 $record->timecreated = time();
1030 $DB->insert_record('user_password_history', $record);
1032 $i = 0;
1033 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1034 foreach ($records as $record) {
1035 $i++;
1036 if ($i > $CFG->passwordreuselimit) {
1037 $DB->delete_records('user_password_history', array('id' => $record->id));
1043 * Was this password used before on change or reset password page?
1045 * The $CFG->passwordreuselimit setting determines
1046 * how many times different password needs to be used
1047 * before allowing previously used password again.
1049 * @param int $userid user id
1050 * @param string $password plaintext password
1051 * @return bool true if password reused
1053 function user_is_previously_used_password($userid, $password) {
1054 global $CFG, $DB;
1056 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1057 return false;
1060 $reused = false;
1062 $i = 0;
1063 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1064 foreach ($records as $record) {
1065 $i++;
1066 if ($i > $CFG->passwordreuselimit) {
1067 $DB->delete_records('user_password_history', array('id' => $record->id));
1068 continue;
1070 // NOTE: this is slow but we cannot compare the hashes directly any more.
1071 if (password_verify($password, $record->hash)) {
1072 $reused = true;
1076 return $reused;
1080 * Remove a user device from the Moodle database (for PUSH notifications usually).
1082 * @param string $uuid The device UUID.
1083 * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1084 * @return bool true if removed, false if the device didn't exists in the database
1085 * @since Moodle 2.9
1087 function user_remove_user_device($uuid, $appid = "") {
1088 global $DB, $USER;
1090 $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
1091 if (!empty($appid)) {
1092 $conditions['appid'] = $appid;
1095 if (!$DB->count_records('user_devices', $conditions)) {
1096 return false;
1099 $DB->delete_records('user_devices', $conditions);
1101 return true;
1105 * Trigger user_list_viewed event.
1107 * @param stdClass $course course object
1108 * @param stdClass $context course context object
1109 * @since Moodle 2.9
1111 function user_list_view($course, $context) {
1113 $event = \core\event\user_list_viewed::create(array(
1114 'objectid' => $course->id,
1115 'courseid' => $course->id,
1116 'context' => $context,
1117 'other' => array(
1118 'courseshortname' => $course->shortname,
1119 'coursefullname' => $course->fullname
1122 $event->trigger();
1126 * Returns the url to use for the "Grades" link in the user navigation.
1128 * @param int $userid The user's ID.
1129 * @param int $courseid The course ID if available.
1130 * @return mixed A URL to be directed to for "Grades".
1132 function user_mygrades_url($userid = null, $courseid = SITEID) {
1133 global $CFG, $USER;
1134 $url = null;
1135 if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
1136 if (isset($userid) && $USER->id != $userid) {
1137 // Send to the gradebook report.
1138 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
1139 array('id' => $courseid, 'userid' => $userid));
1140 } else {
1141 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
1143 } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
1144 && !empty($CFG->gradereport_mygradeurl)) {
1145 $url = $CFG->gradereport_mygradeurl;
1146 } else {
1147 $url = $CFG->wwwroot;
1149 return $url;
1153 * Check if the current user has permission to view details of the supplied user.
1155 * This function supports two modes:
1156 * If the optional $course param is omitted, then this function finds all shared courses and checks whether the current user has
1157 * permission in any of them, returning true if so.
1158 * If the $course param is provided, then this function checks permissions in ONLY that course.
1160 * @param object $user The other user's details.
1161 * @param object $course if provided, only check permissions in this course.
1162 * @param context $usercontext The user context if available.
1163 * @return bool true for ability to view this user, else false.
1165 function user_can_view_profile($user, $course = null, $usercontext = null) {
1166 global $USER, $CFG;
1168 if ($user->deleted) {
1169 return false;
1172 // Do we need to be logged in?
1173 if (empty($CFG->forceloginforprofiles)) {
1174 return true;
1175 } else {
1176 if (!isloggedin() || isguestuser()) {
1177 // User is not logged in and forceloginforprofile is set, we need to return now.
1178 return false;
1182 // Current user can always view their profile.
1183 if ($USER->id == $user->id) {
1184 return true;
1187 // Use callbacks so that (primarily) local plugins can prevent or allow profile access.
1188 $forceallow = false;
1189 $plugintypes = get_plugins_with_function('control_view_profile');
1190 foreach ($plugintypes as $plugins) {
1191 foreach ($plugins as $pluginfunction) {
1192 $result = $pluginfunction($user, $course, $usercontext);
1193 switch ($result) {
1194 case core_user::VIEWPROFILE_DO_NOT_PREVENT:
1195 // If the plugin doesn't stop access, just continue to next plugin or use
1196 // default behaviour.
1197 break;
1198 case core_user::VIEWPROFILE_FORCE_ALLOW:
1199 // Record that we are definitely going to allow it (unless another plugin
1200 // returns _PREVENT).
1201 $forceallow = true;
1202 break;
1203 case core_user::VIEWPROFILE_PREVENT:
1204 // If any plugin returns PREVENT then we return false, regardless of what
1205 // other plugins said.
1206 return false;
1210 if ($forceallow) {
1211 return true;
1214 // Course contacts have visible profiles always.
1215 if (has_coursecontact_role($user->id)) {
1216 return true;
1219 // If we're only checking the capabilities in the single provided course.
1220 if (isset($course)) {
1221 // Confirm that $user is enrolled in the $course we're checking.
1222 if (is_enrolled(context_course::instance($course->id), $user)) {
1223 $userscourses = array($course);
1225 } else {
1226 // Else we're checking whether the current user can view $user's profile anywhere, so check user context first.
1227 if (empty($usercontext)) {
1228 $usercontext = context_user::instance($user->id);
1230 if (has_capability('moodle/user:viewdetails', $usercontext) || has_capability('moodle/user:viewalldetails', $usercontext)) {
1231 return true;
1233 // This returns context information, so we can preload below.
1234 $userscourses = enrol_get_all_users_courses($user->id);
1237 if (empty($userscourses)) {
1238 return false;
1241 foreach ($userscourses as $userscourse) {
1242 context_helper::preload_from_record($userscourse);
1243 $coursecontext = context_course::instance($userscourse->id);
1244 if (has_capability('moodle/user:viewdetails', $coursecontext) ||
1245 has_capability('moodle/user:viewalldetails', $coursecontext)) {
1246 if (!groups_user_groups_visible($userscourse, $user->id)) {
1247 // Not a member of the same group.
1248 continue;
1250 return true;
1253 return false;
1257 * Returns users tagged with a specified tag.
1259 * @param core_tag_tag $tag
1260 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1261 * are displayed on the page and the per-page limit may be bigger
1262 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1263 * to display items in the same context first
1264 * @param int $ctx context id where to search for records
1265 * @param bool $rec search in subcontexts as well
1266 * @param int $page 0-based number of page being displayed
1267 * @return \core_tag\output\tagindex
1269 function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1270 global $PAGE;
1272 if ($ctx && $ctx != context_system::instance()->id) {
1273 $usercount = 0;
1274 } else {
1275 // Users can only be displayed in system context.
1276 $usercount = $tag->count_tagged_items('core', 'user',
1277 'it.deleted=:notdeleted', array('notdeleted' => 0));
1279 $perpage = $exclusivemode ? 24 : 5;
1280 $content = '';
1281 $totalpages = ceil($usercount / $perpage);
1283 if ($usercount) {
1284 $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage,
1285 'it.deleted=:notdeleted', array('notdeleted' => 0));
1286 $renderer = $PAGE->get_renderer('core', 'user');
1287 $content .= $renderer->user_list($userlist, $exclusivemode);
1290 return new core_tag\output\tagindex($tag, 'core', 'user', $content,
1291 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1295 * Returns the SQL used by the participants table.
1297 * @param int $courseid The course id
1298 * @param int $groupid The groupid, 0 means all groups and USERSWITHOUTGROUP no group
1299 * @param int $accesssince The time since last access, 0 means any time
1300 * @param int $roleid The role id, 0 means all roles
1301 * @param int $enrolid The enrolment id, 0 means all enrolment methods will be returned.
1302 * @param int $statusid The user enrolment status, -1 means all enrolments regardless of the status will be returned, if allowed.
1303 * @param string|array $search The search that was performed, empty means perform no search
1304 * @param string $additionalwhere Any additional SQL to add to where
1305 * @param array $additionalparams The additional params
1306 * @return array
1308 function user_get_participants_sql($courseid, $groupid = 0, $accesssince = 0, $roleid = 0, $enrolid = 0, $statusid = -1,
1309 $search = '', $additionalwhere = '', $additionalparams = array()) {
1310 global $DB, $USER, $CFG;
1312 // Get the context.
1313 $context = \context_course::instance($courseid, MUST_EXIST);
1315 $isfrontpage = ($courseid == SITEID);
1317 // Default filter settings. We only show active by default, especially if the user has no capability to review enrolments.
1318 $onlyactive = true;
1319 $onlysuspended = false;
1320 if (has_capability('moodle/course:enrolreview', $context)) {
1321 switch ($statusid) {
1322 case ENROL_USER_ACTIVE:
1323 // Nothing to do here.
1324 break;
1325 case ENROL_USER_SUSPENDED:
1326 $onlyactive = false;
1327 $onlysuspended = true;
1328 break;
1329 default:
1330 // If the user has capability to review user enrolments, but statusid is set to -1, set $onlyactive to false.
1331 $onlyactive = false;
1332 break;
1336 list($esql, $params) = get_enrolled_sql($context, null, $groupid, $onlyactive, $onlysuspended, $enrolid);
1338 $joins = array('FROM {user} u');
1339 $wheres = array();
1341 $userfields = get_extra_user_fields($context);
1342 $userfieldssql = user_picture::fields('u', $userfields);
1344 if ($isfrontpage) {
1345 $select = "SELECT $userfieldssql, u.lastaccess";
1346 $joins[] = "JOIN ($esql) e ON e.id = u.id"; // Everybody on the frontpage usually.
1347 if ($accesssince) {
1348 $wheres[] = user_get_user_lastaccess_sql($accesssince);
1350 } else {
1351 $select = "SELECT $userfieldssql, COALESCE(ul.timeaccess, 0) AS lastaccess";
1352 $joins[] = "JOIN ($esql) e ON e.id = u.id"; // Course enrolled users only.
1353 // Not everybody has accessed the course yet.
1354 $joins[] = 'LEFT JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = :courseid)';
1355 $params['courseid'] = $courseid;
1356 if ($accesssince) {
1357 $wheres[] = user_get_course_lastaccess_sql($accesssince);
1361 // Performance hacks - we preload user contexts together with accounts.
1362 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1363 $ccjoin = 'LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)';
1364 $params['contextlevel'] = CONTEXT_USER;
1365 $select .= $ccselect;
1366 $joins[] = $ccjoin;
1368 // Limit list to users with some role only.
1369 if ($roleid) {
1370 // We want to query both the current context and parent contexts.
1371 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true),
1372 SQL_PARAMS_NAMED, 'relatedctx');
1374 $wheres[] = "u.id IN (SELECT userid FROM {role_assignments} WHERE roleid = :roleid AND contextid $relatedctxsql)";
1375 $params = array_merge($params, array('roleid' => $roleid), $relatedctxparams);
1378 if (!empty($search)) {
1379 if (!is_array($search)) {
1380 $search = [$search];
1382 foreach ($search as $index => $keyword) {
1383 $searchkey1 = 'search' . $index . '1';
1384 $searchkey2 = 'search' . $index . '2';
1385 $searchkey3 = 'search' . $index . '3';
1386 $searchkey4 = 'search' . $index . '4';
1387 $searchkey5 = 'search' . $index . '5';
1388 $searchkey6 = 'search' . $index . '6';
1389 $searchkey7 = 'search' . $index . '7';
1391 $conditions = array();
1392 // Search by fullname.
1393 $fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
1394 $conditions[] = $DB->sql_like($fullname, ':' . $searchkey1, false, false);
1396 // Search by email.
1397 $email = $DB->sql_like('email', ':' . $searchkey2, false, false);
1398 if (!in_array('email', $userfields)) {
1399 $maildisplay = 'maildisplay' . $index;
1400 $userid1 = 'userid' . $index . '1';
1401 // Prevent users who hide their email address from being found by others
1402 // who aren't allowed to see hidden email addresses.
1403 $email = "(". $email ." AND (" .
1404 "u.maildisplay <> :$maildisplay " .
1405 "OR u.id = :$userid1". // User can always find himself.
1406 "))";
1407 $params[$maildisplay] = core_user::MAILDISPLAY_HIDE;
1408 $params[$userid1] = $USER->id;
1410 $conditions[] = $email;
1412 // Search by idnumber.
1413 $idnumber = $DB->sql_like('idnumber', ':' . $searchkey3, false, false);
1414 if (!in_array('idnumber', $userfields)) {
1415 $userid2 = 'userid' . $index . '2';
1416 // Users who aren't allowed to see idnumbers should at most find themselves
1417 // when searching for an idnumber.
1418 $idnumber = "(". $idnumber . " AND u.id = :$userid2)";
1419 $params[$userid2] = $USER->id;
1421 $conditions[] = $idnumber;
1423 if (!empty($CFG->showuseridentity)) {
1424 // Search all user identify fields.
1425 $extrasearchfields = explode(',', $CFG->showuseridentity);
1426 foreach ($extrasearchfields as $extrasearchfield) {
1427 if (in_array($extrasearchfield, ['email', 'idnumber', 'country'])) {
1428 // Already covered above. Search by country not supported.
1429 continue;
1431 $param = $searchkey3 . $extrasearchfield;
1432 $condition = $DB->sql_like($extrasearchfield, ':' . $param, false, false);
1433 $params[$param] = "%$keyword%";
1434 if (!in_array($extrasearchfield, $userfields)) {
1435 // User cannot see this field, but allow match if their own account.
1436 $userid3 = 'userid' . $index . '3' . $extrasearchfield;
1437 $condition = "(". $condition . " AND u.id = :$userid3)";
1438 $params[$userid3] = $USER->id;
1440 $conditions[] = $condition;
1444 // Search by middlename.
1445 $middlename = $DB->sql_like('middlename', ':' . $searchkey4, false, false);
1446 $conditions[] = $middlename;
1448 // Search by alternatename.
1449 $alternatename = $DB->sql_like('alternatename', ':' . $searchkey5, false, false);
1450 $conditions[] = $alternatename;
1452 // Search by firstnamephonetic.
1453 $firstnamephonetic = $DB->sql_like('firstnamephonetic', ':' . $searchkey6, false, false);
1454 $conditions[] = $firstnamephonetic;
1456 // Search by lastnamephonetic.
1457 $lastnamephonetic = $DB->sql_like('lastnamephonetic', ':' . $searchkey7, false, false);
1458 $conditions[] = $lastnamephonetic;
1460 $wheres[] = "(". implode(" OR ", $conditions) .") ";
1461 $params[$searchkey1] = "%$keyword%";
1462 $params[$searchkey2] = "%$keyword%";
1463 $params[$searchkey3] = "%$keyword%";
1464 $params[$searchkey4] = "%$keyword%";
1465 $params[$searchkey5] = "%$keyword%";
1466 $params[$searchkey6] = "%$keyword%";
1467 $params[$searchkey7] = "%$keyword%";
1471 if (!empty($additionalwhere)) {
1472 $wheres[] = $additionalwhere;
1473 $params = array_merge($params, $additionalparams);
1476 $from = implode("\n", $joins);
1477 if ($wheres) {
1478 $where = 'WHERE ' . implode(' AND ', $wheres);
1479 } else {
1480 $where = '';
1483 return array($select, $from, $where, $params);
1487 * Returns the total number of participants for a given course.
1489 * @param int $courseid The course id
1490 * @param int $groupid The groupid, 0 means all groups and USERSWITHOUTGROUP no group
1491 * @param int $accesssince The time since last access, 0 means any time
1492 * @param int $roleid The role id, 0 means all roles
1493 * @param int $enrolid The applied filter for the user enrolment ID.
1494 * @param int $status The applied filter for the user's enrolment status.
1495 * @param string|array $search The search that was performed, empty means perform no search
1496 * @param string $additionalwhere Any additional SQL to add to where
1497 * @param array $additionalparams The additional params
1498 * @return int
1500 function user_get_total_participants($courseid, $groupid = 0, $accesssince = 0, $roleid = 0, $enrolid = 0, $statusid = -1,
1501 $search = '', $additionalwhere = '', $additionalparams = array()) {
1502 global $DB;
1504 list($select, $from, $where, $params) = user_get_participants_sql($courseid, $groupid, $accesssince, $roleid, $enrolid,
1505 $statusid, $search, $additionalwhere, $additionalparams);
1507 return $DB->count_records_sql("SELECT COUNT(u.id) $from $where", $params);
1511 * Returns the participants for a given course.
1513 * @param int $courseid The course id
1514 * @param int $groupid The groupid, 0 means all groups and USERSWITHOUTGROUP no group
1515 * @param int $accesssince The time since last access
1516 * @param int $roleid The role id
1517 * @param int $enrolid The applied filter for the user enrolment ID.
1518 * @param int $status The applied filter for the user's enrolment status.
1519 * @param string $search The search that was performed
1520 * @param string $additionalwhere Any additional SQL to add to where
1521 * @param array $additionalparams The additional params
1522 * @param string $sort The SQL sort
1523 * @param int $limitfrom return a subset of records, starting at this point (optional).
1524 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1525 * @return moodle_recordset
1527 function user_get_participants($courseid, $groupid = 0, $accesssince, $roleid, $enrolid = 0, $statusid, $search,
1528 $additionalwhere = '', $additionalparams = array(), $sort = '', $limitfrom = 0, $limitnum = 0) {
1529 global $DB;
1531 list($select, $from, $where, $params) = user_get_participants_sql($courseid, $groupid, $accesssince, $roleid, $enrolid,
1532 $statusid, $search, $additionalwhere, $additionalparams);
1534 return $DB->get_recordset_sql("$select $from $where $sort", $params, $limitfrom, $limitnum);
1538 * Returns SQL that can be used to limit a query to a period where the user last accessed a course.
1540 * @param int $accesssince The time since last access
1541 * @param string $tableprefix
1542 * @return string
1544 function user_get_course_lastaccess_sql($accesssince = null, $tableprefix = 'ul') {
1545 if (empty($accesssince)) {
1546 return '';
1549 if ($accesssince == -1) { // Never.
1550 return $tableprefix . '.timeaccess = 0';
1551 } else {
1552 return $tableprefix . '.timeaccess != 0 AND ' . $tableprefix . '.timeaccess < ' . $accesssince;
1557 * Returns SQL that can be used to limit a query to a period where the user last accessed the system.
1559 * @param int $accesssince The time since last access
1560 * @param string $tableprefix
1561 * @return string
1563 function user_get_user_lastaccess_sql($accesssince = null, $tableprefix = 'u') {
1564 if (empty($accesssince)) {
1565 return '';
1568 if ($accesssince == -1) { // Never.
1569 return $tableprefix . '.lastaccess = 0';
1570 } else {
1571 return $tableprefix . '.lastaccess != 0 AND ' . $tableprefix . '.lastaccess < ' . $accesssince;
1576 * Callback for inplace editable API.
1578 * @param string $itemtype - Only user_roles is supported.
1579 * @param string $itemid - Courseid and userid separated by a :
1580 * @param string $newvalue - json encoded list of roleids.
1581 * @return \core\output\inplace_editable
1583 function core_user_inplace_editable($itemtype, $itemid, $newvalue) {
1584 if ($itemtype === 'user_roles') {
1585 return \core_user\output\user_roles_editable::update($itemid, $newvalue);
1590 * Map an internal field name to a valid purpose from: "https://www.w3.org/TR/WCAG21/#input-purposes"
1592 * @param integer $userid
1593 * @param string $fieldname
1594 * @return string $purpose (empty string if there is no mapping).
1596 function user_edit_map_field_purpose($userid, $fieldname) {
1597 global $USER;
1599 $currentuser = ($userid == $USER->id) && !\core\session\manager::is_loggedinas();
1600 // These are the fields considered valid to map and auto fill from a browser.
1601 // We do not include fields that are in a collapsed section by default because
1602 // the browser could auto-fill the field and cause a new value to be saved when
1603 // that field was never visible.
1604 $validmappings = array(
1605 'username' => 'username',
1606 'password' => 'current-password',
1607 'firstname' => 'given-name',
1608 'lastname' => 'family-name',
1609 'middlename' => 'additional-name',
1610 'email' => 'email',
1611 'country' => 'country',
1612 'lang' => 'language'
1615 $purpose = '';
1616 // Only set a purpose when editing your own user details.
1617 if ($currentuser && isset($validmappings[$fieldname])) {
1618 $purpose = ' autocomplete="' . $validmappings[$fieldname] . '" ';
1621 return $purpose;