Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.
/lib/ -> authlib.php (source)

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

   1  <?php
   2  
   3  // This file is part of Moodle - http://moodle.org/
   4  //
   5  // Moodle is free software: you can redistribute it and/or modify
   6  // it under the terms of the GNU General Public License as published by
   7  // the Free Software Foundation, either version 3 of the License, or
   8  // (at your option) any later version.
   9  //
  10  // Moodle is distributed in the hope that it will be useful,
  11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13  // GNU General Public License for more details.
  14  //
  15  // You should have received a copy of the GNU General Public License
  16  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  17  
  18  /**
  19   * Multiple plugin authentication Support library
  20   *
  21   * 2006-08-28  File created, AUTH return values defined.
  22   *
  23   * @package    core
  24   * @subpackage auth
  25   * @copyright  1999 onwards Martin Dougiamas  http://dougiamas.com
  26   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  27   */
  28  
  29  defined('MOODLE_INTERNAL') || die();
  30  
  31  /**
  32   * Returned when the login was successful.
  33   */
  34  define('AUTH_OK',     0);
  35  
  36  /**
  37   * Returned when the login was unsuccessful.
  38   */
  39  define('AUTH_FAIL',   1);
  40  
  41  /**
  42   * Returned when the login was denied (a reason for AUTH_FAIL).
  43   */
  44  define('AUTH_DENIED', 2);
  45  
  46  /**
  47   * Returned when some error occurred (a reason for AUTH_FAIL).
  48   */
  49  define('AUTH_ERROR',  4);
  50  
  51  /**
  52   * Authentication - error codes for user confirm
  53   */
  54  define('AUTH_CONFIRM_FAIL', 0);
  55  define('AUTH_CONFIRM_OK', 1);
  56  define('AUTH_CONFIRM_ALREADY', 2);
  57  define('AUTH_CONFIRM_ERROR', 3);
  58  
  59  # MDL-14055
  60  define('AUTH_REMOVEUSER_KEEP', 0);
  61  define('AUTH_REMOVEUSER_SUSPEND', 1);
  62  define('AUTH_REMOVEUSER_FULLDELETE', 2);
  63  
  64  /** Login attempt successful. */
  65  define('AUTH_LOGIN_OK', 0);
  66  
  67  /** Can not login because user does not exist. */
  68  define('AUTH_LOGIN_NOUSER', 1);
  69  
  70  /** Can not login because user is suspended. */
  71  define('AUTH_LOGIN_SUSPENDED', 2);
  72  
  73  /** Can not login, most probably password did not match. */
  74  define('AUTH_LOGIN_FAILED', 3);
  75  
  76  /** Can not login because user is locked out. */
  77  define('AUTH_LOGIN_LOCKOUT', 4);
  78  
  79  /** Can not login becauser user is not authorised. */
  80  define('AUTH_LOGIN_UNAUTHORISED', 5);
  81  
  82  /**
  83   * Abstract authentication plugin.
  84   *
  85   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  86   * @package moodlecore
  87   */
  88  class auth_plugin_base {
  89  
  90      /**
  91       * The configuration details for the plugin.
  92       * @var object
  93       */
  94      var $config;
  95  
  96      /**
  97       * Authentication plugin type - the same as db field.
  98       * @var string
  99       */
 100      var $authtype;
 101      /*
 102       * The fields we can lock and update from/to external authentication backends
 103       * @var array
 104       */
 105      var $userfields = \core_user::AUTHSYNCFIELDS;
 106  
 107      /**
 108       * Moodle custom fields to sync with.
 109       * @var array()
 110       */
 111      var $customfields = null;
 112  
 113      /**
 114       * The tag we want to prepend to any error log messages.
 115       *
 116       * @var string
 117       */
 118      protected $errorlogtag = '';
 119  
 120      /** @var array Stores extra information available to the logged in event. */
 121      protected $extrauserinfo = [];
 122  
 123      /**
 124       * This is the primary method that is used by the authenticate_user_login()
 125       * function in moodlelib.php.
 126       *
 127       * This method should return a boolean indicating
 128       * whether or not the username and password authenticate successfully.
 129       *
 130       * Returns true if the username and password work and false if they are
 131       * wrong or don't exist.
 132       *
 133       * @param string $username The username (with system magic quotes)
 134       * @param string $password The password (with system magic quotes)
 135       *
 136       * @return bool Authentication success or failure.
 137       */
 138      function user_login($username, $password) {
 139          throw new \moodle_exception('mustbeoveride', 'debug', '', 'user_login()' );
 140      }
 141  
 142      /**
 143       * Returns true if this authentication plugin can change the users'
 144       * password.
 145       *
 146       * @return bool
 147       */
 148      function can_change_password() {
 149          //override if needed
 150          return false;
 151      }
 152  
 153      /**
 154       * Returns the URL for changing the users' passwords, or empty if the default
 155       * URL can be used.
 156       *
 157       * This method is used if can_change_password() returns true.
 158       * This method is called only when user is logged in, it may use global $USER.
 159       * If you are using a plugin config variable in this method, please make sure it is set before using it,
 160       * as this method can be called even if the plugin is disabled, in which case the config values won't be set.
 161       *
 162       * @return moodle_url url of the profile page or null if standard used
 163       */
 164      function change_password_url() {
 165          //override if needed
 166          return null;
 167      }
 168  
 169      /**
 170       * Returns true if this authentication plugin can edit the users'
 171       * profile.
 172       *
 173       * @return bool
 174       */
 175      function can_edit_profile() {
 176          //override if needed
 177          return true;
 178      }
 179  
 180      /**
 181       * Returns the URL for editing the users' profile, or empty if the default
 182       * URL can be used.
 183       *
 184       * This method is used if can_edit_profile() returns true.
 185       * This method is called only when user is logged in, it may use global $USER.
 186       *
 187       * @return moodle_url url of the profile page or null if standard used
 188       */
 189      function edit_profile_url() {
 190          //override if needed
 191          return null;
 192      }
 193  
 194      /**
 195       * Returns true if this authentication plugin is "internal".
 196       *
 197       * Internal plugins use password hashes from Moodle user table for authentication.
 198       *
 199       * @return bool
 200       */
 201      function is_internal() {
 202          //override if needed
 203          return true;
 204      }
 205  
 206      /**
 207       * Returns false if this plugin is enabled but not configured.
 208       *
 209       * @return bool
 210       */
 211      public function is_configured() {
 212          return false;
 213      }
 214  
 215      /**
 216       * Indicates if password hashes should be stored in local moodle database.
 217       * @return bool true means md5 password hash stored in user table, false means flag 'not_cached' stored there instead
 218       */
 219      function prevent_local_passwords() {
 220          return !$this->is_internal();
 221      }
 222  
 223      /**
 224       * Indicates if moodle should automatically update internal user
 225       * records with data from external sources using the information
 226       * from get_userinfo() method.
 227       *
 228       * @return bool true means automatically copy data from ext to user table
 229       */
 230      function is_synchronised_with_external() {
 231          return !$this->is_internal();
 232      }
 233  
 234      /**
 235       * Updates the user's password.
 236       *
 237       * In previous versions of Moodle, the function
 238       * auth_user_update_password accepted a username as the first parameter. The
 239       * revised function expects a user object.
 240       *
 241       * @param  object  $user        User table object
 242       * @param  string  $newpassword Plaintext password
 243       *
 244       * @return bool                  True on success
 245       */
 246      function user_update_password($user, $newpassword) {
 247          //override if needed
 248          return true;
 249      }
 250  
 251      /**
 252       * Called when the user record is updated.
 253       * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
 254       * compares information saved modified information to external db.
 255       *
 256       * @param mixed $olduser     Userobject before modifications    (without system magic quotes)
 257       * @param mixed $newuser     Userobject new modified userobject (without system magic quotes)
 258       * @return boolean true if updated or update ignored; false if error
 259       *
 260       */
 261      function user_update($olduser, $newuser) {
 262          //override if needed
 263          return true;
 264      }
 265  
 266      /**
 267       * User delete requested - internal user record is mared as deleted already, username not present anymore.
 268       *
 269       * Do any action in external database.
 270       *
 271       * @param object $user       Userobject before delete    (without system magic quotes)
 272       * @return void
 273       */
 274      function user_delete($olduser) {
 275          //override if needed
 276          return;
 277      }
 278  
 279      /**
 280       * Returns true if plugin allows resetting of internal password.
 281       *
 282       * @return bool
 283       */
 284      function can_reset_password() {
 285          //override if needed
 286          return false;
 287      }
 288  
 289      /**
 290       * Returns true if plugin allows resetting of internal password.
 291       *
 292       * @return bool
 293       */
 294      function can_signup() {
 295          //override if needed
 296          return false;
 297      }
 298  
 299      /**
 300       * Sign up a new user ready for confirmation.
 301       * Password is passed in plaintext.
 302       *
 303       * @param object $user new user object
 304       * @param boolean $notify print notice with link and terminate
 305       */
 306      function user_signup($user, $notify=true) {
 307          //override when can signup
 308          throw new \moodle_exception('mustbeoveride', 'debug', '', 'user_signup()' );
 309      }
 310  
 311      /**
 312       * Return a form to capture user details for account creation.
 313       * This is used in /login/signup.php.
 314       * @return moodle_form A form which edits a record from the user table.
 315       */
 316      function signup_form() {
 317          global $CFG;
 318  
 319          require_once($CFG->dirroot.'/login/signup_form.php');
 320          return new login_signup_form(null, null, 'post', '', array('autocomplete'=>'on'));
 321      }
 322  
 323      /**
 324       * Returns true if plugin allows confirming of new users.
 325       *
 326       * @return bool
 327       */
 328      function can_confirm() {
 329          //override if needed
 330          return false;
 331      }
 332  
 333      /**
 334       * Confirm the new user as registered.
 335       *
 336       * @param string $username
 337       * @param string $confirmsecret
 338       */
 339      function user_confirm($username, $confirmsecret) {
 340          //override when can confirm
 341          throw new \moodle_exception('mustbeoveride', 'debug', '', 'user_confirm()' );
 342      }
 343  
 344      /**
 345       * Checks if user exists in external db
 346       *
 347       * @param string $username (with system magic quotes)
 348       * @return bool
 349       */
 350      function user_exists($username) {
 351          //override if needed
 352          return false;
 353      }
 354  
 355      /**
 356       * return number of days to user password expires
 357       *
 358       * If userpassword does not expire it should return 0. If password is already expired
 359       * it should return negative value.
 360       *
 361       * @param mixed $username username (with system magic quotes)
 362       * @return integer
 363       */
 364      function password_expire($username) {
 365          return 0;
 366      }
 367      /**
 368       * Sync roles for this user - usually creator
 369       *
 370       * @param $user object user object (without system magic quotes)
 371       */
 372      function sync_roles($user) {
 373          //override if needed
 374      }
 375  
 376      /**
 377       * Read user information from external database and returns it as array().
 378       * Function should return all information available. If you are saving
 379       * this information to moodle user-table you should honour synchronisation flags
 380       *
 381       * @param string $username username
 382       *
 383       * @return mixed array with no magic quotes or false on error
 384       */
 385      function get_userinfo($username) {
 386          //override if needed
 387          return array();
 388      }
 389  
 390      /**
 391       * Prints a form for configuring this authentication plugin.
 392       *
 393       * This function is called from admin/auth.php, and outputs a full page with
 394       * a form for configuring this plugin.
 395       *
 396       * @param object $config
 397       * @param object $err
 398       * @param array $user_fields
 399       * @deprecated since Moodle 3.3
 400       */
 401      function config_form($config, $err, $user_fields) {
 402          debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
 403          //override if needed
 404      }
 405  
 406      /**
 407       * A chance to validate form data, and last chance to
 408       * do stuff before it is inserted in config_plugin
 409       * @param object object with submitted configuration settings (without system magic quotes)
 410       * @param array $err array of error messages
 411       * @deprecated since Moodle 3.3
 412       */
 413       function validate_form($form, &$err) {
 414          debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
 415          //override if needed
 416      }
 417  
 418      /**
 419       * Processes and stores configuration data for this authentication plugin.
 420       *
 421       * @param object object with submitted configuration settings (without system magic quotes)
 422       * @deprecated since Moodle 3.3
 423       */
 424      function process_config($config) {
 425          debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
 426          //override if needed
 427          return true;
 428      }
 429  
 430      /**
 431       * Hook for overriding behaviour of login page.
 432       * This method is called from login/index.php page for all enabled auth plugins.
 433       *
 434       * @global object
 435       * @global object
 436       */
 437      function loginpage_hook() {
 438          global $frm;  // can be used to override submitted login form
 439          global $user; // can be used to replace authenticate_user_login()
 440  
 441          //override if needed
 442      }
 443  
 444      /**
 445       * Hook for overriding behaviour before going to the login page.
 446       *
 447       * This method is called from require_login from potentially any page for
 448       * all enabled auth plugins and gives each plugin a chance to redirect
 449       * directly to an external login page, or to instantly login a user where
 450       * possible.
 451       *
 452       * If an auth plugin implements this hook, it must not rely on ONLY this
 453       * hook in order to work, as there are many ways a user can browse directly
 454       * to the standard login page. As a general rule in this case you should
 455       * also implement the loginpage_hook as well.
 456       *
 457       */
 458      function pre_loginpage_hook() {
 459          // override if needed, eg by redirecting to an external login page
 460          // or logging in a user:
 461          // complete_user_login($user);
 462      }
 463  
 464      /**
 465       * Pre user_login hook.
 466       * This method is called from authenticate_user_login() right after the user
 467       * object is generated. This gives the auth plugins an option to make adjustments
 468       * before the verification process starts.
 469       *
 470       * @param object $user user object, later used for $USER
 471       */
 472      public function pre_user_login_hook(&$user) {
 473          // Override if needed.
 474      }
 475  
 476      /**
 477       * Post authentication hook.
 478       * This method is called from authenticate_user_login() for all enabled auth plugins.
 479       *
 480       * @param object $user user object, later used for $USER
 481       * @param string $username (with system magic quotes)
 482       * @param string $password plain text password (with system magic quotes)
 483       */
 484      function user_authenticated_hook(&$user, $username, $password) {
 485          //override if needed
 486      }
 487  
 488      /**
 489       * Pre logout hook.
 490       * This method is called from require_logout() for all enabled auth plugins,
 491       *
 492       * @global object
 493       */
 494      function prelogout_hook() {
 495          global $USER; // use $USER->auth to find the plugin used for login
 496  
 497          //override if needed
 498      }
 499  
 500      /**
 501       * Hook for overriding behaviour of logout page.
 502       * This method is called from login/logout.php page for all enabled auth plugins.
 503       *
 504       * @global object
 505       * @global string
 506       */
 507      function logoutpage_hook() {
 508          global $USER;     // use $USER->auth to find the plugin used for login
 509          global $redirect; // can be used to override redirect after logout
 510  
 511          //override if needed
 512      }
 513  
 514      /**
 515       * Hook called before timing out of database session.
 516       * This is useful for SSO and MNET.
 517       *
 518       * @param object $user
 519       * @param string $sid session id
 520       * @param int $timecreated start of session
 521       * @param int $timemodified user last seen
 522       * @return bool true means do not timeout session yet
 523       */
 524      function ignore_timeout_hook($user, $sid, $timecreated, $timemodified) {
 525          return false;
 526      }
 527  
 528      /**
 529       * Return the properly translated human-friendly title of this auth plugin
 530       *
 531       * @todo Document this function
 532       */
 533      function get_title() {
 534          return get_string('pluginname', "auth_{$this->authtype}");
 535      }
 536  
 537      /**
 538       * Get the auth description (from core or own auth lang files)
 539       *
 540       * @return string The description
 541       */
 542      function get_description() {
 543          $authdescription = get_string("auth_{$this->authtype}description", "auth_{$this->authtype}");
 544          return $authdescription;
 545      }
 546  
 547      /**
 548       * Returns whether or not the captcha element is enabled.
 549       *
 550       * @abstract Implement in child classes
 551       * @return bool
 552       */
 553      function is_captcha_enabled() {
 554          return false;
 555      }
 556  
 557      /**
 558       * Returns whether or not this authentication plugin can be manually set
 559       * for users, for example, when bulk uploading users.
 560       *
 561       * This should be overriden by authentication plugins where setting the
 562       * authentication method manually is allowed.
 563       *
 564       * @return bool
 565       * @since Moodle 2.6
 566       */
 567      function can_be_manually_set() {
 568          // Override if needed.
 569          return false;
 570      }
 571  
 572      /**
 573       * Returns a list of potential IdPs that this authentication plugin supports.
 574       *
 575       * This is used to provide links on the login page and the login block.
 576       *
 577       * The parameter $wantsurl is typically used by the plugin to implement a
 578       * return-url feature.
 579       *
 580       * The returned value is expected to be a list of associative arrays with
 581       * string keys:
 582       *
 583       * - url => (moodle_url|string) URL of the page to send the user to for authentication
 584       * - name => (string) Human readable name of the IdP
 585       * - iconurl => (moodle_url|string) URL of the icon representing the IdP (since Moodle 3.3)
 586       *
 587       * For legacy reasons, pre-3.3 plugins can provide the icon via the key:
 588       *
 589       * - icon => (pix_icon) Icon representing the IdP
 590       *
 591       * @param string $wantsurl The relative url fragment the user wants to get to.
 592       * @return array List of associative arrays with keys url, name, iconurl|icon
 593       */
 594      function loginpage_idp_list($wantsurl) {
 595          return array();
 596      }
 597  
 598      /**
 599       * Return custom user profile fields.
 600       *
 601       * @return array list of custom fields.
 602       */
 603      public function get_custom_user_profile_fields() {
 604          global $CFG;
 605          require_once($CFG->dirroot . '/user/profile/lib.php');
 606  
 607          // If already retrieved then return.
 608          if (!is_null($this->customfields)) {
 609              return $this->customfields;
 610          }
 611  
 612          $this->customfields = array();
 613          if ($proffields = profile_get_custom_fields()) {
 614              foreach ($proffields as $proffield) {
 615                  $this->customfields[] = 'profile_field_'.$proffield->shortname;
 616              }
 617          }
 618          unset($proffields);
 619  
 620          return $this->customfields;
 621      }
 622  
 623      /**
 624       * Post logout hook.
 625       *
 626       * This method is used after moodle logout by auth classes to execute server logout.
 627       *
 628       * @param stdClass $user clone of USER object before the user session was terminated
 629       */
 630      public function postlogout_hook($user) {
 631      }
 632  
 633      /**
 634       * Update a local user record from an external source.
 635       * This is a lighter version of the one in moodlelib -- won't do
 636       * expensive ops such as enrolment.
 637       *
 638       * @param string $username username
 639       * @param array $updatekeys fields to update, false updates all fields.
 640       * @param bool $triggerevent set false if user_updated event should not be triggered.
 641       *             This will not affect user_password_updated event triggering.
 642       * @param bool $suspenduser Should the user be suspended?
 643       * @return stdClass|bool updated user record or false if there is no new info to update.
 644       */
 645      protected function update_user_record($username, $updatekeys = false, $triggerevent = false, $suspenduser = false) {
 646          global $CFG, $DB;
 647  
 648          require_once($CFG->dirroot.'/user/profile/lib.php');
 649  
 650          // Just in case check text case.
 651          $username = trim(core_text::strtolower($username));
 652  
 653          // Get the current user record.
 654          $user = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id));
 655          if (empty($user)) { // Trouble.
 656              error_log($this->errorlogtag . get_string('auth_usernotexist', 'auth', $username));
 657              throw new \moodle_exception('auth_usernotexist', 'auth', '', $username);
 658              die;
 659          }
 660  
 661          // Protect the userid from being overwritten.
 662          $userid = $user->id;
 663  
 664          $needsupdate = false;
 665  
 666          if ($newinfo = $this->get_userinfo($username)) {
 667              $newinfo = truncate_userinfo($newinfo);
 668  
 669              if (empty($updatekeys)) { // All keys? this does not support removing values.
 670                  $updatekeys = array_keys($newinfo);
 671              }
 672  
 673              if (!empty($updatekeys)) {
 674                  $newuser = new stdClass();
 675                  $newuser->id = $userid;
 676                  // The cast to int is a workaround for MDL-53959.
 677                  $newuser->suspended = (int) $suspenduser;
 678                  // Load all custom fields.
 679                  $profilefields = (array) profile_user_record($user->id, false);
 680                  $newprofilefields = [];
 681  
 682                  foreach ($updatekeys as $key) {
 683                      if (isset($newinfo[$key])) {
 684                          $value = $newinfo[$key];
 685                      } else {
 686                          $value = '';
 687                      }
 688  
 689                      if (!empty($this->config->{'field_updatelocal_' . $key})) {
 690                          if (preg_match('/^profile_field_(.*)$/', $key, $match)) {
 691                              // Custom field.
 692                              $field = $match[1];
 693                              $currentvalue = isset($profilefields[$field]) ? $profilefields[$field] : null;
 694                              $newprofilefields[$field] = $value;
 695                          } else {
 696                              // Standard field.
 697                              $currentvalue = isset($user->$key) ? $user->$key : null;
 698                              $newuser->$key = $value;
 699                          }
 700  
 701                          // Only update if it's changed.
 702                          if ($currentvalue !== $value) {
 703                              $needsupdate = true;
 704                          }
 705                      }
 706                  }
 707              }
 708  
 709              if ($needsupdate) {
 710                  user_update_user($newuser, false, $triggerevent);
 711                  profile_save_custom_fields($newuser->id, $newprofilefields);
 712                  return $DB->get_record('user', array('id' => $userid, 'deleted' => 0));
 713              }
 714          }
 715  
 716          return false;
 717      }
 718  
 719      /**
 720       * Return the list of enabled identity providers.
 721       *
 722       * Each identity provider data contains the keys url, name and iconurl (or
 723       * icon). See the documentation of {@link auth_plugin_base::loginpage_idp_list()}
 724       * for detailed description of the returned structure.
 725       *
 726       * @param array $authsequence site's auth sequence (list of auth plugins ordered)
 727       * @return array List of arrays describing the identity providers
 728       */
 729      public static function get_identity_providers($authsequence) {
 730          global $SESSION;
 731  
 732          $identityproviders = [];
 733          foreach ($authsequence as $authname) {
 734              $authplugin = get_auth_plugin($authname);
 735              $wantsurl = (isset($SESSION->wantsurl)) ? $SESSION->wantsurl : '';
 736              $identityproviders = array_merge($identityproviders, $authplugin->loginpage_idp_list($wantsurl));
 737          }
 738          return $identityproviders;
 739      }
 740  
 741      /**
 742       * Prepare a list of identity providers for output.
 743       *
 744       * @param array $identityproviders as returned by {@link self::get_identity_providers()}
 745       * @param renderer_base $output
 746       * @return array the identity providers ready for output
 747       */
 748      public static function prepare_identity_providers_for_output($identityproviders, renderer_base $output) {
 749          $data = [];
 750          foreach ($identityproviders as $idp) {
 751              if (!empty($idp['icon'])) {
 752                  // Pre-3.3 auth plugins provide icon as a pix_icon instance. New auth plugins (since 3.3) provide iconurl.
 753                  $idp['iconurl'] = $output->image_url($idp['icon']->pix, $idp['icon']->component);
 754              }
 755              if ($idp['iconurl'] instanceof moodle_url) {
 756                  $idp['iconurl'] = $idp['iconurl']->out(false);
 757              }
 758              unset($idp['icon']);
 759              if ($idp['url'] instanceof moodle_url) {
 760                  $idp['url'] = $idp['url']->out(false);
 761              }
 762              $data[] = $idp;
 763          }
 764          return $data;
 765      }
 766  
 767      /**
 768       * Returns information on how the specified user can change their password.
 769       *
 770       * @param stdClass $user A user object
 771       * @return string[] An array of strings with keys subject and message
 772       */
 773      public function get_password_change_info(stdClass $user) : array {
 774  
 775          global $USER;
 776  
 777          $site = get_site();
 778          $systemcontext = context_system::instance();
 779  
 780          $data = new stdClass();
 781          $data->firstname = $user->firstname;
 782          $data->lastname  = $user->lastname;
 783          $data->username  = $user->username;
 784          $data->sitename  = format_string($site->fullname);
 785          $data->admin     = generate_email_signoff();
 786  
 787          // This is a workaround as change_password_url() is designed to allow
 788          // use of the $USER global. See MDL-66984.
 789          $olduser = $USER;
 790          $USER = $user;
 791          if ($this->can_change_password() and $this->change_password_url()) {
 792              // We have some external url for password changing.
 793              $data->link = $this->change_password_url()->out();
 794          } else {
 795              // No way to change password, sorry.
 796              $data->link = '';
 797          }
 798          $USER = $olduser;
 799  
 800          if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
 801              $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
 802              $message = get_string('emailpasswordchangeinfo', '', $data);
 803          } else {
 804              $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
 805              $message = get_string('emailpasswordchangeinfofail', '', $data);
 806          }
 807  
 808          return [
 809              'subject' => $subject,
 810              'message' => $message
 811          ];
 812      }
 813  
 814      /**
 815       * Set extra user information.
 816       *
 817       * @param array $values Any Key value pair.
 818       * @return void
 819       */
 820      public function set_extrauserinfo(array $values): void {
 821          $this->extrauserinfo = $values;
 822      }
 823  
 824      /**
 825       * Returns extra user information.
 826       *
 827       * @return array An array of keys and values
 828       */
 829      public function get_extrauserinfo(): array {
 830          return $this->extrauserinfo;
 831      }
 832  }
 833  
 834  /**
 835   * Verify if user is locked out.
 836   *
 837   * @param stdClass $user
 838   * @return bool true if user locked out
 839   */
 840  function login_is_lockedout($user) {
 841      global $CFG;
 842  
 843      if ($user->mnethostid != $CFG->mnet_localhost_id) {
 844          return false;
 845      }
 846      if (isguestuser($user)) {
 847          return false;
 848      }
 849  
 850      if (empty($CFG->lockoutthreshold)) {
 851          // Lockout not enabled.
 852          return false;
 853      }
 854  
 855      if (get_user_preferences('login_lockout_ignored', 0, $user)) {
 856          // This preference may be used for accounts that must not be locked out.
 857          return false;
 858      }
 859  
 860      $locked = get_user_preferences('login_lockout', 0, $user);
 861      if (!$locked) {
 862          return false;
 863      }
 864  
 865      if (empty($CFG->lockoutduration)) {
 866          // Locked out forever.
 867          return true;
 868      }
 869  
 870      if (time() - $locked < $CFG->lockoutduration) {
 871          return true;
 872      }
 873  
 874      login_unlock_account($user);
 875  
 876      return false;
 877  }
 878  
 879  /**
 880   * To be called after valid user login.
 881   * @param stdClass $user
 882   */
 883  function login_attempt_valid($user) {
 884      global $CFG;
 885  
 886      // Note: user_loggedin event is triggered in complete_user_login().
 887  
 888      if ($user->mnethostid != $CFG->mnet_localhost_id) {
 889          return;
 890      }
 891      if (isguestuser($user)) {
 892          return;
 893      }
 894  
 895      // Always unlock here, there might be some race conditions or leftovers when switching threshold.
 896      login_unlock_account($user);
 897  }
 898  
 899  /**
 900   * To be called after failed user login.
 901   * @param stdClass $user
 902   * @throws moodle_exception
 903   */
 904  function login_attempt_failed($user) {
 905      global $CFG;
 906  
 907      if ($user->mnethostid != $CFG->mnet_localhost_id) {
 908          return;
 909      }
 910      if (isguestuser($user)) {
 911          return;
 912      }
 913  
 914      // Force user preferences cache reload to ensure the most up-to-date login_failed_count is fetched.
 915      // This is perhaps overzealous but is the documented way of reloading the cache, as per the test method
 916      // 'test_check_user_preferences_loaded'.
 917      unset($user->preference);
 918  
 919      $resource = 'user:' . $user->id;
 920      $lockfactory = \core\lock\lock_config::get_lock_factory('core_failed_login_count_lock');
 921  
 922      // Get a new lock for the resource, waiting for it for a maximum of 10 seconds.
 923      if ($lock = $lockfactory->get_lock($resource, 10)) {
 924          try {
 925              $count = get_user_preferences('login_failed_count', 0, $user);
 926              $last = get_user_preferences('login_failed_last', 0, $user);
 927              $sincescuccess = get_user_preferences('login_failed_count_since_success', $count, $user);
 928              $sincescuccess = $sincescuccess + 1;
 929              set_user_preference('login_failed_count_since_success', $sincescuccess, $user);
 930  
 931              if (empty($CFG->lockoutthreshold)) {
 932                  // No threshold means no lockout.
 933                  // Always unlock here, there might be some race conditions or leftovers when switching threshold.
 934                  login_unlock_account($user);
 935                  $lock->release();
 936                  return;
 937              }
 938  
 939              if (!empty($CFG->lockoutwindow) and time() - $last > $CFG->lockoutwindow) {
 940                  $count = 0;
 941              }
 942  
 943              $count = $count + 1;
 944  
 945              set_user_preference('login_failed_count', $count, $user);
 946              set_user_preference('login_failed_last', time(), $user);
 947  
 948              if ($count >= $CFG->lockoutthreshold) {
 949                  login_lock_account($user);
 950              }
 951  
 952              // Release locks when we're done.
 953              $lock->release();
 954          } catch (Exception $e) {
 955              // Always release the lock on a failure.
 956              $lock->release();
 957          }
 958      } else {
 959          // We did not get access to the resource in time, give up.
 960          throw new moodle_exception('locktimeout');
 961      }
 962  }
 963  
 964  /**
 965   * Lockout user and send notification email.
 966   *
 967   * @param stdClass $user
 968   */
 969  function login_lock_account($user) {
 970      global $CFG;
 971  
 972      if ($user->mnethostid != $CFG->mnet_localhost_id) {
 973          return;
 974      }
 975      if (isguestuser($user)) {
 976          return;
 977      }
 978  
 979      if (get_user_preferences('login_lockout_ignored', 0, $user)) {
 980          // This user can not be locked out.
 981          return;
 982      }
 983  
 984      $alreadylockedout = get_user_preferences('login_lockout', 0, $user);
 985  
 986      set_user_preference('login_lockout', time(), $user);
 987  
 988      if ($alreadylockedout == 0) {
 989          $secret = random_string(15);
 990          set_user_preference('login_lockout_secret', $secret, $user);
 991  
 992          $oldforcelang = force_current_language($user->lang);
 993  
 994          $site = get_site();
 995          $supportuser = core_user::get_support_user();
 996  
 997          $data = new stdClass();
 998          $data->firstname = $user->firstname;
 999          $data->lastname  = $user->lastname;
1000          $data->username  = $user->username;
1001          $data->sitename  = format_string($site->fullname);
1002          $data->link      = $CFG->wwwroot.'/login/unlock_account.php?u='.$user->id.'&s='.$secret;
1003          $data->admin     = generate_email_signoff();
1004  
1005          $message = get_string('lockoutemailbody', 'admin', $data);
1006          $subject = get_string('lockoutemailsubject', 'admin', format_string($site->fullname));
1007  
1008          if ($message) {
1009              // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
1010              email_to_user($user, $supportuser, $subject, $message);
1011          }
1012  
1013          force_current_language($oldforcelang);
1014      }
1015  }
1016  
1017  /**
1018   * Unlock user account and reset timers.
1019   *
1020   * @param stdClass $user
1021   */
1022  function login_unlock_account($user) {
1023      unset_user_preference('login_lockout', $user);
1024      unset_user_preference('login_failed_count', $user);
1025      unset_user_preference('login_failed_last', $user);
1026  
1027      // Note: do not clear the lockout secret because user might click on the link repeatedly.
1028  }
1029  
1030  /**
1031   * Returns whether or not the captcha element is enabled, and the admin settings fulfil its requirements.
1032   * @return bool
1033   */
1034  function signup_captcha_enabled() {
1035      global $CFG;
1036      $authplugin = get_auth_plugin($CFG->registerauth);
1037      return !empty($CFG->recaptchapublickey) && !empty($CFG->recaptchaprivatekey) && $authplugin->is_captcha_enabled();
1038  }
1039  
1040  /**
1041   * Validates the standard sign-up data (except recaptcha that is validated by the form element).
1042   *
1043   * @param  array $data  the sign-up data
1044   * @param  array $files files among the data
1045   * @return array list of errors, being the key the data element name and the value the error itself
1046   * @since Moodle 3.2
1047   */
1048  function signup_validate_data($data, $files) {
1049      global $CFG, $DB;
1050  
1051      $errors = array();
1052      $authplugin = get_auth_plugin($CFG->registerauth);
1053  
1054      if ($DB->record_exists('user', array('username' => $data['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
1055          $errors['username'] = get_string('usernameexists');
1056      } else {
1057          // Check allowed characters.
1058          if ($data['username'] !== core_text::strtolower($data['username'])) {
1059              $errors['username'] = get_string('usernamelowercase');
1060          } else {
1061              if ($data['username'] !== core_user::clean_field($data['username'], 'username')) {
1062                  $errors['username'] = get_string('invalidusername');
1063              }
1064  
1065          }
1066      }
1067  
1068      // Check if user exists in external db.
1069      // TODO: maybe we should check all enabled plugins instead.
1070      if ($authplugin->user_exists($data['username'])) {
1071          $errors['username'] = get_string('usernameexists');
1072      }
1073  
1074      if (! validate_email($data['email'])) {
1075          $errors['email'] = get_string('invalidemail');
1076  
1077      } else if (empty($CFG->allowaccountssameemail)) {
1078          // Emails in Moodle as case-insensitive and accents-sensitive. Such a combination can lead to very slow queries
1079          // on some DBs such as MySQL. So we first get the list of candidate users in a subselect via more effective
1080          // accent-insensitive query that can make use of the index and only then we search within that limited subset.
1081          $sql = "SELECT 'x'
1082                    FROM {user}
1083                   WHERE " . $DB->sql_equal('email', ':email1', false, true) . "
1084                     AND id IN (SELECT id
1085                                  FROM {user}
1086                                 WHERE " . $DB->sql_equal('email', ':email2', false, false) . "
1087                                   AND mnethostid = :mnethostid)";
1088  
1089          $params = array(
1090              'email1' => $data['email'],
1091              'email2' => $data['email'],
1092              'mnethostid' => $CFG->mnet_localhost_id,
1093          );
1094  
1095          // If there are other user(s) that already have the same email, show an error.
1096          if ($DB->record_exists_sql($sql, $params)) {
1097              $forgotpasswordurl = new moodle_url('/login/forgot_password.php');
1098              $forgotpasswordlink = html_writer::link($forgotpasswordurl, get_string('emailexistshintlink'));
1099              $errors['email'] = get_string('emailexists') . ' ' . get_string('emailexistssignuphint', 'moodle', $forgotpasswordlink);
1100          }
1101      }
1102      if (empty($data['email2'])) {
1103          $errors['email2'] = get_string('missingemail');
1104  
1105      } else if (core_text::strtolower($data['email2']) != core_text::strtolower($data['email'])) {
1106          $errors['email2'] = get_string('invalidemail');
1107      }
1108      if (!isset($errors['email'])) {
1109          if ($err = email_is_not_allowed($data['email'])) {
1110              $errors['email'] = $err;
1111          }
1112      }
1113  
1114      // Construct fake user object to check password policy against required information.
1115      $tempuser = new stdClass();
1116      // To prevent errors with check_password_policy(),
1117      // the temporary user and the guest must not share the same ID.
1118      $tempuser->id = (int)$CFG->siteguest + 1;
1119      $tempuser->username = $data['username'];
1120      $tempuser->firstname = $data['firstname'];
1121      $tempuser->lastname = $data['lastname'];
1122      $tempuser->email = $data['email'];
1123  
1124      $errmsg = '';
1125      if (!check_password_policy($data['password'], $errmsg, $tempuser)) {
1126          $errors['password'] = $errmsg;
1127      }
1128  
1129      // Validate customisable profile fields. (profile_validation expects an object as the parameter with userid set).
1130      $dataobject = (object)$data;
1131      $dataobject->id = 0;
1132      $errors += profile_validation($dataobject, $files);
1133  
1134      return $errors;
1135  }
1136  
1137  /**
1138   * Add the missing fields to a user that is going to be created
1139   *
1140   * @param  stdClass $user the new user object
1141   * @return stdClass the user filled
1142   * @since Moodle 3.2
1143   */
1144  function signup_setup_new_user($user) {
1145      global $CFG;
1146  
1147      $user->confirmed   = 0;
1148      $user->lang        = current_language();
1149      $user->firstaccess = 0;
1150      $user->timecreated = time();
1151      $user->mnethostid  = $CFG->mnet_localhost_id;
1152      $user->secret      = random_string(15);
1153      $user->auth        = $CFG->registerauth;
1154      // Initialize alternate name fields to empty strings.
1155      $namefields = array_diff(\core_user\fields::get_name_fields(), useredit_get_required_name_fields());
1156      foreach ($namefields as $namefield) {
1157          $user->$namefield = '';
1158      }
1159      return $user;
1160  }
1161  
1162  /**
1163   * Check if user confirmation is enabled on this site and return the auth plugin handling registration if enabled.
1164   *
1165   * @return stdClass the current auth plugin handling user registration or false if registration not enabled
1166   * @since Moodle 3.2
1167   */
1168  function signup_get_user_confirmation_authplugin() {
1169      global $CFG;
1170  
1171      if (empty($CFG->registerauth)) {
1172          return false;
1173      }
1174      $authplugin = get_auth_plugin($CFG->registerauth);
1175  
1176      if (!$authplugin->can_confirm()) {
1177          return false;
1178      }
1179      return $authplugin;
1180  }
1181  
1182  /**
1183   * Check if sign-up is enabled in the site. If is enabled, the function will return the authplugin instance.
1184   *
1185   * @return mixed false if sign-up is not enabled, the authplugin instance otherwise.
1186   * @since  Moodle 3.2
1187   */
1188  function signup_is_enabled() {
1189      global $CFG;
1190  
1191      if (!empty($CFG->registerauth)) {
1192          $authplugin = get_auth_plugin($CFG->registerauth);
1193          if ($authplugin->can_signup()) {
1194              return $authplugin;
1195          }
1196      }
1197      return false;
1198  }
1199  
1200  /**
1201   * Helper function used to print locking for auth plugins on admin pages.
1202   * @param stdclass $settings Moodle admin settings instance
1203   * @param string $auth authentication plugin shortname
1204   * @param array $userfields user profile fields
1205   * @param string $helptext help text to be displayed at top of form
1206   * @param boolean $mapremotefields Map fields or lock only.
1207   * @param boolean $updateremotefields Allow remote updates
1208   * @param array $customfields list of custom profile fields
1209   * @since Moodle 3.3
1210   */
1211  function display_auth_lock_options($settings, $auth, $userfields, $helptext, $mapremotefields, $updateremotefields, $customfields = array()) {
1212      global $CFG;
1213      require_once($CFG->dirroot . '/user/profile/lib.php');
1214  
1215      // Introductory explanation and help text.
1216      if ($mapremotefields) {
1217          $settings->add(new admin_setting_heading($auth.'/data_mapping', new lang_string('auth_data_mapping', 'auth'), $helptext));
1218      } else {
1219          $settings->add(new admin_setting_heading($auth.'/auth_fieldlocks', new lang_string('auth_fieldlocks', 'auth'), $helptext));
1220      }
1221  
1222      // Generate the list of options.
1223      $lockoptions = array ('unlocked'        => get_string('unlocked', 'auth'),
1224                            'unlockedifempty' => get_string('unlockedifempty', 'auth'),
1225                            'locked'          => get_string('locked', 'auth'));
1226      $updatelocaloptions = array('oncreate'  => get_string('update_oncreate', 'auth'),
1227                                  'onlogin'   => get_string('update_onlogin', 'auth'));
1228      $updateextoptions = array('0'  => get_string('update_never', 'auth'),
1229                                '1'  => get_string('update_onupdate', 'auth'));
1230  
1231      // Generate the list of profile fields to allow updates / lock.
1232      if (!empty($customfields)) {
1233          $userfields = array_merge($userfields, $customfields);
1234          $allcustomfields = profile_get_custom_fields();
1235          $customfieldname = array_combine(array_column($allcustomfields, 'shortname'), $allcustomfields);
1236      }
1237  
1238      foreach ($userfields as $field) {
1239          // Define the fieldname we display to the  user.
1240          // this includes special handling for some profile fields.
1241          $fieldname = $field;
1242          $fieldnametoolong = false;
1243          if ($fieldname === 'lang') {
1244              $fieldname = get_string('language');
1245          } else if (!empty($customfields) && in_array($field, $customfields)) {
1246              // If custom field then pick name from database.
1247              $fieldshortname = str_replace('profile_field_', '', $fieldname);
1248              $fieldname = $customfieldname[$fieldshortname]->name;
1249              if (core_text::strlen($fieldshortname) > 67) {
1250                  // If custom profile field name is longer than 67 characters we will not be able to store the setting
1251                  // such as 'field_updateremote_profile_field_NOTSOSHORTSHORTNAME' in the database because the character
1252                  // limit for the setting name is 100.
1253                  $fieldnametoolong = true;
1254              }
1255          } else {
1256              $fieldname = get_string($fieldname);
1257          }
1258  
1259          // Generate the list of fields / mappings.
1260          if ($fieldnametoolong) {
1261              // Display a message that the field can not be mapped because it's too long.
1262              $url = new moodle_url('/user/profile/index.php');
1263              $a = (object)['fieldname' => s($fieldname), 'shortname' => s($field), 'charlimit' => 67, 'link' => $url->out()];
1264              $settings->add(new admin_setting_heading($auth.'/field_not_mapped_'.sha1($field), '',
1265                  get_string('cannotmapfield', 'auth', $a)));
1266          } else if ($mapremotefields) {
1267              // We are mapping to a remote field here.
1268              // Mapping.
1269              $settings->add(new admin_setting_configtext("auth_{$auth}/field_map_{$field}",
1270                      get_string('auth_fieldmapping', 'auth', $fieldname), '', '', PARAM_RAW, 30));
1271  
1272              // Update local.
1273              $settings->add(new admin_setting_configselect("auth_{$auth}/field_updatelocal_{$field}",
1274                      get_string('auth_updatelocalfield', 'auth', $fieldname), '', 'oncreate', $updatelocaloptions));
1275  
1276              // Update remote.
1277              if ($updateremotefields) {
1278                      $settings->add(new admin_setting_configselect("auth_{$auth}/field_updateremote_{$field}",
1279                          get_string('auth_updateremotefield', 'auth', $fieldname), '', 0, $updateextoptions));
1280              }
1281  
1282              // Lock fields.
1283              $settings->add(new admin_setting_configselect("auth_{$auth}/field_lock_{$field}",
1284                      get_string('auth_fieldlockfield', 'auth', $fieldname), '', 'unlocked', $lockoptions));
1285  
1286          } else {
1287              // Lock fields Only.
1288              $settings->add(new admin_setting_configselect("auth_{$auth}/field_lock_{$field}",
1289                      get_string('auth_fieldlockfield', 'auth', $fieldname), '', 'unlocked', $lockoptions));
1290          }
1291      }
1292  }