Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
/user/ -> lib.php (source)

Differences Between: [Versions 310 and 311] [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

   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.
  13  //
  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/>.
  16  
  17  /**
  18   * External user API
  19   *
  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
  23   */
  24  
  25  define('USER_FILTER_ENROLMENT', 1);
  26  define('USER_FILTER_GROUP', 2);
  27  define('USER_FILTER_LAST_ACCESS', 3);
  28  define('USER_FILTER_ROLE', 4);
  29  define('USER_FILTER_STATUS', 5);
  30  define('USER_FILTER_STRING', 6);
  31  
  32  /**
  33   * Creates a user
  34   *
  35   * @throws moodle_exception
  36   * @param stdClass $user user to create
  37   * @param bool $updatepassword if true, authentication plugin will update password.
  38   * @param bool $triggerevent set false if user_created event should not be triggred.
  39   *             This will not affect user_password_updated event triggering.
  40   * @return int id of the newly created user
  41   */
  42  function user_create_user($user, $updatepassword = true, $triggerevent = true) {
  43      global $DB;
  44  
  45      // Set the timecreate field to the current time.
  46      if (!is_object($user)) {
  47          $user = (object) $user;
  48      }
  49  
  50      // Check username.
  51      if (trim($user->username) === '') {
  52          throw new moodle_exception('invalidusernameblank');
  53      }
  54  
  55      if ($user->username !== core_text::strtolower($user->username)) {
  56          throw new moodle_exception('usernamelowercase');
  57      }
  58  
  59      if ($user->username !== core_user::clean_field($user->username, 'username')) {
  60          throw new moodle_exception('invalidusername');
  61      }
  62  
  63      // Save the password in a temp value for later.
  64      if ($updatepassword && isset($user->password)) {
  65  
  66          // Check password toward the password policy.
  67          if (!check_password_policy($user->password, $errmsg, $user)) {
  68              throw new moodle_exception($errmsg);
  69          }
  70  
  71          $userpassword = $user->password;
  72          unset($user->password);
  73      }
  74  
  75      // Apply default values for user preferences that are stored in users table.
  76      if (!isset($user->calendartype)) {
  77          $user->calendartype = core_user::get_property_default('calendartype');
  78      }
  79      if (!isset($user->maildisplay)) {
  80          $user->maildisplay = core_user::get_property_default('maildisplay');
  81      }
  82      if (!isset($user->mailformat)) {
  83          $user->mailformat = core_user::get_property_default('mailformat');
  84      }
  85      if (!isset($user->maildigest)) {
  86          $user->maildigest = core_user::get_property_default('maildigest');
  87      }
  88      if (!isset($user->autosubscribe)) {
  89          $user->autosubscribe = core_user::get_property_default('autosubscribe');
  90      }
  91      if (!isset($user->trackforums)) {
  92          $user->trackforums = core_user::get_property_default('trackforums');
  93      }
  94      if (!isset($user->lang)) {
  95          $user->lang = core_user::get_property_default('lang');
  96      }
  97      if (!isset($user->city)) {
  98          $user->city = core_user::get_property_default('city');
  99      }
 100      if (!isset($user->country)) {
 101          // The default value of $CFG->country is 0, but that isn't a valid property for the user field, so switch to ''.
 102          $user->country = core_user::get_property_default('country') ?: '';
 103      }
 104  
 105      $user->timecreated = time();
 106      $user->timemodified = $user->timecreated;
 107  
 108      // Validate user data object.
 109      $uservalidation = core_user::validate($user);
 110      if ($uservalidation !== true) {
 111          foreach ($uservalidation as $field => $message) {
 112              debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
 113              $user->$field = core_user::clean_field($user->$field, $field);
 114          }
 115      }
 116  
 117      // Insert the user into the database.
 118      $newuserid = $DB->insert_record('user', $user);
 119  
 120      // Create USER context for this user.
 121      $usercontext = context_user::instance($newuserid);
 122  
 123      // Update user password if necessary.
 124      if (isset($userpassword)) {
 125          // Get full database user row, in case auth is default.
 126          $newuser = $DB->get_record('user', array('id' => $newuserid));
 127          $authplugin = get_auth_plugin($newuser->auth);
 128          $authplugin->user_update_password($newuser, $userpassword);
 129      }
 130  
 131      // Trigger event If required.
 132      if ($triggerevent) {
 133          \core\event\user_created::create_from_userid($newuserid)->trigger();
 134      }
 135  
 136      // Purge the associated caches for the current user only.
 137      $presignupcache = \cache::make('core', 'presignup');
 138      $presignupcache->purge_current_user();
 139  
 140      return $newuserid;
 141  }
 142  
 143  /**
 144   * Update a user with a user object (will compare against the ID)
 145   *
 146   * @throws moodle_exception
 147   * @param stdClass $user the user to update
 148   * @param bool $updatepassword if true, authentication plugin will update password.
 149   * @param bool $triggerevent set false if user_updated event should not be triggred.
 150   *             This will not affect user_password_updated event triggering.
 151   */
 152  function user_update_user($user, $updatepassword = true, $triggerevent = true) {
 153      global $DB;
 154  
 155      // Set the timecreate field to the current time.
 156      if (!is_object($user)) {
 157          $user = (object) $user;
 158      }
 159  
 160      // Check username.
 161      if (isset($user->username)) {
 162          if ($user->username !== core_text::strtolower($user->username)) {
 163              throw new moodle_exception('usernamelowercase');
 164          } else {
 165              if ($user->username !== core_user::clean_field($user->username, 'username')) {
 166                  throw new moodle_exception('invalidusername');
 167              }
 168          }
 169      }
 170  
 171      // Unset password here, for updating later, if password update is required.
 172      if ($updatepassword && isset($user->password)) {
 173  
 174          // Check password toward the password policy.
 175          if (!check_password_policy($user->password, $errmsg, $user)) {
 176              throw new moodle_exception($errmsg);
 177          }
 178  
 179          $passwd = $user->password;
 180          unset($user->password);
 181      }
 182  
 183      // Make sure calendartype, if set, is valid.
 184      if (empty($user->calendartype)) {
 185          // Unset this variable, must be an empty string, which we do not want to update the calendartype to.
 186          unset($user->calendartype);
 187      }
 188  
 189      $user->timemodified = time();
 190  
 191      // Validate user data object.
 192      $uservalidation = core_user::validate($user);
 193      if ($uservalidation !== true) {
 194          foreach ($uservalidation as $field => $message) {
 195              debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
 196              $user->$field = core_user::clean_field($user->$field, $field);
 197          }
 198      }
 199  
 200      $DB->update_record('user', $user);
 201  
 202      if ($updatepassword) {
 203          // Get full user record.
 204          $updateduser = $DB->get_record('user', array('id' => $user->id));
 205  
 206          // If password was set, then update its hash.
 207          if (isset($passwd)) {
 208              $authplugin = get_auth_plugin($updateduser->auth);
 209              if ($authplugin->can_change_password()) {
 210                  $authplugin->user_update_password($updateduser, $passwd);
 211              }
 212          }
 213      }
 214      // Trigger event if required.
 215      if ($triggerevent) {
 216          \core\event\user_updated::create_from_userid($user->id)->trigger();
 217      }
 218  }
 219  
 220  /**
 221   * Marks user deleted in internal user database and notifies the auth plugin.
 222   * Also unenrols user from all roles and does other cleanup.
 223   *
 224   * @todo Decide if this transaction is really needed (look for internal TODO:)
 225   * @param object $user Userobject before delete    (without system magic quotes)
 226   * @return boolean success
 227   */
 228  function user_delete_user($user) {
 229      return delete_user($user);
 230  }
 231  
 232  /**
 233   * Get users by id
 234   *
 235   * @param array $userids id of users to retrieve
 236   * @return array
 237   */
 238  function user_get_users_by_id($userids) {
 239      global $DB;
 240      return $DB->get_records_list('user', 'id', $userids);
 241  }
 242  
 243  /**
 244   * Returns the list of default 'displayable' fields
 245   *
 246   * Contains database field names but also names used to generate information, such as enrolledcourses
 247   *
 248   * @return array of user fields
 249   */
 250  function user_get_default_fields() {
 251      return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
 252          'address', 'phone1', 'phone2', 'department',
 253          'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
 254          'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
 255          'city', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
 256          'groups', 'roles', 'preferences', 'enrolledcourses', 'suspended', 'lastcourseaccess'
 257      );
 258  }
 259  
 260  /**
 261   *
 262   * Give user record from mdl_user, build an array contains all user details.
 263   *
 264   * Warning: description file urls are 'webservice/pluginfile.php' is use.
 265   *          it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
 266   *
 267   * @throws moodle_exception
 268   * @param stdClass $user user record from mdl_user
 269   * @param stdClass $course moodle course
 270   * @param array $userfields required fields
 271   * @return array|null
 272   */
 273  function user_get_user_details($user, $course = null, array $userfields = array()) {
 274      global $USER, $DB, $CFG, $PAGE;
 275      require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library.
 276      require_once($CFG->dirroot . "/lib/filelib.php");      // File handling on description and friends.
 277  
 278      $defaultfields = user_get_default_fields();
 279  
 280      if (empty($userfields)) {
 281          $userfields = $defaultfields;
 282      }
 283  
 284      foreach ($userfields as $thefield) {
 285          if (!in_array($thefield, $defaultfields)) {
 286              throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
 287          }
 288      }
 289  
 290      // Make sure id and fullname are included.
 291      if (!in_array('id', $userfields)) {
 292          $userfields[] = 'id';
 293      }
 294  
 295      if (!in_array('fullname', $userfields)) {
 296          $userfields[] = 'fullname';
 297      }
 298  
 299      if (!empty($course)) {
 300          $context = context_course::instance($course->id);
 301          $usercontext = context_user::instance($user->id);
 302          $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext));
 303      } else {
 304          $context = context_user::instance($user->id);
 305          $usercontext = $context;
 306          $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
 307      }
 308  
 309      $currentuser = ($user->id == $USER->id);
 310      $isadmin = is_siteadmin($USER);
 311  
 312      // This does not need to include custom profile fields as it is only used to check specific
 313      // fields below.
 314      $showuseridentityfields = \core_user\fields::get_identity_fields($context, false);
 315  
 316      if (!empty($course)) {
 317          $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
 318      } else {
 319          $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
 320      }
 321      $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
 322      if (!empty($course)) {
 323          $canviewuseremail = has_capability('moodle/course:useremail', $context);
 324      } else {
 325          $canviewuseremail = false;
 326      }
 327      $cannotviewdescription   = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
 328      if (!empty($course)) {
 329          $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
 330      } else {
 331          $canaccessallgroups = false;
 332      }
 333  
 334      if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
 335          // Skip this user details.
 336          return null;
 337      }
 338  
 339      $userdetails = array();
 340      $userdetails['id'] = $user->id;
 341  
 342      if (in_array('username', $userfields)) {
 343          if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
 344              $userdetails['username'] = $user->username;
 345          }
 346      }
 347      if ($isadmin or $canviewfullnames) {
 348          if (in_array('firstname', $userfields)) {
 349              $userdetails['firstname'] = $user->firstname;
 350          }
 351          if (in_array('lastname', $userfields)) {
 352              $userdetails['lastname'] = $user->lastname;
 353          }
 354      }
 355      $userdetails['fullname'] = fullname($user, $canviewfullnames);
 356  
 357      if (in_array('customfields', $userfields)) {
 358          $categories = profile_get_user_fields_with_data_by_category($user->id);
 359          $userdetails['customfields'] = array();
 360          foreach ($categories as $categoryid => $fields) {
 361              foreach ($fields as $formfield) {
 362                  if ($formfield->is_visible() and !$formfield->is_empty()) {
 363  
 364                      // TODO: Part of MDL-50728, this conditional coding must be moved to
 365                      // proper profile fields API so they are self-contained.
 366                      // We only use display_data in fields that require text formatting.
 367                      if ($formfield->field->datatype == 'text' or $formfield->field->datatype == 'textarea') {
 368                          $fieldvalue = $formfield->display_data();
 369                      } else {
 370                          // Cases: datetime, checkbox and menu.
 371                          $fieldvalue = $formfield->data;
 372                      }
 373  
 374                      $userdetails['customfields'][] =
 375                          array('name' => $formfield->field->name, 'value' => $fieldvalue,
 376                              'type' => $formfield->field->datatype, 'shortname' => $formfield->field->shortname);
 377                  }
 378              }
 379          }
 380          // Unset customfields if it's empty.
 381          if (empty($userdetails['customfields'])) {
 382              unset($userdetails['customfields']);
 383          }
 384      }
 385  
 386      // Profile image.
 387      if (in_array('profileimageurl', $userfields)) {
 388          $userpicture = new user_picture($user);
 389          $userpicture->size = 1; // Size f1.
 390          $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
 391      }
 392      if (in_array('profileimageurlsmall', $userfields)) {
 393          if (!isset($userpicture)) {
 394              $userpicture = new user_picture($user);
 395          }
 396          $userpicture->size = 0; // Size f2.
 397          $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
 398      }
 399  
 400      // Hidden user field.
 401      if ($canviewhiddenuserfields) {
 402          $hiddenfields = array();
 403          // Address, phone1 and phone2 not appears in hidden fields list but require viewhiddenfields capability
 404          // according to user/profile.php.
 405          if (!empty($user->address) && in_array('address', $userfields)) {
 406              $userdetails['address'] = $user->address;
 407          }
 408      } else {
 409          $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
 410      }
 411  
 412      if (!empty($user->phone1) && in_array('phone1', $userfields) &&
 413              (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) {
 414          $userdetails['phone1'] = $user->phone1;
 415      }
 416      if (!empty($user->phone2) && in_array('phone2', $userfields) &&
 417              (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) {
 418          $userdetails['phone2'] = $user->phone2;
 419      }
 420  
 421      if (isset($user->description) &&
 422          ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
 423          if (in_array('description', $userfields)) {
 424              // Always return the descriptionformat if description is requested.
 425              list($userdetails['description'], $userdetails['descriptionformat']) =
 426                      external_format_text($user->description, $user->descriptionformat,
 427                              $usercontext->id, 'user', 'profile', null);
 428          }
 429      }
 430  
 431      if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
 432          $userdetails['country'] = $user->country;
 433      }
 434  
 435      if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
 436          $userdetails['city'] = $user->city;
 437      }
 438  
 439      if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) {
 440          $userdetails['suspended'] = (bool)$user->suspended;
 441      }
 442  
 443      if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
 444          if ($user->firstaccess) {
 445              $userdetails['firstaccess'] = $user->firstaccess;
 446          } else {
 447              $userdetails['firstaccess'] = 0;
 448          }
 449      }
 450      if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
 451          if ($user->lastaccess) {
 452              $userdetails['lastaccess'] = $user->lastaccess;
 453          } else {
 454              $userdetails['lastaccess'] = 0;
 455          }
 456      }
 457  
 458      // Hidden fields restriction to lastaccess field applies to both site and course access time.
 459      if (in_array('lastcourseaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
 460          if (isset($user->lastcourseaccess)) {
 461              $userdetails['lastcourseaccess'] = $user->lastcourseaccess;
 462          } else {
 463              $userdetails['lastcourseaccess'] = 0;
 464          }
 465      }
 466  
 467      if (in_array('email', $userfields) && (
 468              $currentuser
 469              or (!isset($hiddenfields['email']) and (
 470                  $user->maildisplay == core_user::MAILDISPLAY_EVERYONE
 471                  or ($user->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY and enrol_sharing_course($user, $USER))
 472                  or $canviewuseremail  // TODO: Deprecate/remove for MDL-37479.
 473              ))
 474              or in_array('email', $showuseridentityfields)
 475         )) {
 476          $userdetails['email'] = $user->email;
 477      }
 478  
 479      if (in_array('interests', $userfields)) {
 480          $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
 481          if ($interests) {
 482              $userdetails['interests'] = join(', ', $interests);
 483          }
 484      }
 485  
 486      // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
 487      if (in_array('idnumber', $userfields) && $user->idnumber) {
 488          if (in_array('idnumber', $showuseridentityfields) or $currentuser or
 489                  has_capability('moodle/user:viewalldetails', $context)) {
 490              $userdetails['idnumber'] = $user->idnumber;
 491          }
 492      }
 493      if (in_array('institution', $userfields) && $user->institution) {
 494          if (in_array('institution', $showuseridentityfields) or $currentuser or
 495                  has_capability('moodle/user:viewalldetails', $context)) {
 496              $userdetails['institution'] = $user->institution;
 497          }
 498      }
 499      // Isset because it's ok to have department 0.
 500      if (in_array('department', $userfields) && isset($user->department)) {
 501          if (in_array('department', $showuseridentityfields) or $currentuser or
 502                  has_capability('moodle/user:viewalldetails', $context)) {
 503              $userdetails['department'] = $user->department;
 504          }
 505      }
 506  
 507      if (in_array('roles', $userfields) && !empty($course)) {
 508          // Not a big secret.
 509          $roles = get_user_roles($context, $user->id, false);
 510          $userdetails['roles'] = array();
 511          foreach ($roles as $role) {
 512              $userdetails['roles'][] = array(
 513                  'roleid'       => $role->roleid,
 514                  'name'         => $role->name,
 515                  'shortname'    => $role->shortname,
 516                  'sortorder'    => $role->sortorder
 517              );
 518          }
 519      }
 520  
 521      // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
 522      if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
 523          $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid,
 524                  'g.id, g.name,g.description,g.descriptionformat');
 525          $userdetails['groups'] = array();
 526          foreach ($usergroups as $group) {
 527              list($group->description, $group->descriptionformat) =
 528                  external_format_text($group->description, $group->descriptionformat,
 529                          $context->id, 'group', 'description', $group->id);
 530              $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name,
 531                  'description' => $group->description, 'descriptionformat' => $group->descriptionformat);
 532          }
 533      }
 534      // List of courses where the user is enrolled.
 535      if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
 536          $enrolledcourses = array();
 537          if ($mycourses = enrol_get_users_courses($user->id, true)) {
 538              foreach ($mycourses as $mycourse) {
 539                  if ($mycourse->category) {
 540                      $coursecontext = context_course::instance($mycourse->id);
 541                      $enrolledcourse = array();
 542                      $enrolledcourse['id'] = $mycourse->id;
 543                      $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
 544                      $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
 545                      $enrolledcourses[] = $enrolledcourse;
 546                  }
 547              }
 548              $userdetails['enrolledcourses'] = $enrolledcourses;
 549          }
 550      }
 551  
 552      // User preferences.
 553      if (in_array('preferences', $userfields) && $currentuser) {
 554          $preferences = array();
 555          $userpreferences = get_user_preferences();
 556          foreach ($userpreferences as $prefname => $prefvalue) {
 557              $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
 558          }
 559          $userdetails['preferences'] = $preferences;
 560      }
 561  
 562      if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
 563          $extrafields = ['auth', 'confirmed', 'lang', 'theme', 'timezone', 'mailformat'];
 564          foreach ($extrafields as $extrafield) {
 565              if (in_array($extrafield, $userfields) && isset($user->$extrafield)) {
 566                  $userdetails[$extrafield] = $user->$extrafield;
 567              }
 568          }
 569      }
 570  
 571      // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
 572      if (isset($userdetails['lang'])) {
 573          $userdetails['lang'] = clean_param($userdetails['lang'], PARAM_LANG);
 574      }
 575      if (isset($userdetails['theme'])) {
 576          $userdetails['theme'] = clean_param($userdetails['theme'], PARAM_THEME);
 577      }
 578  
 579      return $userdetails;
 580  }
 581  
 582  /**
 583   * Tries to obtain user details, either recurring directly to the user's system profile
 584   * or through one of the user's course enrollments (course profile).
 585   *
 586   * @param stdClass $user The user.
 587   * @return array if unsuccessful or the allowed user details.
 588   */
 589  function user_get_user_details_courses($user) {
 590      global $USER;
 591      $userdetails = null;
 592  
 593      $systemprofile = false;
 594      if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
 595          $systemprofile = true;
 596      }
 597  
 598      // Try using system profile.
 599      if ($systemprofile) {
 600          $userdetails = user_get_user_details($user, null);
 601      } else {
 602          // Try through course profile.
 603          // Get the courses that the user is enrolled in (only active).
 604          $courses = enrol_get_users_courses($user->id, true);
 605          foreach ($courses as $course) {
 606              if (user_can_view_profile($user, $course)) {
 607                  $userdetails = user_get_user_details($user, $course);
 608              }
 609          }
 610      }
 611  
 612      return $userdetails;
 613  }
 614  
 615  /**
 616   * Check if $USER have the necessary capabilities to obtain user details.
 617   *
 618   * @param stdClass $user
 619   * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
 620   * @return bool true if $USER can view user details.
 621   */
 622  function can_view_user_details_cap($user, $course = null) {
 623      // Check $USER has the capability to view the user details at user context.
 624      $usercontext = context_user::instance($user->id);
 625      $result = has_capability('moodle/user:viewdetails', $usercontext);
 626      // Otherwise can $USER see them at course context.
 627      if (!$result && !empty($course)) {
 628          $context = context_course::instance($course->id);
 629          $result = has_capability('moodle/user:viewdetails', $context);
 630      }
 631      return $result;
 632  }
 633  
 634  /**
 635   * Return a list of page types
 636   * @param string $pagetype current page type
 637   * @param stdClass $parentcontext Block's parent context
 638   * @param stdClass $currentcontext Current context of block
 639   * @return array
 640   */
 641  function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
 642      return array('user-profile' => get_string('page-user-profile', 'pagetype'));
 643  }
 644  
 645  /**
 646   * Count the number of failed login attempts for the given user, since last successful login.
 647   *
 648   * @param int|stdclass $user user id or object.
 649   * @param bool $reset Resets failed login count, if set to true.
 650   *
 651   * @return int number of failed login attempts since the last successful login.
 652   */
 653  function user_count_login_failures($user, $reset = true) {
 654      global $DB;
 655  
 656      if (!is_object($user)) {
 657          $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
 658      }
 659      if ($user->deleted) {
 660          // Deleted user, nothing to do.
 661          return 0;
 662      }
 663      $count = get_user_preferences('login_failed_count_since_success', 0, $user);
 664      if ($reset) {
 665          set_user_preference('login_failed_count_since_success', 0, $user);
 666      }
 667      return $count;
 668  }
 669  
 670  /**
 671   * Converts a string into a flat array of menu items, where each menu items is a
 672   * stdClass with fields type, url, title, pix, and imgsrc.
 673   *
 674   * @param string $text the menu items definition
 675   * @param moodle_page $page the current page
 676   * @return array
 677   */
 678  function user_convert_text_to_menu_items($text, $page) {
 679      global $OUTPUT, $CFG;
 680  
 681      $lines = explode("\n", $text);
 682      $items = array();
 683      $lastchild = null;
 684      $lastdepth = null;
 685      $lastsort = 0;
 686      $children = array();
 687      foreach ($lines as $line) {
 688          $line = trim($line);
 689          $bits = explode('|', $line, 3);
 690          $itemtype = 'link';
 691          if (preg_match("/^#+$/", $line)) {
 692              $itemtype = 'divider';
 693          } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
 694              // Every item must have a name to be valid.
 695              continue;
 696          } else {
 697              $bits[0] = ltrim($bits[0], '-');
 698          }
 699  
 700          // Create the child.
 701          $child = new stdClass();
 702          $child->itemtype = $itemtype;
 703          if ($itemtype === 'divider') {
 704              // Add the divider to the list of children and skip link
 705              // processing.
 706              $children[] = $child;
 707              continue;
 708          }
 709  
 710          // Name processing.
 711          $namebits = explode(',', $bits[0], 2);
 712          if (count($namebits) == 2) {
 713              // Check the validity of the identifier part of the string.
 714              if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
 715                  // Treat this as a language string.
 716                  $child->title = get_string($namebits[0], $namebits[1]);
 717                  $child->titleidentifier = implode(',', $namebits);
 718              }
 719          }
 720          if (empty($child->title)) {
 721              // Use it as is, don't even clean it.
 722              $child->title = $bits[0];
 723              $child->titleidentifier = str_replace(" ", "-", $bits[0]);
 724          }
 725  
 726          // URL processing.
 727          if (!array_key_exists(1, $bits) or empty($bits[1])) {
 728              // Set the url to null, and set the itemtype to invalid.
 729              $bits[1] = null;
 730              $child->itemtype = "invalid";
 731          } else {
 732              // Nasty hack to replace the grades with the direct url.
 733              if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
 734                  $bits[1] = user_mygrades_url();
 735              }
 736  
 737              // Make sure the url is a moodle url.
 738              $bits[1] = new moodle_url(trim($bits[1]));
 739          }
 740          $child->url = $bits[1];
 741  
 742          // PIX processing.
 743          $pixpath = "t/edit";
 744          if (!array_key_exists(2, $bits) or empty($bits[2])) {
 745              // Use the default.
 746              $child->pix = $pixpath;
 747          } else {
 748              // Check for the specified image existing.
 749              if (strpos($bits[2], '../') === 0) {
 750                  // The string starts with '../'.
 751                  // Strip off the first three characters - this should be the pix path.
 752                  $pixpath = substr($bits[2], 3);
 753              } else if (strpos($bits[2], '/') === false) {
 754                  // There is no / in the path. Prefix it with 't/', which is the default path.
 755                  $pixpath = "t/{$bits[2]}";
 756              } else {
 757                  // There is a '/' in the path - this is either a URL, or a standard pix path with no changes required.
 758                  $pixpath = $bits[2];
 759              }
 760              if ($page->theme->resolve_image_location($pixpath, 'moodle', true)) {
 761                  // Use the image.
 762                  $child->pix = $pixpath;
 763              } else {
 764                  // Treat it like a URL.
 765                  $child->pix = null;
 766                  $child->imgsrc = $bits[2];
 767              }
 768          }
 769  
 770          // Add this child to the list of children.
 771          $children[] = $child;
 772      }
 773      return $children;
 774  }
 775  
 776  /**
 777   * Get a list of essential user navigation items.
 778   *
 779   * @param stdclass $user user object.
 780   * @param moodle_page $page page object.
 781   * @param array $options associative array.
 782   *     options are:
 783   *     - avatarsize=35 (size of avatar image)
 784   * @return stdClass $returnobj navigation information object, where:
 785   *
 786   *      $returnobj->navitems    array    array of links where each link is a
 787   *                                       stdClass with fields url, title, and
 788   *                                       pix
 789   *      $returnobj->metadata    array    array of useful user metadata to be
 790   *                                       used when constructing navigation;
 791   *                                       fields include:
 792   *
 793   *          ROLE FIELDS
 794   *          asotherrole    bool    whether viewing as another role
 795   *          rolename       string  name of the role
 796   *
 797   *          USER FIELDS
 798   *          These fields are for the currently-logged in user, or for
 799   *          the user that the real user is currently logged in as.
 800   *
 801   *          userid         int        the id of the user in question
 802   *          userfullname   string     the user's full name
 803   *          userprofileurl moodle_url the url of the user's profile
 804   *          useravatar     string     a HTML fragment - the rendered
 805   *                                    user_picture for this user
 806   *          userloginfail  string     an error string denoting the number
 807   *                                    of login failures since last login
 808   *
 809   *          "REAL USER" FIELDS
 810   *          These fields are for when asotheruser is true, and
 811   *          correspond to the underlying "real user".
 812   *
 813   *          asotheruser        bool    whether viewing as another user
 814   *          realuserid         int        the id of the user in question
 815   *          realuserfullname   string     the user's full name
 816   *          realuserprofileurl moodle_url the url of the user's profile
 817   *          realuseravatar     string     a HTML fragment - the rendered
 818   *                                        user_picture for this user
 819   *
 820   *          MNET PROVIDER FIELDS
 821   *          asmnetuser            bool   whether viewing as a user from an
 822   *                                       MNet provider
 823   *          mnetidprovidername    string name of the MNet provider
 824   *          mnetidproviderwwwroot string URL of the MNet provider
 825   */
 826  function user_get_user_navigation_info($user, $page, $options = array()) {
 827      global $OUTPUT, $DB, $SESSION, $CFG;
 828  
 829      $returnobject = new stdClass();
 830      $returnobject->navitems = array();
 831      $returnobject->metadata = array();
 832  
 833      $course = $page->course;
 834  
 835      // Query the environment.
 836      $context = context_course::instance($course->id);
 837  
 838      // Get basic user metadata.
 839      $returnobject->metadata['userid'] = $user->id;
 840      $returnobject->metadata['userfullname'] = fullname($user);
 841      $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
 842          'id' => $user->id
 843      ));
 844  
 845      $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
 846      if (!empty($options['avatarsize'])) {
 847          $avataroptions['size'] = $options['avatarsize'];
 848      }
 849      $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
 850          $user, $avataroptions
 851      );
 852      // Build a list of items for a regular user.
 853  
 854      // Query MNet status.
 855      if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
 856          $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
 857          $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
 858          $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
 859      }
 860  
 861      // Did the user just log in?
 862      if (isset($SESSION->justloggedin)) {
 863          // Don't unset this flag as login_info still needs it.
 864          if (!empty($CFG->displayloginfailures)) {
 865              // Don't reset the count either, as login_info() still needs it too.
 866              if ($count = user_count_login_failures($user, false)) {
 867  
 868                  // Get login failures string.
 869                  $a = new stdClass();
 870                  $a->attempts = html_writer::tag('span', $count, array('class' => 'value'));
 871                  $returnobject->metadata['userloginfail'] =
 872                      get_string('failedloginattempts', '', $a);
 873  
 874              }
 875          }
 876      }
 877  
 878      // Links: Dashboard.
 879      $myhome = new stdClass();
 880      $myhome->itemtype = 'link';
 881      $myhome->url = new moodle_url('/my/');
 882      $myhome->title = get_string('mymoodle', 'admin');
 883      $myhome->titleidentifier = 'mymoodle,admin';
 884      $myhome->pix = "i/dashboard";
 885      $returnobject->navitems[] = $myhome;
 886  
 887      // Links: My Profile.
 888      $myprofile = new stdClass();
 889      $myprofile->itemtype = 'link';
 890      $myprofile->url = new moodle_url('/user/profile.php', array('id' => $user->id));
 891      $myprofile->title = get_string('profile');
 892      $myprofile->titleidentifier = 'profile,moodle';
 893      $myprofile->pix = "i/user";
 894      $returnobject->navitems[] = $myprofile;
 895  
 896      $returnobject->metadata['asotherrole'] = false;
 897  
 898      // Before we add the last items (usually a logout + switch role link), add any
 899      // custom-defined items.
 900      $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
 901      foreach ($customitems as $item) {
 902          $returnobject->navitems[] = $item;
 903      }
 904  
 905  
 906      if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
 907          $realuser = \core\session\manager::get_realuser();
 908  
 909          // Save values for the real user, as $user will be full of data for the
 910          // user the user is disguised as.
 911          $returnobject->metadata['realuserid'] = $realuser->id;
 912          $returnobject->metadata['realuserfullname'] = fullname($realuser);
 913          $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', array(
 914              'id' => $realuser->id
 915          ));
 916          $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
 917  
 918          // Build a user-revert link.
 919          $userrevert = new stdClass();
 920          $userrevert->itemtype = 'link';
 921          $userrevert->url = new moodle_url('/course/loginas.php', array(
 922              'id' => $course->id,
 923              'sesskey' => sesskey()
 924          ));
 925          $userrevert->pix = "a/logout";
 926          $userrevert->title = get_string('logout');
 927          $userrevert->titleidentifier = 'logout,moodle';
 928          $returnobject->navitems[] = $userrevert;
 929  
 930      } else {
 931  
 932          // Build a logout link.
 933          $logout = new stdClass();
 934          $logout->itemtype = 'link';
 935          $logout->url = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
 936          $logout->pix = "a/logout";
 937          $logout->title = get_string('logout');
 938          $logout->titleidentifier = 'logout,moodle';
 939          $returnobject->navitems[] = $logout;
 940      }
 941  
 942      if (is_role_switched($course->id)) {
 943          if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
 944              // Build role-return link instead of logout link.
 945              $rolereturn = new stdClass();
 946              $rolereturn->itemtype = 'link';
 947              $rolereturn->url = new moodle_url('/course/switchrole.php', array(
 948                  'id' => $course->id,
 949                  'sesskey' => sesskey(),
 950                  'switchrole' => 0,
 951                  'returnurl' => $page->url->out_as_local_url(false)
 952              ));
 953              $rolereturn->pix = "a/logout";
 954              $rolereturn->title = get_string('switchrolereturn');
 955              $rolereturn->titleidentifier = 'switchrolereturn,moodle';
 956              $returnobject->navitems[] = $rolereturn;
 957  
 958              $returnobject->metadata['asotherrole'] = true;
 959              $returnobject->metadata['rolename'] = role_get_name($role, $context);
 960  
 961          }
 962      } else {
 963          // Build switch role link.
 964          $roles = get_switchable_roles($context);
 965          if (is_array($roles) && (count($roles) > 0)) {
 966              $switchrole = new stdClass();
 967              $switchrole->itemtype = 'link';
 968              $switchrole->url = new moodle_url('/course/switchrole.php', array(
 969                  'id' => $course->id,
 970                  'switchrole' => -1,
 971                  'returnurl' => $page->url->out_as_local_url(false)
 972              ));
 973              $switchrole->pix = "i/switchrole";
 974              $switchrole->title = get_string('switchroleto');
 975              $switchrole->titleidentifier = 'switchroleto,moodle';
 976              $returnobject->navitems[] = $switchrole;
 977          }
 978      }
 979  
 980      return $returnobject;
 981  }
 982  
 983  /**
 984   * Add password to the list of used hashes for this user.
 985   *
 986   * This is supposed to be used from:
 987   *  1/ change own password form
 988   *  2/ password reset process
 989   *  3/ user signup in auth plugins if password changing supported
 990   *
 991   * @param int $userid user id
 992   * @param string $password plaintext password
 993   * @return void
 994   */
 995  function user_add_password_history($userid, $password) {
 996      global $CFG, $DB;
 997  
 998      if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
 999          return;
1000      }
1001  
1002      // Note: this is using separate code form normal password hashing because
1003      //       we need to have this under control in the future. Also the auth
1004      //       plugin might not store the passwords locally at all.
1005  
1006      $record = new stdClass();
1007      $record->userid = $userid;
1008      $record->hash = password_hash($password, PASSWORD_DEFAULT);
1009      $record->timecreated = time();
1010      $DB->insert_record('user_password_history', $record);
1011  
1012      $i = 0;
1013      $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1014      foreach ($records as $record) {
1015          $i++;
1016          if ($i > $CFG->passwordreuselimit) {
1017              $DB->delete_records('user_password_history', array('id' => $record->id));
1018          }
1019      }
1020  }
1021  
1022  /**
1023   * Was this password used before on change or reset password page?
1024   *
1025   * The $CFG->passwordreuselimit setting determines
1026   * how many times different password needs to be used
1027   * before allowing previously used password again.
1028   *
1029   * @param int $userid user id
1030   * @param string $password plaintext password
1031   * @return bool true if password reused
1032   */
1033  function user_is_previously_used_password($userid, $password) {
1034      global $CFG, $DB;
1035  
1036      if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1037          return false;
1038      }
1039  
1040      $reused = false;
1041  
1042      $i = 0;
1043      $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1044      foreach ($records as $record) {
1045          $i++;
1046          if ($i > $CFG->passwordreuselimit) {
1047              $DB->delete_records('user_password_history', array('id' => $record->id));
1048              continue;
1049          }
1050          // NOTE: this is slow but we cannot compare the hashes directly any more.
1051          if (password_verify($password, $record->hash)) {
1052              $reused = true;
1053          }
1054      }
1055  
1056      return $reused;
1057  }
1058  
1059  /**
1060   * Remove a user device from the Moodle database (for PUSH notifications usually).
1061   *
1062   * @param string $uuid The device UUID.
1063   * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1064   * @return bool true if removed, false if the device didn't exists in the database
1065   * @since Moodle 2.9
1066   */
1067  function user_remove_user_device($uuid, $appid = "") {
1068      global $DB, $USER;
1069  
1070      $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
1071      if (!empty($appid)) {
1072          $conditions['appid'] = $appid;
1073      }
1074  
1075      if (!$DB->count_records('user_devices', $conditions)) {
1076          return false;
1077      }
1078  
1079      $DB->delete_records('user_devices', $conditions);
1080  
1081      return true;
1082  }
1083  
1084  /**
1085   * Trigger user_list_viewed event.
1086   *
1087   * @param stdClass  $course course  object
1088   * @param stdClass  $context course context object
1089   * @since Moodle 2.9
1090   */
1091  function user_list_view($course, $context) {
1092  
1093      $event = \core\event\user_list_viewed::create(array(
1094          'objectid' => $course->id,
1095          'courseid' => $course->id,
1096          'context' => $context,
1097          'other' => array(
1098              'courseshortname' => $course->shortname,
1099              'coursefullname' => $course->fullname
1100          )
1101      ));
1102      $event->trigger();
1103  }
1104  
1105  /**
1106   * Returns the url to use for the "Grades" link in the user navigation.
1107   *
1108   * @param int $userid The user's ID.
1109   * @param int $courseid The course ID if available.
1110   * @return mixed A URL to be directed to for "Grades".
1111   */
1112  function user_mygrades_url($userid = null, $courseid = SITEID) {
1113      global $CFG, $USER;
1114      $url = null;
1115      if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
1116          if (isset($userid) && $USER->id != $userid) {
1117              // Send to the gradebook report.
1118              $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
1119                      array('id' => $courseid, 'userid' => $userid));
1120          } else {
1121              $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
1122          }
1123      } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
1124              && !empty($CFG->gradereport_mygradeurl)) {
1125          $url = $CFG->gradereport_mygradeurl;
1126      } else {
1127          $url = $CFG->wwwroot;
1128      }
1129      return $url;
1130  }
1131  
1132  /**
1133   * Check if the current user has permission to view details of the supplied user.
1134   *
1135   * This function supports two modes:
1136   * If the optional $course param is omitted, then this function finds all shared courses and checks whether the current user has
1137   * permission in any of them, returning true if so.
1138   * If the $course param is provided, then this function checks permissions in ONLY that course.
1139   *
1140   * @param object $user The other user's details.
1141   * @param object $course if provided, only check permissions in this course.
1142   * @param context $usercontext The user context if available.
1143   * @return bool true for ability to view this user, else false.
1144   */
1145  function user_can_view_profile($user, $course = null, $usercontext = null) {
1146      global $USER, $CFG;
1147  
1148      if ($user->deleted) {
1149          return false;
1150      }
1151  
1152      // Do we need to be logged in?
1153      if (empty($CFG->forceloginforprofiles)) {
1154          return true;
1155      } else {
1156         if (!isloggedin() || isguestuser()) {
1157              // User is not logged in and forceloginforprofile is set, we need to return now.
1158              return false;
1159          }
1160      }
1161  
1162      // Current user can always view their profile.
1163      if ($USER->id == $user->id) {
1164          return true;
1165      }
1166  
1167      // Use callbacks so that (primarily) local plugins can prevent or allow profile access.
1168      $forceallow = false;
1169      $plugintypes = get_plugins_with_function('control_view_profile');
1170      foreach ($plugintypes as $plugins) {
1171          foreach ($plugins as $pluginfunction) {
1172              $result = $pluginfunction($user, $course, $usercontext);
1173              switch ($result) {
1174                  case core_user::VIEWPROFILE_DO_NOT_PREVENT:
1175                      // If the plugin doesn't stop access, just continue to next plugin or use
1176                      // default behaviour.
1177                      break;
1178                  case core_user::VIEWPROFILE_FORCE_ALLOW:
1179                      // Record that we are definitely going to allow it (unless another plugin
1180                      // returns _PREVENT).
1181                      $forceallow = true;
1182                      break;
1183                  case core_user::VIEWPROFILE_PREVENT:
1184                      // If any plugin returns PREVENT then we return false, regardless of what
1185                      // other plugins said.
1186                      return false;
1187              }
1188          }
1189      }
1190      if ($forceallow) {
1191          return true;
1192      }
1193  
1194      // Course contacts have visible profiles always.
1195      if (has_coursecontact_role($user->id)) {
1196          return true;
1197      }
1198  
1199      // If we're only checking the capabilities in the single provided course.
1200      if (isset($course)) {
1201          // Confirm that $user is enrolled in the $course we're checking.
1202          if (is_enrolled(context_course::instance($course->id), $user)) {
1203              $userscourses = array($course);
1204          }
1205      } else {
1206          // Else we're checking whether the current user can view $user's profile anywhere, so check user context first.
1207          if (empty($usercontext)) {
1208              $usercontext = context_user::instance($user->id);
1209          }
1210          if (has_capability('moodle/user:viewdetails', $usercontext) || has_capability('moodle/user:viewalldetails', $usercontext)) {
1211              return true;
1212          }
1213          // This returns context information, so we can preload below.
1214          $userscourses = enrol_get_all_users_courses($user->id);
1215      }
1216  
1217      if (empty($userscourses)) {
1218          return false;
1219      }
1220  
1221      foreach ($userscourses as $userscourse) {
1222          context_helper::preload_from_record($userscourse);
1223          $coursecontext = context_course::instance($userscourse->id);
1224          if (has_capability('moodle/user:viewdetails', $coursecontext) ||
1225              has_capability('moodle/user:viewalldetails', $coursecontext)) {
1226              if (!groups_user_groups_visible($userscourse, $user->id)) {
1227                  // Not a member of the same group.
1228                  continue;
1229              }
1230              return true;
1231          }
1232      }
1233      return false;
1234  }
1235  
1236  /**
1237   * Returns users tagged with a specified tag.
1238   *
1239   * @param core_tag_tag $tag
1240   * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1241   *             are displayed on the page and the per-page limit may be bigger
1242   * @param int $fromctx context id where the link was displayed, may be used by callbacks
1243   *            to display items in the same context first
1244   * @param int $ctx context id where to search for records
1245   * @param bool $rec search in subcontexts as well
1246   * @param int $page 0-based number of page being displayed
1247   * @return \core_tag\output\tagindex
1248   */
1249  function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1250      global $PAGE;
1251  
1252      if ($ctx && $ctx != context_system::instance()->id) {
1253          $usercount = 0;
1254      } else {
1255          // Users can only be displayed in system context.
1256          $usercount = $tag->count_tagged_items('core', 'user',
1257                  'it.deleted=:notdeleted', array('notdeleted' => 0));
1258      }
1259      $perpage = $exclusivemode ? 24 : 5;
1260      $content = '';
1261      $totalpages = ceil($usercount / $perpage);
1262  
1263      if ($usercount) {
1264          $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage,
1265                  'it.deleted=:notdeleted', array('notdeleted' => 0));
1266          $renderer = $PAGE->get_renderer('core', 'user');
1267          $content .= $renderer->user_list($userlist, $exclusivemode);
1268      }
1269  
1270      return new core_tag\output\tagindex($tag, 'core', 'user', $content,
1271              $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1272  }
1273  
1274  /**
1275   * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access a course.
1276   *
1277   * @param int $accesssince The unix timestamp to compare to users' last access
1278   * @param string $tableprefix
1279   * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1280   * @return string
1281   */
1282  function user_get_course_lastaccess_sql($accesssince = null, $tableprefix = 'ul', $haveaccessed = false) {
1283      return user_get_lastaccess_sql('timeaccess', $accesssince, $tableprefix, $haveaccessed);
1284  }
1285  
1286  /**
1287   * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access the system.
1288   *
1289   * @param int $accesssince The unix timestamp to compare to users' last access
1290   * @param string $tableprefix
1291   * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1292   * @return string
1293   */
1294  function user_get_user_lastaccess_sql($accesssince = null, $tableprefix = 'u', $haveaccessed = false) {
1295      return user_get_lastaccess_sql('lastaccess', $accesssince, $tableprefix, $haveaccessed);
1296  }
1297  
1298  /**
1299   * Returns SQL that can be used to limit a query to a period where the user last accessed or
1300   * did not access something recorded by a given table.
1301   *
1302   * @param string $columnname The name of the access column to check against
1303   * @param int $accesssince The unix timestamp to compare to users' last access
1304   * @param string $tableprefix The query prefix of the table to check
1305   * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1306   * @return string
1307   */
1308  function user_get_lastaccess_sql($columnname, $accesssince, $tableprefix, $haveaccessed = false) {
1309      if (empty($accesssince)) {
1310          return '';
1311      }
1312  
1313      // Only users who have accessed since $accesssince.
1314      if ($haveaccessed) {
1315          if ($accesssince == -1) {
1316              // Include all users who have logged in at some point.
1317              $sql = "({$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0)";
1318          } else {
1319              // Users who have accessed since the specified time.
1320              $sql = "{$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0
1321                  AND {$tableprefix}.{$columnname} >= {$accesssince}";
1322          }
1323      } else {
1324          // Only users who have not accessed since $accesssince.
1325  
1326          if ($accesssince == -1) {
1327              // Users who have never accessed.
1328              $sql = "({$tableprefix}.{$columnname} IS NULL OR {$tableprefix}.{$columnname} = 0)";
1329          } else {
1330              // Users who have not accessed since the specified time.
1331              $sql = "({$tableprefix}.{$columnname} IS NULL
1332                      OR ({$tableprefix}.{$columnname} != 0 AND {$tableprefix}.{$columnname} < {$accesssince}))";
1333          }
1334      }
1335  
1336      return $sql;
1337  }
1338  
1339  /**
1340   * Callback for inplace editable API.
1341   *
1342   * @param string $itemtype - Only user_roles is supported.
1343   * @param string $itemid - Courseid and userid separated by a :
1344   * @param string $newvalue - json encoded list of roleids.
1345   * @return \core\output\inplace_editable
1346   */
1347  function core_user_inplace_editable($itemtype, $itemid, $newvalue) {
1348      if ($itemtype === 'user_roles') {
1349          return \core_user\output\user_roles_editable::update($itemid, $newvalue);
1350      }
1351  }
1352  
1353  /**
1354   * Map an internal field name to a valid purpose from: "https://www.w3.org/TR/WCAG21/#input-purposes"
1355   *
1356   * @param integer $userid
1357   * @param string $fieldname
1358   * @return string $purpose (empty string if there is no mapping).
1359   */
1360  function user_edit_map_field_purpose($userid, $fieldname) {
1361      global $USER;
1362  
1363      $currentuser = ($userid == $USER->id) && !\core\session\manager::is_loggedinas();
1364      // These are the fields considered valid to map and auto fill from a browser.
1365      // We do not include fields that are in a collapsed section by default because
1366      // the browser could auto-fill the field and cause a new value to be saved when
1367      // that field was never visible.
1368      $validmappings = array(
1369          'username' => 'username',
1370          'password' => 'current-password',
1371          'firstname' => 'given-name',
1372          'lastname' => 'family-name',
1373          'middlename' => 'additional-name',
1374          'email' => 'email',
1375          'country' => 'country',
1376          'lang' => 'language'
1377      );
1378  
1379      $purpose = '';
1380      // Only set a purpose when editing your own user details.
1381      if ($currentuser && isset($validmappings[$fieldname])) {
1382          $purpose = ' autocomplete="' . $validmappings[$fieldname] . '" ';
1383      }
1384  
1385      return $purpose;
1386  }
1387