Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.
/user/ -> lib.php (source)

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

   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      } else {
 404          $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
 405      }
 406  
 407  
 408      if (!empty($user->address) && (in_array('address', $userfields)
 409              && in_array('address', $showuseridentityfields) || $isadmin)) {
 410          $userdetails['address'] = $user->address;
 411      }
 412      if (!empty($user->phone1) && (in_array('phone1', $userfields)
 413              && in_array('phone1', $showuseridentityfields) || $isadmin)) {
 414          $userdetails['phone1'] = $user->phone1;
 415      }
 416      if (!empty($user->phone2) && (in_array('phone2', $userfields)
 417              && in_array('phone2', $showuseridentityfields) || $isadmin)) {
 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('timezone', $userfields) && (!isset($hiddenfields['timezone']) || $isadmin) && $user->timezone) {
 440          $userdetails['timezone'] = $user->timezone;
 441      }
 442  
 443      if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) {
 444          $userdetails['suspended'] = (bool)$user->suspended;
 445      }
 446  
 447      if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
 448          if ($user->firstaccess) {
 449              $userdetails['firstaccess'] = $user->firstaccess;
 450          } else {
 451              $userdetails['firstaccess'] = 0;
 452          }
 453      }
 454      if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
 455          if ($user->lastaccess) {
 456              $userdetails['lastaccess'] = $user->lastaccess;
 457          } else {
 458              $userdetails['lastaccess'] = 0;
 459          }
 460      }
 461  
 462      // Hidden fields restriction to lastaccess field applies to both site and course access time.
 463      if (in_array('lastcourseaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
 464          if (isset($user->lastcourseaccess)) {
 465              $userdetails['lastcourseaccess'] = $user->lastcourseaccess;
 466          } else {
 467              $userdetails['lastcourseaccess'] = 0;
 468          }
 469      }
 470  
 471      if (in_array('email', $userfields) && (
 472              $currentuser
 473              or (!isset($hiddenfields['email']) and (
 474                  $user->maildisplay == core_user::MAILDISPLAY_EVERYONE
 475                  or ($user->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY and enrol_sharing_course($user, $USER))
 476                  or $canviewuseremail  // TODO: Deprecate/remove for MDL-37479.
 477              ))
 478              or in_array('email', $showuseridentityfields)
 479         )) {
 480          $userdetails['email'] = $user->email;
 481      }
 482  
 483      if (in_array('interests', $userfields)) {
 484          $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
 485          if ($interests) {
 486              $userdetails['interests'] = join(', ', $interests);
 487          }
 488      }
 489  
 490      // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
 491      if (in_array('idnumber', $userfields) && $user->idnumber) {
 492          if (in_array('idnumber', $showuseridentityfields) or $currentuser or
 493                  has_capability('moodle/user:viewalldetails', $context)) {
 494              $userdetails['idnumber'] = $user->idnumber;
 495          }
 496      }
 497      if (in_array('institution', $userfields) && $user->institution) {
 498          if (in_array('institution', $showuseridentityfields) or $currentuser or
 499                  has_capability('moodle/user:viewalldetails', $context)) {
 500              $userdetails['institution'] = $user->institution;
 501          }
 502      }
 503      // Isset because it's ok to have department 0.
 504      if (in_array('department', $userfields) && isset($user->department)) {
 505          if (in_array('department', $showuseridentityfields) or $currentuser or
 506                  has_capability('moodle/user:viewalldetails', $context)) {
 507              $userdetails['department'] = $user->department;
 508          }
 509      }
 510  
 511      if (in_array('roles', $userfields) && !empty($course)) {
 512          // Not a big secret.
 513          $roles = get_user_roles($context, $user->id, false);
 514          $userdetails['roles'] = array();
 515          foreach ($roles as $role) {
 516              $userdetails['roles'][] = array(
 517                  'roleid'       => $role->roleid,
 518                  'name'         => $role->name,
 519                  'shortname'    => $role->shortname,
 520                  'sortorder'    => $role->sortorder
 521              );
 522          }
 523      }
 524  
 525      // Return user groups.
 526      if (in_array('groups', $userfields) && !empty($course)) {
 527          if ($usergroups = groups_get_all_groups($course->id, $user->id)) {
 528              $userdetails['groups'] = [];
 529              foreach ($usergroups as $group) {
 530                  if ($course->groupmode == SEPARATEGROUPS && !$canaccessallgroups && $user->id != $USER->id) {
 531                      // In separate groups, I only have to see the groups shared between both users.
 532                      if (!groups_is_member($group->id, $USER->id)) {
 533                          continue;
 534                      }
 535                  }
 536  
 537                  $userdetails['groups'][] = [
 538                      'id' => $group->id,
 539                      'name' => format_string($group->name),
 540                      'description' => format_text($group->description, $group->descriptionformat, ['context' => $context]),
 541                      'descriptionformat' => $group->descriptionformat
 542                  ];
 543              }
 544          }
 545      }
 546      // List of courses where the user is enrolled.
 547      if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
 548          $enrolledcourses = array();
 549          if ($mycourses = enrol_get_users_courses($user->id, true)) {
 550              foreach ($mycourses as $mycourse) {
 551                  if ($mycourse->category) {
 552                      $coursecontext = context_course::instance($mycourse->id);
 553                      $enrolledcourse = array();
 554                      $enrolledcourse['id'] = $mycourse->id;
 555                      $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
 556                      $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
 557                      $enrolledcourses[] = $enrolledcourse;
 558                  }
 559              }
 560              $userdetails['enrolledcourses'] = $enrolledcourses;
 561          }
 562      }
 563  
 564      // User preferences.
 565      if (in_array('preferences', $userfields) && $currentuser) {
 566          $preferences = array();
 567          $userpreferences = get_user_preferences();
 568          foreach ($userpreferences as $prefname => $prefvalue) {
 569              $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
 570          }
 571          $userdetails['preferences'] = $preferences;
 572      }
 573  
 574      if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
 575          $extrafields = ['auth', 'confirmed', 'lang', 'theme', 'mailformat'];
 576          foreach ($extrafields as $extrafield) {
 577              if (in_array($extrafield, $userfields) && isset($user->$extrafield)) {
 578                  $userdetails[$extrafield] = $user->$extrafield;
 579              }
 580          }
 581      }
 582  
 583      // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
 584      if (isset($userdetails['lang'])) {
 585          $userdetails['lang'] = clean_param($userdetails['lang'], PARAM_LANG);
 586      }
 587      if (isset($userdetails['theme'])) {
 588          $userdetails['theme'] = clean_param($userdetails['theme'], PARAM_THEME);
 589      }
 590  
 591      return $userdetails;
 592  }
 593  
 594  /**
 595   * Tries to obtain user details, either recurring directly to the user's system profile
 596   * or through one of the user's course enrollments (course profile).
 597   *
 598   * @param stdClass $user The user.
 599   * @return array if unsuccessful or the allowed user details.
 600   */
 601  function user_get_user_details_courses($user) {
 602      global $USER;
 603      $userdetails = null;
 604  
 605      $systemprofile = false;
 606      if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
 607          $systemprofile = true;
 608      }
 609  
 610      // Try using system profile.
 611      if ($systemprofile) {
 612          $userdetails = user_get_user_details($user, null);
 613      } else {
 614          // Try through course profile.
 615          // Get the courses that the user is enrolled in (only active).
 616          $courses = enrol_get_users_courses($user->id, true);
 617          foreach ($courses as $course) {
 618              if (user_can_view_profile($user, $course)) {
 619                  $userdetails = user_get_user_details($user, $course);
 620              }
 621          }
 622      }
 623  
 624      return $userdetails;
 625  }
 626  
 627  /**
 628   * Check if $USER have the necessary capabilities to obtain user details.
 629   *
 630   * @param stdClass $user
 631   * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
 632   * @return bool true if $USER can view user details.
 633   */
 634  function can_view_user_details_cap($user, $course = null) {
 635      // Check $USER has the capability to view the user details at user context.
 636      $usercontext = context_user::instance($user->id);
 637      $result = has_capability('moodle/user:viewdetails', $usercontext);
 638      // Otherwise can $USER see them at course context.
 639      if (!$result && !empty($course)) {
 640          $context = context_course::instance($course->id);
 641          $result = has_capability('moodle/user:viewdetails', $context);
 642      }
 643      return $result;
 644  }
 645  
 646  /**
 647   * Return a list of page types
 648   * @param string $pagetype current page type
 649   * @param stdClass $parentcontext Block's parent context
 650   * @param stdClass $currentcontext Current context of block
 651   * @return array
 652   */
 653  function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
 654      return array('user-profile' => get_string('page-user-profile', 'pagetype'));
 655  }
 656  
 657  /**
 658   * Count the number of failed login attempts for the given user, since last successful login.
 659   *
 660   * @param int|stdclass $user user id or object.
 661   * @param bool $reset Resets failed login count, if set to true.
 662   *
 663   * @return int number of failed login attempts since the last successful login.
 664   */
 665  function user_count_login_failures($user, $reset = true) {
 666      global $DB;
 667  
 668      if (!is_object($user)) {
 669          $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
 670      }
 671      if ($user->deleted) {
 672          // Deleted user, nothing to do.
 673          return 0;
 674      }
 675      $count = get_user_preferences('login_failed_count_since_success', 0, $user);
 676      if ($reset) {
 677          set_user_preference('login_failed_count_since_success', 0, $user);
 678      }
 679      return $count;
 680  }
 681  
 682  /**
 683   * Converts a string into a flat array of menu items, where each menu items is a
 684   * stdClass with fields type, url, title.
 685   *
 686   * @param string $text the menu items definition
 687   * @param moodle_page $page the current page
 688   * @return array
 689   */
 690  function user_convert_text_to_menu_items($text, $page) {
 691      global $OUTPUT, $CFG;
 692  
 693      $lines = explode("\n", $text);
 694      $items = array();
 695      $lastchild = null;
 696      $lastdepth = null;
 697      $lastsort = 0;
 698      $children = array();
 699      foreach ($lines as $line) {
 700          $line = trim($line);
 701          $bits = explode('|', $line, 2);
 702          $itemtype = 'link';
 703          if (preg_match("/^#+$/", $line)) {
 704              $itemtype = 'divider';
 705          } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
 706              // Every item must have a name to be valid.
 707              continue;
 708          } else {
 709              $bits[0] = ltrim($bits[0], '-');
 710          }
 711  
 712          // Create the child.
 713          $child = new stdClass();
 714          $child->itemtype = $itemtype;
 715          if ($itemtype === 'divider') {
 716              // Add the divider to the list of children and skip link
 717              // processing.
 718              $children[] = $child;
 719              continue;
 720          }
 721  
 722          // Name processing.
 723          $namebits = explode(',', $bits[0], 2);
 724          if (count($namebits) == 2) {
 725              // Check the validity of the identifier part of the string.
 726              if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
 727                  // Treat this as a language string.
 728                  $child->title = get_string($namebits[0], $namebits[1]);
 729                  $child->titleidentifier = implode(',', $namebits);
 730              }
 731          }
 732          if (empty($child->title)) {
 733              // Use it as is, don't even clean it.
 734              $child->title = $bits[0];
 735              $child->titleidentifier = str_replace(" ", "-", $bits[0]);
 736          }
 737  
 738          // URL processing.
 739          if (!array_key_exists(1, $bits) or empty($bits[1])) {
 740              // Set the url to null, and set the itemtype to invalid.
 741              $bits[1] = null;
 742              $child->itemtype = "invalid";
 743          } else {
 744              // Nasty hack to replace the grades with the direct url.
 745              if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
 746                  $bits[1] = user_mygrades_url();
 747              }
 748  
 749              // Make sure the url is a moodle url.
 750              $bits[1] = new moodle_url(trim($bits[1]));
 751          }
 752          $child->url = $bits[1];
 753  
 754          // Add this child to the list of children.
 755          $children[] = $child;
 756      }
 757      return $children;
 758  }
 759  
 760  /**
 761   * Get a list of essential user navigation items.
 762   *
 763   * @param stdclass $user user object.
 764   * @param moodle_page $page page object.
 765   * @param array $options associative array.
 766   *     options are:
 767   *     - avatarsize=35 (size of avatar image)
 768   * @return stdClass $returnobj navigation information object, where:
 769   *
 770   *      $returnobj->navitems    array    array of links where each link is a
 771   *                                       stdClass with fields url, title, and
 772   *                                       pix
 773   *      $returnobj->metadata    array    array of useful user metadata to be
 774   *                                       used when constructing navigation;
 775   *                                       fields include:
 776   *
 777   *          ROLE FIELDS
 778   *          asotherrole    bool    whether viewing as another role
 779   *          rolename       string  name of the role
 780   *
 781   *          USER FIELDS
 782   *          These fields are for the currently-logged in user, or for
 783   *          the user that the real user is currently logged in as.
 784   *
 785   *          userid         int        the id of the user in question
 786   *          userfullname   string     the user's full name
 787   *          userprofileurl moodle_url the url of the user's profile
 788   *          useravatar     string     a HTML fragment - the rendered
 789   *                                    user_picture for this user
 790   *          userloginfail  string     an error string denoting the number
 791   *                                    of login failures since last login
 792   *
 793   *          "REAL USER" FIELDS
 794   *          These fields are for when asotheruser is true, and
 795   *          correspond to the underlying "real user".
 796   *
 797   *          asotheruser        bool    whether viewing as another user
 798   *          realuserid         int        the id of the user in question
 799   *          realuserfullname   string     the user's full name
 800   *          realuserprofileurl moodle_url the url of the user's profile
 801   *          realuseravatar     string     a HTML fragment - the rendered
 802   *                                        user_picture for this user
 803   *
 804   *          MNET PROVIDER FIELDS
 805   *          asmnetuser            bool   whether viewing as a user from an
 806   *                                       MNet provider
 807   *          mnetidprovidername    string name of the MNet provider
 808   *          mnetidproviderwwwroot string URL of the MNet provider
 809   */
 810  function user_get_user_navigation_info($user, $page, $options = array()) {
 811      global $OUTPUT, $DB, $SESSION, $CFG;
 812  
 813      $returnobject = new stdClass();
 814      $returnobject->navitems = array();
 815      $returnobject->metadata = array();
 816  
 817      $guest = isguestuser();
 818      if (!isloggedin() || $guest) {
 819          $returnobject->unauthenticateduser = [
 820              'guest' => $guest,
 821              'content' => $guest ? 'loggedinasguest' : 'loggedinnot',
 822          ];
 823  
 824          return $returnobject;
 825      }
 826  
 827      $course = $page->course;
 828  
 829      // Query the environment.
 830      $context = context_course::instance($course->id);
 831  
 832      // Get basic user metadata.
 833      $returnobject->metadata['userid'] = $user->id;
 834      $returnobject->metadata['userfullname'] = fullname($user);
 835      $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
 836          'id' => $user->id
 837      ));
 838  
 839      $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
 840      if (!empty($options['avatarsize'])) {
 841          $avataroptions['size'] = $options['avatarsize'];
 842      }
 843      $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
 844          $user, $avataroptions
 845      );
 846      // Build a list of items for a regular user.
 847  
 848      // Query MNet status.
 849      if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
 850          $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
 851          $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
 852          $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
 853      }
 854  
 855      // Did the user just log in?
 856      if (isset($SESSION->justloggedin)) {
 857          // Don't unset this flag as login_info still needs it.
 858          if (!empty($CFG->displayloginfailures)) {
 859              // Don't reset the count either, as login_info() still needs it too.
 860              if ($count = user_count_login_failures($user, false)) {
 861  
 862                  // Get login failures string.
 863                  $a = new stdClass();
 864                  $a->attempts = html_writer::tag('span', $count, array('class' => 'value mr-1 font-weight-bold'));
 865                  $returnobject->metadata['userloginfail'] =
 866                      get_string('failedloginattempts', '', $a);
 867  
 868              }
 869          }
 870      }
 871  
 872      $returnobject->metadata['asotherrole'] = false;
 873  
 874      // Before we add the last items (usually a logout + switch role link), add any
 875      // custom-defined items.
 876      $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
 877      $custommenucount = 0;
 878      foreach ($customitems as $item) {
 879          $returnobject->navitems[] = $item;
 880          if ($item->itemtype !== 'divider' && $item->itemtype !== 'invalid') {
 881              $custommenucount++;
 882          }
 883      }
 884  
 885      if ($custommenucount > 0) {
 886          // Only add a divider if we have customusermenuitems.
 887          $divider = new stdClass();
 888          $divider->itemtype = 'divider';
 889          $returnobject->navitems[] = $divider;
 890      }
 891  
 892      // Links: Preferences.
 893      $preferences = new stdClass();
 894      $preferences->itemtype = 'link';
 895      $preferences->url = new moodle_url('/user/preferences.php');
 896      $preferences->title = get_string('preferences');
 897      $preferences->titleidentifier = 'preferences,moodle';
 898      $returnobject->navitems[] = $preferences;
 899  
 900  
 901      if (is_role_switched($course->id)) {
 902          if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
 903              // Build role-return link instead of logout link.
 904              $rolereturn = new stdClass();
 905              $rolereturn->itemtype = 'link';
 906              $rolereturn->url = new moodle_url('/course/switchrole.php', array(
 907                  'id' => $course->id,
 908                  'sesskey' => sesskey(),
 909                  'switchrole' => 0,
 910                  'returnurl' => $page->url->out_as_local_url(false)
 911              ));
 912              $rolereturn->title = get_string('switchrolereturn');
 913              $rolereturn->titleidentifier = 'switchrolereturn,moodle';
 914              $returnobject->navitems[] = $rolereturn;
 915  
 916              $returnobject->metadata['asotherrole'] = true;
 917              $returnobject->metadata['rolename'] = role_get_name($role, $context);
 918  
 919          }
 920      } else {
 921          // Build switch role link.
 922          $roles = get_switchable_roles($context);
 923          if (is_array($roles) && (count($roles) > 0)) {
 924              $switchrole = new stdClass();
 925              $switchrole->itemtype = 'link';
 926              $switchrole->url = new moodle_url('/course/switchrole.php', array(
 927                  'id' => $course->id,
 928                  'switchrole' => -1,
 929                  'returnurl' => $page->url->out_as_local_url(false)
 930              ));
 931              $switchrole->title = get_string('switchroleto');
 932              $switchrole->titleidentifier = 'switchroleto,moodle';
 933              $returnobject->navitems[] = $switchrole;
 934          }
 935      }
 936  
 937      if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
 938          $realuser = \core\session\manager::get_realuser();
 939  
 940          // Save values for the real user, as $user will be full of data for the
 941          // user is disguised as.
 942          $returnobject->metadata['realuserid'] = $realuser->id;
 943          $returnobject->metadata['realuserfullname'] = fullname($realuser);
 944          $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', [
 945              'id' => $realuser->id
 946          ]);
 947          $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
 948  
 949          // Build a user-revert link.
 950          $userrevert = new stdClass();
 951          $userrevert->itemtype = 'link';
 952          $userrevert->url = new moodle_url('/course/loginas.php', [
 953              'id' => $course->id,
 954              'sesskey' => sesskey()
 955          ]);
 956          $userrevert->title = get_string('logout');
 957          $userrevert->titleidentifier = 'logout,moodle';
 958          $returnobject->navitems[] = $userrevert;
 959      } else {
 960          // Build a logout link.
 961          $logout = new stdClass();
 962          $logout->itemtype = 'link';
 963          $logout->url = new moodle_url('/login/logout.php', ['sesskey' => sesskey()]);
 964          $logout->title = get_string('logout');
 965          $logout->titleidentifier = 'logout,moodle';
 966          $returnobject->navitems[] = $logout;
 967      }
 968  
 969      return $returnobject;
 970  }
 971  
 972  /**
 973   * Add password to the list of used hashes for this user.
 974   *
 975   * This is supposed to be used from:
 976   *  1/ change own password form
 977   *  2/ password reset process
 978   *  3/ user signup in auth plugins if password changing supported
 979   *
 980   * @param int $userid user id
 981   * @param string $password plaintext password
 982   * @return void
 983   */
 984  function user_add_password_history($userid, $password) {
 985      global $CFG, $DB;
 986  
 987      if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
 988          return;
 989      }
 990  
 991      // Note: this is using separate code form normal password hashing because
 992      //       we need to have this under control in the future. Also the auth
 993      //       plugin might not store the passwords locally at all.
 994  
 995      $record = new stdClass();
 996      $record->userid = $userid;
 997      $record->hash = password_hash($password, PASSWORD_DEFAULT);
 998      $record->timecreated = time();
 999      $DB->insert_record('user_password_history', $record);
1000  
1001      $i = 0;
1002      $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1003      foreach ($records as $record) {
1004          $i++;
1005          if ($i > $CFG->passwordreuselimit) {
1006              $DB->delete_records('user_password_history', array('id' => $record->id));
1007          }
1008      }
1009  }
1010  
1011  /**
1012   * Was this password used before on change or reset password page?
1013   *
1014   * The $CFG->passwordreuselimit setting determines
1015   * how many times different password needs to be used
1016   * before allowing previously used password again.
1017   *
1018   * @param int $userid user id
1019   * @param string $password plaintext password
1020   * @return bool true if password reused
1021   */
1022  function user_is_previously_used_password($userid, $password) {
1023      global $CFG, $DB;
1024  
1025      if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
1026          return false;
1027      }
1028  
1029      $reused = false;
1030  
1031      $i = 0;
1032      $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
1033      foreach ($records as $record) {
1034          $i++;
1035          if ($i > $CFG->passwordreuselimit) {
1036              $DB->delete_records('user_password_history', array('id' => $record->id));
1037              continue;
1038          }
1039          // NOTE: this is slow but we cannot compare the hashes directly any more.
1040          if (password_verify($password, $record->hash)) {
1041              $reused = true;
1042          }
1043      }
1044  
1045      return $reused;
1046  }
1047  
1048  /**
1049   * Remove a user device from the Moodle database (for PUSH notifications usually).
1050   *
1051   * @param string $uuid The device UUID.
1052   * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
1053   * @return bool true if removed, false if the device didn't exists in the database
1054   * @since Moodle 2.9
1055   */
1056  function user_remove_user_device($uuid, $appid = "") {
1057      global $DB, $USER;
1058  
1059      $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
1060      if (!empty($appid)) {
1061          $conditions['appid'] = $appid;
1062      }
1063  
1064      if (!$DB->count_records('user_devices', $conditions)) {
1065          return false;
1066      }
1067  
1068      $DB->delete_records('user_devices', $conditions);
1069  
1070      return true;
1071  }
1072  
1073  /**
1074   * Trigger user_list_viewed event.
1075   *
1076   * @param stdClass  $course course  object
1077   * @param stdClass  $context course context object
1078   * @since Moodle 2.9
1079   */
1080  function user_list_view($course, $context) {
1081  
1082      $event = \core\event\user_list_viewed::create(array(
1083          'objectid' => $course->id,
1084          'courseid' => $course->id,
1085          'context' => $context,
1086          'other' => array(
1087              'courseshortname' => $course->shortname,
1088              'coursefullname' => $course->fullname
1089          )
1090      ));
1091      $event->trigger();
1092  }
1093  
1094  /**
1095   * Returns the url to use for the "Grades" link in the user navigation.
1096   *
1097   * @param int $userid The user's ID.
1098   * @param int $courseid The course ID if available.
1099   * @return mixed A URL to be directed to for "Grades".
1100   */
1101  function user_mygrades_url($userid = null, $courseid = SITEID) {
1102      global $CFG, $USER;
1103      $url = null;
1104      if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
1105          if (isset($userid) && $USER->id != $userid) {
1106              // Send to the gradebook report.
1107              $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
1108                      array('id' => $courseid, 'userid' => $userid));
1109          } else {
1110              $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
1111          }
1112      } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
1113              && !empty($CFG->gradereport_mygradeurl)) {
1114          $url = $CFG->gradereport_mygradeurl;
1115      } else {
1116          $url = $CFG->wwwroot;
1117      }
1118      return $url;
1119  }
1120  
1121  /**
1122   * Check if the current user has permission to view details of the supplied user.
1123   *
1124   * This function supports two modes:
1125   * If the optional $course param is omitted, then this function finds all shared courses and checks whether the current user has
1126   * permission in any of them, returning true if so.
1127   * If the $course param is provided, then this function checks permissions in ONLY that course.
1128   *
1129   * @param object $user The other user's details.
1130   * @param object $course if provided, only check permissions in this course.
1131   * @param context $usercontext The user context if available.
1132   * @return bool true for ability to view this user, else false.
1133   */
1134  function user_can_view_profile($user, $course = null, $usercontext = null) {
1135      global $USER, $CFG;
1136  
1137      if ($user->deleted) {
1138          return false;
1139      }
1140  
1141      // Do we need to be logged in?
1142      if (empty($CFG->forceloginforprofiles)) {
1143          return true;
1144      } else {
1145         if (!isloggedin() || isguestuser()) {
1146              // User is not logged in and forceloginforprofile is set, we need to return now.
1147              return false;
1148          }
1149      }
1150  
1151      // Current user can always view their profile.
1152      if ($USER->id == $user->id) {
1153          return true;
1154      }
1155  
1156      // Use callbacks so that (primarily) local plugins can prevent or allow profile access.
1157      $forceallow = false;
1158      $plugintypes = get_plugins_with_function('control_view_profile');
1159      foreach ($plugintypes as $plugins) {
1160          foreach ($plugins as $pluginfunction) {
1161              $result = $pluginfunction($user, $course, $usercontext);
1162              switch ($result) {
1163                  case core_user::VIEWPROFILE_DO_NOT_PREVENT:
1164                      // If the plugin doesn't stop access, just continue to next plugin or use
1165                      // default behaviour.
1166                      break;
1167                  case core_user::VIEWPROFILE_FORCE_ALLOW:
1168                      // Record that we are definitely going to allow it (unless another plugin
1169                      // returns _PREVENT).
1170                      $forceallow = true;
1171                      break;
1172                  case core_user::VIEWPROFILE_PREVENT:
1173                      // If any plugin returns PREVENT then we return false, regardless of what
1174                      // other plugins said.
1175                      return false;
1176              }
1177          }
1178      }
1179      if ($forceallow) {
1180          return true;
1181      }
1182  
1183      // Course contacts have visible profiles always.
1184      if (has_coursecontact_role($user->id)) {
1185          return true;
1186      }
1187  
1188      // If we're only checking the capabilities in the single provided course.
1189      if (isset($course)) {
1190          // Confirm that $user is enrolled in the $course we're checking.
1191          if (is_enrolled(context_course::instance($course->id), $user)) {
1192              $userscourses = array($course);
1193          }
1194      } else {
1195          // Else we're checking whether the current user can view $user's profile anywhere, so check user context first.
1196          if (empty($usercontext)) {
1197              $usercontext = context_user::instance($user->id);
1198          }
1199          if (has_capability('moodle/user:viewdetails', $usercontext) || has_capability('moodle/user:viewalldetails', $usercontext)) {
1200              return true;
1201          }
1202          // This returns context information, so we can preload below.
1203          $userscourses = enrol_get_all_users_courses($user->id);
1204      }
1205  
1206      if (empty($userscourses)) {
1207          return false;
1208      }
1209  
1210      foreach ($userscourses as $userscourse) {
1211          context_helper::preload_from_record($userscourse);
1212          $coursecontext = context_course::instance($userscourse->id);
1213          if (has_capability('moodle/user:viewdetails', $coursecontext) ||
1214              has_capability('moodle/user:viewalldetails', $coursecontext)) {
1215              if (!groups_user_groups_visible($userscourse, $user->id)) {
1216                  // Not a member of the same group.
1217                  continue;
1218              }
1219              return true;
1220          }
1221      }
1222      return false;
1223  }
1224  
1225  /**
1226   * Returns users tagged with a specified tag.
1227   *
1228   * @param core_tag_tag $tag
1229   * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1230   *             are displayed on the page and the per-page limit may be bigger
1231   * @param int $fromctx context id where the link was displayed, may be used by callbacks
1232   *            to display items in the same context first
1233   * @param int $ctx context id where to search for records
1234   * @param bool $rec search in subcontexts as well
1235   * @param int $page 0-based number of page being displayed
1236   * @return \core_tag\output\tagindex
1237   */
1238  function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1239      global $PAGE;
1240  
1241      if ($ctx && $ctx != context_system::instance()->id) {
1242          $usercount = 0;
1243      } else {
1244          // Users can only be displayed in system context.
1245          $usercount = $tag->count_tagged_items('core', 'user',
1246                  'it.deleted=:notdeleted', array('notdeleted' => 0));
1247      }
1248      $perpage = $exclusivemode ? 24 : 5;
1249      $content = '';
1250      $totalpages = ceil($usercount / $perpage);
1251  
1252      if ($usercount) {
1253          $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage,
1254                  'it.deleted=:notdeleted', array('notdeleted' => 0));
1255          $renderer = $PAGE->get_renderer('core', 'user');
1256          $content .= $renderer->user_list($userlist, $exclusivemode);
1257      }
1258  
1259      return new core_tag\output\tagindex($tag, 'core', 'user', $content,
1260              $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1261  }
1262  
1263  /**
1264   * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access a course.
1265   *
1266   * @param int $accesssince The unix timestamp to compare to users' last access
1267   * @param string $tableprefix
1268   * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1269   * @return string
1270   */
1271  function user_get_course_lastaccess_sql($accesssince = null, $tableprefix = 'ul', $haveaccessed = false) {
1272      return user_get_lastaccess_sql('timeaccess', $accesssince, $tableprefix, $haveaccessed);
1273  }
1274  
1275  /**
1276   * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access the system.
1277   *
1278   * @param int $accesssince The unix timestamp to compare to users' last access
1279   * @param string $tableprefix
1280   * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1281   * @return string
1282   */
1283  function user_get_user_lastaccess_sql($accesssince = null, $tableprefix = 'u', $haveaccessed = false) {
1284      return user_get_lastaccess_sql('lastaccess', $accesssince, $tableprefix, $haveaccessed);
1285  }
1286  
1287  /**
1288   * Returns SQL that can be used to limit a query to a period where the user last accessed or
1289   * did not access something recorded by a given table.
1290   *
1291   * @param string $columnname The name of the access column to check against
1292   * @param int $accesssince The unix timestamp to compare to users' last access
1293   * @param string $tableprefix The query prefix of the table to check
1294   * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional)
1295   * @return string
1296   */
1297  function user_get_lastaccess_sql($columnname, $accesssince, $tableprefix, $haveaccessed = false) {
1298      if (empty($accesssince)) {
1299          return '';
1300      }
1301  
1302      // Only users who have accessed since $accesssince.
1303      if ($haveaccessed) {
1304          if ($accesssince == -1) {
1305              // Include all users who have logged in at some point.
1306              $sql = "({$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0)";
1307          } else {
1308              // Users who have accessed since the specified time.
1309              $sql = "{$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0
1310                  AND {$tableprefix}.{$columnname} >= {$accesssince}";
1311          }
1312      } else {
1313          // Only users who have not accessed since $accesssince.
1314  
1315          if ($accesssince == -1) {
1316              // Users who have never accessed.
1317              $sql = "({$tableprefix}.{$columnname} IS NULL OR {$tableprefix}.{$columnname} = 0)";
1318          } else {
1319              // Users who have not accessed since the specified time.
1320              $sql = "({$tableprefix}.{$columnname} IS NULL
1321                      OR ({$tableprefix}.{$columnname} != 0 AND {$tableprefix}.{$columnname} < {$accesssince}))";
1322          }
1323      }
1324  
1325      return $sql;
1326  }
1327  
1328  /**
1329   * Callback for inplace editable API.
1330   *
1331   * @param string $itemtype - Only user_roles is supported.
1332   * @param string $itemid - Courseid and userid separated by a :
1333   * @param string $newvalue - json encoded list of roleids.
1334   * @return \core\output\inplace_editable
1335   */
1336  function core_user_inplace_editable($itemtype, $itemid, $newvalue) {
1337      if ($itemtype === 'user_roles') {
1338          return \core_user\output\user_roles_editable::update($itemid, $newvalue);
1339      }
1340  }
1341  
1342  /**
1343   * Map an internal field name to a valid purpose from: "https://www.w3.org/TR/WCAG21/#input-purposes"
1344   *
1345   * @param integer $userid
1346   * @param string $fieldname
1347   * @return string $purpose (empty string if there is no mapping).
1348   */
1349  function user_edit_map_field_purpose($userid, $fieldname) {
1350      global $USER;
1351  
1352      $currentuser = ($userid == $USER->id) && !\core\session\manager::is_loggedinas();
1353      // These are the fields considered valid to map and auto fill from a browser.
1354      // We do not include fields that are in a collapsed section by default because
1355      // the browser could auto-fill the field and cause a new value to be saved when
1356      // that field was never visible.
1357      $validmappings = array(
1358          'username' => 'username',
1359          'password' => 'current-password',
1360          'firstname' => 'given-name',
1361          'lastname' => 'family-name',
1362          'middlename' => 'additional-name',
1363          'email' => 'email',
1364          'country' => 'country',
1365          'lang' => 'language'
1366      );
1367  
1368      $purpose = '';
1369      // Only set a purpose when editing your own user details.
1370      if ($currentuser && isset($validmappings[$fieldname])) {
1371          $purpose = ' autocomplete="' . $validmappings[$fieldname] . '" ';
1372      }
1373  
1374      return $purpose;
1375  }
1376