MDL-40589 - Theme/CLEAN - Flip YUI3 tree item icon in RTL mode in folder resource
[moodle.git] / lib / authlib.php
blobfd8057e1d10c6e530b36989a5b4c2790033ecc35
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'
121 * Moodle custom fields to sync with.
122 * @var array()
124 var $customfields = null;
128 * This is the primary method that is used by the authenticate_user_login()
129 * function in moodlelib.php.
131 * This method should return a boolean indicating
132 * whether or not the username and password authenticate successfully.
134 * Returns true if the username and password work and false if they are
135 * wrong or don't exist.
137 * @param string $username The username (with system magic quotes)
138 * @param string $password The password (with system magic quotes)
140 * @return bool Authentication success or failure.
142 function user_login($username, $password) {
143 print_error('mustbeoveride', 'debug', '', 'user_login()' );
147 * Returns true if this authentication plugin can change the users'
148 * password.
150 * @return bool
152 function can_change_password() {
153 //override if needed
154 return false;
158 * Returns the URL for changing the users' passwords, or empty if the default
159 * URL can be used.
161 * This method is used if can_change_password() returns true.
162 * This method is called only when user is logged in, it may use global $USER.
164 * @return moodle_url url of the profile page or null if standard used
166 function change_password_url() {
167 //override if needed
168 return null;
172 * Returns true if this authentication plugin can edit the users'
173 * profile.
175 * @return bool
177 function can_edit_profile() {
178 //override if needed
179 return true;
183 * Returns the URL for editing the users' profile, or empty if the default
184 * URL can be used.
186 * This method is used if can_edit_profile() returns true.
187 * This method is called only when user is logged in, it may use global $USER.
189 * @return moodle_url url of the profile page or null if standard used
191 function edit_profile_url() {
192 //override if needed
193 return null;
197 * Returns true if this authentication plugin is "internal".
199 * Internal plugins use password hashes from Moodle user table for authentication.
201 * @return bool
203 function is_internal() {
204 //override if needed
205 return true;
209 * Indicates if password hashes should be stored in local moodle database.
210 * @return bool true means md5 password hash stored in user table, false means flag 'not_cached' stored there instead
212 function prevent_local_passwords() {
213 return !$this->is_internal();
217 * Indicates if moodle should automatically update internal user
218 * records with data from external sources using the information
219 * from get_userinfo() method.
221 * @return bool true means automatically copy data from ext to user table
223 function is_synchronised_with_external() {
224 return !$this->is_internal();
228 * Updates the user's password.
230 * In previous versions of Moodle, the function
231 * auth_user_update_password accepted a username as the first parameter. The
232 * revised function expects a user object.
234 * @param object $user User table object
235 * @param string $newpassword Plaintext password
237 * @return bool True on success
239 function user_update_password($user, $newpassword) {
240 //override if needed
241 return true;
245 * Called when the user record is updated.
246 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
247 * compares information saved modified information to external db.
249 * @param mixed $olduser Userobject before modifications (without system magic quotes)
250 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
251 * @return boolean true if updated or update ignored; false if error
254 function user_update($olduser, $newuser) {
255 //override if needed
256 return true;
260 * User delete requested - internal user record is mared as deleted already, username not present anymore.
262 * Do any action in external database.
264 * @param object $user Userobject before delete (without system magic quotes)
265 * @return void
267 function user_delete($olduser) {
268 //override if needed
269 return;
273 * Returns true if plugin allows resetting of internal password.
275 * @return bool
277 function can_reset_password() {
278 //override if needed
279 return false;
283 * Returns true if plugin allows resetting of internal password.
285 * @return bool
287 function can_signup() {
288 //override if needed
289 return false;
293 * Sign up a new user ready for confirmation.
294 * Password is passed in plaintext.
296 * @param object $user new user object
297 * @param boolean $notify print notice with link and terminate
299 function user_signup($user, $notify=true) {
300 //override when can signup
301 print_error('mustbeoveride', 'debug', '', 'user_signup()' );
305 * Return a form to capture user details for account creation.
306 * This is used in /login/signup.php.
307 * @return moodle_form A form which edits a record from the user table.
309 function signup_form() {
310 global $CFG;
312 require_once($CFG->dirroot.'/login/signup_form.php');
313 return new login_signup_form(null, null, 'post', '', array('autocomplete'=>'on'));
317 * Returns true if plugin allows confirming of new users.
319 * @return bool
321 function can_confirm() {
322 //override if needed
323 return false;
327 * Confirm the new user as registered.
329 * @param string $username
330 * @param string $confirmsecret
332 function user_confirm($username, $confirmsecret) {
333 //override when can confirm
334 print_error('mustbeoveride', 'debug', '', 'user_confirm()' );
338 * Checks if user exists in external db
340 * @param string $username (with system magic quotes)
341 * @return bool
343 function user_exists($username) {
344 //override if needed
345 return false;
349 * return number of days to user password expires
351 * If userpassword does not expire it should return 0. If password is already expired
352 * it should return negative value.
354 * @param mixed $username username (with system magic quotes)
355 * @return integer
357 function password_expire($username) {
358 return 0;
361 * Sync roles for this user - usually creator
363 * @param $user object user object (without system magic quotes)
365 function sync_roles($user) {
366 //override if needed
370 * Read user information from external database and returns it as array().
371 * Function should return all information available. If you are saving
372 * this information to moodle user-table you should honour synchronisation flags
374 * @param string $username username
376 * @return mixed array with no magic quotes or false on error
378 function get_userinfo($username) {
379 //override if needed
380 return array();
384 * Prints a form for configuring this authentication plugin.
386 * This function is called from admin/auth.php, and outputs a full page with
387 * a form for configuring this plugin.
389 * @param object $config
390 * @param object $err
391 * @param array $user_fields
393 function config_form($config, $err, $user_fields) {
394 //override if needed
398 * A chance to validate form data, and last chance to
399 * do stuff before it is inserted in config_plugin
400 * @param object object with submitted configuration settings (without system magic quotes)
401 * @param array $err array of error messages
403 function validate_form($form, &$err) {
404 //override if needed
408 * Processes and stores configuration data for this authentication plugin.
410 * @param object object with submitted configuration settings (without system magic quotes)
412 function process_config($config) {
413 //override if needed
414 return true;
418 * Hook for overriding behaviour of login page.
419 * This method is called from login/index.php page for all enabled auth plugins.
421 * @global object
422 * @global object
424 function loginpage_hook() {
425 global $frm; // can be used to override submitted login form
426 global $user; // can be used to replace authenticate_user_login()
428 //override if needed
432 * Post authentication hook.
433 * This method is called from authenticate_user_login() for all enabled auth plugins.
435 * @param object $user user object, later used for $USER
436 * @param string $username (with system magic quotes)
437 * @param string $password plain text password (with system magic quotes)
439 function user_authenticated_hook(&$user, $username, $password) {
440 //override if needed
444 * Pre logout hook.
445 * This method is called from require_logout() for all enabled auth plugins,
447 * @global object
449 function prelogout_hook() {
450 global $USER; // use $USER->auth to find the plugin used for login
452 //override if needed
456 * Hook for overriding behaviour of logout page.
457 * This method is called from login/logout.php page for all enabled auth plugins.
459 * @global object
460 * @global string
462 function logoutpage_hook() {
463 global $USER; // use $USER->auth to find the plugin used for login
464 global $redirect; // can be used to override redirect after logout
466 //override if needed
470 * Hook called before timing out of database session.
471 * This is useful for SSO and MNET.
473 * @param object $user
474 * @param string $sid session id
475 * @param int $timecreated start of session
476 * @param int $timemodified user last seen
477 * @return bool true means do not timeout session yet
479 function ignore_timeout_hook($user, $sid, $timecreated, $timemodified) {
480 return false;
484 * Return the properly translated human-friendly title of this auth plugin
486 * @todo Document this function
488 function get_title() {
489 return get_string('pluginname', "auth_{$this->authtype}");
493 * Get the auth description (from core or own auth lang files)
495 * @return string The description
497 function get_description() {
498 $authdescription = get_string("auth_{$this->authtype}description", "auth_{$this->authtype}");
499 return $authdescription;
503 * Returns whether or not the captcha element is enabled, and the admin settings fulfil its requirements.
505 * @abstract Implement in child classes
506 * @return bool
508 function is_captcha_enabled() {
509 return false;
513 * Returns a list of potential IdPs that this authentication plugin supports.
514 * This is used to provide links on the login page.
516 * @param string $wantsurl the relative url fragment the user wants to get to. You can use this to compose a returnurl, for example
518 * @return array like:
519 * array(
520 * array(
521 * 'url' => 'http://someurl',
522 * 'icon' => new pix_icon(...),
523 * 'name' => get_string('somename', 'auth_yourplugin'),
524 * ),
527 function loginpage_idp_list($wantsurl) {
528 return array();
532 * Return custom user profile fields.
534 * @return array list of custom fields.
536 public function get_custom_user_profile_fields() {
537 global $DB;
538 // If already retrieved then return.
539 if (!is_null($this->customfields)) {
540 return $this->customfields;
543 $this->customfields = array();
544 if ($proffields = $DB->get_records('user_info_field')) {
545 foreach ($proffields as $proffield) {
546 $this->customfields[] = 'profile_field_'.$proffield->shortname;
549 unset($proffields);
551 return $this->customfields;
557 * Verify if user is locked out.
559 * @param stdClass $user
560 * @return bool true if user locked out
562 function login_is_lockedout($user) {
563 global $CFG;
565 if ($user->mnethostid != $CFG->mnet_localhost_id) {
566 return false;
568 if (isguestuser($user)) {
569 return false;
572 if (empty($CFG->lockoutthreshold)) {
573 // Lockout not enabled.
574 return false;
577 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
578 // This preference may be used for accounts that must not be locked out.
579 return false;
582 $locked = get_user_preferences('login_lockout', 0, $user);
583 if (!$locked) {
584 return false;
587 if (empty($CFG->lockoutduration)) {
588 // Locked out forever.
589 return true;
592 if (time() - $locked < $CFG->lockoutduration) {
593 return true;
596 login_unlock_account($user);
598 return false;
602 * To be called after valid user login.
603 * @param stdClass $user
605 function login_attempt_valid($user) {
606 global $CFG;
608 if ($user->mnethostid != $CFG->mnet_localhost_id) {
609 return;
611 if (isguestuser($user)) {
612 return;
615 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
616 login_unlock_account($user);
620 * To be called after failed user login.
621 * @param stdClass $user
623 function login_attempt_failed($user) {
624 global $CFG;
626 if ($user->mnethostid != $CFG->mnet_localhost_id) {
627 return;
629 if (isguestuser($user)) {
630 return;
633 if (empty($CFG->lockoutthreshold)) {
634 // No threshold means no lockout.
635 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
636 login_unlock_account($user);
637 return;
640 $count = get_user_preferences('login_failed_count', 0, $user);
641 $last = get_user_preferences('login_failed_last', 0, $user);
643 if (!empty($CFG->lockoutwindow) and time() - $last > $CFG->lockoutwindow) {
644 $count = 0;
647 $count = $count+1;
649 set_user_preference('login_failed_count', $count, $user);
650 set_user_preference('login_failed_last', time(), $user);
652 if ($count >= $CFG->lockoutthreshold) {
653 login_lock_account($user);
658 * Lockout user and send notification email.
660 * @param stdClass $user
662 function login_lock_account($user) {
663 global $CFG, $SESSION;
665 if ($user->mnethostid != $CFG->mnet_localhost_id) {
666 return;
668 if (isguestuser($user)) {
669 return;
672 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
673 // This user can not be locked out.
674 return;
677 $alreadylockedout = get_user_preferences('login_lockout', 0, $user);
679 set_user_preference('login_lockout', time(), $user);
681 if ($alreadylockedout == 0) {
682 $secret = random_string(15);
683 set_user_preference('login_lockout_secret', $secret, $user);
685 // Some nasty hackery to get strings and dates localised for target user.
686 $sessionlang = isset($SESSION->lang) ? $SESSION->lang : null;
687 if (get_string_manager()->translation_exists($user->lang, false)) {
688 $SESSION->lang = $user->lang;
689 moodle_setlocale();
692 $site = get_site();
693 $supportuser = generate_email_supportuser();
695 $data = new stdClass();
696 $data->firstname = $user->firstname;
697 $data->lastname = $user->lastname;
698 $data->username = $user->username;
699 $data->sitename = format_string($site->fullname);
700 $data->link = $CFG->wwwroot.'/login/unlock_account.php?u='.$user->id.'&s='.$secret;
701 $data->admin = generate_email_signoff();
703 $message = get_string('lockoutemailbody', 'admin', $data);
704 $subject = get_string('lockoutemailsubject', 'admin', format_string($site->fullname));
706 if ($message) {
707 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
708 email_to_user($user, $supportuser, $subject, $message);
711 if ($SESSION->lang !== $sessionlang) {
712 $SESSION->lang = $sessionlang;
713 moodle_setlocale();
719 * Unlock user account and reset timers.
721 * @param stdClass $user
723 function login_unlock_account($user) {
724 unset_user_preference('login_lockout', $user);
725 unset_user_preference('login_failed_count', $user);
726 unset_user_preference('login_failed_last', $user);
728 // Note: do not clear the lockout secret because user might click on the link repeatedly.