Merge branch 'install_master' of https://git.in.moodle.com/amosbot/moodle-install
[moodle.git] / user / lib.php
blobc53da28660037ec6388521c0af381e8357aa1a52
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
26 /**
27 * Creates a user
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) {
37 global $CFG, $DB;
39 // Set the timecreate field to the current time.
40 if (!is_object($user)) {
41 $user = (object) $user;
44 // Check username.
45 if ($user->username !== core_text::strtolower($user->username)) {
46 throw new moodle_exception('usernamelowercase');
47 } else {
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;
71 } else {
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.
113 if ($triggerevent) {
114 \core\event\user_created::create_from_userid($newuserid)->trigger();
117 return $newuserid;
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) {
130 global $DB;
132 // Set the timecreate field to the current time.
133 if (!is_object($user)) {
134 $user = (object) $user;
137 // Check username.
138 if (isset($user->username)) {
139 if ($user->username !== core_text::strtolower($user->username)) {
140 throw new moodle_exception('usernamelowercase');
141 } else {
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);
167 } else {
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.
188 if ($triggerevent) {
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);
206 * Get users by id
208 * @param array $userids id of users to retrieve
209 * @return array
211 function user_get_users_by_id($userids) {
212 global $DB;
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
244 * @return array|null
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));
276 } else {
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);
289 } else {
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);
295 } else {
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);
301 } else {
302 $canaccessallgroups = false;
305 if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
306 // Skip this user details.
307 return null;
310 $userdetails = array();
311 $userdetails['id'] = $user->id;
313 if (in_array('username', $userfields)) {
314 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
315 $userdetails['username'] = $user->username;
318 if ($isadmin or $canviewfullnames) {
319 if (in_array('firstname', $userfields)) {
320 $userdetails['firstname'] = $user->firstname;
322 if (in_array('lastname', $userfields)) {
323 $userdetails['lastname'] = $user->lastname;
326 $userdetails['fullname'] = fullname($user);
328 if (in_array('customfields', $userfields)) {
329 $fields = $DB->get_recordset_sql("SELECT f.*
330 FROM {user_info_field} f
331 JOIN {user_info_category} c
332 ON f.categoryid=c.id
333 ORDER BY c.sortorder ASC, f.sortorder ASC");
334 $userdetails['customfields'] = array();
335 foreach ($fields as $field) {
336 require_once($CFG->dirroot.'/user/profile/field/'.$field->datatype.'/field.class.php');
337 $newfield = 'profile_field_'.$field->datatype;
338 $formfield = new $newfield($field->id, $user->id);
339 if ($formfield->is_visible() and !$formfield->is_empty()) {
341 // TODO: Part of MDL-50728, this conditional coding must be moved to
342 // proper profile fields API so they are self-contained.
343 // We only use display_data in fields that require text formatting.
344 if ($field->datatype == 'text' or $field->datatype == 'textarea') {
345 $fieldvalue = $formfield->display_data();
346 } else {
347 // Cases: datetime, checkbox and menu.
348 $fieldvalue = $formfield->data;
351 $userdetails['customfields'][] =
352 array('name' => $formfield->field->name, 'value' => $fieldvalue,
353 'type' => $field->datatype, 'shortname' => $formfield->field->shortname);
356 $fields->close();
357 // Unset customfields if it's empty.
358 if (empty($userdetails['customfields'])) {
359 unset($userdetails['customfields']);
363 // Profile image.
364 if (in_array('profileimageurl', $userfields)) {
365 $profileimageurl = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', null, '/', 'f1');
366 $userdetails['profileimageurl'] = $profileimageurl->out(false);
368 if (in_array('profileimageurlsmall', $userfields)) {
369 $profileimageurlsmall = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', null, '/', 'f2');
370 $userdetails['profileimageurlsmall'] = $profileimageurlsmall->out(false);
373 // Hidden user field.
374 if ($canviewhiddenuserfields) {
375 $hiddenfields = array();
376 // Address, phone1 and phone2 not appears in hidden fields list but require viewhiddenfields capability
377 // according to user/profile.php.
378 if ($user->address && in_array('address', $userfields)) {
379 $userdetails['address'] = $user->address;
381 } else {
382 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
385 if ($user->phone1 && in_array('phone1', $userfields) &&
386 (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) {
387 $userdetails['phone1'] = $user->phone1;
389 if ($user->phone2 && in_array('phone2', $userfields) &&
390 (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) {
391 $userdetails['phone2'] = $user->phone2;
394 if (isset($user->description) &&
395 ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
396 if (in_array('description', $userfields)) {
397 // Always return the descriptionformat if description is requested.
398 list($userdetails['description'], $userdetails['descriptionformat']) =
399 external_format_text($user->description, $user->descriptionformat,
400 $usercontext->id, 'user', 'profile', null);
404 if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
405 $userdetails['country'] = $user->country;
408 if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
409 $userdetails['city'] = $user->city;
412 if (in_array('url', $userfields) && $user->url && (!isset($hiddenfields['webpage']) or $isadmin)) {
413 $url = $user->url;
414 if (strpos($user->url, '://') === false) {
415 $url = 'http://'. $url;
417 $user->url = clean_param($user->url, PARAM_URL);
418 $userdetails['url'] = $user->url;
421 if (in_array('icq', $userfields) && $user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) {
422 $userdetails['icq'] = $user->icq;
425 if (in_array('skype', $userfields) && $user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) {
426 $userdetails['skype'] = $user->skype;
428 if (in_array('yahoo', $userfields) && $user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) {
429 $userdetails['yahoo'] = $user->yahoo;
431 if (in_array('aim', $userfields) && $user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) {
432 $userdetails['aim'] = $user->aim;
434 if (in_array('msn', $userfields) && $user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) {
435 $userdetails['msn'] = $user->msn;
438 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
439 if ($user->firstaccess) {
440 $userdetails['firstaccess'] = $user->firstaccess;
441 } else {
442 $userdetails['firstaccess'] = 0;
445 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
446 if ($user->lastaccess) {
447 $userdetails['lastaccess'] = $user->lastaccess;
448 } else {
449 $userdetails['lastaccess'] = 0;
453 if (in_array('email', $userfields) && ($isadmin // The admin is allowed the users email.
454 or $currentuser // Of course the current user is as well.
455 or $canviewuseremail // This is a capability in course context, it will be false in usercontext.
456 or in_array('email', $showuseridentityfields)
457 or $user->maildisplay == 1
458 or ($user->maildisplay == 2 and enrol_sharing_course($user, $USER)))) {
459 $userdetails['email'] = $user->email;
462 if (in_array('interests', $userfields) && !empty($CFG->usetags)) {
463 require_once($CFG->dirroot . '/tag/lib.php');
464 if ($interests = tag_get_tags_csv('user', $user->id, TAG_RETURN_TEXT) ) {
465 $userdetails['interests'] = $interests;
469 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
470 if (in_array('idnumber', $userfields) && $user->idnumber) {
471 if (in_array('idnumber', $showuseridentityfields) or $currentuser or
472 has_capability('moodle/user:viewalldetails', $context)) {
473 $userdetails['idnumber'] = $user->idnumber;
476 if (in_array('institution', $userfields) && $user->institution) {
477 if (in_array('institution', $showuseridentityfields) or $currentuser or
478 has_capability('moodle/user:viewalldetails', $context)) {
479 $userdetails['institution'] = $user->institution;
482 // Isset because it's ok to have department 0.
483 if (in_array('department', $userfields) && isset($user->department)) {
484 if (in_array('department', $showuseridentityfields) or $currentuser or
485 has_capability('moodle/user:viewalldetails', $context)) {
486 $userdetails['department'] = $user->department;
490 if (in_array('roles', $userfields) && !empty($course)) {
491 // Not a big secret.
492 $roles = get_user_roles($context, $user->id, false);
493 $userdetails['roles'] = array();
494 foreach ($roles as $role) {
495 $userdetails['roles'][] = array(
496 'roleid' => $role->roleid,
497 'name' => $role->name,
498 'shortname' => $role->shortname,
499 'sortorder' => $role->sortorder
504 // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
505 if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
506 $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid,
507 'g.id, g.name,g.description,g.descriptionformat');
508 $userdetails['groups'] = array();
509 foreach ($usergroups as $group) {
510 list($group->description, $group->descriptionformat) =
511 external_format_text($group->description, $group->descriptionformat,
512 $context->id, 'group', 'description', $group->id);
513 $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name,
514 'description' => $group->description, 'descriptionformat' => $group->descriptionformat);
517 // List of courses where the user is enrolled.
518 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
519 $enrolledcourses = array();
520 if ($mycourses = enrol_get_users_courses($user->id, true)) {
521 foreach ($mycourses as $mycourse) {
522 if ($mycourse->category) {
523 $coursecontext = context_course::instance($mycourse->id);
524 $enrolledcourse = array();
525 $enrolledcourse['id'] = $mycourse->id;
526 $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
527 $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
528 $enrolledcourses[] = $enrolledcourse;
531 $userdetails['enrolledcourses'] = $enrolledcourses;
535 // User preferences.
536 if (in_array('preferences', $userfields) && $currentuser) {
537 $preferences = array();
538 $userpreferences = get_user_preferences();
539 foreach ($userpreferences as $prefname => $prefvalue) {
540 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
542 $userdetails['preferences'] = $preferences;
545 return $userdetails;
549 * Tries to obtain user details, either recurring directly to the user's system profile
550 * or through one of the user's course enrollments (course profile).
552 * @param stdClass $user The user.
553 * @return array if unsuccessful or the allowed user details.
555 function user_get_user_details_courses($user) {
556 global $USER;
557 $userdetails = null;
559 // Get the courses that the user is enrolled in (only active).
560 $courses = enrol_get_users_courses($user->id, true);
562 $systemprofile = false;
563 if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
564 $systemprofile = true;
567 // Try using system profile.
568 if ($systemprofile) {
569 $userdetails = user_get_user_details($user, null);
570 } else {
571 // Try through course profile.
572 foreach ($courses as $course) {
573 if (can_view_user_details_cap($user, $course) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
574 $userdetails = user_get_user_details($user, $course);
579 return $userdetails;
583 * Check if $USER have the necessary capabilities to obtain user details.
585 * @param stdClass $user
586 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
587 * @return bool true if $USER can view user details.
589 function can_view_user_details_cap($user, $course = null) {
590 // Check $USER has the capability to view the user details at user context.
591 $usercontext = context_user::instance($user->id);
592 $result = has_capability('moodle/user:viewdetails', $usercontext);
593 // Otherwise can $USER see them at course context.
594 if (!$result && !empty($course)) {
595 $context = context_course::instance($course->id);
596 $result = has_capability('moodle/user:viewdetails', $context);
598 return $result;
602 * Return a list of page types
603 * @param string $pagetype current page type
604 * @param stdClass $parentcontext Block's parent context
605 * @param stdClass $currentcontext Current context of block
606 * @return array
608 function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
609 return array('user-profile' => get_string('page-user-profile', 'pagetype'));
613 * Count the number of failed login attempts for the given user, since last successful login.
615 * @param int|stdclass $user user id or object.
616 * @param bool $reset Resets failed login count, if set to true.
618 * @return int number of failed login attempts since the last successful login.
620 function user_count_login_failures($user, $reset = true) {
621 global $DB;
623 if (!is_object($user)) {
624 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
626 if ($user->deleted) {
627 // Deleted user, nothing to do.
628 return 0;
630 $count = get_user_preferences('login_failed_count_since_success', 0, $user);
631 if ($reset) {
632 set_user_preference('login_failed_count_since_success', 0, $user);
634 return $count;
638 * Converts a string into a flat array of menu items, where each menu items is a
639 * stdClass with fields type, url, title, pix, and imgsrc.
641 * @param string $text the menu items definition
642 * @param moodle_page $page the current page
643 * @return array
645 function user_convert_text_to_menu_items($text, $page) {
646 global $OUTPUT, $CFG;
648 $lines = explode("\n", $text);
649 $items = array();
650 $lastchild = null;
651 $lastdepth = null;
652 $lastsort = 0;
653 $children = array();
654 foreach ($lines as $line) {
655 $line = trim($line);
656 $bits = explode('|', $line, 3);
657 $itemtype = 'link';
658 if (preg_match("/^#+$/", $line)) {
659 $itemtype = 'divider';
660 } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
661 // Every item must have a name to be valid.
662 continue;
663 } else {
664 $bits[0] = ltrim($bits[0], '-');
667 // Create the child.
668 $child = new stdClass();
669 $child->itemtype = $itemtype;
670 if ($itemtype === 'divider') {
671 // Add the divider to the list of children and skip link
672 // processing.
673 $children[] = $child;
674 continue;
677 // Name processing.
678 $namebits = explode(',', $bits[0], 2);
679 if (count($namebits) == 2) {
680 // Check the validity of the identifier part of the string.
681 if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
682 // Treat this as a language string.
683 $child->title = get_string($namebits[0], $namebits[1]);
686 if (empty($child->title)) {
687 // Use it as is, don't even clean it.
688 $child->title = $bits[0];
691 // URL processing.
692 if (!array_key_exists(1, $bits) or empty($bits[1])) {
693 // Set the url to null, and set the itemtype to invalid.
694 $bits[1] = null;
695 $child->itemtype = "invalid";
696 } else {
697 // Nasty hack to replace the grades with the direct url.
698 if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
699 $bits[1] = user_mygrades_url();
702 // Make sure the url is a moodle url.
703 $bits[1] = new moodle_url(trim($bits[1]));
705 $child->url = $bits[1];
707 // PIX processing.
708 $pixpath = "t/edit";
709 if (!array_key_exists(2, $bits) or empty($bits[2])) {
710 // Use the default.
711 $child->pix = $pixpath;
712 } else {
713 // Check for the specified image existing.
714 $pixpath = "t/" . $bits[2];
715 if ($page->theme->resolve_image_location($pixpath, 'moodle', true)) {
716 // Use the image.
717 $child->pix = $pixpath;
718 } else {
719 // Treat it like a URL.
720 $child->pix = null;
721 $child->imgsrc = $bits[2];
725 // Add this child to the list of children.
726 $children[] = $child;
728 return $children;
732 * Get a list of essential user navigation items.
734 * @param stdclass $user user object.
735 * @param moodle_page $page page object.
736 * @param array $options associative array.
737 * options are:
738 * - avatarsize=35 (size of avatar image)
739 * @return stdClass $returnobj navigation information object, where:
741 * $returnobj->navitems array array of links where each link is a
742 * stdClass with fields url, title, and
743 * pix
744 * $returnobj->metadata array array of useful user metadata to be
745 * used when constructing navigation;
746 * fields include:
748 * ROLE FIELDS
749 * asotherrole bool whether viewing as another role
750 * rolename string name of the role
752 * USER FIELDS
753 * These fields are for the currently-logged in user, or for
754 * the user that the real user is currently logged in as.
756 * userid int the id of the user in question
757 * userfullname string the user's full name
758 * userprofileurl moodle_url the url of the user's profile
759 * useravatar string a HTML fragment - the rendered
760 * user_picture for this user
761 * userloginfail string an error string denoting the number
762 * of login failures since last login
764 * "REAL USER" FIELDS
765 * These fields are for when asotheruser is true, and
766 * correspond to the underlying "real user".
768 * asotheruser bool whether viewing as another user
769 * realuserid int the id of the user in question
770 * realuserfullname string the user's full name
771 * realuserprofileurl moodle_url the url of the user's profile
772 * realuseravatar string a HTML fragment - the rendered
773 * user_picture for this user
775 * MNET PROVIDER FIELDS
776 * asmnetuser bool whether viewing as a user from an
777 * MNet provider
778 * mnetidprovidername string name of the MNet provider
779 * mnetidproviderwwwroot string URL of the MNet provider
781 function user_get_user_navigation_info($user, $page, $options = array()) {
782 global $OUTPUT, $DB, $SESSION, $CFG;
784 $returnobject = new stdClass();
785 $returnobject->navitems = array();
786 $returnobject->metadata = array();
788 $course = $page->course;
790 // Query the environment.
791 $context = context_course::instance($course->id);
793 // Get basic user metadata.
794 $returnobject->metadata['userid'] = $user->id;
795 $returnobject->metadata['userfullname'] = fullname($user, true);
796 $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
797 'id' => $user->id
800 $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
801 if (!empty($options['avatarsize'])) {
802 $avataroptions['size'] = $options['avatarsize'];
804 $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
805 $user, $avataroptions
807 // Build a list of items for a regular user.
809 // Query MNet status.
810 if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
811 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
812 $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
813 $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
816 // Did the user just log in?
817 if (isset($SESSION->justloggedin)) {
818 // Don't unset this flag as login_info still needs it.
819 if (!empty($CFG->displayloginfailures)) {
820 // We're already in /user/lib.php, so we don't need to include.
821 if ($count = user_count_login_failures($user)) {
823 // Get login failures string.
824 $a = new stdClass();
825 $a->attempts = html_writer::tag('span', $count, array('class' => 'value'));
826 $returnobject->metadata['userloginfail'] =
827 get_string('failedloginattempts', '', $a);
833 // Links: Dashboard.
834 $myhome = new stdClass();
835 $myhome->itemtype = 'link';
836 $myhome->url = new moodle_url('/my/');
837 $myhome->title = get_string('mymoodle', 'admin');
838 $myhome->pix = "i/course";
839 $returnobject->navitems[] = $myhome;
841 // Links: My Profile.
842 $myprofile = new stdClass();
843 $myprofile->itemtype = 'link';
844 $myprofile->url = new moodle_url('/user/profile.php', array('id' => $user->id));
845 $myprofile->title = get_string('profile');
846 $myprofile->pix = "i/user";
847 $returnobject->navitems[] = $myprofile;
849 // Links: Role-return or logout link.
850 $lastobj = null;
851 $buildlogout = true;
852 $returnobject->metadata['asotherrole'] = false;
853 if (is_role_switched($course->id)) {
854 if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
855 // Build role-return link instead of logout link.
856 $rolereturn = new stdClass();
857 $rolereturn->itemtype = 'link';
858 $rolereturn->url = new moodle_url('/course/switchrole.php', array(
859 'id' => $course->id,
860 'sesskey' => sesskey(),
861 'switchrole' => 0,
862 'returnurl' => $page->url->out_as_local_url(false)
864 $rolereturn->pix = "a/logout";
865 $rolereturn->title = get_string('switchrolereturn');
866 $lastobj = $rolereturn;
868 $returnobject->metadata['asotherrole'] = true;
869 $returnobject->metadata['rolename'] = role_get_name($role, $context);
871 $buildlogout = false;
875 if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
876 $realuser = \core\session\manager::get_realuser();
878 // Save values for the real user, as $user will be full of data for the
879 // user the user is disguised as.
880 $returnobject->metadata['realuserid'] = $realuser->id;
881 $returnobject->metadata['realuserfullname'] = fullname($realuser, true);
882 $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', array(
883 'id' => $realuser->id
885 $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
887 // Build a user-revert link.
888 $userrevert = new stdClass();
889 $userrevert->itemtype = 'link';
890 $userrevert->url = new moodle_url('/course/loginas.php', array(
891 'id' => $course->id,
892 'sesskey' => sesskey()
894 $userrevert->pix = "a/logout";
895 $userrevert->title = get_string('logout');
896 $lastobj = $userrevert;
898 $buildlogout = false;
901 if ($buildlogout) {
902 // Build a logout link.
903 $logout = new stdClass();
904 $logout->itemtype = 'link';
905 $logout->url = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
906 $logout->pix = "a/logout";
907 $logout->title = get_string('logout');
908 $lastobj = $logout;
911 // Before we add the last item (usually a logout link), add any
912 // custom-defined items.
913 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
914 foreach ($customitems as $item) {
915 $returnobject->navitems[] = $item;
918 // Add the last item to the list.
919 if (!is_null($lastobj)) {
920 $returnobject->navitems[] = $lastobj;
923 return $returnobject;
927 * Add password to the list of used hashes for this user.
929 * This is supposed to be used from:
930 * 1/ change own password form
931 * 2/ password reset process
932 * 3/ user signup in auth plugins if password changing supported
934 * @param int $userid user id
935 * @param string $password plaintext password
936 * @return void
938 function user_add_password_history($userid, $password) {
939 global $CFG, $DB;
940 require_once($CFG->libdir.'/password_compat/lib/password.php');
942 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
943 return;
946 // Note: this is using separate code form normal password hashing because
947 // we need to have this under control in the future. Also the auth
948 // plugin might not store the passwords locally at all.
950 $record = new stdClass();
951 $record->userid = $userid;
952 $record->hash = password_hash($password, PASSWORD_DEFAULT);
953 $record->timecreated = time();
954 $DB->insert_record('user_password_history', $record);
956 $i = 0;
957 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
958 foreach ($records as $record) {
959 $i++;
960 if ($i > $CFG->passwordreuselimit) {
961 $DB->delete_records('user_password_history', array('id' => $record->id));
967 * Was this password used before on change or reset password page?
969 * The $CFG->passwordreuselimit setting determines
970 * how many times different password needs to be used
971 * before allowing previously used password again.
973 * @param int $userid user id
974 * @param string $password plaintext password
975 * @return bool true if password reused
977 function user_is_previously_used_password($userid, $password) {
978 global $CFG, $DB;
979 require_once($CFG->libdir.'/password_compat/lib/password.php');
981 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
982 return false;
985 $reused = false;
987 $i = 0;
988 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
989 foreach ($records as $record) {
990 $i++;
991 if ($i > $CFG->passwordreuselimit) {
992 $DB->delete_records('user_password_history', array('id' => $record->id));
993 continue;
995 // NOTE: this is slow but we cannot compare the hashes directly any more.
996 if (password_verify($password, $record->hash)) {
997 $reused = true;
1001 return $reused;
1005 * Remove a user device from the Moodle database (for PUSH notifications usually).
1007 * @param string $uuid The device UUID.
1008 * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1009 * @return bool true if removed, false if the device didn't exists in the database
1010 * @since Moodle 2.9
1012 function user_remove_user_device($uuid, $appid = "") {
1013 global $DB, $USER;
1015 $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
1016 if (!empty($appid)) {
1017 $conditions['appid'] = $appid;
1020 if (!$DB->count_records('user_devices', $conditions)) {
1021 return false;
1024 $DB->delete_records('user_devices', $conditions);
1026 return true;
1030 * Trigger user_list_viewed event.
1032 * @param stdClass $course course object
1033 * @param stdClass $context course context object
1034 * @since Moodle 2.9
1036 function user_list_view($course, $context) {
1038 $event = \core\event\user_list_viewed::create(array(
1039 'objectid' => $course->id,
1040 'courseid' => $course->id,
1041 'context' => $context,
1042 'other' => array(
1043 'courseshortname' => $course->shortname,
1044 'coursefullname' => $course->fullname
1047 $event->trigger();
1051 * Returns the url to use for the "Grades" link in the user navigation.
1053 * @param int $userid The user's ID.
1054 * @param int $courseid The course ID if available.
1055 * @return mixed A URL to be directed to for "Grades".
1057 function user_mygrades_url($userid = null, $courseid = SITEID) {
1058 global $CFG, $USER;
1059 $url = null;
1060 if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
1061 if (isset($userid) && $USER->id != $userid) {
1062 // Send to the gradebook report.
1063 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
1064 array('id' => $courseid, 'userid' => $userid));
1065 } else {
1066 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
1068 } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
1069 && !empty($CFG->gradereport_mygradeurl)) {
1070 $url = $CFG->gradereport_mygradeurl;
1071 } else {
1072 $url = $CFG->wwwroot;
1074 return $url;
1078 * Check if a user has the permission to viewdetails in a shared course's context.
1080 * @param object $user The other user's details.
1081 * @param object $course Use this course to see if we have permission to see this user's profile.
1082 * @param context $usercontext The user context if available.
1083 * @return bool true for ability to view this user, else false.
1085 function user_can_view_profile($user, $course = null, $usercontext = null) {
1086 global $USER, $CFG;
1088 if ($user->deleted) {
1089 return false;
1092 // If any of these four things, return true.
1093 // Number 1.
1094 if ($USER->id == $user->id) {
1095 return true;
1098 // Number 2.
1099 if (empty($CFG->forceloginforprofiles)) {
1100 return true;
1103 if (empty($usercontext)) {
1104 $usercontext = context_user::instance($user->id);
1106 // Number 3.
1107 if (has_capability('moodle/user:viewdetails', $usercontext)) {
1108 return true;
1111 // Number 4.
1112 if (has_coursecontact_role($user->id)) {
1113 return true;
1116 if (isset($course)) {
1117 $sharedcourses = array($course);
1118 } else {
1119 $sharedcourses = enrol_get_shared_courses($USER->id, $user->id, true);
1121 foreach ($sharedcourses as $sharedcourse) {
1122 $coursecontext = context_course::instance($sharedcourse->id);
1123 if (has_capability('moodle/user:viewdetails', $coursecontext)) {
1124 if (!groups_user_groups_visible($sharedcourse, $user->id)) {
1125 // Not a member of the same group.
1126 continue;
1128 return true;
1131 return false;