2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
21 * @copyright 2009 Moodle Pty Ltd (http://moodle.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 * @throws moodle_exception
30 * @param stdClass $user user to create
31 * @param bool $updatepassword if true, authentication plugin will update password.
32 * @param bool $triggerevent set false if user_created event should not be triggred.
33 * This will not affect user_password_updated event triggering.
34 * @return int id of the newly created user
36 function user_create_user($user, $updatepassword = true, $triggerevent = true) {
39 // Set the timecreate field to the current time.
40 if (!is_object($user)) {
41 $user = (object) $user;
45 if ($user->username !== core_text::strtolower($user->username)) {
46 throw new moodle_exception('usernamelowercase');
48 if ($user->username !== clean_param($user->username, PARAM_USERNAME)) {
49 throw new moodle_exception('invalidusername');
53 // Save the password in a temp value for later.
54 if ($updatepassword && isset($user->password)) {
56 // Check password toward the password policy.
57 if (!check_password_policy($user->password, $errmsg)) {
58 throw new moodle_exception($errmsg);
61 $userpassword = $user->password;
62 unset($user->password);
65 // Make sure calendartype, if set, is valid.
66 if (!empty($user->calendartype)) {
67 $availablecalendartypes = \core_calendar\type_factory::get_list_of_calendar_types();
68 if (empty($availablecalendartypes[$user->calendartype])) {
69 $user->calendartype = $CFG->calendartype;
72 $user->calendartype = $CFG->calendartype;
75 // Apply default values for user preferences that are stored in users table.
76 if (!isset($user->maildisplay)) {
77 $user->maildisplay = $CFG->defaultpreference_maildisplay;
79 if (!isset($user->mailformat)) {
80 $user->mailformat = $CFG->defaultpreference_mailformat;
82 if (!isset($user->maildigest)) {
83 $user->maildigest = $CFG->defaultpreference_maildigest;
85 if (!isset($user->autosubscribe)) {
86 $user->autosubscribe = $CFG->defaultpreference_autosubscribe;
88 if (!isset($user->trackforums)) {
89 $user->trackforums = $CFG->defaultpreference_trackforums;
91 if (!isset($user->lang)) {
92 $user->lang = $CFG->lang;
95 $user->timecreated = time();
96 $user->timemodified = $user->timecreated;
98 // Insert the user into the database.
99 $newuserid = $DB->insert_record('user', $user);
101 // Create USER context for this user.
102 $usercontext = context_user::instance($newuserid);
104 // Update user password if necessary.
105 if (isset($userpassword)) {
106 // Get full database user row, in case auth is default.
107 $newuser = $DB->get_record('user', array('id' => $newuserid));
108 $authplugin = get_auth_plugin($newuser->auth);
109 $authplugin->user_update_password($newuser, $userpassword);
112 // Trigger event If required.
114 \core\event\user_created::create_from_userid($newuserid)->trigger();
121 * Update a user with a user object (will compare against the ID)
123 * @throws moodle_exception
124 * @param stdClass $user the user to update
125 * @param bool $updatepassword if true, authentication plugin will update password.
126 * @param bool $triggerevent set false if user_updated event should not be triggred.
127 * This will not affect user_password_updated event triggering.
129 function user_update_user($user, $updatepassword = true, $triggerevent = true) {
132 // Set the timecreate field to the current time.
133 if (!is_object($user)) {
134 $user = (object) $user;
138 if (isset($user->username)) {
139 if ($user->username !== core_text::strtolower($user->username)) {
140 throw new moodle_exception('usernamelowercase');
142 if ($user->username !== clean_param($user->username, PARAM_USERNAME)) {
143 throw new moodle_exception('invalidusername');
148 // Unset password here, for updating later, if password update is required.
149 if ($updatepassword && isset($user->password)) {
151 // Check password toward the password policy.
152 if (!check_password_policy($user->password, $errmsg)) {
153 throw new moodle_exception($errmsg);
156 $passwd = $user->password;
157 unset($user->password);
160 // Make sure calendartype, if set, is valid.
161 if (!empty($user->calendartype)) {
162 $availablecalendartypes = \core_calendar\type_factory::get_list_of_calendar_types();
163 // If it doesn't exist, then unset this value, we do not want to update the user's value.
164 if (empty($availablecalendartypes[$user->calendartype])) {
165 unset($user->calendartype);
168 // Unset this variable, must be an empty string, which we do not want to update the calendartype to.
169 unset($user->calendartype);
172 $user->timemodified = time();
173 $DB->update_record('user', $user);
175 if ($updatepassword) {
176 // Get full user record.
177 $updateduser = $DB->get_record('user', array('id' => $user->id));
179 // If password was set, then update its hash.
180 if (isset($passwd)) {
181 $authplugin = get_auth_plugin($updateduser->auth);
182 if ($authplugin->can_change_password()) {
183 $authplugin->user_update_password($updateduser, $passwd);
187 // Trigger event if required.
189 \core\event\user_updated::create_from_userid($user->id)->trigger();
194 * Marks user deleted in internal user database and notifies the auth plugin.
195 * Also unenrols user from all roles and does other cleanup.
197 * @todo Decide if this transaction is really needed (look for internal TODO:)
198 * @param object $user Userobject before delete (without system magic quotes)
199 * @return boolean success
201 function user_delete_user($user) {
202 return delete_user($user);
208 * @param array $userids id of users to retrieve
211 function user_get_users_by_id($userids) {
213 return $DB->get_records_list('user', 'id', $userids);
217 * Returns the list of default 'displayable' fields
219 * Contains database field names but also names used to generate information, such as enrolledcourses
221 * @return array of user fields
223 function user_get_default_fields() {
224 return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
225 'address', 'phone1', 'phone2', 'icq', 'skype', 'yahoo', 'aim', 'msn', 'department',
226 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
227 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
228 'city', 'url', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
229 'groups', 'roles', 'preferences', 'enrolledcourses'
235 * Give user record from mdl_user, build an array contains all user details.
237 * Warning: description file urls are 'webservice/pluginfile.php' is use.
238 * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
240 * @throws moodle_exception
241 * @param stdClass $user user record from mdl_user
242 * @param stdClass $course moodle course
243 * @param array $userfields required fields
246 function user_get_user_details($user, $course = null, array $userfields = array()) {
247 global $USER, $DB, $CFG;
248 require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library.
249 require_once($CFG->dirroot . "/lib/filelib.php"); // File handling on description and friends.
251 $defaultfields = user_get_default_fields();
253 if (empty($userfields)) {
254 $userfields = $defaultfields;
257 foreach ($userfields as $thefield) {
258 if (!in_array($thefield, $defaultfields)) {
259 throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
263 // Make sure id and fullname are included.
264 if (!in_array('id', $userfields)) {
265 $userfields[] = 'id';
268 if (!in_array('fullname', $userfields)) {
269 $userfields[] = 'fullname';
272 if (!empty($course)) {
273 $context = context_course::instance($course->id);
274 $usercontext = context_user::instance($user->id);
275 $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext));
277 $context = context_user::instance($user->id);
278 $usercontext = $context;
279 $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
282 $currentuser = ($user->id == $USER->id);
283 $isadmin = is_siteadmin($USER);
285 $showuseridentityfields = get_extra_user_fields($context);
287 if (!empty($course)) {
288 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
290 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
292 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
293 if (!empty($course)) {
294 $canviewuseremail = has_capability('moodle/course:useremail', $context);
296 $canviewuseremail = false;
298 $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
299 if (!empty($course)) {
300 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
302 $canaccessallgroups = false;
305 if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
306 // Skip this user details.
310 $userdetails = array();
311 $userdetails['id'] = $user->id;
313 if (($isadmin or $currentuser) and in_array('username', $userfields)) {
314 $userdetails['username'] = $user->username;
316 if ($isadmin or $canviewfullnames) {
317 if (in_array('firstname', $userfields)) {
318 $userdetails['firstname'] = $user->firstname;
320 if (in_array('lastname', $userfields)) {
321 $userdetails['lastname'] = $user->lastname;
324 $userdetails['fullname'] = fullname($user);
326 if (in_array('customfields', $userfields)) {
327 $fields = $DB->get_recordset_sql("SELECT f.*
328 FROM {user_info_field} f
329 JOIN {user_info_category} c
331 ORDER BY c.sortorder ASC, f.sortorder ASC");
332 $userdetails['customfields'] = array();
333 foreach ($fields as $field) {
334 require_once($CFG->dirroot.'/user/profile/field/'.$field->datatype.'/field.class.php');
335 $newfield = 'profile_field_'.$field->datatype;
336 $formfield = new $newfield($field->id, $user->id);
337 if ($formfield->is_visible() and !$formfield->is_empty()) {
339 // We only use display_data in fields that require text formatting.
340 if ($field->datatype == 'text' or $field->datatype == 'textarea') {
341 $fieldvalue = $formfield->display_data();
343 // Cases: datetime, checkbox and menu.
344 $fieldvalue = $formfield->data;
347 $userdetails['customfields'][] =
348 array('name' => $formfield->field->name, 'value' => $fieldvalue,
349 'type' => $field->datatype, 'shortname' => $formfield->field->shortname);
353 // Unset customfields if it's empty.
354 if (empty($userdetails['customfields'])) {
355 unset($userdetails['customfields']);
360 if (in_array('profileimageurl', $userfields)) {
361 $profileimageurl = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', null, '/', 'f1');
362 $userdetails['profileimageurl'] = $profileimageurl->out(false);
364 if (in_array('profileimageurlsmall', $userfields)) {
365 $profileimageurlsmall = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', null, '/', 'f2');
366 $userdetails['profileimageurlsmall'] = $profileimageurlsmall->out(false);
369 // Hidden user field.
370 if ($canviewhiddenuserfields) {
371 $hiddenfields = array();
372 // Address, phone1 and phone2 not appears in hidden fields list but require viewhiddenfields capability
373 // according to user/profile.php.
374 if ($user->address && in_array('address', $userfields)) {
375 $userdetails['address'] = $user->address;
378 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
381 if ($user->phone1 && in_array('phone1', $userfields) &&
382 (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) {
383 $userdetails['phone1'] = $user->phone1;
385 if ($user->phone2 && in_array('phone2', $userfields) &&
386 (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) {
387 $userdetails['phone2'] = $user->phone2;
390 if (isset($user->description) &&
391 ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
392 if (in_array('description', $userfields)) {
393 // Always return the descriptionformat if description is requested.
394 list($userdetails['description'], $userdetails['descriptionformat']) =
395 external_format_text($user->description, $user->descriptionformat,
396 $usercontext->id, 'user', 'profile', null);
400 if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
401 $userdetails['country'] = $user->country;
404 if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
405 $userdetails['city'] = $user->city;
408 if (in_array('url', $userfields) && $user->url && (!isset($hiddenfields['webpage']) or $isadmin)) {
410 if (strpos($user->url, '://') === false) {
411 $url = 'http://'. $url;
413 $user->url = clean_param($user->url, PARAM_URL);
414 $userdetails['url'] = $user->url;
417 if (in_array('icq', $userfields) && $user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) {
418 $userdetails['icq'] = $user->icq;
421 if (in_array('skype', $userfields) && $user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) {
422 $userdetails['skype'] = $user->skype;
424 if (in_array('yahoo', $userfields) && $user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) {
425 $userdetails['yahoo'] = $user->yahoo;
427 if (in_array('aim', $userfields) && $user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) {
428 $userdetails['aim'] = $user->aim;
430 if (in_array('msn', $userfields) && $user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) {
431 $userdetails['msn'] = $user->msn;
434 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
435 if ($user->firstaccess) {
436 $userdetails['firstaccess'] = $user->firstaccess;
438 $userdetails['firstaccess'] = 0;
441 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
442 if ($user->lastaccess) {
443 $userdetails['lastaccess'] = $user->lastaccess;
445 $userdetails['lastaccess'] = 0;
449 if (in_array('email', $userfields) && ($isadmin // The admin is allowed the users email.
450 or $currentuser // Of course the current user is as well.
451 or $canviewuseremail // This is a capability in course context, it will be false in usercontext.
452 or in_array('email', $showuseridentityfields)
453 or $user->maildisplay == 1
454 or ($user->maildisplay == 2 and enrol_sharing_course($user, $USER)))) {
455 $userdetails['email'] = $user->email;
458 if (in_array('interests', $userfields) && !empty($CFG->usetags)) {
459 require_once($CFG->dirroot . '/tag/lib.php');
460 if ($interests = tag_get_tags_csv('user', $user->id, TAG_RETURN_TEXT) ) {
461 $userdetails['interests'] = $interests;
465 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
466 if ($isadmin or $currentuser or in_array('idnumber', $showuseridentityfields)) {
467 if (in_array('idnumber', $userfields) && $user->idnumber) {
468 $userdetails['idnumber'] = $user->idnumber;
471 if ($isadmin or $currentuser or in_array('institution', $showuseridentityfields)) {
472 if (in_array('institution', $userfields) && $user->institution) {
473 $userdetails['institution'] = $user->institution;
476 if ($isadmin or $currentuser or in_array('department', $showuseridentityfields)) {
477 if (in_array('department', $userfields) && isset($user->department)) { // Isset because it's ok to have department 0.
478 $userdetails['department'] = $user->department;
482 if (in_array('roles', $userfields) && !empty($course)) {
484 $roles = get_user_roles($context, $user->id, false);
485 $userdetails['roles'] = array();
486 foreach ($roles as $role) {
487 $userdetails['roles'][] = array(
488 'roleid' => $role->roleid,
489 'name' => $role->name,
490 'shortname' => $role->shortname,
491 'sortorder' => $role->sortorder
496 // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
497 if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
498 $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid,
499 'g.id, g.name,g.description,g.descriptionformat');
500 $userdetails['groups'] = array();
501 foreach ($usergroups as $group) {
502 list($group->description, $group->descriptionformat) =
503 external_format_text($group->description, $group->descriptionformat,
504 $context->id, 'group', 'description', $group->id);
505 $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name,
506 'description' => $group->description, 'descriptionformat' => $group->descriptionformat);
509 // List of courses where the user is enrolled.
510 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
511 $enrolledcourses = array();
512 if ($mycourses = enrol_get_users_courses($user->id, true)) {
513 foreach ($mycourses as $mycourse) {
514 if ($mycourse->category) {
515 $coursecontext = context_course::instance($mycourse->id);
516 $enrolledcourse = array();
517 $enrolledcourse['id'] = $mycourse->id;
518 $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
519 $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
520 $enrolledcourses[] = $enrolledcourse;
523 $userdetails['enrolledcourses'] = $enrolledcourses;
528 if (in_array('preferences', $userfields) && $currentuser) {
529 $preferences = array();
530 $userpreferences = get_user_preferences();
531 foreach ($userpreferences as $prefname => $prefvalue) {
532 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
534 $userdetails['preferences'] = $preferences;
541 * Tries to obtain user details, either recurring directly to the user's system profile
542 * or through one of the user's course enrollments (course profile).
544 * @param stdClass $user The user.
545 * @return array if unsuccessful or the allowed user details.
547 function user_get_user_details_courses($user) {
551 // Get the courses that the user is enrolled in (only active).
552 $courses = enrol_get_users_courses($user->id, true);
554 $systemprofile = false;
555 if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
556 $systemprofile = true;
559 // Try using system profile.
560 if ($systemprofile) {
561 $userdetails = user_get_user_details($user, null);
563 // Try through course profile.
564 foreach ($courses as $course) {
565 if (can_view_user_details_cap($user, $course) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
566 $userdetails = user_get_user_details($user, $course);
575 * Check if $USER have the necessary capabilities to obtain user details.
577 * @param stdClass $user
578 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
579 * @return bool true if $USER can view user details.
581 function can_view_user_details_cap($user, $course = null) {
582 // Check $USER has the capability to view the user details at user context.
583 $usercontext = context_user::instance($user->id);
584 $result = has_capability('moodle/user:viewdetails', $usercontext);
585 // Otherwise can $USER see them at course context.
586 if (!$result && !empty($course)) {
587 $context = context_course::instance($course->id);
588 $result = has_capability('moodle/user:viewdetails', $context);
594 * Return a list of page types
595 * @param string $pagetype current page type
596 * @param stdClass $parentcontext Block's parent context
597 * @param stdClass $currentcontext Current context of block
600 function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
601 return array('user-profile' => get_string('page-user-profile', 'pagetype'));
605 * Count the number of failed login attempts for the given user, since last successful login.
607 * @param int|stdclass $user user id or object.
608 * @param bool $reset Resets failed login count, if set to true.
610 * @return int number of failed login attempts since the last successful login.
612 function user_count_login_failures($user, $reset = true) {
615 if (!is_object($user)) {
616 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
618 if ($user->deleted) {
619 // Deleted user, nothing to do.
622 $count = get_user_preferences('login_failed_count_since_success', 0, $user);
624 set_user_preference('login_failed_count_since_success', 0, $user);
630 * Converts a string into a flat array of menu items, where each menu items is a
631 * stdClass with fields type, url, title, pix, and imgsrc.
633 * @param string $text the menu items definition
634 * @param moodle_page $page the current page
637 function user_convert_text_to_menu_items($text, $page) {
638 global $OUTPUT, $CFG;
640 $lines = explode("\n", $text);
646 foreach ($lines as $line) {
648 $bits = explode('|', $line, 3);
650 if (preg_match("/^#+$/", $line)) {
651 $itemtype = 'divider';
652 } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
653 // Every item must have a name to be valid.
656 $bits[0] = ltrim($bits[0], '-');
660 $child = new stdClass();
661 $child->itemtype = $itemtype;
662 if ($itemtype === 'divider') {
663 // Add the divider to the list of children and skip link
665 $children[] = $child;
670 $namebits = explode(',', $bits[0], 2);
671 if (count($namebits) == 2) {
672 // Check the validity of the identifier part of the string.
673 if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
674 // Treat this as a language string.
675 $child->title = get_string($namebits[0], $namebits[1]);
678 if (empty($child->title)) {
679 // Use it as is, don't even clean it.
680 $child->title = $bits[0];
684 if (!array_key_exists(1, $bits) or empty($bits[1])) {
685 // Set the url to null, and set the itemtype to invalid.
687 $child->itemtype = "invalid";
689 // Nasty hack to replace the grades with the direct url.
690 if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
691 $bits[1] = user_mygrades_url();
694 // Make sure the url is a moodle url.
695 $bits[1] = new moodle_url(trim($bits[1]));
697 $child->url = $bits[1];
701 if (!array_key_exists(2, $bits) or empty($bits[2])) {
703 $child->pix = $pixpath;
705 // Check for the specified image existing.
706 $pixpath = "t/" . $bits[2];
707 if ($page->theme->resolve_image_location($pixpath, 'moodle', true)) {
709 $child->pix = $pixpath;
711 // Treat it like a URL.
713 $child->imgsrc = $bits[2];
717 // Add this child to the list of children.
718 $children[] = $child;
724 * Get a list of essential user navigation items.
726 * @param stdclass $user user object.
727 * @param moodle_page $page page object.
728 * @return stdClass $returnobj navigation information object, where:
730 * $returnobj->navitems array array of links where each link is a
731 * stdClass with fields url, title, and
733 * $returnobj->metadata array array of useful user metadata to be
734 * used when constructing navigation;
738 * asotherrole bool whether viewing as another role
739 * rolename string name of the role
742 * These fields are for the currently-logged in user, or for
743 * the user that the real user is currently logged in as.
745 * userid int the id of the user in question
746 * userfullname string the user's full name
747 * userprofileurl moodle_url the url of the user's profile
748 * useravatar string a HTML fragment - the rendered
749 * user_picture for this user
750 * userloginfail string an error string denoting the number
751 * of login failures since last login
754 * These fields are for when asotheruser is true, and
755 * correspond to the underlying "real user".
757 * asotheruser bool whether viewing as another user
758 * realuserid int the id of the user in question
759 * realuserfullname string the user's full name
760 * realuserprofileurl moodle_url the url of the user's profile
761 * realuseravatar string a HTML fragment - the rendered
762 * user_picture for this user
764 * MNET PROVIDER FIELDS
765 * asmnetuser bool whether viewing as a user from an
767 * mnetidprovidername string name of the MNet provider
768 * mnetidproviderwwwroot string URL of the MNet provider
770 function user_get_user_navigation_info($user, $page) {
771 global $OUTPUT, $DB, $SESSION, $CFG;
773 $returnobject = new stdClass();
774 $returnobject->navitems = array();
775 $returnobject->metadata = array();
777 $course = $page->course;
779 // Query the environment.
780 $context = context_course::instance($course->id);
782 // Get basic user metadata.
783 $returnobject->metadata['userid'] = $user->id;
784 $returnobject->metadata['userfullname'] = fullname($user, true);
785 $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
788 $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
792 'visibletoscreenreaders' => false
795 // Build a list of items for a regular user.
797 // Query MNet status.
798 if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
799 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
800 $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
801 $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
804 // Did the user just log in?
805 if (isset($SESSION->justloggedin)) {
806 // Don't unset this flag as login_info still needs it.
807 if (!empty($CFG->displayloginfailures)) {
808 // We're already in /user/lib.php, so we don't need to include.
809 if ($count = user_count_login_failures($user)) {
811 // Get login failures string.
813 $a->attempts = html_writer::tag('span', $count, array('class' => 'value'));
814 $returnobject->metadata['userloginfail'] =
815 get_string('failedloginattempts', '', $a);
822 $myhome = new stdClass();
823 $myhome->itemtype = 'link';
824 $myhome->url = new moodle_url('/my/');
825 $myhome->title = get_string('mymoodle', 'admin');
826 $myhome->pix = "i/course";
827 $returnobject->navitems[] = $myhome;
829 // Links: My Profile.
830 $myprofile = new stdClass();
831 $myprofile->itemtype = 'link';
832 $myprofile->url = new moodle_url('/user/profile.php', array('id' => $user->id));
833 $myprofile->title = get_string('profile');
834 $myprofile->pix = "i/user";
835 $returnobject->navitems[] = $myprofile;
837 // Links: Role-return or logout link.
840 $returnobject->metadata['asotherrole'] = false;
841 if (is_role_switched($course->id)) {
842 if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
843 // Build role-return link instead of logout link.
844 $rolereturn = new stdClass();
845 $rolereturn->itemtype = 'link';
846 $rolereturn->url = new moodle_url('/course/switchrole.php', array(
848 'sesskey' => sesskey(),
850 'returnurl' => $page->url->out_as_local_url(false)
852 $rolereturn->pix = "a/logout";
853 $rolereturn->title = get_string('switchrolereturn');
854 $lastobj = $rolereturn;
856 $returnobject->metadata['asotherrole'] = true;
857 $returnobject->metadata['rolename'] = role_get_name($role, $context);
859 $buildlogout = false;
863 if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
864 $realuser = \core\session\manager::get_realuser();
866 // Save values for the real user, as $user will be full of data for the
867 // user the user is disguised as.
868 $returnobject->metadata['realuserid'] = $realuser->id;
869 $returnobject->metadata['realuserfullname'] = fullname($realuser, true);
870 $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', array(
871 'id' => $realuser->id
873 $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture (
877 'visibletoscreenreaders' => false
881 // Build a user-revert link.
882 $userrevert = new stdClass();
883 $userrevert->itemtype = 'link';
884 $userrevert->url = new moodle_url('/course/loginas.php', array(
886 'sesskey' => sesskey()
888 $userrevert->pix = "a/logout";
889 $userrevert->title = get_string('logout');
890 $lastobj = $userrevert;
892 $buildlogout = false;
896 // Build a logout link.
897 $logout = new stdClass();
898 $logout->itemtype = 'link';
899 $logout->url = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
900 $logout->pix = "a/logout";
901 $logout->title = get_string('logout');
905 // Before we add the last item (usually a logout link), add any
906 // custom-defined items.
907 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
908 foreach ($customitems as $item) {
909 $returnobject->navitems[] = $item;
912 // Add the last item to the list.
913 if (!is_null($lastobj)) {
914 $returnobject->navitems[] = $lastobj;
917 return $returnobject;
921 * Add password to the list of used hashes for this user.
923 * This is supposed to be used from:
924 * 1/ change own password form
925 * 2/ password reset process
926 * 3/ user signup in auth plugins if password changing supported
928 * @param int $userid user id
929 * @param string $password plaintext password
932 function user_add_password_history($userid, $password) {
934 require_once($CFG->libdir.'/password_compat/lib/password.php');
936 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
940 // Note: this is using separate code form normal password hashing because
941 // we need to have this under control in the future. Also the auth
942 // plugin might not store the passwords locally at all.
944 $record = new stdClass();
945 $record->userid = $userid;
946 $record->hash = password_hash($password, PASSWORD_DEFAULT);
947 $record->timecreated = time();
948 $DB->insert_record('user_password_history', $record);
951 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
952 foreach ($records as $record) {
954 if ($i > $CFG->passwordreuselimit) {
955 $DB->delete_records('user_password_history', array('id' => $record->id));
961 * Was this password used before on change or reset password page?
963 * The $CFG->passwordreuselimit setting determines
964 * how many times different password needs to be used
965 * before allowing previously used password again.
967 * @param int $userid user id
968 * @param string $password plaintext password
969 * @return bool true if password reused
971 function user_is_previously_used_password($userid, $password) {
973 require_once($CFG->libdir.'/password_compat/lib/password.php');
975 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
982 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
983 foreach ($records as $record) {
985 if ($i > $CFG->passwordreuselimit) {
986 $DB->delete_records('user_password_history', array('id' => $record->id));
989 // NOTE: this is slow but we cannot compare the hashes directly any more.
990 if (password_verify($password, $record->hash)) {
999 * Remove a user device from the Moodle database (for PUSH notifications usually).
1001 * @param string $uuid The device UUID.
1002 * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1003 * @return bool true if removed, false if the device didn't exists in the database
1006 function user_remove_user_device($uuid, $appid = "") {
1009 $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
1010 if (!empty($appid)) {
1011 $conditions['appid'] = $appid;
1014 if (!$DB->count_records('user_devices', $conditions)) {
1018 $DB->delete_records('user_devices', $conditions);
1024 * Trigger user_list_viewed event.
1026 * @param stdClass $course course object
1027 * @param stdClass $context course context object
1030 function user_list_view($course, $context) {
1032 $event = \core\event\user_list_viewed::create(array(
1033 'objectid' => $course->id,
1034 'courseid' => $course->id,
1035 'context' => $context,
1037 'courseshortname' => $course->shortname,
1038 'coursefullname' => $course->fullname
1045 * Returns the url to use for the "Grades" link in the user navigation.
1047 * @param int $userid The user's ID.
1048 * @param int $courseid The course ID if available.
1049 * @return mixed A URL to be directed to for "Grades".
1051 function user_mygrades_url($userid = null, $courseid = SITEID) {
1054 if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
1055 if (isset($userid) && $USER->id != $userid) {
1056 // Send to the gradebook report.
1057 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
1058 array('id' => $courseid, 'userid' => $userid));
1060 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
1062 } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
1063 && !empty($CFG->gradereport_mygradeurl)) {
1064 $url = $CFG->gradereport_mygradeurl;
1066 $url = $CFG->wwwroot;