MDL-80612 auth: Allow plugins to identify Moodle users on the CLI
[moodle.git] / lib / authlib.php
blob7a8d9097f7b305cb8512bf6a850f94eafb2d6be1
1 <?php
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.
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/>.
18 /**
19 * Multiple plugin authentication Support library
21 * 2006-08-28 File created, AUTH return values defined.
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
29 defined('MOODLE_INTERNAL') || die();
31 /**
32 * Returned when the login was successful.
34 define('AUTH_OK', 0);
36 /**
37 * Returned when the login was unsuccessful.
39 define('AUTH_FAIL', 1);
41 /**
42 * Returned when the login was denied (a reason for AUTH_FAIL).
44 define('AUTH_DENIED', 2);
46 /**
47 * Returned when some error occurred (a reason for AUTH_FAIL).
49 define('AUTH_ERROR', 4);
51 /**
52 * Authentication - error codes for user confirm
54 define('AUTH_CONFIRM_FAIL', 0);
55 define('AUTH_CONFIRM_OK', 1);
56 define('AUTH_CONFIRM_ALREADY', 2);
57 define('AUTH_CONFIRM_ERROR', 3);
59 # MDL-14055
60 define('AUTH_REMOVEUSER_KEEP', 0);
61 define('AUTH_REMOVEUSER_SUSPEND', 1);
62 define('AUTH_REMOVEUSER_FULLDELETE', 2);
64 /** Login attempt successful. */
65 define('AUTH_LOGIN_OK', 0);
67 /** Can not login because user does not exist. */
68 define('AUTH_LOGIN_NOUSER', 1);
70 /** Can not login because user is suspended. */
71 define('AUTH_LOGIN_SUSPENDED', 2);
73 /** Can not login, most probably password did not match. */
74 define('AUTH_LOGIN_FAILED', 3);
76 /** Can not login because user is locked out. */
77 define('AUTH_LOGIN_LOCKOUT', 4);
79 /** Can not login becauser user is not authorised. */
80 define('AUTH_LOGIN_UNAUTHORISED', 5);
82 /** Can not login, failed reCaptcha challenge. */
83 define('AUTH_LOGIN_FAILED_RECAPTCHA', 6);
85 /**
86 * Abstract authentication plugin.
88 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
89 * @package moodlecore
91 class auth_plugin_base {
93 /**
94 * The configuration details for the plugin.
95 * @var object
97 var $config;
99 /**
100 * Authentication plugin type - the same as db field.
101 * @var string
103 var $authtype;
105 * The fields we can lock and update from/to external authentication backends
106 * @var array
108 var $userfields = \core_user::AUTHSYNCFIELDS;
111 * Moodle custom fields to sync with.
112 * @var array()
114 var $customfields = null;
117 * The tag we want to prepend to any error log messages.
119 * @var string
121 protected $errorlogtag = '';
123 /** @var array Stores extra information available to the logged in event. */
124 protected $extrauserinfo = [];
127 * This is the primary method that is used by the authenticate_user_login()
128 * function in moodlelib.php.
130 * This method should return a boolean indicating
131 * whether or not the username and password authenticate successfully.
133 * Returns true if the username and password work and false if they are
134 * wrong or don't exist.
136 * @param string $username The username (with system magic quotes)
137 * @param string $password The password (with system magic quotes)
139 * @return bool Authentication success or failure.
141 function user_login($username, $password) {
142 throw new \moodle_exception('mustbeoveride', 'debug', '', 'user_login()' );
146 * Returns true if this authentication plugin can change the users'
147 * password.
149 * @return bool
151 function can_change_password() {
152 //override if needed
153 return false;
157 * Returns the URL for changing the users' passwords, or empty if the default
158 * URL can be used.
160 * This method is used if can_change_password() returns true.
161 * This method is called only when user is logged in, it may use global $USER.
162 * If you are using a plugin config variable in this method, please make sure it is set before using it,
163 * as this method can be called even if the plugin is disabled, in which case the config values won't be set.
165 * @return moodle_url url of the profile page or null if standard used
167 function change_password_url() {
168 //override if needed
169 return null;
173 * Returns true if this authentication plugin can edit the users'
174 * profile.
176 * @return bool
178 function can_edit_profile() {
179 //override if needed
180 return true;
184 * Returns the URL for editing the users' profile, or empty if the default
185 * URL can be used.
187 * This method is used if can_edit_profile() returns true.
188 * This method is called only when user is logged in, it may use global $USER.
190 * @return moodle_url url of the profile page or null if standard used
192 function edit_profile_url() {
193 //override if needed
194 return null;
198 * Returns true if this authentication plugin is "internal".
200 * Internal plugins use password hashes from Moodle user table for authentication.
202 * @return bool
204 function is_internal() {
205 //override if needed
206 return true;
210 * Returns false if this plugin is enabled but not configured.
212 * @return bool
214 public function is_configured() {
215 return false;
219 * Indicates if password hashes should be stored in local moodle database.
220 * @return bool true means md5 password hash stored in user table, false means flag 'not_cached' stored there instead
222 function prevent_local_passwords() {
223 return !$this->is_internal();
227 * Indicates if moodle should automatically update internal user
228 * records with data from external sources using the information
229 * from get_userinfo() method.
231 * @return bool true means automatically copy data from ext to user table
233 function is_synchronised_with_external() {
234 return !$this->is_internal();
238 * Updates the user's password.
240 * In previous versions of Moodle, the function
241 * auth_user_update_password accepted a username as the first parameter. The
242 * revised function expects a user object.
244 * @param object $user User table object
245 * @param string $newpassword Plaintext password
247 * @return bool True on success
249 function user_update_password($user, $newpassword) {
250 //override if needed
251 return true;
255 * Called when the user record is updated.
256 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
257 * compares information saved modified information to external db.
259 * @param mixed $olduser Userobject before modifications (without system magic quotes)
260 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
261 * @return boolean true if updated or update ignored; false if error
264 function user_update($olduser, $newuser) {
265 //override if needed
266 return true;
270 * User delete requested - internal user record is mared as deleted already, username not present anymore.
272 * Do any action in external database.
274 * @param object $user Userobject before delete (without system magic quotes)
275 * @return void
277 function user_delete($olduser) {
278 //override if needed
279 return;
283 * Returns true if plugin allows resetting of internal password.
285 * @return bool
287 function can_reset_password() {
288 //override if needed
289 return false;
293 * Returns true if plugin allows resetting of internal password.
295 * @return bool
297 function can_signup() {
298 //override if needed
299 return false;
303 * Sign up a new user ready for confirmation.
304 * Password is passed in plaintext.
306 * @param object $user new user object
307 * @param boolean $notify print notice with link and terminate
309 function user_signup($user, $notify=true) {
310 //override when can signup
311 throw new \moodle_exception('mustbeoveride', 'debug', '', 'user_signup()' );
315 * Return a form to capture user details for account creation.
316 * This is used in /login/signup.php.
317 * @return moodle_form A form which edits a record from the user table.
319 function signup_form() {
320 global $CFG;
322 require_once($CFG->dirroot.'/login/signup_form.php');
323 return new login_signup_form(null, null, 'post', '', array('autocomplete'=>'on'));
327 * Returns true if plugin allows confirming of new users.
329 * @return bool
331 function can_confirm() {
332 //override if needed
333 return false;
337 * Confirm the new user as registered.
339 * @param string $username
340 * @param string $confirmsecret
342 function user_confirm($username, $confirmsecret) {
343 //override when can confirm
344 throw new \moodle_exception('mustbeoveride', 'debug', '', 'user_confirm()' );
348 * Checks if user exists in external db
350 * @param string $username (with system magic quotes)
351 * @return bool
353 function user_exists($username) {
354 //override if needed
355 return false;
359 * return number of days to user password expires
361 * If userpassword does not expire it should return 0. If password is already expired
362 * it should return negative value.
364 * @param mixed $username username (with system magic quotes)
365 * @return integer
367 function password_expire($username) {
368 return 0;
371 * Sync roles for this user - usually creator
373 * @param $user object user object (without system magic quotes)
375 function sync_roles($user) {
376 //override if needed
380 * Read user information from external database and returns it as array().
381 * Function should return all information available. If you are saving
382 * this information to moodle user-table you should honour synchronisation flags
384 * @param string $username username
386 * @return mixed array with no magic quotes or false on error
388 function get_userinfo($username) {
389 //override if needed
390 return array();
394 * Prints a form for configuring this authentication plugin.
396 * This function is called from admin/auth.php, and outputs a full page with
397 * a form for configuring this plugin.
399 * @param object $config
400 * @param object $err
401 * @param array $user_fields
402 * @deprecated since Moodle 3.3
404 function config_form($config, $err, $user_fields) {
405 debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
406 //override if needed
410 * A chance to validate form data, and last chance to
411 * do stuff before it is inserted in config_plugin
412 * @param object object with submitted configuration settings (without system magic quotes)
413 * @param array $err array of error messages
414 * @deprecated since Moodle 3.3
416 function validate_form($form, &$err) {
417 debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
418 //override if needed
422 * Processes and stores configuration data for this authentication plugin.
424 * @param object object with submitted configuration settings (without system magic quotes)
425 * @deprecated since Moodle 3.3
427 function process_config($config) {
428 debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
429 //override if needed
430 return true;
434 * Hook for overriding behaviour of login page.
435 * This method is called from login/index.php page for all enabled auth plugins.
437 * @global object
438 * @global object
440 function loginpage_hook() {
441 global $frm; // can be used to override submitted login form
442 global $user; // can be used to replace authenticate_user_login()
444 //override if needed
448 * Hook for overriding behaviour before going to the login page.
450 * This method is called from require_login from potentially any page for
451 * all enabled auth plugins and gives each plugin a chance to redirect
452 * directly to an external login page, or to instantly login a user where
453 * possible.
455 * If an auth plugin implements this hook, it must not rely on ONLY this
456 * hook in order to work, as there are many ways a user can browse directly
457 * to the standard login page. As a general rule in this case you should
458 * also implement the loginpage_hook as well.
461 function pre_loginpage_hook() {
462 // override if needed, eg by redirecting to an external login page
463 // or logging in a user:
464 // complete_user_login($user);
468 * Pre user_login hook.
469 * This method is called from authenticate_user_login() right after the user
470 * object is generated. This gives the auth plugins an option to make adjustments
471 * before the verification process starts.
473 * @param object $user user object, later used for $USER
475 public function pre_user_login_hook(&$user) {
476 // Override if needed.
480 * Post authentication hook.
481 * This method is called from authenticate_user_login() for all enabled auth plugins.
483 * @param object $user user object, later used for $USER
484 * @param string $username (with system magic quotes)
485 * @param string $password plain text password (with system magic quotes)
487 function user_authenticated_hook(&$user, $username, $password) {
488 //override if needed
492 * Pre logout hook.
493 * This method is called from require_logout() for all enabled auth plugins,
495 * @global object
497 function prelogout_hook() {
498 global $USER; // use $USER->auth to find the plugin used for login
500 //override if needed
504 * Hook for overriding behaviour of logout page.
505 * This method is called from login/logout.php page for all enabled auth plugins.
507 * @global object
508 * @global string
510 function logoutpage_hook() {
511 global $USER; // use $USER->auth to find the plugin used for login
512 global $redirect; // can be used to override redirect after logout
514 //override if needed
518 * Hook called before timing out of database session.
519 * This is useful for SSO and MNET.
521 * @param object $user
522 * @param string $sid session id
523 * @param int $timecreated start of session
524 * @param int $timemodified user last seen
525 * @return bool true means do not timeout session yet
527 function ignore_timeout_hook($user, $sid, $timecreated, $timemodified) {
528 return false;
532 * Return the properly translated human-friendly title of this auth plugin
534 * @todo Document this function
536 function get_title() {
537 return get_string('pluginname', "auth_{$this->authtype}");
541 * Get the auth description (from core or own auth lang files)
543 * @return string The description
545 function get_description() {
546 $authdescription = get_string("auth_{$this->authtype}description", "auth_{$this->authtype}");
547 return $authdescription;
551 * Returns whether or not the captcha element is enabled.
553 * @abstract Implement in child classes
554 * @return bool
556 function is_captcha_enabled() {
557 return false;
561 * Returns whether or not this authentication plugin can be manually set
562 * for users, for example, when bulk uploading users.
564 * This should be overriden by authentication plugins where setting the
565 * authentication method manually is allowed.
567 * @return bool
568 * @since Moodle 2.6
570 function can_be_manually_set() {
571 // Override if needed.
572 return false;
576 * Returns a list of potential IdPs that this authentication plugin supports.
578 * This is used to provide links on the login page and the login block.
580 * The parameter $wantsurl is typically used by the plugin to implement a
581 * return-url feature.
583 * The returned value is expected to be a list of associative arrays with
584 * string keys:
586 * - url => (moodle_url|string) URL of the page to send the user to for authentication
587 * - name => (string) Human readable name of the IdP
588 * - iconurl => (moodle_url|string) URL of the icon representing the IdP (since Moodle 3.3)
590 * For legacy reasons, pre-3.3 plugins can provide the icon via the key:
592 * - icon => (pix_icon) Icon representing the IdP
594 * @param string $wantsurl The relative url fragment the user wants to get to.
595 * @return array List of associative arrays with keys url, name, iconurl|icon
597 function loginpage_idp_list($wantsurl) {
598 return array();
602 * Return custom user profile fields.
604 * @return array list of custom fields.
606 public function get_custom_user_profile_fields() {
607 global $CFG;
608 require_once($CFG->dirroot . '/user/profile/lib.php');
610 // If already retrieved then return.
611 if (!is_null($this->customfields)) {
612 return $this->customfields;
615 $this->customfields = array();
616 if ($proffields = profile_get_custom_fields()) {
617 foreach ($proffields as $proffield) {
618 $this->customfields[] = 'profile_field_'.$proffield->shortname;
621 unset($proffields);
623 return $this->customfields;
627 * Post logout hook.
629 * This method is used after moodle logout by auth classes to execute server logout.
631 * @param stdClass $user clone of USER object before the user session was terminated
633 public function postlogout_hook($user) {
637 * Update a local user record from an external source.
638 * This is a lighter version of the one in moodlelib -- won't do
639 * expensive ops such as enrolment.
641 * @param string $username username
642 * @param array $updatekeys fields to update, false updates all fields.
643 * @param bool $triggerevent set false if user_updated event should not be triggered.
644 * This will not affect user_password_updated event triggering.
645 * @param bool $suspenduser Should the user be suspended?
646 * @return stdClass|bool updated user record or false if there is no new info to update.
648 protected function update_user_record($username, $updatekeys = false, $triggerevent = false, $suspenduser = false) {
649 global $CFG, $DB;
651 require_once($CFG->dirroot.'/user/profile/lib.php');
653 // Just in case check text case.
654 $username = trim(core_text::strtolower($username));
656 // Get the current user record.
657 $user = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id));
658 if (empty($user)) { // Trouble.
659 error_log($this->errorlogtag . get_string('auth_usernotexist', 'auth', $username));
660 throw new \moodle_exception('auth_usernotexist', 'auth', '', $username);
661 die;
664 // Protect the userid from being overwritten.
665 $userid = $user->id;
667 $needsupdate = false;
669 if ($newinfo = $this->get_userinfo($username)) {
670 $newinfo = truncate_userinfo($newinfo);
672 if (empty($updatekeys)) { // All keys? this does not support removing values.
673 $updatekeys = array_keys($newinfo);
676 if (!empty($updatekeys)) {
677 $newuser = new stdClass();
678 $newuser->id = $userid;
679 // The cast to int is a workaround for MDL-53959.
680 $newuser->suspended = (int) $suspenduser;
681 // Load all custom fields.
682 $profilefields = (array) profile_user_record($user->id, false);
683 $newprofilefields = [];
685 foreach ($updatekeys as $key) {
686 if (isset($newinfo[$key])) {
687 $value = $newinfo[$key];
688 } else {
689 $value = '';
692 if (!empty($this->config->{'field_updatelocal_' . $key})) {
693 if (preg_match('/^profile_field_(.*)$/', $key, $match)) {
694 // Custom field.
695 $field = $match[1];
696 $currentvalue = isset($profilefields[$field]) ? $profilefields[$field] : null;
697 $newprofilefields[$field] = $value;
698 } else {
699 // Standard field.
700 $currentvalue = isset($user->$key) ? $user->$key : null;
701 $newuser->$key = $value;
704 // Only update if it's changed.
705 if ($currentvalue !== $value) {
706 $needsupdate = true;
712 if ($needsupdate) {
713 user_update_user($newuser, false, $triggerevent);
714 profile_save_custom_fields($newuser->id, $newprofilefields);
715 return $DB->get_record('user', array('id' => $userid, 'deleted' => 0));
719 return false;
723 * Return the list of enabled identity providers.
725 * Each identity provider data contains the keys url, name and iconurl (or
726 * icon). See the documentation of {@link auth_plugin_base::loginpage_idp_list()}
727 * for detailed description of the returned structure.
729 * @param array $authsequence site's auth sequence (list of auth plugins ordered)
730 * @return array List of arrays describing the identity providers
732 public static function get_identity_providers($authsequence) {
733 global $SESSION;
735 $identityproviders = [];
736 foreach ($authsequence as $authname) {
737 $authplugin = get_auth_plugin($authname);
738 $wantsurl = (isset($SESSION->wantsurl)) ? $SESSION->wantsurl : '';
739 $identityproviders = array_merge($identityproviders, $authplugin->loginpage_idp_list($wantsurl));
741 return $identityproviders;
745 * Prepare a list of identity providers for output.
747 * @param array $identityproviders as returned by {@link self::get_identity_providers()}
748 * @param renderer_base $output
749 * @return array the identity providers ready for output
751 public static function prepare_identity_providers_for_output($identityproviders, renderer_base $output) {
752 $data = [];
753 foreach ($identityproviders as $idp) {
754 if (!empty($idp['icon'])) {
755 // Pre-3.3 auth plugins provide icon as a pix_icon instance. New auth plugins (since 3.3) provide iconurl.
756 $idp['iconurl'] = $output->image_url($idp['icon']->pix, $idp['icon']->component);
758 if ($idp['iconurl'] instanceof moodle_url) {
759 $idp['iconurl'] = $idp['iconurl']->out(false);
761 unset($idp['icon']);
762 if ($idp['url'] instanceof moodle_url) {
763 $idp['url'] = $idp['url']->out(false);
765 $data[] = $idp;
767 return $data;
771 * Returns information on how the specified user can change their password.
773 * @param stdClass $user A user object
774 * @return string[] An array of strings with keys subject and message
776 public function get_password_change_info(stdClass $user): array {
778 global $USER;
780 $site = get_site();
781 $systemcontext = context_system::instance();
783 $data = new stdClass();
784 $data->firstname = $user->firstname;
785 $data->lastname = $user->lastname;
786 $data->username = $user->username;
787 $data->sitename = format_string($site->fullname);
788 $data->admin = generate_email_signoff();
790 // This is a workaround as change_password_url() is designed to allow
791 // use of the $USER global. See MDL-66984.
792 $olduser = $USER;
793 $USER = $user;
794 if ($this->can_change_password() and $this->change_password_url()) {
795 // We have some external url for password changing.
796 $data->link = $this->change_password_url()->out();
797 } else {
798 // No way to change password, sorry.
799 $data->link = '';
801 $USER = $olduser;
803 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
804 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
805 $message = get_string('emailpasswordchangeinfo', '', $data);
806 } else {
807 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
808 $message = get_string('emailpasswordchangeinfofail', '', $data);
811 return [
812 'subject' => $subject,
813 'message' => $message
818 * Set extra user information.
820 * @param array $values Any Key value pair.
821 * @return void
823 public function set_extrauserinfo(array $values): void {
824 $this->extrauserinfo = $values;
828 * Returns extra user information.
830 * @return array An array of keys and values
832 public function get_extrauserinfo(): array {
833 return $this->extrauserinfo;
837 * Returns the enabled auth plugins
839 * @return array of plugin classes
841 public static function get_enabled_auth_plugin_classes(): array {
842 $plugins = [];
843 $authsequence = get_enabled_auth_plugins();
844 foreach ($authsequence as $authname) {
845 $plugins[] = get_auth_plugin($authname);
847 return $plugins;
851 * Find an OS level admin Moodle user account
853 * Used when running CLI scripts. Only accounts which are
854 * site admin will be accepted.
856 * @return null|stdClass Admin user record if found
858 public static function find_cli_admin_user(): ?stdClass {
859 $plugins = static::get_enabled_auth_plugin_classes();
860 foreach ($plugins as $authplugin) {
861 $user = $authplugin->find_cli_user();
862 // This MUST be a valid admin user.
863 if (!empty($user) && is_siteadmin($user->id)) {
864 return $user;
867 return null;
871 * Find and login as an OS level admin Moodle user account
873 * Used for running CLI scripts which must be admin accounts.
875 public static function login_cli_admin_user(): void {
876 $user = static::find_cli_admin_user();
877 if (!empty($user)) {
878 \core\session\manager::set_user($user);
883 * Identify a Moodle account on the CLI
885 * For example a plugin might use posix_geteuid and posix_getpwuid
886 * to find the username of the OS level user and then match that
887 * against Moodle user accounts.
889 * @return null|stdClass User user record if found
891 public function find_cli_user(): ?stdClass {
892 // Override if needed.
893 return null;
898 * Verify if user is locked out.
900 * @param stdClass $user
901 * @return bool true if user locked out
903 function login_is_lockedout($user) {
904 global $CFG;
906 if ($user->mnethostid != $CFG->mnet_localhost_id) {
907 return false;
909 if (isguestuser($user)) {
910 return false;
913 if (empty($CFG->lockoutthreshold)) {
914 // Lockout not enabled.
915 return false;
918 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
919 // This preference may be used for accounts that must not be locked out.
920 return false;
923 $locked = get_user_preferences('login_lockout', 0, $user);
924 if (!$locked) {
925 return false;
928 if (empty($CFG->lockoutduration)) {
929 // Locked out forever.
930 return true;
933 if (time() - $locked < $CFG->lockoutduration) {
934 return true;
937 login_unlock_account($user);
939 return false;
943 * To be called after valid user login.
944 * @param stdClass $user
946 function login_attempt_valid($user) {
947 global $CFG;
949 // Note: user_loggedin event is triggered in complete_user_login().
951 if ($user->mnethostid != $CFG->mnet_localhost_id) {
952 return;
954 if (isguestuser($user)) {
955 return;
958 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
959 login_unlock_account($user);
963 * To be called after failed user login.
964 * @param stdClass $user
965 * @throws moodle_exception
967 function login_attempt_failed($user) {
968 global $CFG;
970 if ($user->mnethostid != $CFG->mnet_localhost_id) {
971 return;
973 if (isguestuser($user)) {
974 return;
977 // Force user preferences cache reload to ensure the most up-to-date login_failed_count is fetched.
978 // This is perhaps overzealous but is the documented way of reloading the cache, as per the test method
979 // 'test_check_user_preferences_loaded'.
980 unset($user->preference);
982 $resource = 'user:' . $user->id;
983 $lockfactory = \core\lock\lock_config::get_lock_factory('core_failed_login_count_lock');
985 // Get a new lock for the resource, waiting for it for a maximum of 10 seconds.
986 if ($lock = $lockfactory->get_lock($resource, 10)) {
987 try {
988 $count = get_user_preferences('login_failed_count', 0, $user);
989 $last = get_user_preferences('login_failed_last', 0, $user);
990 $sincescuccess = get_user_preferences('login_failed_count_since_success', $count, $user);
991 $sincescuccess = $sincescuccess + 1;
992 set_user_preference('login_failed_count_since_success', $sincescuccess, $user);
994 if (empty($CFG->lockoutthreshold)) {
995 // No threshold means no lockout.
996 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
997 login_unlock_account($user);
998 $lock->release();
999 return;
1002 if (!empty($CFG->lockoutwindow) and time() - $last > $CFG->lockoutwindow) {
1003 $count = 0;
1006 $count = $count + 1;
1008 set_user_preference('login_failed_count', $count, $user);
1009 set_user_preference('login_failed_last', time(), $user);
1011 if ($count >= $CFG->lockoutthreshold) {
1012 login_lock_account($user);
1015 // Release locks when we're done.
1016 $lock->release();
1017 } catch (Exception $e) {
1018 // Always release the lock on a failure.
1019 $lock->release();
1021 } else {
1022 // We did not get access to the resource in time, give up.
1023 throw new moodle_exception('locktimeout');
1028 * Lockout user and send notification email.
1030 * @param stdClass $user
1032 function login_lock_account($user) {
1033 global $CFG;
1035 if ($user->mnethostid != $CFG->mnet_localhost_id) {
1036 return;
1038 if (isguestuser($user)) {
1039 return;
1042 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
1043 // This user can not be locked out.
1044 return;
1047 $alreadylockedout = get_user_preferences('login_lockout', 0, $user);
1049 set_user_preference('login_lockout', time(), $user);
1051 if ($alreadylockedout == 0) {
1052 $secret = random_string(15);
1053 set_user_preference('login_lockout_secret', $secret, $user);
1055 $oldforcelang = force_current_language($user->lang);
1057 $site = get_site();
1058 $supportuser = core_user::get_support_user();
1060 $data = new stdClass();
1061 $data->firstname = $user->firstname;
1062 $data->lastname = $user->lastname;
1063 $data->username = $user->username;
1064 $data->sitename = format_string($site->fullname);
1065 $data->link = $CFG->wwwroot.'/login/unlock_account.php?u='.$user->id.'&s='.$secret;
1066 $data->admin = generate_email_signoff();
1068 $message = get_string('lockoutemailbody', 'admin', $data);
1069 $subject = get_string('lockoutemailsubject', 'admin', format_string($site->fullname));
1071 if ($message) {
1072 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
1073 email_to_user($user, $supportuser, $subject, $message);
1076 force_current_language($oldforcelang);
1081 * Unlock user account and reset timers.
1083 * @param stdClass $user
1084 * @param bool $notify Notify the user their account has been unlocked.
1086 function login_unlock_account($user, bool $notify = false) {
1087 global $SESSION;
1089 unset_user_preference('login_lockout', $user);
1090 unset_user_preference('login_failed_count', $user);
1091 unset_user_preference('login_failed_last', $user);
1093 if ($notify) {
1094 $SESSION->logininfomsg = get_string('accountunlocked', 'admin');
1096 // Note: do not clear the lockout secret because user might click on the link repeatedly.
1100 * Returns whether or not the captcha element is enabled, and the admin settings fulfil its requirements.
1101 * @return bool
1103 function signup_captcha_enabled() {
1104 global $CFG;
1105 $authplugin = get_auth_plugin($CFG->registerauth);
1106 return !empty($CFG->recaptchapublickey) && !empty($CFG->recaptchaprivatekey) && $authplugin->is_captcha_enabled();
1110 * Returns whether the captcha element is enabled for the login form, and the admin settings fulfil its requirements.
1111 * @return bool
1113 function login_captcha_enabled(): bool {
1114 global $CFG;
1115 return !empty($CFG->recaptchapublickey) && !empty($CFG->recaptchaprivatekey) && $CFG->enableloginrecaptcha == true;
1119 * Check the submitted captcha is valid or not.
1121 * @param string|bool $captcha The value submitted in the login form that we are validating.
1122 * If false is passed for the captcha, this function will always return true.
1123 * @return boolean If the submitted captcha is valid.
1125 function validate_login_captcha(string|bool $captcha): bool {
1126 global $CFG;
1127 if (!empty($CFG->alternateloginurl)) {
1128 // An external login page cannot use the reCaptcha.
1129 return true;
1131 if ($captcha === false) {
1132 // The authenticate_user_login() is a core function was extended to validate captcha.
1133 // For existing uses other than the login form it does not need to validate the captcha.
1134 // Example: login/change_password_form.php or login/token.php.
1135 return true;
1138 require_once($CFG->libdir . '/recaptchalib_v2.php');
1139 $response = recaptcha_check_response(RECAPTCHA_VERIFY_URL, $CFG->recaptchaprivatekey, getremoteaddr(), $captcha);
1140 return $response['isvalid'];
1144 * Validates the standard sign-up data (except recaptcha that is validated by the form element).
1146 * @param array $data the sign-up data
1147 * @param array $files files among the data
1148 * @return array list of errors, being the key the data element name and the value the error itself
1149 * @since Moodle 3.2
1151 function signup_validate_data($data, $files) {
1152 global $CFG, $DB;
1154 $errors = array();
1155 $authplugin = get_auth_plugin($CFG->registerauth);
1157 if ($DB->record_exists('user', array('username' => $data['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
1158 $errors['username'] = get_string('usernameexists');
1159 } else {
1160 // Check allowed characters.
1161 if ($data['username'] !== core_text::strtolower($data['username'])) {
1162 $errors['username'] = get_string('usernamelowercase');
1163 } else {
1164 if ($data['username'] !== core_user::clean_field($data['username'], 'username')) {
1165 $errors['username'] = get_string('invalidusername');
1171 // Check if user exists in external db.
1172 // TODO: maybe we should check all enabled plugins instead.
1173 if ($authplugin->user_exists($data['username'])) {
1174 $errors['username'] = get_string('usernameexists');
1177 if (! validate_email($data['email'])) {
1178 $errors['email'] = get_string('invalidemail');
1180 } else if (empty($CFG->allowaccountssameemail)) {
1181 // Emails in Moodle as case-insensitive and accents-sensitive. Such a combination can lead to very slow queries
1182 // on some DBs such as MySQL. So we first get the list of candidate users in a subselect via more effective
1183 // accent-insensitive query that can make use of the index and only then we search within that limited subset.
1184 $sql = "SELECT 'x'
1185 FROM {user}
1186 WHERE " . $DB->sql_equal('email', ':email1', false, true) . "
1187 AND id IN (SELECT id
1188 FROM {user}
1189 WHERE " . $DB->sql_equal('email', ':email2', false, false) . "
1190 AND mnethostid = :mnethostid)";
1192 $params = array(
1193 'email1' => $data['email'],
1194 'email2' => $data['email'],
1195 'mnethostid' => $CFG->mnet_localhost_id,
1198 // If there are other user(s) that already have the same email, show an error.
1199 if ($DB->record_exists_sql($sql, $params)) {
1200 $forgotpasswordurl = new moodle_url('/login/forgot_password.php');
1201 $forgotpasswordlink = html_writer::link($forgotpasswordurl, get_string('emailexistshintlink'));
1202 $errors['email'] = get_string('emailexists') . ' ' . get_string('emailexistssignuphint', 'moodle', $forgotpasswordlink);
1205 if (empty($data['email2'])) {
1206 $errors['email2'] = get_string('missingemail');
1208 } else if (core_text::strtolower($data['email2']) != core_text::strtolower($data['email'])) {
1209 $errors['email2'] = get_string('invalidemail');
1211 if (!isset($errors['email'])) {
1212 if ($err = email_is_not_allowed($data['email'])) {
1213 $errors['email'] = $err;
1217 // Construct fake user object to check password policy against required information.
1218 $tempuser = new stdClass();
1219 // To prevent errors with check_password_policy(),
1220 // the temporary user and the guest must not share the same ID.
1221 $tempuser->id = (int)$CFG->siteguest + 1;
1222 $tempuser->username = $data['username'];
1223 $tempuser->firstname = $data['firstname'];
1224 $tempuser->lastname = $data['lastname'];
1225 $tempuser->email = $data['email'];
1227 $errmsg = '';
1228 if (!check_password_policy($data['password'], $errmsg, $tempuser)) {
1229 $errors['password'] = $errmsg;
1232 // Validate customisable profile fields. (profile_validation expects an object as the parameter with userid set).
1233 $dataobject = (object)$data;
1234 $dataobject->id = 0;
1235 $errors += profile_validation($dataobject, $files);
1237 return $errors;
1241 * Add the missing fields to a user that is going to be created
1243 * @param stdClass $user the new user object
1244 * @return stdClass the user filled
1245 * @since Moodle 3.2
1247 function signup_setup_new_user($user) {
1248 global $CFG;
1250 $user->confirmed = 0;
1251 $user->lang = current_language();
1252 $user->firstaccess = 0;
1253 $user->timecreated = time();
1254 $user->mnethostid = $CFG->mnet_localhost_id;
1255 $user->secret = random_string(15);
1256 $user->auth = $CFG->registerauth;
1257 // Initialize alternate name fields to empty strings.
1258 $namefields = array_diff(\core_user\fields::get_name_fields(), useredit_get_required_name_fields());
1259 foreach ($namefields as $namefield) {
1260 $user->$namefield = '';
1262 return $user;
1266 * Check if user confirmation is enabled on this site and return the auth plugin handling registration if enabled.
1268 * @return stdClass the current auth plugin handling user registration or false if registration not enabled
1269 * @since Moodle 3.2
1271 function signup_get_user_confirmation_authplugin() {
1272 global $CFG;
1274 if (empty($CFG->registerauth)) {
1275 return false;
1277 $authplugin = get_auth_plugin($CFG->registerauth);
1279 if (!$authplugin->can_confirm()) {
1280 return false;
1282 return $authplugin;
1286 * Check if sign-up is enabled in the site. If is enabled, the function will return the authplugin instance.
1288 * @return mixed false if sign-up is not enabled, the authplugin instance otherwise.
1289 * @since Moodle 3.2
1291 function signup_is_enabled() {
1292 global $CFG;
1294 if (!empty($CFG->registerauth)) {
1295 $authplugin = get_auth_plugin($CFG->registerauth);
1296 if ($authplugin->can_signup()) {
1297 return $authplugin;
1300 return false;
1304 * Helper function used to print locking for auth plugins on admin pages.
1305 * @param admin_settingpage $settings Moodle admin settings instance
1306 * @param string $auth authentication plugin shortname
1307 * @param array $userfields user profile fields
1308 * @param string $helptext help text to be displayed at top of form
1309 * @param boolean $mapremotefields Map fields or lock only.
1310 * @param boolean $updateremotefields Allow remote updates
1311 * @param array $customfields list of custom profile fields
1312 * @since Moodle 3.3
1314 function display_auth_lock_options($settings, $auth, $userfields, $helptext, $mapremotefields, $updateremotefields, $customfields = array()) {
1315 global $CFG;
1316 require_once($CFG->dirroot . '/user/profile/lib.php');
1318 // Introductory explanation and help text.
1319 if ($mapremotefields) {
1320 $settings->add(new admin_setting_heading($auth.'/data_mapping', new lang_string('auth_data_mapping', 'auth'), $helptext));
1321 } else {
1322 $settings->add(new admin_setting_heading($auth.'/auth_fieldlocks', new lang_string('auth_fieldlocks', 'auth'), $helptext));
1325 // Generate the list of options.
1326 $lockoptions = array ('unlocked' => get_string('unlocked', 'auth'),
1327 'unlockedifempty' => get_string('unlockedifempty', 'auth'),
1328 'locked' => get_string('locked', 'auth'));
1329 $updatelocaloptions = array('oncreate' => get_string('update_oncreate', 'auth'),
1330 'onlogin' => get_string('update_onlogin', 'auth'));
1331 $updateextoptions = array('0' => get_string('update_never', 'auth'),
1332 '1' => get_string('update_onupdate', 'auth'));
1334 // Generate the list of profile fields to allow updates / lock.
1335 if (!empty($customfields)) {
1336 $userfields = array_merge($userfields, $customfields);
1337 $allcustomfields = profile_get_custom_fields();
1338 $customfieldname = array_combine(array_column($allcustomfields, 'shortname'), $allcustomfields);
1341 foreach ($userfields as $field) {
1342 // Define the fieldname we display to the user.
1343 // this includes special handling for some profile fields.
1344 $fieldname = $field;
1345 $fieldnametoolong = false;
1346 if ($fieldname === 'lang') {
1347 $fieldname = get_string('language');
1348 } else if (!empty($customfields) && in_array($field, $customfields)) {
1349 // If custom field then pick name from database.
1350 $fieldshortname = str_replace('profile_field_', '', $fieldname);
1351 $fieldname = $customfieldname[$fieldshortname]->name;
1352 if (core_text::strlen($fieldshortname) > 67) {
1353 // If custom profile field name is longer than 67 characters we will not be able to store the setting
1354 // such as 'field_updateremote_profile_field_NOTSOSHORTSHORTNAME' in the database because the character
1355 // limit for the setting name is 100.
1356 $fieldnametoolong = true;
1358 } else {
1359 $fieldname = get_string($fieldname);
1362 // Generate the list of fields / mappings.
1363 if ($fieldnametoolong) {
1364 // Display a message that the field can not be mapped because it's too long.
1365 $url = new moodle_url('/user/profile/index.php');
1366 $a = (object)['fieldname' => s($fieldname), 'shortname' => s($field), 'charlimit' => 67, 'link' => $url->out()];
1367 $settings->add(new admin_setting_heading($auth.'/field_not_mapped_'.sha1($field), '',
1368 get_string('cannotmapfield', 'auth', $a)));
1369 } else if ($mapremotefields) {
1370 // We are mapping to a remote field here.
1371 // Mapping.
1372 $settings->add(new admin_setting_configtext("auth_{$auth}/field_map_{$field}",
1373 get_string('auth_fieldmapping', 'auth', $fieldname), '', '', PARAM_RAW, 30));
1375 // Update local.
1376 $settings->add(new admin_setting_configselect("auth_{$auth}/field_updatelocal_{$field}",
1377 get_string('auth_updatelocalfield', 'auth', $fieldname), '', 'oncreate', $updatelocaloptions));
1379 // Update remote.
1380 if ($updateremotefields) {
1381 $settings->add(new admin_setting_configselect("auth_{$auth}/field_updateremote_{$field}",
1382 get_string('auth_updateremotefield', 'auth', $fieldname), '', 0, $updateextoptions));
1385 // Lock fields.
1386 $settings->add(new admin_setting_configselect("auth_{$auth}/field_lock_{$field}",
1387 get_string('auth_fieldlockfield', 'auth', $fieldname), '', 'unlocked', $lockoptions));
1389 } else {
1390 // Lock fields Only.
1391 $settings->add(new admin_setting_configselect("auth_{$auth}/field_lock_{$field}",
1392 get_string('auth_fieldlockfield', 'auth', $fieldname), '', 'unlocked', $lockoptions));