MDL-78962 core/loadingicon: remove jQuery requirement in the API
[moodle.git] / lib / authlib.php
blob2d742cdc5c3bd58220fc83903f88aa2fe386109e
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 /**
83 * Abstract authentication plugin.
85 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
86 * @package moodlecore
88 class auth_plugin_base {
90 /**
91 * The configuration details for the plugin.
92 * @var object
94 var $config;
96 /**
97 * Authentication plugin type - the same as db field.
98 * @var string
100 var $authtype;
102 * The fields we can lock and update from/to external authentication backends
103 * @var array
105 var $userfields = \core_user::AUTHSYNCFIELDS;
108 * Moodle custom fields to sync with.
109 * @var array()
111 var $customfields = null;
114 * The tag we want to prepend to any error log messages.
116 * @var string
118 protected $errorlogtag = '';
120 /** @var array Stores extra information available to the logged in event. */
121 protected $extrauserinfo = [];
124 * This is the primary method that is used by the authenticate_user_login()
125 * function in moodlelib.php.
127 * This method should return a boolean indicating
128 * whether or not the username and password authenticate successfully.
130 * Returns true if the username and password work and false if they are
131 * wrong or don't exist.
133 * @param string $username The username (with system magic quotes)
134 * @param string $password The password (with system magic quotes)
136 * @return bool Authentication success or failure.
138 function user_login($username, $password) {
139 throw new \moodle_exception('mustbeoveride', 'debug', '', 'user_login()' );
143 * Returns true if this authentication plugin can change the users'
144 * password.
146 * @return bool
148 function can_change_password() {
149 //override if needed
150 return false;
154 * Returns the URL for changing the users' passwords, or empty if the default
155 * URL can be used.
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.
162 * @return moodle_url url of the profile page or null if standard used
164 function change_password_url() {
165 //override if needed
166 return null;
170 * Returns true if this authentication plugin can edit the users'
171 * profile.
173 * @return bool
175 function can_edit_profile() {
176 //override if needed
177 return true;
181 * Returns the URL for editing the users' profile, or empty if the default
182 * URL can be used.
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.
187 * @return moodle_url url of the profile page or null if standard used
189 function edit_profile_url() {
190 //override if needed
191 return null;
195 * Returns true if this authentication plugin is "internal".
197 * Internal plugins use password hashes from Moodle user table for authentication.
199 * @return bool
201 function is_internal() {
202 //override if needed
203 return true;
207 * Returns false if this plugin is enabled but not configured.
209 * @return bool
211 public function is_configured() {
212 return false;
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
219 function prevent_local_passwords() {
220 return !$this->is_internal();
224 * Indicates if moodle should automatically update internal user
225 * records with data from external sources using the information
226 * from get_userinfo() method.
228 * @return bool true means automatically copy data from ext to user table
230 function is_synchronised_with_external() {
231 return !$this->is_internal();
235 * Updates the user's password.
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.
241 * @param object $user User table object
242 * @param string $newpassword Plaintext password
244 * @return bool True on success
246 function user_update_password($user, $newpassword) {
247 //override if needed
248 return true;
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.
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
261 function user_update($olduser, $newuser) {
262 //override if needed
263 return true;
267 * User delete requested - internal user record is mared as deleted already, username not present anymore.
269 * Do any action in external database.
271 * @param object $user Userobject before delete (without system magic quotes)
272 * @return void
274 function user_delete($olduser) {
275 //override if needed
276 return;
280 * Returns true if plugin allows resetting of internal password.
282 * @return bool
284 function can_reset_password() {
285 //override if needed
286 return false;
290 * Returns true if plugin allows resetting of internal password.
292 * @return bool
294 function can_signup() {
295 //override if needed
296 return false;
300 * Sign up a new user ready for confirmation.
301 * Password is passed in plaintext.
303 * @param object $user new user object
304 * @param boolean $notify print notice with link and terminate
306 function user_signup($user, $notify=true) {
307 //override when can signup
308 throw new \moodle_exception('mustbeoveride', 'debug', '', 'user_signup()' );
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.
316 function signup_form() {
317 global $CFG;
319 require_once($CFG->dirroot.'/login/signup_form.php');
320 return new login_signup_form(null, null, 'post', '', array('autocomplete'=>'on'));
324 * Returns true if plugin allows confirming of new users.
326 * @return bool
328 function can_confirm() {
329 //override if needed
330 return false;
334 * Confirm the new user as registered.
336 * @param string $username
337 * @param string $confirmsecret
339 function user_confirm($username, $confirmsecret) {
340 //override when can confirm
341 throw new \moodle_exception('mustbeoveride', 'debug', '', 'user_confirm()' );
345 * Checks if user exists in external db
347 * @param string $username (with system magic quotes)
348 * @return bool
350 function user_exists($username) {
351 //override if needed
352 return false;
356 * return number of days to user password expires
358 * If userpassword does not expire it should return 0. If password is already expired
359 * it should return negative value.
361 * @param mixed $username username (with system magic quotes)
362 * @return integer
364 function password_expire($username) {
365 return 0;
368 * Sync roles for this user - usually creator
370 * @param $user object user object (without system magic quotes)
372 function sync_roles($user) {
373 //override if needed
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
381 * @param string $username username
383 * @return mixed array with no magic quotes or false on error
385 function get_userinfo($username) {
386 //override if needed
387 return array();
391 * Prints a form for configuring this authentication plugin.
393 * This function is called from admin/auth.php, and outputs a full page with
394 * a form for configuring this plugin.
396 * @param object $config
397 * @param object $err
398 * @param array $user_fields
399 * @deprecated since Moodle 3.3
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
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
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
419 * Processes and stores configuration data for this authentication plugin.
421 * @param object object with submitted configuration settings (without system magic quotes)
422 * @deprecated since Moodle 3.3
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;
431 * Hook for overriding behaviour of login page.
432 * This method is called from login/index.php page for all enabled auth plugins.
434 * @global object
435 * @global object
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()
441 //override if needed
445 * Hook for overriding behaviour before going to the login page.
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.
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.
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);
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.
470 * @param object $user user object, later used for $USER
472 public function pre_user_login_hook(&$user) {
473 // Override if needed.
477 * Post authentication hook.
478 * This method is called from authenticate_user_login() for all enabled auth plugins.
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)
484 function user_authenticated_hook(&$user, $username, $password) {
485 //override if needed
489 * Pre logout hook.
490 * This method is called from require_logout() for all enabled auth plugins,
492 * @global object
494 function prelogout_hook() {
495 global $USER; // use $USER->auth to find the plugin used for login
497 //override if needed
501 * Hook for overriding behaviour of logout page.
502 * This method is called from login/logout.php page for all enabled auth plugins.
504 * @global object
505 * @global string
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
511 //override if needed
515 * Hook called before timing out of database session.
516 * This is useful for SSO and MNET.
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
524 function ignore_timeout_hook($user, $sid, $timecreated, $timemodified) {
525 return false;
529 * Return the properly translated human-friendly title of this auth plugin
531 * @todo Document this function
533 function get_title() {
534 return get_string('pluginname', "auth_{$this->authtype}");
538 * Get the auth description (from core or own auth lang files)
540 * @return string The description
542 function get_description() {
543 $authdescription = get_string("auth_{$this->authtype}description", "auth_{$this->authtype}");
544 return $authdescription;
548 * Returns whether or not the captcha element is enabled.
550 * @abstract Implement in child classes
551 * @return bool
553 function is_captcha_enabled() {
554 return false;
558 * Returns whether or not this authentication plugin can be manually set
559 * for users, for example, when bulk uploading users.
561 * This should be overriden by authentication plugins where setting the
562 * authentication method manually is allowed.
564 * @return bool
565 * @since Moodle 2.6
567 function can_be_manually_set() {
568 // Override if needed.
569 return false;
573 * Returns a list of potential IdPs that this authentication plugin supports.
575 * This is used to provide links on the login page and the login block.
577 * The parameter $wantsurl is typically used by the plugin to implement a
578 * return-url feature.
580 * The returned value is expected to be a list of associative arrays with
581 * string keys:
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)
587 * For legacy reasons, pre-3.3 plugins can provide the icon via the key:
589 * - icon => (pix_icon) Icon representing the IdP
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
594 function loginpage_idp_list($wantsurl) {
595 return array();
599 * Return custom user profile fields.
601 * @return array list of custom fields.
603 public function get_custom_user_profile_fields() {
604 global $CFG;
605 require_once($CFG->dirroot . '/user/profile/lib.php');
607 // If already retrieved then return.
608 if (!is_null($this->customfields)) {
609 return $this->customfields;
612 $this->customfields = array();
613 if ($proffields = profile_get_custom_fields()) {
614 foreach ($proffields as $proffield) {
615 $this->customfields[] = 'profile_field_'.$proffield->shortname;
618 unset($proffields);
620 return $this->customfields;
624 * Post logout hook.
626 * This method is used after moodle logout by auth classes to execute server logout.
628 * @param stdClass $user clone of USER object before the user session was terminated
630 public function postlogout_hook($user) {
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.
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.
645 protected function update_user_record($username, $updatekeys = false, $triggerevent = false, $suspenduser = false) {
646 global $CFG, $DB;
648 require_once($CFG->dirroot.'/user/profile/lib.php');
650 // Just in case check text case.
651 $username = trim(core_text::strtolower($username));
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;
661 // Protect the userid from being overwritten.
662 $userid = $user->id;
664 $needsupdate = false;
666 if ($newinfo = $this->get_userinfo($username)) {
667 $newinfo = truncate_userinfo($newinfo);
669 if (empty($updatekeys)) { // All keys? this does not support removing values.
670 $updatekeys = array_keys($newinfo);
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 = [];
682 foreach ($updatekeys as $key) {
683 if (isset($newinfo[$key])) {
684 $value = $newinfo[$key];
685 } else {
686 $value = '';
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;
701 // Only update if it's changed.
702 if ($currentvalue !== $value) {
703 $needsupdate = true;
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));
716 return false;
720 * Return the list of enabled identity providers.
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.
726 * @param array $authsequence site's auth sequence (list of auth plugins ordered)
727 * @return array List of arrays describing the identity providers
729 public static function get_identity_providers($authsequence) {
730 global $SESSION;
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));
738 return $identityproviders;
742 * Prepare a list of identity providers for output.
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
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);
755 if ($idp['iconurl'] instanceof moodle_url) {
756 $idp['iconurl'] = $idp['iconurl']->out(false);
758 unset($idp['icon']);
759 if ($idp['url'] instanceof moodle_url) {
760 $idp['url'] = $idp['url']->out(false);
762 $data[] = $idp;
764 return $data;
768 * Returns information on how the specified user can change their password.
770 * @param stdClass $user A user object
771 * @return string[] An array of strings with keys subject and message
773 public function get_password_change_info(stdClass $user) : array {
775 global $USER;
777 $site = get_site();
778 $systemcontext = context_system::instance();
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();
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 = '';
798 $USER = $olduser;
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);
808 return [
809 'subject' => $subject,
810 'message' => $message
815 * Set extra user information.
817 * @param array $values Any Key value pair.
818 * @return void
820 public function set_extrauserinfo(array $values): void {
821 $this->extrauserinfo = $values;
825 * Returns extra user information.
827 * @return array An array of keys and values
829 public function get_extrauserinfo(): array {
830 return $this->extrauserinfo;
835 * Verify if user is locked out.
837 * @param stdClass $user
838 * @return bool true if user locked out
840 function login_is_lockedout($user) {
841 global $CFG;
843 if ($user->mnethostid != $CFG->mnet_localhost_id) {
844 return false;
846 if (isguestuser($user)) {
847 return false;
850 if (empty($CFG->lockoutthreshold)) {
851 // Lockout not enabled.
852 return false;
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;
860 $locked = get_user_preferences('login_lockout', 0, $user);
861 if (!$locked) {
862 return false;
865 if (empty($CFG->lockoutduration)) {
866 // Locked out forever.
867 return true;
870 if (time() - $locked < $CFG->lockoutduration) {
871 return true;
874 login_unlock_account($user);
876 return false;
880 * To be called after valid user login.
881 * @param stdClass $user
883 function login_attempt_valid($user) {
884 global $CFG;
886 // Note: user_loggedin event is triggered in complete_user_login().
888 if ($user->mnethostid != $CFG->mnet_localhost_id) {
889 return;
891 if (isguestuser($user)) {
892 return;
895 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
896 login_unlock_account($user);
900 * To be called after failed user login.
901 * @param stdClass $user
902 * @throws moodle_exception
904 function login_attempt_failed($user) {
905 global $CFG;
907 if ($user->mnethostid != $CFG->mnet_localhost_id) {
908 return;
910 if (isguestuser($user)) {
911 return;
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);
919 $resource = 'user:' . $user->id;
920 $lockfactory = \core\lock\lock_config::get_lock_factory('core_failed_login_count_lock');
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);
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;
939 if (!empty($CFG->lockoutwindow) and time() - $last > $CFG->lockoutwindow) {
940 $count = 0;
943 $count = $count + 1;
945 set_user_preference('login_failed_count', $count, $user);
946 set_user_preference('login_failed_last', time(), $user);
948 if ($count >= $CFG->lockoutthreshold) {
949 login_lock_account($user);
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();
958 } else {
959 // We did not get access to the resource in time, give up.
960 throw new moodle_exception('locktimeout');
965 * Lockout user and send notification email.
967 * @param stdClass $user
969 function login_lock_account($user) {
970 global $CFG;
972 if ($user->mnethostid != $CFG->mnet_localhost_id) {
973 return;
975 if (isguestuser($user)) {
976 return;
979 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
980 // This user can not be locked out.
981 return;
984 $alreadylockedout = get_user_preferences('login_lockout', 0, $user);
986 set_user_preference('login_lockout', time(), $user);
988 if ($alreadylockedout == 0) {
989 $secret = random_string(15);
990 set_user_preference('login_lockout_secret', $secret, $user);
992 $oldforcelang = force_current_language($user->lang);
994 $site = get_site();
995 $supportuser = core_user::get_support_user();
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();
1005 $message = get_string('lockoutemailbody', 'admin', $data);
1006 $subject = get_string('lockoutemailsubject', 'admin', format_string($site->fullname));
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);
1013 force_current_language($oldforcelang);
1018 * Unlock user account and reset timers.
1020 * @param stdClass $user
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);
1027 // Note: do not clear the lockout secret because user might click on the link repeatedly.
1031 * Returns whether or not the captcha element is enabled, and the admin settings fulfil its requirements.
1032 * @return bool
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();
1041 * Validates the standard sign-up data (except recaptcha that is validated by the form element).
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
1048 function signup_validate_data($data, $files) {
1049 global $CFG, $DB;
1051 $errors = array();
1052 $authplugin = get_auth_plugin($CFG->registerauth);
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');
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');
1074 if (! validate_email($data['email'])) {
1075 $errors['email'] = get_string('invalidemail');
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)";
1089 $params = array(
1090 'email1' => $data['email'],
1091 'email2' => $data['email'],
1092 'mnethostid' => $CFG->mnet_localhost_id,
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);
1102 if (empty($data['email2'])) {
1103 $errors['email2'] = get_string('missingemail');
1105 } else if (core_text::strtolower($data['email2']) != core_text::strtolower($data['email'])) {
1106 $errors['email2'] = get_string('invalidemail');
1108 if (!isset($errors['email'])) {
1109 if ($err = email_is_not_allowed($data['email'])) {
1110 $errors['email'] = $err;
1114 // Construct fake user object to check password policy against required information.
1115 $tempuser = new stdClass();
1116 $tempuser->id = 1;
1117 $tempuser->username = $data['username'];
1118 $tempuser->firstname = $data['firstname'];
1119 $tempuser->lastname = $data['lastname'];
1120 $tempuser->email = $data['email'];
1122 $errmsg = '';
1123 if (!check_password_policy($data['password'], $errmsg, $tempuser)) {
1124 $errors['password'] = $errmsg;
1127 // Validate customisable profile fields. (profile_validation expects an object as the parameter with userid set).
1128 $dataobject = (object)$data;
1129 $dataobject->id = 0;
1130 $errors += profile_validation($dataobject, $files);
1132 return $errors;
1136 * Add the missing fields to a user that is going to be created
1138 * @param stdClass $user the new user object
1139 * @return stdClass the user filled
1140 * @since Moodle 3.2
1142 function signup_setup_new_user($user) {
1143 global $CFG;
1145 $user->confirmed = 0;
1146 $user->lang = current_language();
1147 $user->firstaccess = 0;
1148 $user->timecreated = time();
1149 $user->mnethostid = $CFG->mnet_localhost_id;
1150 $user->secret = random_string(15);
1151 $user->auth = $CFG->registerauth;
1152 // Initialize alternate name fields to empty strings.
1153 $namefields = array_diff(\core_user\fields::get_name_fields(), useredit_get_required_name_fields());
1154 foreach ($namefields as $namefield) {
1155 $user->$namefield = '';
1157 return $user;
1161 * Check if user confirmation is enabled on this site and return the auth plugin handling registration if enabled.
1163 * @return stdClass the current auth plugin handling user registration or false if registration not enabled
1164 * @since Moodle 3.2
1166 function signup_get_user_confirmation_authplugin() {
1167 global $CFG;
1169 if (empty($CFG->registerauth)) {
1170 return false;
1172 $authplugin = get_auth_plugin($CFG->registerauth);
1174 if (!$authplugin->can_confirm()) {
1175 return false;
1177 return $authplugin;
1181 * Check if sign-up is enabled in the site. If is enabled, the function will return the authplugin instance.
1183 * @return mixed false if sign-up is not enabled, the authplugin instance otherwise.
1184 * @since Moodle 3.2
1186 function signup_is_enabled() {
1187 global $CFG;
1189 if (!empty($CFG->registerauth)) {
1190 $authplugin = get_auth_plugin($CFG->registerauth);
1191 if ($authplugin->can_signup()) {
1192 return $authplugin;
1195 return false;
1199 * Helper function used to print locking for auth plugins on admin pages.
1200 * @param admin_settingpage $settings Moodle admin settings instance
1201 * @param string $auth authentication plugin shortname
1202 * @param array $userfields user profile fields
1203 * @param string $helptext help text to be displayed at top of form
1204 * @param boolean $mapremotefields Map fields or lock only.
1205 * @param boolean $updateremotefields Allow remote updates
1206 * @param array $customfields list of custom profile fields
1207 * @since Moodle 3.3
1209 function display_auth_lock_options($settings, $auth, $userfields, $helptext, $mapremotefields, $updateremotefields, $customfields = array()) {
1210 global $CFG;
1211 require_once($CFG->dirroot . '/user/profile/lib.php');
1213 // Introductory explanation and help text.
1214 if ($mapremotefields) {
1215 $settings->add(new admin_setting_heading($auth.'/data_mapping', new lang_string('auth_data_mapping', 'auth'), $helptext));
1216 } else {
1217 $settings->add(new admin_setting_heading($auth.'/auth_fieldlocks', new lang_string('auth_fieldlocks', 'auth'), $helptext));
1220 // Generate the list of options.
1221 $lockoptions = array ('unlocked' => get_string('unlocked', 'auth'),
1222 'unlockedifempty' => get_string('unlockedifempty', 'auth'),
1223 'locked' => get_string('locked', 'auth'));
1224 $updatelocaloptions = array('oncreate' => get_string('update_oncreate', 'auth'),
1225 'onlogin' => get_string('update_onlogin', 'auth'));
1226 $updateextoptions = array('0' => get_string('update_never', 'auth'),
1227 '1' => get_string('update_onupdate', 'auth'));
1229 // Generate the list of profile fields to allow updates / lock.
1230 if (!empty($customfields)) {
1231 $userfields = array_merge($userfields, $customfields);
1232 $allcustomfields = profile_get_custom_fields();
1233 $customfieldname = array_combine(array_column($allcustomfields, 'shortname'), $allcustomfields);
1236 foreach ($userfields as $field) {
1237 // Define the fieldname we display to the user.
1238 // this includes special handling for some profile fields.
1239 $fieldname = $field;
1240 $fieldnametoolong = false;
1241 if ($fieldname === 'lang') {
1242 $fieldname = get_string('language');
1243 } else if (!empty($customfields) && in_array($field, $customfields)) {
1244 // If custom field then pick name from database.
1245 $fieldshortname = str_replace('profile_field_', '', $fieldname);
1246 $fieldname = $customfieldname[$fieldshortname]->name;
1247 if (core_text::strlen($fieldshortname) > 67) {
1248 // If custom profile field name is longer than 67 characters we will not be able to store the setting
1249 // such as 'field_updateremote_profile_field_NOTSOSHORTSHORTNAME' in the database because the character
1250 // limit for the setting name is 100.
1251 $fieldnametoolong = true;
1253 } else {
1254 $fieldname = get_string($fieldname);
1257 // Generate the list of fields / mappings.
1258 if ($fieldnametoolong) {
1259 // Display a message that the field can not be mapped because it's too long.
1260 $url = new moodle_url('/user/profile/index.php');
1261 $a = (object)['fieldname' => s($fieldname), 'shortname' => s($field), 'charlimit' => 67, 'link' => $url->out()];
1262 $settings->add(new admin_setting_heading($auth.'/field_not_mapped_'.sha1($field), '',
1263 get_string('cannotmapfield', 'auth', $a)));
1264 } else if ($mapremotefields) {
1265 // We are mapping to a remote field here.
1266 // Mapping.
1267 $settings->add(new admin_setting_configtext("auth_{$auth}/field_map_{$field}",
1268 get_string('auth_fieldmapping', 'auth', $fieldname), '', '', PARAM_RAW, 30));
1270 // Update local.
1271 $settings->add(new admin_setting_configselect("auth_{$auth}/field_updatelocal_{$field}",
1272 get_string('auth_updatelocalfield', 'auth', $fieldname), '', 'oncreate', $updatelocaloptions));
1274 // Update remote.
1275 if ($updateremotefields) {
1276 $settings->add(new admin_setting_configselect("auth_{$auth}/field_updateremote_{$field}",
1277 get_string('auth_updateremotefield', 'auth', $fieldname), '', 0, $updateextoptions));
1280 // Lock fields.
1281 $settings->add(new admin_setting_configselect("auth_{$auth}/field_lock_{$field}",
1282 get_string('auth_fieldlockfield', 'auth', $fieldname), '', 'unlocked', $lockoptions));
1284 } else {
1285 // Lock fields Only.
1286 $settings->add(new admin_setting_configselect("auth_{$auth}/field_lock_{$field}",
1287 get_string('auth_fieldlockfield', 'auth', $fieldname), '', 'unlocked', $lockoptions));