Merge branch 'wip-MDL-58697-33-assigngrading' of git://github.com/adamann2/moodle...
[moodle.git] / user / lib.php
blob94cd765a3fdbcaacfdf0e19a14e284e1a05fc4f0
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * External user API
20 * @package core_user
21 * @copyright 2009 Moodle Pty Ltd (http://moodle.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 /**
26 * Creates a user
28 * @throws moodle_exception
29 * @param stdClass $user user to create
30 * @param bool $updatepassword if true, authentication plugin will update password.
31 * @param bool $triggerevent set false if user_created event should not be triggred.
32 * This will not affect user_password_updated event triggering.
33 * @return int id of the newly created user
35 function user_create_user($user, $updatepassword = true, $triggerevent = true) {
36 global $DB;
38 // Set the timecreate field to the current time.
39 if (!is_object($user)) {
40 $user = (object) $user;
43 // Check username.
44 if ($user->username !== core_text::strtolower($user->username)) {
45 throw new moodle_exception('usernamelowercase');
46 } else {
47 if ($user->username !== core_user::clean_field($user->username, 'username')) {
48 throw new moodle_exception('invalidusername');
52 // Save the password in a temp value for later.
53 if ($updatepassword && isset($user->password)) {
55 // Check password toward the password policy.
56 if (!check_password_policy($user->password, $errmsg)) {
57 throw new moodle_exception($errmsg);
60 $userpassword = $user->password;
61 unset($user->password);
64 // Apply default values for user preferences that are stored in users table.
65 if (!isset($user->calendartype)) {
66 $user->calendartype = core_user::get_property_default('calendartype');
68 if (!isset($user->maildisplay)) {
69 $user->maildisplay = core_user::get_property_default('maildisplay');
71 if (!isset($user->mailformat)) {
72 $user->mailformat = core_user::get_property_default('mailformat');
74 if (!isset($user->maildigest)) {
75 $user->maildigest = core_user::get_property_default('maildigest');
77 if (!isset($user->autosubscribe)) {
78 $user->autosubscribe = core_user::get_property_default('autosubscribe');
80 if (!isset($user->trackforums)) {
81 $user->trackforums = core_user::get_property_default('trackforums');
83 if (!isset($user->lang)) {
84 $user->lang = core_user::get_property_default('lang');
87 $user->timecreated = time();
88 $user->timemodified = $user->timecreated;
90 // Validate user data object.
91 $uservalidation = core_user::validate($user);
92 if ($uservalidation !== true) {
93 foreach ($uservalidation as $field => $message) {
94 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
95 $user->$field = core_user::clean_field($user->$field, $field);
99 // Insert the user into the database.
100 $newuserid = $DB->insert_record('user', $user);
102 // Create USER context for this user.
103 $usercontext = context_user::instance($newuserid);
105 // Update user password if necessary.
106 if (isset($userpassword)) {
107 // Get full database user row, in case auth is default.
108 $newuser = $DB->get_record('user', array('id' => $newuserid));
109 $authplugin = get_auth_plugin($newuser->auth);
110 $authplugin->user_update_password($newuser, $userpassword);
113 // Trigger event If required.
114 if ($triggerevent) {
115 \core\event\user_created::create_from_userid($newuserid)->trigger();
118 return $newuserid;
122 * Update a user with a user object (will compare against the ID)
124 * @throws moodle_exception
125 * @param stdClass $user the user to update
126 * @param bool $updatepassword if true, authentication plugin will update password.
127 * @param bool $triggerevent set false if user_updated event should not be triggred.
128 * This will not affect user_password_updated event triggering.
130 function user_update_user($user, $updatepassword = true, $triggerevent = true) {
131 global $DB;
133 // Set the timecreate field to the current time.
134 if (!is_object($user)) {
135 $user = (object) $user;
138 // Check username.
139 if (isset($user->username)) {
140 if ($user->username !== core_text::strtolower($user->username)) {
141 throw new moodle_exception('usernamelowercase');
142 } else {
143 if ($user->username !== core_user::clean_field($user->username, 'username')) {
144 throw new moodle_exception('invalidusername');
149 // Unset password here, for updating later, if password update is required.
150 if ($updatepassword && isset($user->password)) {
152 // Check password toward the password policy.
153 if (!check_password_policy($user->password, $errmsg)) {
154 throw new moodle_exception($errmsg);
157 $passwd = $user->password;
158 unset($user->password);
161 // Make sure calendartype, if set, is valid.
162 if (empty($user->calendartype)) {
163 // Unset this variable, must be an empty string, which we do not want to update the calendartype to.
164 unset($user->calendartype);
167 $user->timemodified = time();
169 // Validate user data object.
170 $uservalidation = core_user::validate($user);
171 if ($uservalidation !== true) {
172 foreach ($uservalidation as $field => $message) {
173 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
174 $user->$field = core_user::clean_field($user->$field, $field);
178 $DB->update_record('user', $user);
180 if ($updatepassword) {
181 // Get full user record.
182 $updateduser = $DB->get_record('user', array('id' => $user->id));
184 // If password was set, then update its hash.
185 if (isset($passwd)) {
186 $authplugin = get_auth_plugin($updateduser->auth);
187 if ($authplugin->can_change_password()) {
188 $authplugin->user_update_password($updateduser, $passwd);
192 // Trigger event if required.
193 if ($triggerevent) {
194 \core\event\user_updated::create_from_userid($user->id)->trigger();
199 * Marks user deleted in internal user database and notifies the auth plugin.
200 * Also unenrols user from all roles and does other cleanup.
202 * @todo Decide if this transaction is really needed (look for internal TODO:)
203 * @param object $user Userobject before delete (without system magic quotes)
204 * @return boolean success
206 function user_delete_user($user) {
207 return delete_user($user);
211 * Get users by id
213 * @param array $userids id of users to retrieve
214 * @return array
216 function user_get_users_by_id($userids) {
217 global $DB;
218 return $DB->get_records_list('user', 'id', $userids);
222 * Returns the list of default 'displayable' fields
224 * Contains database field names but also names used to generate information, such as enrolledcourses
226 * @return array of user fields
228 function user_get_default_fields() {
229 return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
230 'address', 'phone1', 'phone2', 'icq', 'skype', 'yahoo', 'aim', 'msn', 'department',
231 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
232 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
233 'city', 'url', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
234 'groups', 'roles', 'preferences', 'enrolledcourses', 'suspended'
240 * Give user record from mdl_user, build an array contains all user details.
242 * Warning: description file urls are 'webservice/pluginfile.php' is use.
243 * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
245 * @throws moodle_exception
246 * @param stdClass $user user record from mdl_user
247 * @param stdClass $course moodle course
248 * @param array $userfields required fields
249 * @return array|null
251 function user_get_user_details($user, $course = null, array $userfields = array()) {
252 global $USER, $DB, $CFG, $PAGE;
253 require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library.
254 require_once($CFG->dirroot . "/lib/filelib.php"); // File handling on description and friends.
256 $defaultfields = user_get_default_fields();
258 if (empty($userfields)) {
259 $userfields = $defaultfields;
262 foreach ($userfields as $thefield) {
263 if (!in_array($thefield, $defaultfields)) {
264 throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
268 // Make sure id and fullname are included.
269 if (!in_array('id', $userfields)) {
270 $userfields[] = 'id';
273 if (!in_array('fullname', $userfields)) {
274 $userfields[] = 'fullname';
277 if (!empty($course)) {
278 $context = context_course::instance($course->id);
279 $usercontext = context_user::instance($user->id);
280 $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext));
281 } else {
282 $context = context_user::instance($user->id);
283 $usercontext = $context;
284 $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
287 $currentuser = ($user->id == $USER->id);
288 $isadmin = is_siteadmin($USER);
290 $showuseridentityfields = get_extra_user_fields($context);
292 if (!empty($course)) {
293 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
294 } else {
295 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
297 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
298 if (!empty($course)) {
299 $canviewuseremail = has_capability('moodle/course:useremail', $context);
300 } else {
301 $canviewuseremail = false;
303 $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
304 if (!empty($course)) {
305 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
306 } else {
307 $canaccessallgroups = false;
310 if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
311 // Skip this user details.
312 return null;
315 $userdetails = array();
316 $userdetails['id'] = $user->id;
318 if (in_array('username', $userfields)) {
319 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
320 $userdetails['username'] = $user->username;
323 if ($isadmin or $canviewfullnames) {
324 if (in_array('firstname', $userfields)) {
325 $userdetails['firstname'] = $user->firstname;
327 if (in_array('lastname', $userfields)) {
328 $userdetails['lastname'] = $user->lastname;
331 $userdetails['fullname'] = fullname($user);
333 if (in_array('customfields', $userfields)) {
334 $fields = $DB->get_recordset_sql("SELECT f.*
335 FROM {user_info_field} f
336 JOIN {user_info_category} c
337 ON f.categoryid=c.id
338 ORDER BY c.sortorder ASC, f.sortorder ASC");
339 $userdetails['customfields'] = array();
340 foreach ($fields as $field) {
341 require_once($CFG->dirroot.'/user/profile/field/'.$field->datatype.'/field.class.php');
342 $newfield = 'profile_field_'.$field->datatype;
343 $formfield = new $newfield($field->id, $user->id);
344 if ($formfield->is_visible() and !$formfield->is_empty()) {
346 // TODO: Part of MDL-50728, this conditional coding must be moved to
347 // proper profile fields API so they are self-contained.
348 // We only use display_data in fields that require text formatting.
349 if ($field->datatype == 'text' or $field->datatype == 'textarea') {
350 $fieldvalue = $formfield->display_data();
351 } else {
352 // Cases: datetime, checkbox and menu.
353 $fieldvalue = $formfield->data;
356 $userdetails['customfields'][] =
357 array('name' => $formfield->field->name, 'value' => $fieldvalue,
358 'type' => $field->datatype, 'shortname' => $formfield->field->shortname);
361 $fields->close();
362 // Unset customfields if it's empty.
363 if (empty($userdetails['customfields'])) {
364 unset($userdetails['customfields']);
368 // Profile image.
369 if (in_array('profileimageurl', $userfields)) {
370 $userpicture = new user_picture($user);
371 $userpicture->size = 1; // Size f1.
372 $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
374 if (in_array('profileimageurlsmall', $userfields)) {
375 if (!isset($userpicture)) {
376 $userpicture = new user_picture($user);
378 $userpicture->size = 0; // Size f2.
379 $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
382 // Hidden user field.
383 if ($canviewhiddenuserfields) {
384 $hiddenfields = array();
385 // Address, phone1 and phone2 not appears in hidden fields list but require viewhiddenfields capability
386 // according to user/profile.php.
387 if (!empty($user->address) && in_array('address', $userfields)) {
388 $userdetails['address'] = $user->address;
390 } else {
391 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
394 if (!empty($user->phone1) && in_array('phone1', $userfields) &&
395 (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) {
396 $userdetails['phone1'] = $user->phone1;
398 if (!empty($user->phone2) && in_array('phone2', $userfields) &&
399 (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) {
400 $userdetails['phone2'] = $user->phone2;
403 if (isset($user->description) &&
404 ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
405 if (in_array('description', $userfields)) {
406 // Always return the descriptionformat if description is requested.
407 list($userdetails['description'], $userdetails['descriptionformat']) =
408 external_format_text($user->description, $user->descriptionformat,
409 $usercontext->id, 'user', 'profile', null);
413 if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
414 $userdetails['country'] = $user->country;
417 if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
418 $userdetails['city'] = $user->city;
421 if (in_array('url', $userfields) && $user->url && (!isset($hiddenfields['webpage']) or $isadmin)) {
422 $url = $user->url;
423 if (strpos($user->url, '://') === false) {
424 $url = 'http://'. $url;
426 $user->url = clean_param($user->url, PARAM_URL);
427 $userdetails['url'] = $user->url;
430 if (in_array('icq', $userfields) && $user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) {
431 $userdetails['icq'] = $user->icq;
434 if (in_array('skype', $userfields) && $user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) {
435 $userdetails['skype'] = $user->skype;
437 if (in_array('yahoo', $userfields) && $user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) {
438 $userdetails['yahoo'] = $user->yahoo;
440 if (in_array('aim', $userfields) && $user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) {
441 $userdetails['aim'] = $user->aim;
443 if (in_array('msn', $userfields) && $user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) {
444 $userdetails['msn'] = $user->msn;
446 if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) {
447 $userdetails['suspended'] = (bool)$user->suspended;
450 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
451 if ($user->firstaccess) {
452 $userdetails['firstaccess'] = $user->firstaccess;
453 } else {
454 $userdetails['firstaccess'] = 0;
457 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
458 if ($user->lastaccess) {
459 $userdetails['lastaccess'] = $user->lastaccess;
460 } else {
461 $userdetails['lastaccess'] = 0;
465 if (in_array('email', $userfields) && ($isadmin // The admin is allowed the users email.
466 or $currentuser // Of course the current user is as well.
467 or $canviewuseremail // This is a capability in course context, it will be false in usercontext.
468 or in_array('email', $showuseridentityfields)
469 or $user->maildisplay == 1
470 or ($user->maildisplay == 2 and enrol_sharing_course($user, $USER)))) {
471 $userdetails['email'] = $user->email;
474 if (in_array('interests', $userfields)) {
475 $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
476 if ($interests) {
477 $userdetails['interests'] = join(', ', $interests);
481 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
482 if (in_array('idnumber', $userfields) && $user->idnumber) {
483 if (in_array('idnumber', $showuseridentityfields) or $currentuser or
484 has_capability('moodle/user:viewalldetails', $context)) {
485 $userdetails['idnumber'] = $user->idnumber;
488 if (in_array('institution', $userfields) && $user->institution) {
489 if (in_array('institution', $showuseridentityfields) or $currentuser or
490 has_capability('moodle/user:viewalldetails', $context)) {
491 $userdetails['institution'] = $user->institution;
494 // Isset because it's ok to have department 0.
495 if (in_array('department', $userfields) && isset($user->department)) {
496 if (in_array('department', $showuseridentityfields) or $currentuser or
497 has_capability('moodle/user:viewalldetails', $context)) {
498 $userdetails['department'] = $user->department;
502 if (in_array('roles', $userfields) && !empty($course)) {
503 // Not a big secret.
504 $roles = get_user_roles($context, $user->id, false);
505 $userdetails['roles'] = array();
506 foreach ($roles as $role) {
507 $userdetails['roles'][] = array(
508 'roleid' => $role->roleid,
509 'name' => $role->name,
510 'shortname' => $role->shortname,
511 'sortorder' => $role->sortorder
516 // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
517 if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
518 $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid,
519 'g.id, g.name,g.description,g.descriptionformat');
520 $userdetails['groups'] = array();
521 foreach ($usergroups as $group) {
522 list($group->description, $group->descriptionformat) =
523 external_format_text($group->description, $group->descriptionformat,
524 $context->id, 'group', 'description', $group->id);
525 $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name,
526 'description' => $group->description, 'descriptionformat' => $group->descriptionformat);
529 // List of courses where the user is enrolled.
530 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
531 $enrolledcourses = array();
532 if ($mycourses = enrol_get_users_courses($user->id, true)) {
533 foreach ($mycourses as $mycourse) {
534 if ($mycourse->category) {
535 $coursecontext = context_course::instance($mycourse->id);
536 $enrolledcourse = array();
537 $enrolledcourse['id'] = $mycourse->id;
538 $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
539 $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
540 $enrolledcourses[] = $enrolledcourse;
543 $userdetails['enrolledcourses'] = $enrolledcourses;
547 // User preferences.
548 if (in_array('preferences', $userfields) && $currentuser) {
549 $preferences = array();
550 $userpreferences = get_user_preferences();
551 foreach ($userpreferences as $prefname => $prefvalue) {
552 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
554 $userdetails['preferences'] = $preferences;
557 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
558 $extrafields = ['auth', 'confirmed', 'lang', 'theme', 'timezone', 'mailformat'];
559 foreach ($extrafields as $extrafield) {
560 if (in_array($extrafield, $userfields) && isset($user->$extrafield)) {
561 $userdetails[$extrafield] = $user->$extrafield;
566 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
567 if (isset($userdetails['lang'])) {
568 $userdetails['lang'] = clean_param($userdetails['lang'], PARAM_LANG);
570 if (isset($userdetails['theme'])) {
571 $userdetails['theme'] = clean_param($userdetails['theme'], PARAM_THEME);
574 return $userdetails;
578 * Tries to obtain user details, either recurring directly to the user's system profile
579 * or through one of the user's course enrollments (course profile).
581 * @param stdClass $user The user.
582 * @return array if unsuccessful or the allowed user details.
584 function user_get_user_details_courses($user) {
585 global $USER;
586 $userdetails = null;
588 // Get the courses that the user is enrolled in (only active).
589 $courses = enrol_get_users_courses($user->id, true);
591 $systemprofile = false;
592 if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
593 $systemprofile = true;
596 // Try using system profile.
597 if ($systemprofile) {
598 $userdetails = user_get_user_details($user, null);
599 } else {
600 // Try through course profile.
601 foreach ($courses as $course) {
602 if (can_view_user_details_cap($user, $course) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
603 $userdetails = user_get_user_details($user, $course);
608 return $userdetails;
612 * Check if $USER have the necessary capabilities to obtain user details.
614 * @param stdClass $user
615 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
616 * @return bool true if $USER can view user details.
618 function can_view_user_details_cap($user, $course = null) {
619 // Check $USER has the capability to view the user details at user context.
620 $usercontext = context_user::instance($user->id);
621 $result = has_capability('moodle/user:viewdetails', $usercontext);
622 // Otherwise can $USER see them at course context.
623 if (!$result && !empty($course)) {
624 $context = context_course::instance($course->id);
625 $result = has_capability('moodle/user:viewdetails', $context);
627 return $result;
631 * Return a list of page types
632 * @param string $pagetype current page type
633 * @param stdClass $parentcontext Block's parent context
634 * @param stdClass $currentcontext Current context of block
635 * @return array
637 function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
638 return array('user-profile' => get_string('page-user-profile', 'pagetype'));
642 * Count the number of failed login attempts for the given user, since last successful login.
644 * @param int|stdclass $user user id or object.
645 * @param bool $reset Resets failed login count, if set to true.
647 * @return int number of failed login attempts since the last successful login.
649 function user_count_login_failures($user, $reset = true) {
650 global $DB;
652 if (!is_object($user)) {
653 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
655 if ($user->deleted) {
656 // Deleted user, nothing to do.
657 return 0;
659 $count = get_user_preferences('login_failed_count_since_success', 0, $user);
660 if ($reset) {
661 set_user_preference('login_failed_count_since_success', 0, $user);
663 return $count;
667 * Converts a string into a flat array of menu items, where each menu items is a
668 * stdClass with fields type, url, title, pix, and imgsrc.
670 * @param string $text the menu items definition
671 * @param moodle_page $page the current page
672 * @return array
674 function user_convert_text_to_menu_items($text, $page) {
675 global $OUTPUT, $CFG;
677 $lines = explode("\n", $text);
678 $items = array();
679 $lastchild = null;
680 $lastdepth = null;
681 $lastsort = 0;
682 $children = array();
683 foreach ($lines as $line) {
684 $line = trim($line);
685 $bits = explode('|', $line, 3);
686 $itemtype = 'link';
687 if (preg_match("/^#+$/", $line)) {
688 $itemtype = 'divider';
689 } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
690 // Every item must have a name to be valid.
691 continue;
692 } else {
693 $bits[0] = ltrim($bits[0], '-');
696 // Create the child.
697 $child = new stdClass();
698 $child->itemtype = $itemtype;
699 if ($itemtype === 'divider') {
700 // Add the divider to the list of children and skip link
701 // processing.
702 $children[] = $child;
703 continue;
706 // Name processing.
707 $namebits = explode(',', $bits[0], 2);
708 if (count($namebits) == 2) {
709 // Check the validity of the identifier part of the string.
710 if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
711 // Treat this as a language string.
712 $child->title = get_string($namebits[0], $namebits[1]);
713 $child->titleidentifier = implode(',', $namebits);
716 if (empty($child->title)) {
717 // Use it as is, don't even clean it.
718 $child->title = $bits[0];
719 $child->titleidentifier = str_replace(" ", "-", $bits[0]);
722 // URL processing.
723 if (!array_key_exists(1, $bits) or empty($bits[1])) {
724 // Set the url to null, and set the itemtype to invalid.
725 $bits[1] = null;
726 $child->itemtype = "invalid";
727 } else {
728 // Nasty hack to replace the grades with the direct url.
729 if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
730 $bits[1] = user_mygrades_url();
733 // Make sure the url is a moodle url.
734 $bits[1] = new moodle_url(trim($bits[1]));
736 $child->url = $bits[1];
738 // PIX processing.
739 $pixpath = "t/edit";
740 if (!array_key_exists(2, $bits) or empty($bits[2])) {
741 // Use the default.
742 $child->pix = $pixpath;
743 } else {
744 // Check for the specified image existing.
745 $pixpath = "t/" . $bits[2];
746 if ($page->theme->resolve_image_location($pixpath, 'moodle', true)) {
747 // Use the image.
748 $child->pix = $pixpath;
749 } else {
750 // Treat it like a URL.
751 $child->pix = null;
752 $child->imgsrc = $bits[2];
756 // Add this child to the list of children.
757 $children[] = $child;
759 return $children;
763 * Get a list of essential user navigation items.
765 * @param stdclass $user user object.
766 * @param moodle_page $page page object.
767 * @param array $options associative array.
768 * options are:
769 * - avatarsize=35 (size of avatar image)
770 * @return stdClass $returnobj navigation information object, where:
772 * $returnobj->navitems array array of links where each link is a
773 * stdClass with fields url, title, and
774 * pix
775 * $returnobj->metadata array array of useful user metadata to be
776 * used when constructing navigation;
777 * fields include:
779 * ROLE FIELDS
780 * asotherrole bool whether viewing as another role
781 * rolename string name of the role
783 * USER FIELDS
784 * These fields are for the currently-logged in user, or for
785 * the user that the real user is currently logged in as.
787 * userid int the id of the user in question
788 * userfullname string the user's full name
789 * userprofileurl moodle_url the url of the user's profile
790 * useravatar string a HTML fragment - the rendered
791 * user_picture for this user
792 * userloginfail string an error string denoting the number
793 * of login failures since last login
795 * "REAL USER" FIELDS
796 * These fields are for when asotheruser is true, and
797 * correspond to the underlying "real user".
799 * asotheruser bool whether viewing as another user
800 * realuserid int the id of the user in question
801 * realuserfullname string the user's full name
802 * realuserprofileurl moodle_url the url of the user's profile
803 * realuseravatar string a HTML fragment - the rendered
804 * user_picture for this user
806 * MNET PROVIDER FIELDS
807 * asmnetuser bool whether viewing as a user from an
808 * MNet provider
809 * mnetidprovidername string name of the MNet provider
810 * mnetidproviderwwwroot string URL of the MNet provider
812 function user_get_user_navigation_info($user, $page, $options = array()) {
813 global $OUTPUT, $DB, $SESSION, $CFG;
815 $returnobject = new stdClass();
816 $returnobject->navitems = array();
817 $returnobject->metadata = array();
819 $course = $page->course;
821 // Query the environment.
822 $context = context_course::instance($course->id);
824 // Get basic user metadata.
825 $returnobject->metadata['userid'] = $user->id;
826 $returnobject->metadata['userfullname'] = fullname($user, true);
827 $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
828 'id' => $user->id
831 $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
832 if (!empty($options['avatarsize'])) {
833 $avataroptions['size'] = $options['avatarsize'];
835 $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
836 $user, $avataroptions
838 // Build a list of items for a regular user.
840 // Query MNet status.
841 if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
842 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
843 $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
844 $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
847 // Did the user just log in?
848 if (isset($SESSION->justloggedin)) {
849 // Don't unset this flag as login_info still needs it.
850 if (!empty($CFG->displayloginfailures)) {
851 // Don't reset the count either, as login_info() still needs it too.
852 if ($count = user_count_login_failures($user, false)) {
854 // Get login failures string.
855 $a = new stdClass();
856 $a->attempts = html_writer::tag('span', $count, array('class' => 'value'));
857 $returnobject->metadata['userloginfail'] =
858 get_string('failedloginattempts', '', $a);
864 // Links: Dashboard.
865 $myhome = new stdClass();
866 $myhome->itemtype = 'link';
867 $myhome->url = new moodle_url('/my/');
868 $myhome->title = get_string('mymoodle', 'admin');
869 $myhome->titleidentifier = 'mymoodle,admin';
870 $myhome->pix = "i/dashboard";
871 $returnobject->navitems[] = $myhome;
873 // Links: My Profile.
874 $myprofile = new stdClass();
875 $myprofile->itemtype = 'link';
876 $myprofile->url = new moodle_url('/user/profile.php', array('id' => $user->id));
877 $myprofile->title = get_string('profile');
878 $myprofile->titleidentifier = 'profile,moodle';
879 $myprofile->pix = "i/user";
880 $returnobject->navitems[] = $myprofile;
882 $returnobject->metadata['asotherrole'] = false;
884 // Before we add the last items (usually a logout + switch role link), add any
885 // custom-defined items.
886 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
887 foreach ($customitems as $item) {
888 $returnobject->navitems[] = $item;
892 if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
893 $realuser = \core\session\manager::get_realuser();
895 // Save values for the real user, as $user will be full of data for the
896 // user the user is disguised as.
897 $returnobject->metadata['realuserid'] = $realuser->id;
898 $returnobject->metadata['realuserfullname'] = fullname($realuser, true);
899 $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', array(
900 'id' => $realuser->id
902 $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
904 // Build a user-revert link.
905 $userrevert = new stdClass();
906 $userrevert->itemtype = 'link';
907 $userrevert->url = new moodle_url('/course/loginas.php', array(
908 'id' => $course->id,
909 'sesskey' => sesskey()
911 $userrevert->pix = "a/logout";
912 $userrevert->title = get_string('logout');
913 $userrevert->titleidentifier = 'logout,moodle';
914 $returnobject->navitems[] = $userrevert;
916 } else {
918 // Build a logout link.
919 $logout = new stdClass();
920 $logout->itemtype = 'link';
921 $logout->url = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
922 $logout->pix = "a/logout";
923 $logout->title = get_string('logout');
924 $logout->titleidentifier = 'logout,moodle';
925 $returnobject->navitems[] = $logout;
928 if (is_role_switched($course->id)) {
929 if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
930 // Build role-return link instead of logout link.
931 $rolereturn = new stdClass();
932 $rolereturn->itemtype = 'link';
933 $rolereturn->url = new moodle_url('/course/switchrole.php', array(
934 'id' => $course->id,
935 'sesskey' => sesskey(),
936 'switchrole' => 0,
937 'returnurl' => $page->url->out_as_local_url(false)
939 $rolereturn->pix = "a/logout";
940 $rolereturn->title = get_string('switchrolereturn');
941 $rolereturn->titleidentifier = 'switchrolereturn,moodle';
942 $returnobject->navitems[] = $rolereturn;
944 $returnobject->metadata['asotherrole'] = true;
945 $returnobject->metadata['rolename'] = role_get_name($role, $context);
948 } else {
949 // Build switch role link.
950 $roles = get_switchable_roles($context);
951 if (is_array($roles) && (count($roles) > 0)) {
952 $switchrole = new stdClass();
953 $switchrole->itemtype = 'link';
954 $switchrole->url = new moodle_url('/course/switchrole.php', array(
955 'id' => $course->id,
956 'switchrole' => -1,
957 'returnurl' => $page->url->out_as_local_url(false)
959 $switchrole->pix = "i/switchrole";
960 $switchrole->title = get_string('switchroleto');
961 $switchrole->titleidentifier = 'switchroleto,moodle';
962 $returnobject->navitems[] = $switchrole;
966 return $returnobject;
970 * Add password to the list of used hashes for this user.
972 * This is supposed to be used from:
973 * 1/ change own password form
974 * 2/ password reset process
975 * 3/ user signup in auth plugins if password changing supported
977 * @param int $userid user id
978 * @param string $password plaintext password
979 * @return void
981 function user_add_password_history($userid, $password) {
982 global $CFG, $DB;
984 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
985 return;
988 // Note: this is using separate code form normal password hashing because
989 // we need to have this under control in the future. Also the auth
990 // plugin might not store the passwords locally at all.
992 $record = new stdClass();
993 $record->userid = $userid;
994 $record->hash = password_hash($password, PASSWORD_DEFAULT);
995 $record->timecreated = time();
996 $DB->insert_record('user_password_history', $record);
998 $i = 0;
999 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1000 foreach ($records as $record) {
1001 $i++;
1002 if ($i > $CFG->passwordreuselimit) {
1003 $DB->delete_records('user_password_history', array('id' => $record->id));
1009 * Was this password used before on change or reset password page?
1011 * The $CFG->passwordreuselimit setting determines
1012 * how many times different password needs to be used
1013 * before allowing previously used password again.
1015 * @param int $userid user id
1016 * @param string $password plaintext password
1017 * @return bool true if password reused
1019 function user_is_previously_used_password($userid, $password) {
1020 global $CFG, $DB;
1022 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1023 return false;
1026 $reused = false;
1028 $i = 0;
1029 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1030 foreach ($records as $record) {
1031 $i++;
1032 if ($i > $CFG->passwordreuselimit) {
1033 $DB->delete_records('user_password_history', array('id' => $record->id));
1034 continue;
1036 // NOTE: this is slow but we cannot compare the hashes directly any more.
1037 if (password_verify($password, $record->hash)) {
1038 $reused = true;
1042 return $reused;
1046 * Remove a user device from the Moodle database (for PUSH notifications usually).
1048 * @param string $uuid The device UUID.
1049 * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1050 * @return bool true if removed, false if the device didn't exists in the database
1051 * @since Moodle 2.9
1053 function user_remove_user_device($uuid, $appid = "") {
1054 global $DB, $USER;
1056 $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
1057 if (!empty($appid)) {
1058 $conditions['appid'] = $appid;
1061 if (!$DB->count_records('user_devices', $conditions)) {
1062 return false;
1065 $DB->delete_records('user_devices', $conditions);
1067 return true;
1071 * Trigger user_list_viewed event.
1073 * @param stdClass $course course object
1074 * @param stdClass $context course context object
1075 * @since Moodle 2.9
1077 function user_list_view($course, $context) {
1079 $event = \core\event\user_list_viewed::create(array(
1080 'objectid' => $course->id,
1081 'courseid' => $course->id,
1082 'context' => $context,
1083 'other' => array(
1084 'courseshortname' => $course->shortname,
1085 'coursefullname' => $course->fullname
1088 $event->trigger();
1092 * Returns the url to use for the "Grades" link in the user navigation.
1094 * @param int $userid The user's ID.
1095 * @param int $courseid The course ID if available.
1096 * @return mixed A URL to be directed to for "Grades".
1098 function user_mygrades_url($userid = null, $courseid = SITEID) {
1099 global $CFG, $USER;
1100 $url = null;
1101 if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
1102 if (isset($userid) && $USER->id != $userid) {
1103 // Send to the gradebook report.
1104 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
1105 array('id' => $courseid, 'userid' => $userid));
1106 } else {
1107 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
1109 } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
1110 && !empty($CFG->gradereport_mygradeurl)) {
1111 $url = $CFG->gradereport_mygradeurl;
1112 } else {
1113 $url = $CFG->wwwroot;
1115 return $url;
1119 * Check if the current user has permission to view details of the supplied user.
1121 * This function supports two modes:
1122 * If the optional $course param is omitted, then this function finds all shared courses and checks whether the current user has
1123 * permission in any of them, returning true if so.
1124 * If the $course param is provided, then this function checks permissions in ONLY that course.
1126 * @param object $user The other user's details.
1127 * @param object $course if provided, only check permissions in this course.
1128 * @param context $usercontext The user context if available.
1129 * @return bool true for ability to view this user, else false.
1131 function user_can_view_profile($user, $course = null, $usercontext = null) {
1132 global $USER, $CFG;
1134 if ($user->deleted) {
1135 return false;
1138 // Do we need to be logged in?
1139 if (empty($CFG->forceloginforprofiles)) {
1140 return true;
1141 } else {
1142 if (!isloggedin() || isguestuser()) {
1143 // User is not logged in and forceloginforprofile is set, we need to return now.
1144 return false;
1148 // Current user can always view their profile.
1149 if ($USER->id == $user->id) {
1150 return true;
1153 // Course contacts have visible profiles always.
1154 if (has_coursecontact_role($user->id)) {
1155 return true;
1158 // If we're only checking the capabilities in the single provided course.
1159 if (isset($course)) {
1160 // Confirm that $user is enrolled in the $course we're checking.
1161 if (is_enrolled(context_course::instance($course->id), $user)) {
1162 $userscourses = array($course);
1164 } else {
1165 // Else we're checking whether the current user can view $user's profile anywhere, so check user context first.
1166 if (empty($usercontext)) {
1167 $usercontext = context_user::instance($user->id);
1169 if (has_capability('moodle/user:viewdetails', $usercontext) || has_capability('moodle/user:viewalldetails', $usercontext)) {
1170 return true;
1172 // This returns context information, so we can preload below.
1173 $userscourses = enrol_get_all_users_courses($user->id);
1176 if (empty($userscourses)) {
1177 return false;
1180 foreach ($userscourses as $userscourse) {
1181 context_helper::preload_from_record($userscourse);
1182 $coursecontext = context_course::instance($userscourse->id);
1183 if (has_capability('moodle/user:viewdetails', $coursecontext) ||
1184 has_capability('moodle/user:viewalldetails', $coursecontext)) {
1185 if (!groups_user_groups_visible($userscourse, $user->id)) {
1186 // Not a member of the same group.
1187 continue;
1189 return true;
1192 return false;
1196 * Returns users tagged with a specified tag.
1198 * @param core_tag_tag $tag
1199 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1200 * are displayed on the page and the per-page limit may be bigger
1201 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1202 * to display items in the same context first
1203 * @param int $ctx context id where to search for records
1204 * @param bool $rec search in subcontexts as well
1205 * @param int $page 0-based number of page being displayed
1206 * @return \core_tag\output\tagindex
1208 function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1209 global $PAGE;
1211 if ($ctx && $ctx != context_system::instance()->id) {
1212 $usercount = 0;
1213 } else {
1214 // Users can only be displayed in system context.
1215 $usercount = $tag->count_tagged_items('core', 'user',
1216 'it.deleted=:notdeleted', array('notdeleted' => 0));
1218 $perpage = $exclusivemode ? 24 : 5;
1219 $content = '';
1220 $totalpages = ceil($usercount / $perpage);
1222 if ($usercount) {
1223 $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage,
1224 'it.deleted=:notdeleted', array('notdeleted' => 0));
1225 $renderer = $PAGE->get_renderer('core', 'user');
1226 $content .= $renderer->user_list($userlist, $exclusivemode);
1229 return new core_tag\output\tagindex($tag, 'core', 'user', $content,
1230 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);