Moodle release 3.4.1
[moodle.git] / lib / authlib.php
blobe1735fd7909bb1ee823b9580908fd6b86f7666b3
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 * This is the primary method that is used by the authenticate_user_login()
115 * function in moodlelib.php.
117 * This method should return a boolean indicating
118 * whether or not the username and password authenticate successfully.
120 * Returns true if the username and password work and false if they are
121 * wrong or don't exist.
123 * @param string $username The username (with system magic quotes)
124 * @param string $password The password (with system magic quotes)
126 * @return bool Authentication success or failure.
128 function user_login($username, $password) {
129 print_error('mustbeoveride', 'debug', '', 'user_login()' );
133 * Returns true if this authentication plugin can change the users'
134 * password.
136 * @return bool
138 function can_change_password() {
139 //override if needed
140 return false;
144 * Returns the URL for changing the users' passwords, or empty if the default
145 * URL can be used.
147 * This method is used if can_change_password() returns true.
148 * This method is called only when user is logged in, it may use global $USER.
149 * If you are using a plugin config variable in this method, please make sure it is set before using it,
150 * as this method can be called even if the plugin is disabled, in which case the config values won't be set.
152 * @return moodle_url url of the profile page or null if standard used
154 function change_password_url() {
155 //override if needed
156 return null;
160 * Returns true if this authentication plugin can edit the users'
161 * profile.
163 * @return bool
165 function can_edit_profile() {
166 //override if needed
167 return true;
171 * Returns the URL for editing the users' profile, or empty if the default
172 * URL can be used.
174 * This method is used if can_edit_profile() returns true.
175 * This method is called only when user is logged in, it may use global $USER.
177 * @return moodle_url url of the profile page or null if standard used
179 function edit_profile_url() {
180 //override if needed
181 return null;
185 * Returns true if this authentication plugin is "internal".
187 * Internal plugins use password hashes from Moodle user table for authentication.
189 * @return bool
191 function is_internal() {
192 //override if needed
193 return true;
197 * Returns false if this plugin is enabled but not configured.
199 * @return bool
201 public function is_configured() {
202 return false;
206 * Indicates if password hashes should be stored in local moodle database.
207 * @return bool true means md5 password hash stored in user table, false means flag 'not_cached' stored there instead
209 function prevent_local_passwords() {
210 return !$this->is_internal();
214 * Indicates if moodle should automatically update internal user
215 * records with data from external sources using the information
216 * from get_userinfo() method.
218 * @return bool true means automatically copy data from ext to user table
220 function is_synchronised_with_external() {
221 return !$this->is_internal();
225 * Updates the user's password.
227 * In previous versions of Moodle, the function
228 * auth_user_update_password accepted a username as the first parameter. The
229 * revised function expects a user object.
231 * @param object $user User table object
232 * @param string $newpassword Plaintext password
234 * @return bool True on success
236 function user_update_password($user, $newpassword) {
237 //override if needed
238 return true;
242 * Called when the user record is updated.
243 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
244 * compares information saved modified information to external db.
246 * @param mixed $olduser Userobject before modifications (without system magic quotes)
247 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
248 * @return boolean true if updated or update ignored; false if error
251 function user_update($olduser, $newuser) {
252 //override if needed
253 return true;
257 * User delete requested - internal user record is mared as deleted already, username not present anymore.
259 * Do any action in external database.
261 * @param object $user Userobject before delete (without system magic quotes)
262 * @return void
264 function user_delete($olduser) {
265 //override if needed
266 return;
270 * Returns true if plugin allows resetting of internal password.
272 * @return bool
274 function can_reset_password() {
275 //override if needed
276 return false;
280 * Returns true if plugin allows resetting of internal password.
282 * @return bool
284 function can_signup() {
285 //override if needed
286 return false;
290 * Sign up a new user ready for confirmation.
291 * Password is passed in plaintext.
293 * @param object $user new user object
294 * @param boolean $notify print notice with link and terminate
296 function user_signup($user, $notify=true) {
297 //override when can signup
298 print_error('mustbeoveride', 'debug', '', 'user_signup()' );
302 * Return a form to capture user details for account creation.
303 * This is used in /login/signup.php.
304 * @return moodle_form A form which edits a record from the user table.
306 function signup_form() {
307 global $CFG;
309 require_once($CFG->dirroot.'/login/signup_form.php');
310 return new login_signup_form(null, null, 'post', '', array('autocomplete'=>'on'));
314 * Returns true if plugin allows confirming of new users.
316 * @return bool
318 function can_confirm() {
319 //override if needed
320 return false;
324 * Confirm the new user as registered.
326 * @param string $username
327 * @param string $confirmsecret
329 function user_confirm($username, $confirmsecret) {
330 //override when can confirm
331 print_error('mustbeoveride', 'debug', '', 'user_confirm()' );
335 * Checks if user exists in external db
337 * @param string $username (with system magic quotes)
338 * @return bool
340 function user_exists($username) {
341 //override if needed
342 return false;
346 * return number of days to user password expires
348 * If userpassword does not expire it should return 0. If password is already expired
349 * it should return negative value.
351 * @param mixed $username username (with system magic quotes)
352 * @return integer
354 function password_expire($username) {
355 return 0;
358 * Sync roles for this user - usually creator
360 * @param $user object user object (without system magic quotes)
362 function sync_roles($user) {
363 //override if needed
367 * Read user information from external database and returns it as array().
368 * Function should return all information available. If you are saving
369 * this information to moodle user-table you should honour synchronisation flags
371 * @param string $username username
373 * @return mixed array with no magic quotes or false on error
375 function get_userinfo($username) {
376 //override if needed
377 return array();
381 * Prints a form for configuring this authentication plugin.
383 * This function is called from admin/auth.php, and outputs a full page with
384 * a form for configuring this plugin.
386 * @param object $config
387 * @param object $err
388 * @param array $user_fields
389 * @deprecated since Moodle 3.3
391 function config_form($config, $err, $user_fields) {
392 debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
393 //override if needed
397 * A chance to validate form data, and last chance to
398 * do stuff before it is inserted in config_plugin
399 * @param object object with submitted configuration settings (without system magic quotes)
400 * @param array $err array of error messages
401 * @deprecated since Moodle 3.3
403 function validate_form($form, &$err) {
404 debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
405 //override if needed
409 * Processes and stores configuration data for this authentication plugin.
411 * @param object object with submitted configuration settings (without system magic quotes)
412 * @deprecated since Moodle 3.3
414 function process_config($config) {
415 debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
416 //override if needed
417 return true;
421 * Hook for overriding behaviour of login page.
422 * This method is called from login/index.php page for all enabled auth plugins.
424 * @global object
425 * @global object
427 function loginpage_hook() {
428 global $frm; // can be used to override submitted login form
429 global $user; // can be used to replace authenticate_user_login()
431 //override if needed
435 * Hook for overriding behaviour before going to the login page.
437 * This method is called from require_login from potentially any page for
438 * all enabled auth plugins and gives each plugin a chance to redirect
439 * directly to an external login page, or to instantly login a user where
440 * possible.
442 * If an auth plugin implements this hook, it must not rely on ONLY this
443 * hook in order to work, as there are many ways a user can browse directly
444 * to the standard login page. As a general rule in this case you should
445 * also implement the loginpage_hook as well.
448 function pre_loginpage_hook() {
449 // override if needed, eg by redirecting to an external login page
450 // or logging in a user:
451 // complete_user_login($user);
455 * Pre user_login hook.
456 * This method is called from authenticate_user_login() right after the user
457 * object is generated. This gives the auth plugins an option to make adjustments
458 * before the verification process starts.
460 * @param object $user user object, later used for $USER
462 public function pre_user_login_hook(&$user) {
463 // Override if needed.
467 * Post authentication hook.
468 * This method is called from authenticate_user_login() for all enabled auth plugins.
470 * @param object $user user object, later used for $USER
471 * @param string $username (with system magic quotes)
472 * @param string $password plain text password (with system magic quotes)
474 function user_authenticated_hook(&$user, $username, $password) {
475 //override if needed
479 * Pre logout hook.
480 * This method is called from require_logout() for all enabled auth plugins,
482 * @global object
484 function prelogout_hook() {
485 global $USER; // use $USER->auth to find the plugin used for login
487 //override if needed
491 * Hook for overriding behaviour of logout page.
492 * This method is called from login/logout.php page for all enabled auth plugins.
494 * @global object
495 * @global string
497 function logoutpage_hook() {
498 global $USER; // use $USER->auth to find the plugin used for login
499 global $redirect; // can be used to override redirect after logout
501 //override if needed
505 * Hook called before timing out of database session.
506 * This is useful for SSO and MNET.
508 * @param object $user
509 * @param string $sid session id
510 * @param int $timecreated start of session
511 * @param int $timemodified user last seen
512 * @return bool true means do not timeout session yet
514 function ignore_timeout_hook($user, $sid, $timecreated, $timemodified) {
515 return false;
519 * Return the properly translated human-friendly title of this auth plugin
521 * @todo Document this function
523 function get_title() {
524 return get_string('pluginname', "auth_{$this->authtype}");
528 * Get the auth description (from core or own auth lang files)
530 * @return string The description
532 function get_description() {
533 $authdescription = get_string("auth_{$this->authtype}description", "auth_{$this->authtype}");
534 return $authdescription;
538 * Returns whether or not the captcha element is enabled.
540 * @abstract Implement in child classes
541 * @return bool
543 function is_captcha_enabled() {
544 return false;
548 * Returns whether or not this authentication plugin can be manually set
549 * for users, for example, when bulk uploading users.
551 * This should be overriden by authentication plugins where setting the
552 * authentication method manually is allowed.
554 * @return bool
555 * @since Moodle 2.6
557 function can_be_manually_set() {
558 // Override if needed.
559 return false;
563 * Returns a list of potential IdPs that this authentication plugin supports.
565 * This is used to provide links on the login page and the login block.
567 * The parameter $wantsurl is typically used by the plugin to implement a
568 * return-url feature.
570 * The returned value is expected to be a list of associative arrays with
571 * string keys:
573 * - url => (moodle_url|string) URL of the page to send the user to for authentication
574 * - name => (string) Human readable name of the IdP
575 * - iconurl => (moodle_url|string) URL of the icon representing the IdP (since Moodle 3.3)
577 * For legacy reasons, pre-3.3 plugins can provide the icon via the key:
579 * - icon => (pix_icon) Icon representing the IdP
581 * @param string $wantsurl The relative url fragment the user wants to get to.
582 * @return array List of associative arrays with keys url, name, iconurl|icon
584 function loginpage_idp_list($wantsurl) {
585 return array();
589 * Return custom user profile fields.
591 * @return array list of custom fields.
593 public function get_custom_user_profile_fields() {
594 global $DB;
595 // If already retrieved then return.
596 if (!is_null($this->customfields)) {
597 return $this->customfields;
600 $this->customfields = array();
601 if ($proffields = $DB->get_records('user_info_field')) {
602 foreach ($proffields as $proffield) {
603 $this->customfields[] = 'profile_field_'.$proffield->shortname;
606 unset($proffields);
608 return $this->customfields;
612 * Post logout hook.
614 * This method is used after moodle logout by auth classes to execute server logout.
616 * @param stdClass $user clone of USER object before the user session was terminated
618 public function postlogout_hook($user) {
622 * Return the list of enabled identity providers.
624 * Each identity provider data contains the keys url, name and iconurl (or
625 * icon). See the documentation of {@link auth_plugin_base::loginpage_idp_list()}
626 * for detailed description of the returned structure.
628 * @param array $authsequence site's auth sequence (list of auth plugins ordered)
629 * @return array List of arrays describing the identity providers
631 public static function get_identity_providers($authsequence) {
632 global $SESSION;
634 $identityproviders = [];
635 foreach ($authsequence as $authname) {
636 $authplugin = get_auth_plugin($authname);
637 $wantsurl = (isset($SESSION->wantsurl)) ? $SESSION->wantsurl : '';
638 $identityproviders = array_merge($identityproviders, $authplugin->loginpage_idp_list($wantsurl));
640 return $identityproviders;
644 * Prepare a list of identity providers for output.
646 * @param array $identityproviders as returned by {@link self::get_identity_providers()}
647 * @param renderer_base $output
648 * @return array the identity providers ready for output
650 public static function prepare_identity_providers_for_output($identityproviders, renderer_base $output) {
651 $data = [];
652 foreach ($identityproviders as $idp) {
653 if (!empty($idp['icon'])) {
654 // Pre-3.3 auth plugins provide icon as a pix_icon instance. New auth plugins (since 3.3) provide iconurl.
655 $idp['iconurl'] = $output->image_url($idp['icon']->pix, $idp['icon']->component);
657 if ($idp['iconurl'] instanceof moodle_url) {
658 $idp['iconurl'] = $idp['iconurl']->out(false);
660 unset($idp['icon']);
661 if ($idp['url'] instanceof moodle_url) {
662 $idp['url'] = $idp['url']->out(false);
664 $data[] = $idp;
666 return $data;
671 * Verify if user is locked out.
673 * @param stdClass $user
674 * @return bool true if user locked out
676 function login_is_lockedout($user) {
677 global $CFG;
679 if ($user->mnethostid != $CFG->mnet_localhost_id) {
680 return false;
682 if (isguestuser($user)) {
683 return false;
686 if (empty($CFG->lockoutthreshold)) {
687 // Lockout not enabled.
688 return false;
691 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
692 // This preference may be used for accounts that must not be locked out.
693 return false;
696 $locked = get_user_preferences('login_lockout', 0, $user);
697 if (!$locked) {
698 return false;
701 if (empty($CFG->lockoutduration)) {
702 // Locked out forever.
703 return true;
706 if (time() - $locked < $CFG->lockoutduration) {
707 return true;
710 login_unlock_account($user);
712 return false;
716 * To be called after valid user login.
717 * @param stdClass $user
719 function login_attempt_valid($user) {
720 global $CFG;
722 // Note: user_loggedin event is triggered in complete_user_login().
724 if ($user->mnethostid != $CFG->mnet_localhost_id) {
725 return;
727 if (isguestuser($user)) {
728 return;
731 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
732 login_unlock_account($user);
736 * To be called after failed user login.
737 * @param stdClass $user
739 function login_attempt_failed($user) {
740 global $CFG;
742 if ($user->mnethostid != $CFG->mnet_localhost_id) {
743 return;
745 if (isguestuser($user)) {
746 return;
749 $count = get_user_preferences('login_failed_count', 0, $user);
750 $last = get_user_preferences('login_failed_last', 0, $user);
751 $sincescuccess = get_user_preferences('login_failed_count_since_success', $count, $user);
752 $sincescuccess = $sincescuccess + 1;
753 set_user_preference('login_failed_count_since_success', $sincescuccess, $user);
755 if (empty($CFG->lockoutthreshold)) {
756 // No threshold means no lockout.
757 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
758 login_unlock_account($user);
759 return;
762 if (!empty($CFG->lockoutwindow) and time() - $last > $CFG->lockoutwindow) {
763 $count = 0;
766 $count = $count+1;
768 set_user_preference('login_failed_count', $count, $user);
769 set_user_preference('login_failed_last', time(), $user);
771 if ($count >= $CFG->lockoutthreshold) {
772 login_lock_account($user);
777 * Lockout user and send notification email.
779 * @param stdClass $user
781 function login_lock_account($user) {
782 global $CFG;
784 if ($user->mnethostid != $CFG->mnet_localhost_id) {
785 return;
787 if (isguestuser($user)) {
788 return;
791 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
792 // This user can not be locked out.
793 return;
796 $alreadylockedout = get_user_preferences('login_lockout', 0, $user);
798 set_user_preference('login_lockout', time(), $user);
800 if ($alreadylockedout == 0) {
801 $secret = random_string(15);
802 set_user_preference('login_lockout_secret', $secret, $user);
804 $oldforcelang = force_current_language($user->lang);
806 $site = get_site();
807 $supportuser = core_user::get_support_user();
809 $data = new stdClass();
810 $data->firstname = $user->firstname;
811 $data->lastname = $user->lastname;
812 $data->username = $user->username;
813 $data->sitename = format_string($site->fullname);
814 $data->link = $CFG->wwwroot.'/login/unlock_account.php?u='.$user->id.'&s='.$secret;
815 $data->admin = generate_email_signoff();
817 $message = get_string('lockoutemailbody', 'admin', $data);
818 $subject = get_string('lockoutemailsubject', 'admin', format_string($site->fullname));
820 if ($message) {
821 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
822 email_to_user($user, $supportuser, $subject, $message);
825 force_current_language($oldforcelang);
830 * Unlock user account and reset timers.
832 * @param stdClass $user
834 function login_unlock_account($user) {
835 unset_user_preference('login_lockout', $user);
836 unset_user_preference('login_failed_count', $user);
837 unset_user_preference('login_failed_last', $user);
839 // Note: do not clear the lockout secret because user might click on the link repeatedly.
843 * Returns whether or not the captcha element is enabled, and the admin settings fulfil its requirements.
844 * @return bool
846 function signup_captcha_enabled() {
847 global $CFG;
848 $authplugin = get_auth_plugin($CFG->registerauth);
849 return !empty($CFG->recaptchapublickey) && !empty($CFG->recaptchaprivatekey) && $authplugin->is_captcha_enabled();
853 * Validates the standard sign-up data (except recaptcha that is validated by the form element).
855 * @param array $data the sign-up data
856 * @param array $files files among the data
857 * @return array list of errors, being the key the data element name and the value the error itself
858 * @since Moodle 3.2
860 function signup_validate_data($data, $files) {
861 global $CFG, $DB;
863 $errors = array();
864 $authplugin = get_auth_plugin($CFG->registerauth);
866 if ($DB->record_exists('user', array('username' => $data['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
867 $errors['username'] = get_string('usernameexists');
868 } else {
869 // Check allowed characters.
870 if ($data['username'] !== core_text::strtolower($data['username'])) {
871 $errors['username'] = get_string('usernamelowercase');
872 } else {
873 if ($data['username'] !== core_user::clean_field($data['username'], 'username')) {
874 $errors['username'] = get_string('invalidusername');
880 // Check if user exists in external db.
881 // TODO: maybe we should check all enabled plugins instead.
882 if ($authplugin->user_exists($data['username'])) {
883 $errors['username'] = get_string('usernameexists');
886 if (! validate_email($data['email'])) {
887 $errors['email'] = get_string('invalidemail');
889 } else if ($DB->record_exists('user', array('email' => $data['email']))) {
890 $errors['email'] = get_string('emailexists') . ' ' .
891 get_string('emailexistssignuphint', 'moodle',
892 html_writer::link(new moodle_url('/login/forgot_password.php'), get_string('emailexistshintlink')));
894 if (empty($data['email2'])) {
895 $errors['email2'] = get_string('missingemail');
897 } else if ($data['email2'] != $data['email']) {
898 $errors['email2'] = get_string('invalidemail');
900 if (!isset($errors['email'])) {
901 if ($err = email_is_not_allowed($data['email'])) {
902 $errors['email'] = $err;
906 $errmsg = '';
907 if (!check_password_policy($data['password'], $errmsg)) {
908 $errors['password'] = $errmsg;
911 // Validate customisable profile fields. (profile_validation expects an object as the parameter with userid set).
912 $dataobject = (object)$data;
913 $dataobject->id = 0;
914 $errors += profile_validation($dataobject, $files);
916 return $errors;
920 * Add the missing fields to a user that is going to be created
922 * @param stdClass $user the new user object
923 * @return stdClass the user filled
924 * @since Moodle 3.2
926 function signup_setup_new_user($user) {
927 global $CFG;
929 $user->confirmed = 0;
930 $user->lang = current_language();
931 $user->firstaccess = 0;
932 $user->timecreated = time();
933 $user->mnethostid = $CFG->mnet_localhost_id;
934 $user->secret = random_string(15);
935 $user->auth = $CFG->registerauth;
936 // Initialize alternate name fields to empty strings.
937 $namefields = array_diff(get_all_user_name_fields(), useredit_get_required_name_fields());
938 foreach ($namefields as $namefield) {
939 $user->$namefield = '';
941 return $user;
945 * Check if user confirmation is enabled on this site and return the auth plugin handling registration if enabled.
947 * @return stdClass the current auth plugin handling user registration or false if registration not enabled
948 * @since Moodle 3.2
950 function signup_get_user_confirmation_authplugin() {
951 global $CFG;
953 if (empty($CFG->registerauth)) {
954 return false;
956 $authplugin = get_auth_plugin($CFG->registerauth);
958 if (!$authplugin->can_confirm()) {
959 return false;
961 return $authplugin;
965 * Check if sign-up is enabled in the site. If is enabled, the function will return the authplugin instance.
967 * @return mixed false if sign-up is not enabled, the authplugin instance otherwise.
968 * @since Moodle 3.2
970 function signup_is_enabled() {
971 global $CFG;
973 if (!empty($CFG->registerauth)) {
974 $authplugin = get_auth_plugin($CFG->registerauth);
975 if ($authplugin->can_signup()) {
976 return $authplugin;
979 return false;
983 * Helper function used to print locking for auth plugins on admin pages.
984 * @param stdclass $settings Moodle admin settings instance
985 * @param string $auth authentication plugin shortname
986 * @param array $userfields user profile fields
987 * @param string $helptext help text to be displayed at top of form
988 * @param boolean $mapremotefields Map fields or lock only.
989 * @param boolean $updateremotefields Allow remote updates
990 * @param array $customfields list of custom profile fields
991 * @since Moodle 3.3
993 function display_auth_lock_options($settings, $auth, $userfields, $helptext, $mapremotefields, $updateremotefields, $customfields = array()) {
994 global $DB;
996 // Introductory explanation and help text.
997 if ($mapremotefields) {
998 $settings->add(new admin_setting_heading($auth.'/data_mapping', new lang_string('auth_data_mapping', 'auth'), $helptext));
999 } else {
1000 $settings->add(new admin_setting_heading($auth.'/auth_fieldlocks', new lang_string('auth_fieldlocks', 'auth'), $helptext));
1003 // Generate the list of options.
1004 $lockoptions = array ('unlocked' => get_string('unlocked', 'auth'),
1005 'unlockedifempty' => get_string('unlockedifempty', 'auth'),
1006 'locked' => get_string('locked', 'auth'));
1007 $updatelocaloptions = array('oncreate' => get_string('update_oncreate', 'auth'),
1008 'onlogin' => get_string('update_onlogin', 'auth'));
1009 $updateextoptions = array('0' => get_string('update_never', 'auth'),
1010 '1' => get_string('update_onupdate', 'auth'));
1012 // Generate the list of profile fields to allow updates / lock.
1013 if (!empty($customfields)) {
1014 $userfields = array_merge($userfields, $customfields);
1015 $customfieldname = $DB->get_records('user_info_field', null, '', 'shortname, name');
1018 foreach ($userfields as $field) {
1019 // Define the fieldname we display to the user.
1020 // this includes special handling for some profile fields.
1021 $fieldname = $field;
1022 $fieldnametoolong = false;
1023 if ($fieldname === 'lang') {
1024 $fieldname = get_string('language');
1025 } else if (!empty($customfields) && in_array($field, $customfields)) {
1026 // If custom field then pick name from database.
1027 $fieldshortname = str_replace('profile_field_', '', $fieldname);
1028 $fieldname = $customfieldname[$fieldshortname]->name;
1029 if (core_text::strlen($fieldshortname) > 67) {
1030 // If custom profile field name is longer than 67 characters we will not be able to store the setting
1031 // such as 'field_updateremote_profile_field_NOTSOSHORTSHORTNAME' in the database because the character
1032 // limit for the setting name is 100.
1033 $fieldnametoolong = true;
1035 } else if ($fieldname == 'url') {
1036 $fieldname = get_string('webpage');
1037 } else {
1038 $fieldname = get_string($fieldname);
1041 // Generate the list of fields / mappings.
1042 if ($fieldnametoolong) {
1043 // Display a message that the field can not be mapped because it's too long.
1044 $url = new moodle_url('/user/profile/index.php');
1045 $a = (object)['fieldname' => s($fieldname), 'shortname' => s($field), 'charlimit' => 67, 'link' => $url->out()];
1046 $settings->add(new admin_setting_heading($auth.'/field_not_mapped_'.sha1($field), '',
1047 get_string('cannotmapfield', 'auth', $a)));
1048 } else if ($mapremotefields) {
1049 // We are mapping to a remote field here.
1050 // Mapping.
1051 $settings->add(new admin_setting_configtext("auth_{$auth}/field_map_{$field}",
1052 get_string('auth_fieldmapping', 'auth', $fieldname), '', '', PARAM_RAW, 30));
1054 // Update local.
1055 $settings->add(new admin_setting_configselect("auth_{$auth}/field_updatelocal_{$field}",
1056 get_string('auth_updatelocalfield', 'auth', $fieldname), '', 'oncreate', $updatelocaloptions));
1058 // Update remote.
1059 if ($updateremotefields) {
1060 $settings->add(new admin_setting_configselect("auth_{$auth}/field_updateremote_{$field}",
1061 get_string('auth_updateremotefield', 'auth', $fieldname), '', 0, $updateextoptions));
1064 // Lock fields.
1065 $settings->add(new admin_setting_configselect("auth_{$auth}/field_lock_{$field}",
1066 get_string('auth_fieldlockfield', 'auth', $fieldname), '', 'unlocked', $lockoptions));
1068 } else {
1069 // Lock fields Only.
1070 $settings->add(new admin_setting_configselect("auth_{$auth}/field_lock_{$field}",
1071 get_string('auth_fieldlockfield', 'auth', $fieldname), '', 'unlocked', $lockoptions));