Merge branch 'm25_MDL-40200_Notices_When_Viewing_Profile_Invalid_UserId' of https...
[moodle.git] / lib / authlib.php
blobf8aa82026124710bffc03f883c6492a8dd652aec
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);
80 /**
81 * Abstract authentication plugin.
83 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
84 * @package moodlecore
86 class auth_plugin_base {
88 /**
89 * The configuration details for the plugin.
90 * @var object
92 var $config;
94 /**
95 * Authentication plugin type - the same as db field.
96 * @var string
98 var $authtype;
100 * The fields we can lock and update from/to external authentication backends
101 * @var array
103 var $userfields = array(
104 'firstname',
105 'lastname',
106 'email',
107 'city',
108 'country',
109 'lang',
110 'description',
111 'url',
112 'idnumber',
113 'institution',
114 'department',
115 'phone1',
116 'phone2',
117 'address'
122 * This is the primary method that is used by the authenticate_user_login()
123 * function in moodlelib.php.
125 * This method should return a boolean indicating
126 * whether or not the username and password authenticate successfully.
128 * Returns true if the username and password work and false if they are
129 * wrong or don't exist.
131 * @param string $username The username (with system magic quotes)
132 * @param string $password The password (with system magic quotes)
134 * @return bool Authentication success or failure.
136 function user_login($username, $password) {
137 print_error('mustbeoveride', 'debug', '', 'user_login()' );
141 * Returns true if this authentication plugin can change the users'
142 * password.
144 * @return bool
146 function can_change_password() {
147 //override if needed
148 return false;
152 * Returns the URL for changing the users' passwords, or empty if the default
153 * URL can be used.
155 * This method is used if can_change_password() returns true.
156 * This method is called only when user is logged in, it may use global $USER.
158 * @return moodle_url url of the profile page or null if standard used
160 function change_password_url() {
161 //override if needed
162 return null;
166 * Returns true if this authentication plugin can edit the users'
167 * profile.
169 * @return bool
171 function can_edit_profile() {
172 //override if needed
173 return true;
177 * Returns the URL for editing the users' profile, or empty if the default
178 * URL can be used.
180 * This method is used if can_edit_profile() returns true.
181 * This method is called only when user is logged in, it may use global $USER.
183 * @return moodle_url url of the profile page or null if standard used
185 function edit_profile_url() {
186 //override if needed
187 return null;
191 * Returns true if this authentication plugin is "internal".
193 * Internal plugins use password hashes from Moodle user table for authentication.
195 * @return bool
197 function is_internal() {
198 //override if needed
199 return true;
203 * Indicates if password hashes should be stored in local moodle database.
204 * @return bool true means md5 password hash stored in user table, false means flag 'not_cached' stored there instead
206 function prevent_local_passwords() {
207 return !$this->is_internal();
211 * Indicates if moodle should automatically update internal user
212 * records with data from external sources using the information
213 * from get_userinfo() method.
215 * @return bool true means automatically copy data from ext to user table
217 function is_synchronised_with_external() {
218 return !$this->is_internal();
222 * Updates the user's password.
224 * In previous versions of Moodle, the function
225 * auth_user_update_password accepted a username as the first parameter. The
226 * revised function expects a user object.
228 * @param object $user User table object
229 * @param string $newpassword Plaintext password
231 * @return bool True on success
233 function user_update_password($user, $newpassword) {
234 //override if needed
235 return true;
239 * Called when the user record is updated.
240 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
241 * compares information saved modified information to external db.
243 * @param mixed $olduser Userobject before modifications (without system magic quotes)
244 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
245 * @return boolean true if updated or update ignored; false if error
248 function user_update($olduser, $newuser) {
249 //override if needed
250 return true;
254 * User delete requested - internal user record is mared as deleted already, username not present anymore.
256 * Do any action in external database.
258 * @param object $user Userobject before delete (without system magic quotes)
259 * @return void
261 function user_delete($olduser) {
262 //override if needed
263 return;
267 * Returns true if plugin allows resetting of internal password.
269 * @return bool
271 function can_reset_password() {
272 //override if needed
273 return false;
277 * Returns true if plugin allows resetting of internal password.
279 * @return bool
281 function can_signup() {
282 //override if needed
283 return false;
287 * Sign up a new user ready for confirmation.
288 * Password is passed in plaintext.
290 * @param object $user new user object
291 * @param boolean $notify print notice with link and terminate
293 function user_signup($user, $notify=true) {
294 //override when can signup
295 print_error('mustbeoveride', 'debug', '', 'user_signup()' );
299 * Return a form to capture user details for account creation.
300 * This is used in /login/signup.php.
301 * @return moodle_form A form which edits a record from the user table.
303 function signup_form() {
304 global $CFG;
306 require_once($CFG->dirroot.'/login/signup_form.php');
307 return new login_signup_form(null, null, 'post', '', array('autocomplete'=>'on'));
311 * Returns true if plugin allows confirming of new users.
313 * @return bool
315 function can_confirm() {
316 //override if needed
317 return false;
321 * Confirm the new user as registered.
323 * @param string $username
324 * @param string $confirmsecret
326 function user_confirm($username, $confirmsecret) {
327 //override when can confirm
328 print_error('mustbeoveride', 'debug', '', 'user_confirm()' );
332 * Checks if user exists in external db
334 * @param string $username (with system magic quotes)
335 * @return bool
337 function user_exists($username) {
338 //override if needed
339 return false;
343 * return number of days to user password expires
345 * If userpassword does not expire it should return 0. If password is already expired
346 * it should return negative value.
348 * @param mixed $username username (with system magic quotes)
349 * @return integer
351 function password_expire($username) {
352 return 0;
355 * Sync roles for this user - usually creator
357 * @param $user object user object (without system magic quotes)
359 function sync_roles($user) {
360 //override if needed
364 * Read user information from external database and returns it as array().
365 * Function should return all information available. If you are saving
366 * this information to moodle user-table you should honour synchronisation flags
368 * @param string $username username
370 * @return mixed array with no magic quotes or false on error
372 function get_userinfo($username) {
373 //override if needed
374 return array();
378 * Prints a form for configuring this authentication plugin.
380 * This function is called from admin/auth.php, and outputs a full page with
381 * a form for configuring this plugin.
383 * @param object $config
384 * @param object $err
385 * @param array $user_fields
387 function config_form($config, $err, $user_fields) {
388 //override if needed
392 * A chance to validate form data, and last chance to
393 * do stuff before it is inserted in config_plugin
394 * @param object object with submitted configuration settings (without system magic quotes)
395 * @param array $err array of error messages
397 function validate_form($form, &$err) {
398 //override if needed
402 * Processes and stores configuration data for this authentication plugin.
404 * @param object object with submitted configuration settings (without system magic quotes)
406 function process_config($config) {
407 //override if needed
408 return true;
412 * Hook for overriding behaviour of login page.
413 * This method is called from login/index.php page for all enabled auth plugins.
415 * @global object
416 * @global object
418 function loginpage_hook() {
419 global $frm; // can be used to override submitted login form
420 global $user; // can be used to replace authenticate_user_login()
422 //override if needed
426 * Post authentication hook.
427 * This method is called from authenticate_user_login() for all enabled auth plugins.
429 * @param object $user user object, later used for $USER
430 * @param string $username (with system magic quotes)
431 * @param string $password plain text password (with system magic quotes)
433 function user_authenticated_hook(&$user, $username, $password) {
434 //override if needed
438 * Pre logout hook.
439 * This method is called from require_logout() for all enabled auth plugins,
441 * @global object
443 function prelogout_hook() {
444 global $USER; // use $USER->auth to find the plugin used for login
446 //override if needed
450 * Hook for overriding behaviour of logout page.
451 * This method is called from login/logout.php page for all enabled auth plugins.
453 * @global object
454 * @global string
456 function logoutpage_hook() {
457 global $USER; // use $USER->auth to find the plugin used for login
458 global $redirect; // can be used to override redirect after logout
460 //override if needed
464 * Hook called before timing out of database session.
465 * This is useful for SSO and MNET.
467 * @param object $user
468 * @param string $sid session id
469 * @param int $timecreated start of session
470 * @param int $timemodified user last seen
471 * @return bool true means do not timeout session yet
473 function ignore_timeout_hook($user, $sid, $timecreated, $timemodified) {
474 return false;
478 * Return the properly translated human-friendly title of this auth plugin
480 * @todo Document this function
482 function get_title() {
483 return get_string('pluginname', "auth_{$this->authtype}");
487 * Get the auth description (from core or own auth lang files)
489 * @return string The description
491 function get_description() {
492 $authdescription = get_string("auth_{$this->authtype}description", "auth_{$this->authtype}");
493 return $authdescription;
497 * Returns whether or not the captcha element is enabled, and the admin settings fulfil its requirements.
499 * @abstract Implement in child classes
500 * @return bool
502 function is_captcha_enabled() {
503 return false;
507 * Returns a list of potential IdPs that this authentication plugin supports.
508 * This is used to provide links on the login page.
510 * @param string $wantsurl the relative url fragment the user wants to get to. You can use this to compose a returnurl, for example
512 * @return array like:
513 * array(
514 * array(
515 * 'url' => 'http://someurl',
516 * 'icon' => new pix_icon(...),
517 * 'name' => get_string('somename', 'auth_yourplugin'),
518 * ),
521 function loginpage_idp_list($wantsurl) {
522 return array();
528 * Verify if user is locked out.
530 * @param stdClass $user
531 * @return bool true if user locked out
533 function login_is_lockedout($user) {
534 global $CFG;
536 if ($user->mnethostid != $CFG->mnet_localhost_id) {
537 return false;
539 if (isguestuser($user)) {
540 return false;
543 if (empty($CFG->lockoutthreshold)) {
544 // Lockout not enabled.
545 return false;
548 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
549 // This preference may be used for accounts that must not be locked out.
550 return false;
553 $locked = get_user_preferences('login_lockout', 0, $user);
554 if (!$locked) {
555 return false;
558 if (empty($CFG->lockoutduration)) {
559 // Locked out forever.
560 return true;
563 if (time() - $locked < $CFG->lockoutduration) {
564 return true;
567 login_unlock_account($user);
569 return false;
573 * To be called after valid user login.
574 * @param stdClass $user
576 function login_attempt_valid($user) {
577 global $CFG;
579 if ($user->mnethostid != $CFG->mnet_localhost_id) {
580 return;
582 if (isguestuser($user)) {
583 return;
586 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
587 login_unlock_account($user);
591 * To be called after failed user login.
592 * @param stdClass $user
594 function login_attempt_failed($user) {
595 global $CFG;
597 if ($user->mnethostid != $CFG->mnet_localhost_id) {
598 return;
600 if (isguestuser($user)) {
601 return;
604 if (empty($CFG->lockoutthreshold)) {
605 // No threshold means no lockout.
606 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
607 login_unlock_account($user);
608 return;
611 $count = get_user_preferences('login_failed_count', 0, $user);
612 $last = get_user_preferences('login_failed_last', 0, $user);
614 if (!empty($CFG->lockoutwindow) and time() - $last > $CFG->lockoutwindow) {
615 $count = 0;
618 $count = $count+1;
620 set_user_preference('login_failed_count', $count, $user);
621 set_user_preference('login_failed_last', time(), $user);
623 if ($count >= $CFG->lockoutthreshold) {
624 login_lock_account($user);
629 * Lockout user and send notification email.
631 * @param stdClass $user
633 function login_lock_account($user) {
634 global $CFG, $SESSION;
636 if ($user->mnethostid != $CFG->mnet_localhost_id) {
637 return;
639 if (isguestuser($user)) {
640 return;
643 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
644 // This user can not be locked out.
645 return;
648 $alreadylockedout = get_user_preferences('login_lockout', 0, $user);
650 set_user_preference('login_lockout', time(), $user);
652 if ($alreadylockedout == 0) {
653 $secret = random_string(15);
654 set_user_preference('login_lockout_secret', $secret, $user);
656 // Some nasty hackery to get strings and dates localised for target user.
657 $sessionlang = isset($SESSION->lang) ? $SESSION->lang : null;
658 if (get_string_manager()->translation_exists($user->lang, false)) {
659 $SESSION->lang = $user->lang;
660 moodle_setlocale();
663 $site = get_site();
664 $supportuser = generate_email_supportuser();
666 $data = new stdClass();
667 $data->firstname = $user->firstname;
668 $data->lastname = $user->lastname;
669 $data->username = $user->username;
670 $data->sitename = format_string($site->fullname);
671 $data->link = $CFG->wwwroot.'/login/unlock_account.php?u='.$user->id.'&s='.$secret;
672 $data->admin = generate_email_signoff();
674 $message = get_string('lockoutemailbody', 'admin', $data);
675 $subject = get_string('lockoutemailsubject', 'admin', format_string($site->fullname));
677 if ($message) {
678 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
679 email_to_user($user, $supportuser, $subject, $message);
682 if ($SESSION->lang !== $sessionlang) {
683 $SESSION->lang = $sessionlang;
684 moodle_setlocale();
690 * Unlock user account and reset timers.
692 * @param stdClass $user
694 function login_unlock_account($user) {
695 unset_user_preference('login_lockout', $user);
696 unset_user_preference('login_failed_count', $user);
697 unset_user_preference('login_failed_last', $user);
699 // Note: do not clear the lockout secret because user might click on the link repeatedly.