MDL-53031 mod_assign: add session check on assignment plugins management
[moodle.git] / user / lib.php
blobdc137bb60340c2c10c424b8259bf7dfeacfc56f0
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;
92 $user->timecreated = time();
93 $user->timemodified = $user->timecreated;
95 // Insert the user into the database.
96 $newuserid = $DB->insert_record('user', $user);
98 // Create USER context for this user.
99 $usercontext = context_user::instance($newuserid);
101 // Update user password if necessary.
102 if (isset($userpassword)) {
103 // Get full database user row, in case auth is default.
104 $newuser = $DB->get_record('user', array('id' => $newuserid));
105 $authplugin = get_auth_plugin($newuser->auth);
106 $authplugin->user_update_password($newuser, $userpassword);
109 // Trigger event If required.
110 if ($triggerevent) {
111 \core\event\user_created::create_from_userid($newuserid)->trigger();
114 return $newuserid;
118 * Update a user with a user object (will compare against the ID)
120 * @throws moodle_exception
121 * @param stdClass $user the user to update
122 * @param bool $updatepassword if true, authentication plugin will update password.
123 * @param bool $triggerevent set false if user_updated event should not be triggred.
124 * This will not affect user_password_updated event triggering.
126 function user_update_user($user, $updatepassword = true, $triggerevent = true) {
127 global $DB;
129 // Set the timecreate field to the current time.
130 if (!is_object($user)) {
131 $user = (object) $user;
134 // Check username.
135 if (isset($user->username)) {
136 if ($user->username !== core_text::strtolower($user->username)) {
137 throw new moodle_exception('usernamelowercase');
138 } else {
139 if ($user->username !== clean_param($user->username, PARAM_USERNAME)) {
140 throw new moodle_exception('invalidusername');
145 // Unset password here, for updating later, if password update is required.
146 if ($updatepassword && isset($user->password)) {
148 // Check password toward the password policy.
149 if (!check_password_policy($user->password, $errmsg)) {
150 throw new moodle_exception($errmsg);
153 $passwd = $user->password;
154 unset($user->password);
157 // Make sure calendartype, if set, is valid.
158 if (!empty($user->calendartype)) {
159 $availablecalendartypes = \core_calendar\type_factory::get_list_of_calendar_types();
160 // If it doesn't exist, then unset this value, we do not want to update the user's value.
161 if (empty($availablecalendartypes[$user->calendartype])) {
162 unset($user->calendartype);
164 } else {
165 // Unset this variable, must be an empty string, which we do not want to update the calendartype to.
166 unset($user->calendartype);
169 $user->timemodified = time();
170 $DB->update_record('user', $user);
172 if ($updatepassword) {
173 // Get full user record.
174 $updateduser = $DB->get_record('user', array('id' => $user->id));
176 // If password was set, then update its hash.
177 if (isset($passwd)) {
178 $authplugin = get_auth_plugin($updateduser->auth);
179 if ($authplugin->can_change_password()) {
180 $authplugin->user_update_password($updateduser, $passwd);
184 // Trigger event if required.
185 if ($triggerevent) {
186 \core\event\user_updated::create_from_userid($user->id)->trigger();
191 * Marks user deleted in internal user database and notifies the auth plugin.
192 * Also unenrols user from all roles and does other cleanup.
194 * @todo Decide if this transaction is really needed (look for internal TODO:)
195 * @param object $user Userobject before delete (without system magic quotes)
196 * @return boolean success
198 function user_delete_user($user) {
199 return delete_user($user);
203 * Get users by id
205 * @param array $userids id of users to retrieve
206 * @return array
208 function user_get_users_by_id($userids) {
209 global $DB;
210 return $DB->get_records_list('user', 'id', $userids);
214 * Returns the list of default 'displayable' fields
216 * Contains database field names but also names used to generate information, such as enrolledcourses
218 * @return array of user fields
220 function user_get_default_fields() {
221 return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
222 'address', 'phone1', 'phone2', 'icq', 'skype', 'yahoo', 'aim', 'msn', 'department',
223 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
224 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
225 'city', 'url', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
226 'groups', 'roles', 'preferences', 'enrolledcourses'
232 * Give user record from mdl_user, build an array contains all user details.
234 * Warning: description file urls are 'webservice/pluginfile.php' is use.
235 * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
237 * @throws moodle_exception
238 * @param stdClass $user user record from mdl_user
239 * @param stdClass $course moodle course
240 * @param array $userfields required fields
241 * @return array|null
243 function user_get_user_details($user, $course = null, array $userfields = array()) {
244 global $USER, $DB, $CFG, $PAGE;
245 require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library.
246 require_once($CFG->dirroot . "/lib/filelib.php"); // File handling on description and friends.
248 $defaultfields = user_get_default_fields();
250 if (empty($userfields)) {
251 $userfields = $defaultfields;
254 foreach ($userfields as $thefield) {
255 if (!in_array($thefield, $defaultfields)) {
256 throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
260 // Make sure id and fullname are included.
261 if (!in_array('id', $userfields)) {
262 $userfields[] = 'id';
265 if (!in_array('fullname', $userfields)) {
266 $userfields[] = 'fullname';
269 if (!empty($course)) {
270 $context = context_course::instance($course->id);
271 $usercontext = context_user::instance($user->id);
272 $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext));
273 } else {
274 $context = context_user::instance($user->id);
275 $usercontext = $context;
276 $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
279 $currentuser = ($user->id == $USER->id);
280 $isadmin = is_siteadmin($USER);
282 $showuseridentityfields = get_extra_user_fields($context);
284 if (!empty($course)) {
285 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
286 } else {
287 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
289 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
290 if (!empty($course)) {
291 $canviewuseremail = has_capability('moodle/course:useremail', $context);
292 } else {
293 $canviewuseremail = false;
295 $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
296 if (!empty($course)) {
297 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
298 } else {
299 $canaccessallgroups = false;
302 if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
303 // Skip this user details.
304 return null;
307 $userdetails = array();
308 $userdetails['id'] = $user->id;
310 if (in_array('username', $userfields)) {
311 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
312 $userdetails['username'] = $user->username;
315 if ($isadmin or $canviewfullnames) {
316 if (in_array('firstname', $userfields)) {
317 $userdetails['firstname'] = $user->firstname;
319 if (in_array('lastname', $userfields)) {
320 $userdetails['lastname'] = $user->lastname;
323 $userdetails['fullname'] = fullname($user);
325 if (in_array('customfields', $userfields)) {
326 $fields = $DB->get_recordset_sql("SELECT f.*
327 FROM {user_info_field} f
328 JOIN {user_info_category} c
329 ON f.categoryid=c.id
330 ORDER BY c.sortorder ASC, f.sortorder ASC");
331 $userdetails['customfields'] = array();
332 foreach ($fields as $field) {
333 require_once($CFG->dirroot.'/user/profile/field/'.$field->datatype.'/field.class.php');
334 $newfield = 'profile_field_'.$field->datatype;
335 $formfield = new $newfield($field->id, $user->id);
336 if ($formfield->is_visible() and !$formfield->is_empty()) {
338 // We only use display_data in fields that require text formatting.
339 if ($field->datatype == 'text' or $field->datatype == 'textarea') {
340 $fieldvalue = $formfield->display_data();
341 } else {
342 // Cases: datetime, checkbox and menu.
343 $fieldvalue = $formfield->data;
346 $userdetails['customfields'][] =
347 array('name' => $formfield->field->name, 'value' => $fieldvalue,
348 'type' => $field->datatype, 'shortname' => $formfield->field->shortname);
351 $fields->close();
352 // Unset customfields if it's empty.
353 if (empty($userdetails['customfields'])) {
354 unset($userdetails['customfields']);
358 // Profile image.
359 if (in_array('profileimageurl', $userfields)) {
360 $userpicture = new user_picture($user);
361 $userpicture->size = 1; // Size f1.
362 $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
364 if (in_array('profileimageurlsmall', $userfields)) {
365 if (!isset($userpicture)) {
366 $userpicture = new user_picture($user);
368 $userpicture->size = 0; // Size f2.
369 $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
372 // Hidden user field.
373 if ($canviewhiddenuserfields) {
374 $hiddenfields = array();
375 // Address, phone1 and phone2 not appears in hidden fields list but require viewhiddenfields capability
376 // according to user/profile.php.
377 if ($user->address && in_array('address', $userfields)) {
378 $userdetails['address'] = $user->address;
380 } else {
381 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
384 if ($user->phone1 && in_array('phone1', $userfields) &&
385 (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) {
386 $userdetails['phone1'] = $user->phone1;
388 if ($user->phone2 && in_array('phone2', $userfields) &&
389 (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) {
390 $userdetails['phone2'] = $user->phone2;
393 if (isset($user->description) &&
394 ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
395 if (in_array('description', $userfields)) {
396 // Always return the descriptionformat if description is requested.
397 list($userdetails['description'], $userdetails['descriptionformat']) =
398 external_format_text($user->description, $user->descriptionformat,
399 $usercontext->id, 'user', 'profile', null);
403 if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
404 $userdetails['country'] = $user->country;
407 if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
408 $userdetails['city'] = $user->city;
411 if (in_array('url', $userfields) && $user->url && (!isset($hiddenfields['webpage']) or $isadmin)) {
412 $url = $user->url;
413 if (strpos($user->url, '://') === false) {
414 $url = 'http://'. $url;
416 $user->url = clean_param($user->url, PARAM_URL);
417 $userdetails['url'] = $user->url;
420 if (in_array('icq', $userfields) && $user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) {
421 $userdetails['icq'] = $user->icq;
424 if (in_array('skype', $userfields) && $user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) {
425 $userdetails['skype'] = $user->skype;
427 if (in_array('yahoo', $userfields) && $user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) {
428 $userdetails['yahoo'] = $user->yahoo;
430 if (in_array('aim', $userfields) && $user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) {
431 $userdetails['aim'] = $user->aim;
433 if (in_array('msn', $userfields) && $user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) {
434 $userdetails['msn'] = $user->msn;
437 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
438 if ($user->firstaccess) {
439 $userdetails['firstaccess'] = $user->firstaccess;
440 } else {
441 $userdetails['firstaccess'] = 0;
444 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
445 if ($user->lastaccess) {
446 $userdetails['lastaccess'] = $user->lastaccess;
447 } else {
448 $userdetails['lastaccess'] = 0;
452 if (in_array('email', $userfields) && ($isadmin // The admin is allowed the users email.
453 or $currentuser // Of course the current user is as well.
454 or $canviewuseremail // This is a capability in course context, it will be false in usercontext.
455 or in_array('email', $showuseridentityfields)
456 or $user->maildisplay == 1
457 or ($user->maildisplay == 2 and enrol_sharing_course($user, $USER)))) {
458 $userdetails['email'] = $user->email;
461 if (in_array('interests', $userfields) && !empty($CFG->usetags)) {
462 require_once($CFG->dirroot . '/tag/lib.php');
463 if ($interests = tag_get_tags_csv('user', $user->id, TAG_RETURN_TEXT) ) {
464 $userdetails['interests'] = $interests;
468 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
469 if (in_array('idnumber', $userfields) && $user->idnumber) {
470 if (in_array('idnumber', $showuseridentityfields) or $currentuser or
471 has_capability('moodle/user:viewalldetails', $context)) {
472 $userdetails['idnumber'] = $user->idnumber;
475 if (in_array('institution', $userfields) && $user->institution) {
476 if (in_array('institution', $showuseridentityfields) or $currentuser or
477 has_capability('moodle/user:viewalldetails', $context)) {
478 $userdetails['institution'] = $user->institution;
481 // Isset because it's ok to have department 0.
482 if (in_array('department', $userfields) && isset($user->department)) {
483 if (in_array('department', $showuseridentityfields) or $currentuser or
484 has_capability('moodle/user:viewalldetails', $context)) {
485 $userdetails['department'] = $user->department;
489 if (in_array('roles', $userfields) && !empty($course)) {
490 // Not a big secret.
491 $roles = get_user_roles($context, $user->id, false);
492 $userdetails['roles'] = array();
493 foreach ($roles as $role) {
494 $userdetails['roles'][] = array(
495 'roleid' => $role->roleid,
496 'name' => $role->name,
497 'shortname' => $role->shortname,
498 'sortorder' => $role->sortorder
503 // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
504 if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
505 $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid,
506 'g.id, g.name,g.description,g.descriptionformat');
507 $userdetails['groups'] = array();
508 foreach ($usergroups as $group) {
509 list($group->description, $group->descriptionformat) =
510 external_format_text($group->description, $group->descriptionformat,
511 $context->id, 'group', 'description', $group->id);
512 $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name,
513 'description' => $group->description, 'descriptionformat' => $group->descriptionformat);
516 // List of courses where the user is enrolled.
517 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
518 $enrolledcourses = array();
519 if ($mycourses = enrol_get_users_courses($user->id, true)) {
520 foreach ($mycourses as $mycourse) {
521 if ($mycourse->category) {
522 $coursecontext = context_course::instance($mycourse->id);
523 $enrolledcourse = array();
524 $enrolledcourse['id'] = $mycourse->id;
525 $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
526 $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
527 $enrolledcourses[] = $enrolledcourse;
530 $userdetails['enrolledcourses'] = $enrolledcourses;
534 // User preferences.
535 if (in_array('preferences', $userfields) && $currentuser) {
536 $preferences = array();
537 $userpreferences = get_user_preferences();
538 foreach ($userpreferences as $prefname => $prefvalue) {
539 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
541 $userdetails['preferences'] = $preferences;
544 return $userdetails;
548 * Tries to obtain user details, either recurring directly to the user's system profile
549 * or through one of the user's course enrollments (course profile).
551 * @param stdClass $user The user.
552 * @return array if unsuccessful or the allowed user details.
554 function user_get_user_details_courses($user) {
555 global $USER;
556 $userdetails = null;
558 // Get the courses that the user is enrolled in (only active).
559 $courses = enrol_get_users_courses($user->id, true);
561 $systemprofile = false;
562 if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
563 $systemprofile = true;
566 // Try using system profile.
567 if ($systemprofile) {
568 $userdetails = user_get_user_details($user, null);
569 } else {
570 // Try through course profile.
571 foreach ($courses as $course) {
572 if (can_view_user_details_cap($user, $course) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
573 $userdetails = user_get_user_details($user, $course);
578 return $userdetails;
582 * Check if $USER have the necessary capabilities to obtain user details.
584 * @param stdClass $user
585 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
586 * @return bool true if $USER can view user details.
588 function can_view_user_details_cap($user, $course = null) {
589 // Check $USER has the capability to view the user details at user context.
590 $usercontext = context_user::instance($user->id);
591 $result = has_capability('moodle/user:viewdetails', $usercontext);
592 // Otherwise can $USER see them at course context.
593 if (!$result && !empty($course)) {
594 $context = context_course::instance($course->id);
595 $result = has_capability('moodle/user:viewdetails', $context);
597 return $result;
601 * Return a list of page types
602 * @param string $pagetype current page type
603 * @param stdClass $parentcontext Block's parent context
604 * @param stdClass $currentcontext Current context of block
605 * @return array
607 function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
608 return array('user-profile' => get_string('page-user-profile', 'pagetype'));
612 * Count the number of failed login attempts for the given user, since last successful login.
614 * @param int|stdclass $user user id or object.
615 * @param bool $reset Resets failed login count, if set to true.
617 * @return int number of failed login attempts since the last successful login.
619 function user_count_login_failures($user, $reset = true) {
620 global $DB;
622 if (!is_object($user)) {
623 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
625 if ($user->deleted) {
626 // Deleted user, nothing to do.
627 return 0;
629 $count = get_user_preferences('login_failed_count_since_success', 0, $user);
630 if ($reset) {
631 set_user_preference('login_failed_count_since_success', 0, $user);
633 return $count;
637 * Converts a string into a flat array of menu items, where each menu items is a
638 * stdClass with fields type, url, title, pix, and imgsrc.
640 * @param string $text the menu items definition
641 * @param moodle_page $page the current page
642 * @return array
644 function user_convert_text_to_menu_items($text, $page) {
645 global $OUTPUT, $CFG;
647 $lines = explode("\n", $text);
648 $items = array();
649 $lastchild = null;
650 $lastdepth = null;
651 $lastsort = 0;
652 $children = array();
653 foreach ($lines as $line) {
654 $line = trim($line);
655 $bits = explode('|', $line, 3);
656 $itemtype = 'link';
657 if (preg_match("/^#+$/", $line)) {
658 $itemtype = 'divider';
659 } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
660 // Every item must have a name to be valid.
661 continue;
662 } else {
663 $bits[0] = ltrim($bits[0], '-');
666 // Create the child.
667 $child = new stdClass();
668 $child->itemtype = $itemtype;
669 if ($itemtype === 'divider') {
670 // Add the divider to the list of children and skip link
671 // processing.
672 $children[] = $child;
673 continue;
676 // Name processing.
677 $namebits = explode(',', $bits[0], 2);
678 if (count($namebits) == 2) {
679 // Check the validity of the identifier part of the string.
680 if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
681 // Treat this as a language string.
682 $child->title = get_string($namebits[0], $namebits[1]);
685 if (empty($child->title)) {
686 // Use it as is, don't even clean it.
687 $child->title = $bits[0];
690 // URL processing.
691 if (!array_key_exists(1, $bits) or empty($bits[1])) {
692 // Set the url to null, and set the itemtype to invalid.
693 $bits[1] = null;
694 $child->itemtype = "invalid";
695 } else {
696 // Make sure the url is a moodle url.
697 $bits[1] = new moodle_url(trim($bits[1]));
699 $child->url = $bits[1];
701 // PIX processing.
702 $pixpath = "t/edit";
703 if (!array_key_exists(2, $bits) or empty($bits[2])) {
704 // Use the default.
705 $child->pix = $pixpath;
706 } else {
707 // Check for the specified image existing.
708 $pixpath = "t/" . $bits[2];
709 if ($page->theme->resolve_image_location($pixpath, 'moodle', true)) {
710 // Use the image.
711 $child->pix = $pixpath;
712 } else {
713 // Treat it like a URL.
714 $child->pix = null;
715 $child->imgsrc = $bits[2];
719 // Add this child to the list of children.
720 $children[] = $child;
722 return $children;
726 * Get a list of essential user navigation items.
728 * @param stdclass $user user object.
729 * @param moodle_page $page page object.
730 * @return stdClass $returnobj navigation information object, where:
732 * $returnobj->navitems array array of links where each link is a
733 * stdClass with fields url, title, and
734 * pix
735 * $returnobj->metadata array array of useful user metadata to be
736 * used when constructing navigation;
737 * fields include:
739 * ROLE FIELDS
740 * asotherrole bool whether viewing as another role
741 * rolename string name of the role
743 * USER FIELDS
744 * These fields are for the currently-logged in user, or for
745 * the user that the real user is currently logged in as.
747 * userid int the id of the user in question
748 * userfullname string the user's full name
749 * userprofileurl moodle_url the url of the user's profile
750 * useravatar string a HTML fragment - the rendered
751 * user_picture for this user
752 * userloginfail string an error string denoting the number
753 * of login failures since last login
755 * "REAL USER" FIELDS
756 * These fields are for when asotheruser is true, and
757 * correspond to the underlying "real user".
759 * asotheruser bool whether viewing as another user
760 * realuserid int the id of the user in question
761 * realuserfullname string the user's full name
762 * realuserprofileurl moodle_url the url of the user's profile
763 * realuseravatar string a HTML fragment - the rendered
764 * user_picture for this user
766 * MNET PROVIDER FIELDS
767 * asmnetuser bool whether viewing as a user from an
768 * MNet provider
769 * mnetidprovidername string name of the MNet provider
770 * mnetidproviderwwwroot string URL of the MNet provider
772 function user_get_user_navigation_info($user, $page) {
773 global $OUTPUT, $DB, $SESSION, $CFG;
775 $returnobject = new stdClass();
776 $returnobject->navitems = array();
777 $returnobject->metadata = array();
779 $course = $page->course;
781 // Query the environment.
782 $context = context_course::instance($course->id);
784 // Get basic user metadata.
785 $returnobject->metadata['userid'] = $user->id;
786 $returnobject->metadata['userfullname'] = fullname($user, true);
787 $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
788 'id' => $user->id
790 $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
791 $user,
792 array(
793 'link' => false,
794 'visibletoscreenreaders' => false
797 // Build a list of items for a regular user.
799 // Query MNet status.
800 if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
801 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
802 $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
803 $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
806 // Did the user just log in?
807 if (isset($SESSION->justloggedin)) {
808 // Don't unset this flag as login_info still needs it.
809 if (!empty($CFG->displayloginfailures)) {
810 // We're already in /user/lib.php, so we don't need to include.
811 if ($count = user_count_login_failures($user)) {
813 // Get login failures string.
814 $a = new stdClass();
815 $a->attempts = html_writer::tag('span', $count, array('class' => 'value'));
816 $returnobject->metadata['userloginfail'] =
817 get_string('failedloginattempts', '', $a);
823 // Links: My Home.
824 $myhome = new stdClass();
825 $myhome->itemtype = 'link';
826 $myhome->url = new moodle_url('/my/');
827 $myhome->title = get_string('mymoodle', 'admin');
828 $myhome->pix = "i/course";
829 $returnobject->navitems[] = $myhome;
831 // Links: My Profile.
832 $myprofile = new stdClass();
833 $myprofile->itemtype = 'link';
834 $myprofile->url = new moodle_url('/user/profile.php', array('id' => $user->id));
835 $myprofile->title = get_string('myprofile');
836 $myprofile->pix = "i/user";
837 $returnobject->navitems[] = $myprofile;
839 // Links: Role-return or logout link.
840 $lastobj = null;
841 $buildlogout = true;
842 $returnobject->metadata['asotherrole'] = false;
843 if (is_role_switched($course->id)) {
844 if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
845 // Build role-return link instead of logout link.
846 $rolereturn = new stdClass();
847 $rolereturn->itemtype = 'link';
848 $rolereturn->url = new moodle_url('/course/switchrole.php', array(
849 'id' => $course->id,
850 'sesskey' => sesskey(),
851 'switchrole' => 0,
852 'returnurl' => $page->url->out_as_local_url(false)
854 $rolereturn->pix = "a/logout";
855 $rolereturn->title = get_string('switchrolereturn');
856 $lastobj = $rolereturn;
858 $returnobject->metadata['asotherrole'] = true;
859 $returnobject->metadata['rolename'] = role_get_name($role, $context);
861 $buildlogout = false;
865 if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
866 $realuser = \core\session\manager::get_realuser();
868 // Save values for the real user, as $user will be full of data for the
869 // user the user is disguised as.
870 $returnobject->metadata['realuserid'] = $realuser->id;
871 $returnobject->metadata['realuserfullname'] = fullname($realuser, true);
872 $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', array(
873 'id' => $realuser->id
875 $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture (
876 $realuser,
877 array(
878 'link' => false,
879 'visibletoscreenreaders' => false
883 // Build a user-revert link.
884 $userrevert = new stdClass();
885 $userrevert->itemtype = 'link';
886 $userrevert->url = new moodle_url('/course/loginas.php', array(
887 'id' => $course->id,
888 'sesskey' => sesskey()
890 $userrevert->pix = "a/logout";
891 $userrevert->title = get_string('logout');
892 $lastobj = $userrevert;
894 $buildlogout = false;
897 if ($buildlogout) {
898 // Build a logout link.
899 $logout = new stdClass();
900 $logout->itemtype = 'link';
901 $logout->url = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
902 $logout->pix = "a/logout";
903 $logout->title = get_string('logout');
904 $lastobj = $logout;
907 // Before we add the last item (usually a logout link), add any
908 // custom-defined items.
909 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
910 foreach ($customitems as $item) {
911 $returnobject->navitems[] = $item;
914 // Add the last item to the list.
915 if (!is_null($lastobj)) {
916 $returnobject->navitems[] = $lastobj;
919 return $returnobject;