3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
19 * Multiple plugin authentication Support library
21 * 2006-08-28 File created, AUTH return values defined.
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();
32 * Returned when the login was successful.
37 * Returned when the login was unsuccessful.
39 define('AUTH_FAIL', 1);
42 * Returned when the login was denied (a reason for AUTH_FAIL).
44 define('AUTH_DENIED', 2);
47 * Returned when some error occurred (a reason for AUTH_FAIL).
49 define('AUTH_ERROR', 4);
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);
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);
83 * Abstract authentication plugin.
85 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
88 class auth_plugin_base
{
91 * The configuration details for the plugin.
97 * Authentication plugin type - the same as db field.
102 * The fields we can lock and update from/to external authentication backends
105 var $userfields = \core_user
::AUTHSYNCFIELDS
;
108 * Moodle custom fields to sync with.
111 var $customfields = null;
114 * The tag we want to prepend to any error log messages.
118 protected $errorlogtag = '';
121 * This is the primary method that is used by the authenticate_user_login()
122 * function in moodlelib.php.
124 * This method should return a boolean indicating
125 * whether or not the username and password authenticate successfully.
127 * Returns true if the username and password work and false if they are
128 * wrong or don't exist.
130 * @param string $username The username (with system magic quotes)
131 * @param string $password The password (with system magic quotes)
133 * @return bool Authentication success or failure.
135 function user_login($username, $password) {
136 print_error('mustbeoveride', 'debug', '', 'user_login()' );
140 * Returns true if this authentication plugin can change the users'
145 function can_change_password() {
151 * Returns the URL for changing the users' passwords, or empty if the default
154 * This method is used if can_change_password() returns true.
155 * This method is called only when user is logged in, it may use global $USER.
156 * If you are using a plugin config variable in this method, please make sure it is set before using it,
157 * as this method can be called even if the plugin is disabled, in which case the config values won't be set.
159 * @return moodle_url url of the profile page or null if standard used
161 function change_password_url() {
167 * Returns true if this authentication plugin can edit the users'
172 function can_edit_profile() {
178 * Returns the URL for editing the users' profile, or empty if the default
181 * This method is used if can_edit_profile() returns true.
182 * This method is called only when user is logged in, it may use global $USER.
184 * @return moodle_url url of the profile page or null if standard used
186 function edit_profile_url() {
192 * Returns true if this authentication plugin is "internal".
194 * Internal plugins use password hashes from Moodle user table for authentication.
198 function is_internal() {
204 * Returns false if this plugin is enabled but not configured.
208 public function is_configured() {
213 * Indicates if password hashes should be stored in local moodle database.
214 * @return bool true means md5 password hash stored in user table, false means flag 'not_cached' stored there instead
216 function prevent_local_passwords() {
217 return !$this->is_internal();
221 * Indicates if moodle should automatically update internal user
222 * records with data from external sources using the information
223 * from get_userinfo() method.
225 * @return bool true means automatically copy data from ext to user table
227 function is_synchronised_with_external() {
228 return !$this->is_internal();
232 * Updates the user's password.
234 * In previous versions of Moodle, the function
235 * auth_user_update_password accepted a username as the first parameter. The
236 * revised function expects a user object.
238 * @param object $user User table object
239 * @param string $newpassword Plaintext password
241 * @return bool True on success
243 function user_update_password($user, $newpassword) {
249 * Called when the user record is updated.
250 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
251 * compares information saved modified information to external db.
253 * @param mixed $olduser Userobject before modifications (without system magic quotes)
254 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
255 * @return boolean true if updated or update ignored; false if error
258 function user_update($olduser, $newuser) {
264 * User delete requested - internal user record is mared as deleted already, username not present anymore.
266 * Do any action in external database.
268 * @param object $user Userobject before delete (without system magic quotes)
271 function user_delete($olduser) {
277 * Returns true if plugin allows resetting of internal password.
281 function can_reset_password() {
287 * Returns true if plugin allows resetting of internal password.
291 function can_signup() {
297 * Sign up a new user ready for confirmation.
298 * Password is passed in plaintext.
300 * @param object $user new user object
301 * @param boolean $notify print notice with link and terminate
303 function user_signup($user, $notify=true) {
304 //override when can signup
305 print_error('mustbeoveride', 'debug', '', 'user_signup()' );
309 * Return a form to capture user details for account creation.
310 * This is used in /login/signup.php.
311 * @return moodle_form A form which edits a record from the user table.
313 function signup_form() {
316 require_once($CFG->dirroot
.'/login/signup_form.php');
317 return new login_signup_form(null, null, 'post', '', array('autocomplete'=>'on'));
321 * Returns true if plugin allows confirming of new users.
325 function can_confirm() {
331 * Confirm the new user as registered.
333 * @param string $username
334 * @param string $confirmsecret
336 function user_confirm($username, $confirmsecret) {
337 //override when can confirm
338 print_error('mustbeoveride', 'debug', '', 'user_confirm()' );
342 * Checks if user exists in external db
344 * @param string $username (with system magic quotes)
347 function user_exists($username) {
353 * return number of days to user password expires
355 * If userpassword does not expire it should return 0. If password is already expired
356 * it should return negative value.
358 * @param mixed $username username (with system magic quotes)
361 function password_expire($username) {
365 * Sync roles for this user - usually creator
367 * @param $user object user object (without system magic quotes)
369 function sync_roles($user) {
374 * Read user information from external database and returns it as array().
375 * Function should return all information available. If you are saving
376 * this information to moodle user-table you should honour synchronisation flags
378 * @param string $username username
380 * @return mixed array with no magic quotes or false on error
382 function get_userinfo($username) {
388 * Prints a form for configuring this authentication plugin.
390 * This function is called from admin/auth.php, and outputs a full page with
391 * a form for configuring this plugin.
393 * @param object $config
395 * @param array $user_fields
396 * @deprecated since Moodle 3.3
398 function config_form($config, $err, $user_fields) {
399 debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
404 * A chance to validate form data, and last chance to
405 * do stuff before it is inserted in config_plugin
406 * @param object object with submitted configuration settings (without system magic quotes)
407 * @param array $err array of error messages
408 * @deprecated since Moodle 3.3
410 function validate_form($form, &$err) {
411 debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
416 * Processes and stores configuration data for this authentication plugin.
418 * @param object object with submitted configuration settings (without system magic quotes)
419 * @deprecated since Moodle 3.3
421 function process_config($config) {
422 debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
428 * Hook for overriding behaviour of login page.
429 * This method is called from login/index.php page for all enabled auth plugins.
434 function loginpage_hook() {
435 global $frm; // can be used to override submitted login form
436 global $user; // can be used to replace authenticate_user_login()
442 * Hook for overriding behaviour before going to the login page.
444 * This method is called from require_login from potentially any page for
445 * all enabled auth plugins and gives each plugin a chance to redirect
446 * directly to an external login page, or to instantly login a user where
449 * If an auth plugin implements this hook, it must not rely on ONLY this
450 * hook in order to work, as there are many ways a user can browse directly
451 * to the standard login page. As a general rule in this case you should
452 * also implement the loginpage_hook as well.
455 function pre_loginpage_hook() {
456 // override if needed, eg by redirecting to an external login page
457 // or logging in a user:
458 // complete_user_login($user);
462 * Pre user_login hook.
463 * This method is called from authenticate_user_login() right after the user
464 * object is generated. This gives the auth plugins an option to make adjustments
465 * before the verification process starts.
467 * @param object $user user object, later used for $USER
469 public function pre_user_login_hook(&$user) {
470 // Override if needed.
474 * Post authentication hook.
475 * This method is called from authenticate_user_login() for all enabled auth plugins.
477 * @param object $user user object, later used for $USER
478 * @param string $username (with system magic quotes)
479 * @param string $password plain text password (with system magic quotes)
481 function user_authenticated_hook(&$user, $username, $password) {
487 * This method is called from require_logout() for all enabled auth plugins,
491 function prelogout_hook() {
492 global $USER; // use $USER->auth to find the plugin used for login
498 * Hook for overriding behaviour of logout page.
499 * This method is called from login/logout.php page for all enabled auth plugins.
504 function logoutpage_hook() {
505 global $USER; // use $USER->auth to find the plugin used for login
506 global $redirect; // can be used to override redirect after logout
512 * Hook called before timing out of database session.
513 * This is useful for SSO and MNET.
515 * @param object $user
516 * @param string $sid session id
517 * @param int $timecreated start of session
518 * @param int $timemodified user last seen
519 * @return bool true means do not timeout session yet
521 function ignore_timeout_hook($user, $sid, $timecreated, $timemodified) {
526 * Return the properly translated human-friendly title of this auth plugin
528 * @todo Document this function
530 function get_title() {
531 return get_string('pluginname', "auth_{$this->authtype}");
535 * Get the auth description (from core or own auth lang files)
537 * @return string The description
539 function get_description() {
540 $authdescription = get_string("auth_{$this->authtype}description", "auth_{$this->authtype}");
541 return $authdescription;
545 * Returns whether or not the captcha element is enabled.
547 * @abstract Implement in child classes
550 function is_captcha_enabled() {
555 * Returns whether or not this authentication plugin can be manually set
556 * for users, for example, when bulk uploading users.
558 * This should be overriden by authentication plugins where setting the
559 * authentication method manually is allowed.
564 function can_be_manually_set() {
565 // Override if needed.
570 * Returns a list of potential IdPs that this authentication plugin supports.
572 * This is used to provide links on the login page and the login block.
574 * The parameter $wantsurl is typically used by the plugin to implement a
575 * return-url feature.
577 * The returned value is expected to be a list of associative arrays with
580 * - url => (moodle_url|string) URL of the page to send the user to for authentication
581 * - name => (string) Human readable name of the IdP
582 * - iconurl => (moodle_url|string) URL of the icon representing the IdP (since Moodle 3.3)
584 * For legacy reasons, pre-3.3 plugins can provide the icon via the key:
586 * - icon => (pix_icon) Icon representing the IdP
588 * @param string $wantsurl The relative url fragment the user wants to get to.
589 * @return array List of associative arrays with keys url, name, iconurl|icon
591 function loginpage_idp_list($wantsurl) {
596 * Return custom user profile fields.
598 * @return array list of custom fields.
600 public function get_custom_user_profile_fields() {
602 require_once($CFG->dirroot
. '/user/profile/lib.php');
604 // If already retrieved then return.
605 if (!is_null($this->customfields
)) {
606 return $this->customfields
;
609 $this->customfields
= array();
610 if ($proffields = profile_get_custom_fields()) {
611 foreach ($proffields as $proffield) {
612 $this->customfields
[] = 'profile_field_'.$proffield->shortname
;
617 return $this->customfields
;
623 * This method is used after moodle logout by auth classes to execute server logout.
625 * @param stdClass $user clone of USER object before the user session was terminated
627 public function postlogout_hook($user) {
631 * Update a local user record from an external source.
632 * This is a lighter version of the one in moodlelib -- won't do
633 * expensive ops such as enrolment.
635 * @param string $username username
636 * @param array $updatekeys fields to update, false updates all fields.
637 * @param bool $triggerevent set false if user_updated event should not be triggered.
638 * This will not affect user_password_updated event triggering.
639 * @param bool $suspenduser Should the user be suspended?
640 * @return stdClass|bool updated user record or false if there is no new info to update.
642 protected function update_user_record($username, $updatekeys = false, $triggerevent = false, $suspenduser = false) {
645 require_once($CFG->dirroot
.'/user/profile/lib.php');
647 // Just in case check text case.
648 $username = trim(core_text
::strtolower($username));
650 // Get the current user record.
651 $user = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
));
652 if (empty($user)) { // Trouble.
653 error_log($this->errorlogtag
. get_string('auth_usernotexist', 'auth', $username));
654 print_error('auth_usernotexist', 'auth', '', $username);
658 // Protect the userid from being overwritten.
661 $needsupdate = false;
663 if ($newinfo = $this->get_userinfo($username)) {
664 $newinfo = truncate_userinfo($newinfo);
666 if (empty($updatekeys)) { // All keys? this does not support removing values.
667 $updatekeys = array_keys($newinfo);
670 if (!empty($updatekeys)) {
671 $newuser = new stdClass();
672 $newuser->id
= $userid;
673 // The cast to int is a workaround for MDL-53959.
674 $newuser->suspended
= (int) $suspenduser;
675 // Load all custom fields.
676 $profilefields = (array) profile_user_record($user->id
, false);
677 $newprofilefields = [];
679 foreach ($updatekeys as $key) {
680 if (isset($newinfo[$key])) {
681 $value = $newinfo[$key];
686 if (!empty($this->config
->{'field_updatelocal_' . $key})) {
687 if (preg_match('/^profile_field_(.*)$/', $key, $match)) {
690 $currentvalue = isset($profilefields[$field]) ?
$profilefields[$field] : null;
691 $newprofilefields[$field] = $value;
694 $currentvalue = isset($user->$key) ?
$user->$key : null;
695 $newuser->$key = $value;
698 // Only update if it's changed.
699 if ($currentvalue !== $value) {
707 user_update_user($newuser, false, $triggerevent);
708 profile_save_custom_fields($newuser->id
, $newprofilefields);
709 return $DB->get_record('user', array('id' => $userid, 'deleted' => 0));
717 * Return the list of enabled identity providers.
719 * Each identity provider data contains the keys url, name and iconurl (or
720 * icon). See the documentation of {@link auth_plugin_base::loginpage_idp_list()}
721 * for detailed description of the returned structure.
723 * @param array $authsequence site's auth sequence (list of auth plugins ordered)
724 * @return array List of arrays describing the identity providers
726 public static function get_identity_providers($authsequence) {
729 $identityproviders = [];
730 foreach ($authsequence as $authname) {
731 $authplugin = get_auth_plugin($authname);
732 $wantsurl = (isset($SESSION->wantsurl
)) ?
$SESSION->wantsurl
: '';
733 $identityproviders = array_merge($identityproviders, $authplugin->loginpage_idp_list($wantsurl));
735 return $identityproviders;
739 * Prepare a list of identity providers for output.
741 * @param array $identityproviders as returned by {@link self::get_identity_providers()}
742 * @param renderer_base $output
743 * @return array the identity providers ready for output
745 public static function prepare_identity_providers_for_output($identityproviders, renderer_base
$output) {
747 foreach ($identityproviders as $idp) {
748 if (!empty($idp['icon'])) {
749 // Pre-3.3 auth plugins provide icon as a pix_icon instance. New auth plugins (since 3.3) provide iconurl.
750 $idp['iconurl'] = $output->image_url($idp['icon']->pix
, $idp['icon']->component
);
752 if ($idp['iconurl'] instanceof moodle_url
) {
753 $idp['iconurl'] = $idp['iconurl']->out(false);
756 if ($idp['url'] instanceof moodle_url
) {
757 $idp['url'] = $idp['url']->out(false);
765 * Returns information on how the specified user can change their password.
767 * @param stdClass $user A user object
768 * @return string[] An array of strings with keys subject and message
770 public function get_password_change_info(stdClass
$user) : array {
775 $systemcontext = context_system
::instance();
777 $data = new stdClass();
778 $data->firstname
= $user->firstname
;
779 $data->lastname
= $user->lastname
;
780 $data->username
= $user->username
;
781 $data->sitename
= format_string($site->fullname
);
782 $data->admin
= generate_email_signoff();
784 // This is a workaround as change_password_url() is designed to allow
785 // use of the $USER global. See MDL-66984.
788 if ($this->can_change_password() and $this->change_password_url()) {
789 // We have some external url for password changing.
790 $data->link
= $this->change_password_url()->out();
792 // No way to change password, sorry.
797 if (!empty($data->link
) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id
)) {
798 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
799 $message = get_string('emailpasswordchangeinfo', '', $data);
801 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
802 $message = get_string('emailpasswordchangeinfofail', '', $data);
806 'subject' => $subject,
807 'message' => $message
813 * Verify if user is locked out.
815 * @param stdClass $user
816 * @return bool true if user locked out
818 function login_is_lockedout($user) {
821 if ($user->mnethostid
!= $CFG->mnet_localhost_id
) {
824 if (isguestuser($user)) {
828 if (empty($CFG->lockoutthreshold
)) {
829 // Lockout not enabled.
833 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
834 // This preference may be used for accounts that must not be locked out.
838 $locked = get_user_preferences('login_lockout', 0, $user);
843 if (empty($CFG->lockoutduration
)) {
844 // Locked out forever.
848 if (time() - $locked < $CFG->lockoutduration
) {
852 login_unlock_account($user);
858 * To be called after valid user login.
859 * @param stdClass $user
861 function login_attempt_valid($user) {
864 // Note: user_loggedin event is triggered in complete_user_login().
866 if ($user->mnethostid
!= $CFG->mnet_localhost_id
) {
869 if (isguestuser($user)) {
873 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
874 login_unlock_account($user);
878 * To be called after failed user login.
879 * @param stdClass $user
881 function login_attempt_failed($user) {
884 if ($user->mnethostid
!= $CFG->mnet_localhost_id
) {
887 if (isguestuser($user)) {
891 $count = get_user_preferences('login_failed_count', 0, $user);
892 $last = get_user_preferences('login_failed_last', 0, $user);
893 $sincescuccess = get_user_preferences('login_failed_count_since_success', $count, $user);
894 $sincescuccess = $sincescuccess +
1;
895 set_user_preference('login_failed_count_since_success', $sincescuccess, $user);
897 if (empty($CFG->lockoutthreshold
)) {
898 // No threshold means no lockout.
899 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
900 login_unlock_account($user);
904 if (!empty($CFG->lockoutwindow
) and time() - $last > $CFG->lockoutwindow
) {
910 set_user_preference('login_failed_count', $count, $user);
911 set_user_preference('login_failed_last', time(), $user);
913 if ($count >= $CFG->lockoutthreshold
) {
914 login_lock_account($user);
919 * Lockout user and send notification email.
921 * @param stdClass $user
923 function login_lock_account($user) {
926 if ($user->mnethostid
!= $CFG->mnet_localhost_id
) {
929 if (isguestuser($user)) {
933 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
934 // This user can not be locked out.
938 $alreadylockedout = get_user_preferences('login_lockout', 0, $user);
940 set_user_preference('login_lockout', time(), $user);
942 if ($alreadylockedout == 0) {
943 $secret = random_string(15);
944 set_user_preference('login_lockout_secret', $secret, $user);
946 $oldforcelang = force_current_language($user->lang
);
949 $supportuser = core_user
::get_support_user();
951 $data = new stdClass();
952 $data->firstname
= $user->firstname
;
953 $data->lastname
= $user->lastname
;
954 $data->username
= $user->username
;
955 $data->sitename
= format_string($site->fullname
);
956 $data->link
= $CFG->wwwroot
.'/login/unlock_account.php?u='.$user->id
.'&s='.$secret;
957 $data->admin
= generate_email_signoff();
959 $message = get_string('lockoutemailbody', 'admin', $data);
960 $subject = get_string('lockoutemailsubject', 'admin', format_string($site->fullname
));
963 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
964 email_to_user($user, $supportuser, $subject, $message);
967 force_current_language($oldforcelang);
972 * Unlock user account and reset timers.
974 * @param stdClass $user
976 function login_unlock_account($user) {
977 unset_user_preference('login_lockout', $user);
978 unset_user_preference('login_failed_count', $user);
979 unset_user_preference('login_failed_last', $user);
981 // Note: do not clear the lockout secret because user might click on the link repeatedly.
985 * Returns whether or not the captcha element is enabled, and the admin settings fulfil its requirements.
988 function signup_captcha_enabled() {
990 $authplugin = get_auth_plugin($CFG->registerauth
);
991 return !empty($CFG->recaptchapublickey
) && !empty($CFG->recaptchaprivatekey
) && $authplugin->is_captcha_enabled();
995 * Validates the standard sign-up data (except recaptcha that is validated by the form element).
997 * @param array $data the sign-up data
998 * @param array $files files among the data
999 * @return array list of errors, being the key the data element name and the value the error itself
1002 function signup_validate_data($data, $files) {
1006 $authplugin = get_auth_plugin($CFG->registerauth
);
1008 if ($DB->record_exists('user', array('username' => $data['username'], 'mnethostid' => $CFG->mnet_localhost_id
))) {
1009 $errors['username'] = get_string('usernameexists');
1011 // Check allowed characters.
1012 if ($data['username'] !== core_text
::strtolower($data['username'])) {
1013 $errors['username'] = get_string('usernamelowercase');
1015 if ($data['username'] !== core_user
::clean_field($data['username'], 'username')) {
1016 $errors['username'] = get_string('invalidusername');
1022 // Check if user exists in external db.
1023 // TODO: maybe we should check all enabled plugins instead.
1024 if ($authplugin->user_exists($data['username'])) {
1025 $errors['username'] = get_string('usernameexists');
1028 if (! validate_email($data['email'])) {
1029 $errors['email'] = get_string('invalidemail');
1031 } else if (empty($CFG->allowaccountssameemail
)) {
1032 // Emails in Moodle as case-insensitive and accents-sensitive. Such a combination can lead to very slow queries
1033 // on some DBs such as MySQL. So we first get the list of candidate users in a subselect via more effective
1034 // accent-insensitive query that can make use of the index and only then we search within that limited subset.
1037 WHERE " . $DB->sql_equal('email', ':email1', false, true) . "
1038 AND id IN (SELECT id
1040 WHERE " . $DB->sql_equal('email', ':email2', false, false) . "
1041 AND mnethostid = :mnethostid)";
1044 'email1' => $data['email'],
1045 'email2' => $data['email'],
1046 'mnethostid' => $CFG->mnet_localhost_id
,
1049 // If there are other user(s) that already have the same email, show an error.
1050 if ($DB->record_exists_sql($sql, $params)) {
1051 $forgotpasswordurl = new moodle_url('/login/forgot_password.php');
1052 $forgotpasswordlink = html_writer
::link($forgotpasswordurl, get_string('emailexistshintlink'));
1053 $errors['email'] = get_string('emailexists') . ' ' . get_string('emailexistssignuphint', 'moodle', $forgotpasswordlink);
1056 if (empty($data['email2'])) {
1057 $errors['email2'] = get_string('missingemail');
1059 } else if (core_text
::strtolower($data['email2']) != core_text
::strtolower($data['email'])) {
1060 $errors['email2'] = get_string('invalidemail');
1062 if (!isset($errors['email'])) {
1063 if ($err = email_is_not_allowed($data['email'])) {
1064 $errors['email'] = $err;
1068 // Construct fake user object to check password policy against required information.
1069 $tempuser = new stdClass();
1071 $tempuser->username
= $data['username'];
1072 $tempuser->firstname
= $data['firstname'];
1073 $tempuser->lastname
= $data['lastname'];
1074 $tempuser->email
= $data['email'];
1077 if (!check_password_policy($data['password'], $errmsg, $tempuser)) {
1078 $errors['password'] = $errmsg;
1081 // Validate customisable profile fields. (profile_validation expects an object as the parameter with userid set).
1082 $dataobject = (object)$data;
1083 $dataobject->id
= 0;
1084 $errors +
= profile_validation($dataobject, $files);
1090 * Add the missing fields to a user that is going to be created
1092 * @param stdClass $user the new user object
1093 * @return stdClass the user filled
1096 function signup_setup_new_user($user) {
1099 $user->confirmed
= 0;
1100 $user->lang
= current_language();
1101 $user->firstaccess
= 0;
1102 $user->timecreated
= time();
1103 $user->mnethostid
= $CFG->mnet_localhost_id
;
1104 $user->secret
= random_string(15);
1105 $user->auth
= $CFG->registerauth
;
1106 // Initialize alternate name fields to empty strings.
1107 $namefields = array_diff(\core_user\fields
::get_name_fields(), useredit_get_required_name_fields());
1108 foreach ($namefields as $namefield) {
1109 $user->$namefield = '';
1115 * Check if user confirmation is enabled on this site and return the auth plugin handling registration if enabled.
1117 * @return stdClass the current auth plugin handling user registration or false if registration not enabled
1120 function signup_get_user_confirmation_authplugin() {
1123 if (empty($CFG->registerauth
)) {
1126 $authplugin = get_auth_plugin($CFG->registerauth
);
1128 if (!$authplugin->can_confirm()) {
1135 * Check if sign-up is enabled in the site. If is enabled, the function will return the authplugin instance.
1137 * @return mixed false if sign-up is not enabled, the authplugin instance otherwise.
1140 function signup_is_enabled() {
1143 if (!empty($CFG->registerauth
)) {
1144 $authplugin = get_auth_plugin($CFG->registerauth
);
1145 if ($authplugin->can_signup()) {
1153 * Helper function used to print locking for auth plugins on admin pages.
1154 * @param stdclass $settings Moodle admin settings instance
1155 * @param string $auth authentication plugin shortname
1156 * @param array $userfields user profile fields
1157 * @param string $helptext help text to be displayed at top of form
1158 * @param boolean $mapremotefields Map fields or lock only.
1159 * @param boolean $updateremotefields Allow remote updates
1160 * @param array $customfields list of custom profile fields
1163 function display_auth_lock_options($settings, $auth, $userfields, $helptext, $mapremotefields, $updateremotefields, $customfields = array()) {
1165 require_once($CFG->dirroot
. '/user/profile/lib.php');
1167 // Introductory explanation and help text.
1168 if ($mapremotefields) {
1169 $settings->add(new admin_setting_heading($auth.'/data_mapping', new lang_string('auth_data_mapping', 'auth'), $helptext));
1171 $settings->add(new admin_setting_heading($auth.'/auth_fieldlocks', new lang_string('auth_fieldlocks', 'auth'), $helptext));
1174 // Generate the list of options.
1175 $lockoptions = array ('unlocked' => get_string('unlocked', 'auth'),
1176 'unlockedifempty' => get_string('unlockedifempty', 'auth'),
1177 'locked' => get_string('locked', 'auth'));
1178 $updatelocaloptions = array('oncreate' => get_string('update_oncreate', 'auth'),
1179 'onlogin' => get_string('update_onlogin', 'auth'));
1180 $updateextoptions = array('0' => get_string('update_never', 'auth'),
1181 '1' => get_string('update_onupdate', 'auth'));
1183 // Generate the list of profile fields to allow updates / lock.
1184 if (!empty($customfields)) {
1185 $userfields = array_merge($userfields, $customfields);
1186 $allcustomfields = profile_get_custom_fields();
1187 $customfieldname = array_combine(array_column($allcustomfields, 'shortname'), $allcustomfields);
1190 foreach ($userfields as $field) {
1191 // Define the fieldname we display to the user.
1192 // this includes special handling for some profile fields.
1193 $fieldname = $field;
1194 $fieldnametoolong = false;
1195 if ($fieldname === 'lang') {
1196 $fieldname = get_string('language');
1197 } else if (!empty($customfields) && in_array($field, $customfields)) {
1198 // If custom field then pick name from database.
1199 $fieldshortname = str_replace('profile_field_', '', $fieldname);
1200 $fieldname = $customfieldname[$fieldshortname]->name
;
1201 if (core_text
::strlen($fieldshortname) > 67) {
1202 // If custom profile field name is longer than 67 characters we will not be able to store the setting
1203 // such as 'field_updateremote_profile_field_NOTSOSHORTSHORTNAME' in the database because the character
1204 // limit for the setting name is 100.
1205 $fieldnametoolong = true;
1208 $fieldname = get_string($fieldname);
1211 // Generate the list of fields / mappings.
1212 if ($fieldnametoolong) {
1213 // Display a message that the field can not be mapped because it's too long.
1214 $url = new moodle_url('/user/profile/index.php');
1215 $a = (object)['fieldname' => s($fieldname), 'shortname' => s($field), 'charlimit' => 67, 'link' => $url->out()];
1216 $settings->add(new admin_setting_heading($auth.'/field_not_mapped_'.sha1($field), '',
1217 get_string('cannotmapfield', 'auth', $a)));
1218 } else if ($mapremotefields) {
1219 // We are mapping to a remote field here.
1221 $settings->add(new admin_setting_configtext("auth_{$auth}/field_map_{$field}",
1222 get_string('auth_fieldmapping', 'auth', $fieldname), '', '', PARAM_RAW
, 30));
1225 $settings->add(new admin_setting_configselect("auth_{$auth}/field_updatelocal_{$field}",
1226 get_string('auth_updatelocalfield', 'auth', $fieldname), '', 'oncreate', $updatelocaloptions));
1229 if ($updateremotefields) {
1230 $settings->add(new admin_setting_configselect("auth_{$auth}/field_updateremote_{$field}",
1231 get_string('auth_updateremotefield', 'auth', $fieldname), '', 0, $updateextoptions));
1235 $settings->add(new admin_setting_configselect("auth_{$auth}/field_lock_{$field}",
1236 get_string('auth_fieldlockfield', 'auth', $fieldname), '', 'unlocked', $lockoptions));
1239 // Lock fields Only.
1240 $settings->add(new admin_setting_configselect("auth_{$auth}/field_lock_{$field}",
1241 get_string('auth_fieldlockfield', 'auth', $fieldname), '', 'unlocked', $lockoptions));