Merge branch 'MDL-68112-master' of git://github.com/peterRd/moodle
[moodle.git] / login / index.php
blob7f6656026abef00cb5e2d8de9e5cc156df651257
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 * Main login page.
21 * @package core
22 * @subpackage auth
23 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 require('../config.php');
28 require_once('lib.php');
30 redirect_if_major_upgrade_required();
32 $testsession = optional_param('testsession', 0, PARAM_INT); // test session works properly
33 $anchor = optional_param('anchor', '', PARAM_RAW); // Used to restore hash anchor to wantsurl.
35 $resendconfirmemail = optional_param('resendconfirmemail', false, PARAM_BOOL);
37 // It might be safe to do this for non-Behat sites, or there might
38 // be a security risk. For now we only allow it on Behat sites.
39 // If you wants to do the analysis, you may be able to remove the
40 // if (BEHAT_SITE_RUNNING).
41 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
42 $wantsurl = optional_param('wantsurl', '', PARAM_LOCALURL); // Overrides $SESSION->wantsurl if given.
43 if ($wantsurl !== '') {
44 $SESSION->wantsurl = (new moodle_url($wantsurl))->out(false);
48 $context = context_system::instance();
49 $PAGE->set_url("$CFG->wwwroot/login/index.php");
50 $PAGE->set_context($context);
51 $PAGE->set_pagelayout('login');
53 /// Initialize variables
54 $errormsg = '';
55 $errorcode = 0;
57 // login page requested session test
58 if ($testsession) {
59 if ($testsession == $USER->id) {
60 if (isset($SESSION->wantsurl)) {
61 $urltogo = $SESSION->wantsurl;
62 } else {
63 $urltogo = $CFG->wwwroot.'/';
65 unset($SESSION->wantsurl);
66 redirect($urltogo);
67 } else {
68 // TODO: try to find out what is the exact reason why sessions do not work
69 $errormsg = get_string("cookiesnotenabled");
70 $errorcode = 1;
74 /// Check for timed out sessions
75 if (!empty($SESSION->has_timed_out)) {
76 $session_has_timed_out = true;
77 unset($SESSION->has_timed_out);
78 } else {
79 $session_has_timed_out = false;
82 $frm = false;
83 $user = false;
85 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
86 foreach($authsequence as $authname) {
87 $authplugin = get_auth_plugin($authname);
88 // The auth plugin's loginpage_hook() can eventually set $frm and/or $user.
89 $authplugin->loginpage_hook();
93 /// Define variables used in page
94 $site = get_site();
96 // Ignore any active pages in the navigation/settings.
97 // We do this because there won't be an active page there, and by ignoring the active pages the
98 // navigation and settings won't be initialised unless something else needs them.
99 $PAGE->navbar->ignore_active();
100 $loginsite = get_string("loginsite");
101 $PAGE->navbar->add($loginsite);
103 if ($user !== false or $frm !== false or $errormsg !== '') {
104 // some auth plugin already supplied full user, fake form data or prevented user login with error message
106 } else if (!empty($SESSION->wantsurl) && file_exists($CFG->dirroot.'/login/weblinkauth.php')) {
107 // Handles the case of another Moodle site linking into a page on this site
108 //TODO: move weblink into own auth plugin
109 include($CFG->dirroot.'/login/weblinkauth.php');
110 if (function_exists('weblink_auth')) {
111 $user = weblink_auth($SESSION->wantsurl);
113 if ($user) {
114 $frm->username = $user->username;
115 } else {
116 $frm = data_submitted();
119 } else {
120 $frm = data_submitted();
123 // Restore the #anchor to the original wantsurl. Note that this
124 // will only work for internal auth plugins, SSO plugins such as
125 // SAML / CAS / OIDC will have to handle this correctly directly.
126 if ($anchor && isset($SESSION->wantsurl) && strpos($SESSION->wantsurl, '#') === false) {
127 $wantsurl = new moodle_url($SESSION->wantsurl);
128 $wantsurl->set_anchor(substr($anchor, 1));
129 $SESSION->wantsurl = $wantsurl->out();
132 /// Check if the user has actually submitted login data to us
134 if ($frm and isset($frm->username)) { // Login WITH cookies
136 $frm->username = trim(core_text::strtolower($frm->username));
138 if (is_enabled_auth('none') ) {
139 if ($frm->username !== core_user::clean_field($frm->username, 'username')) {
140 $errormsg = get_string('username').': '.get_string("invalidusername");
141 $errorcode = 2;
142 $user = null;
146 if ($user) {
147 // The auth plugin has already provided the user via the loginpage_hook() called above.
148 } else if (($frm->username == 'guest') and empty($CFG->guestloginbutton)) {
149 $user = false; /// Can't log in as guest if guest button is disabled
150 $frm = false;
151 } else {
152 if (empty($errormsg)) {
153 $logintoken = isset($frm->logintoken) ? $frm->logintoken : '';
154 $user = authenticate_user_login($frm->username, $frm->password, false, $errorcode, $logintoken);
158 // Intercept 'restored' users to provide them with info & reset password
159 if (!$user and $frm and is_restored_user($frm->username)) {
160 $PAGE->set_title(get_string('restoredaccount'));
161 $PAGE->set_heading($site->fullname);
162 echo $OUTPUT->header();
163 echo $OUTPUT->heading(get_string('restoredaccount'));
164 echo $OUTPUT->box(get_string('restoredaccountinfo'), 'generalbox boxaligncenter');
165 require_once('restored_password_form.php'); // Use our "supplanter" login_forgot_password_form. MDL-20846
166 $form = new login_forgot_password_form('forgot_password.php', array('username' => $frm->username));
167 $form->display();
168 echo $OUTPUT->footer();
169 die;
172 if ($user) {
174 // language setup
175 if (isguestuser($user)) {
176 // no predefined language for guests - use existing session or default site lang
177 unset($user->lang);
179 } else if (!empty($user->lang)) {
180 // unset previous session language - use user preference instead
181 unset($SESSION->lang);
184 if (empty($user->confirmed)) { // This account was never confirmed
185 $PAGE->set_title(get_string("mustconfirm"));
186 $PAGE->set_heading($site->fullname);
187 echo $OUTPUT->header();
188 echo $OUTPUT->heading(get_string("mustconfirm"));
189 if ($resendconfirmemail) {
190 if (!send_confirmation_email($user)) {
191 echo $OUTPUT->notification(get_string('emailconfirmsentfailure'), \core\output\notification::NOTIFY_ERROR);
192 } else {
193 echo $OUTPUT->notification(get_string('emailconfirmsentsuccess'), \core\output\notification::NOTIFY_SUCCESS);
196 echo $OUTPUT->box(get_string("emailconfirmsent", "", s($user->email)), "generalbox boxaligncenter");
197 $resendconfirmurl = new moodle_url('/login/index.php',
199 'username' => $frm->username,
200 'password' => $frm->password,
201 'resendconfirmemail' => true
204 echo $OUTPUT->single_button($resendconfirmurl, get_string('emailconfirmationresend'));
205 echo $OUTPUT->footer();
206 die;
209 /// Let's get them all set up.
210 complete_user_login($user);
212 \core\session\manager::apply_concurrent_login_limit($user->id, session_id());
214 // sets the username cookie
215 if (!empty($CFG->nolastloggedin)) {
216 // do not store last logged in user in cookie
217 // auth plugins can temporarily override this from loginpage_hook()
218 // do not save $CFG->nolastloggedin in database!
220 } else if (empty($CFG->rememberusername) or ($CFG->rememberusername == 2 and empty($frm->rememberusername))) {
221 // no permanent cookies, delete old one if exists
222 set_moodle_cookie('');
224 } else {
225 set_moodle_cookie($USER->username);
228 $urltogo = core_login_get_return_url();
230 /// check if user password has expired
231 /// Currently supported only for ldap-authentication module
232 $userauth = get_auth_plugin($USER->auth);
233 if (!isguestuser() and !empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
234 $externalchangepassword = false;
235 if ($userauth->can_change_password()) {
236 $passwordchangeurl = $userauth->change_password_url();
237 if (!$passwordchangeurl) {
238 $passwordchangeurl = $CFG->wwwroot.'/login/change_password.php';
239 } else {
240 $externalchangepassword = true;
242 } else {
243 $passwordchangeurl = $CFG->wwwroot.'/login/change_password.php';
245 $days2expire = $userauth->password_expire($USER->username);
246 $PAGE->set_title("$site->fullname: $loginsite");
247 $PAGE->set_heading("$site->fullname");
248 if (intval($days2expire) > 0 && intval($days2expire) < intval($userauth->config->expiration_warning)) {
249 echo $OUTPUT->header();
250 echo $OUTPUT->confirm(get_string('auth_passwordwillexpire', 'auth', $days2expire), $passwordchangeurl, $urltogo);
251 echo $OUTPUT->footer();
252 exit;
253 } elseif (intval($days2expire) < 0 ) {
254 if ($externalchangepassword) {
255 // We end the session if the change password form is external. This prevents access to the site
256 // until the password is correctly changed.
257 require_logout();
258 } else {
259 // If we use the standard change password form, this user preference will be reset when the password
260 // is changed. Until then it will prevent access to the site.
261 set_user_preference('auth_forcepasswordchange', 1, $USER);
263 echo $OUTPUT->header();
264 echo $OUTPUT->confirm(get_string('auth_passwordisexpired', 'auth'), $passwordchangeurl, $urltogo);
265 echo $OUTPUT->footer();
266 exit;
270 // Discard any errors before the last redirect.
271 unset($SESSION->loginerrormsg);
273 // test the session actually works by redirecting to self
274 $SESSION->wantsurl = $urltogo;
275 redirect(new moodle_url(get_login_url(), array('testsession'=>$USER->id)));
277 } else {
278 if (empty($errormsg)) {
279 if ($errorcode == AUTH_LOGIN_UNAUTHORISED) {
280 $errormsg = get_string("unauthorisedlogin", "", $frm->username);
281 } else {
282 $errormsg = get_string("invalidlogin");
283 $errorcode = 3;
289 /// Detect problems with timedout sessions
290 if ($session_has_timed_out and !data_submitted()) {
291 $errormsg = get_string('sessionerroruser', 'error');
292 $errorcode = 4;
295 /// First, let's remember where the user was trying to get to before they got here
297 if (empty($SESSION->wantsurl)) {
298 $SESSION->wantsurl = null;
299 $referer = get_local_referer(false);
300 if ($referer &&
301 $referer != $CFG->wwwroot &&
302 $referer != $CFG->wwwroot . '/' &&
303 $referer != $CFG->wwwroot . '/login/' &&
304 strpos($referer, $CFG->wwwroot . '/login/?') !== 0 &&
305 strpos($referer, $CFG->wwwroot . '/login/index.php') !== 0) { // There might be some extra params such as ?lang=.
306 $SESSION->wantsurl = $referer;
310 /// Redirect to alternative login URL if needed
311 if (!empty($CFG->alternateloginurl)) {
312 $loginurl = new moodle_url($CFG->alternateloginurl);
314 $loginurlstr = $loginurl->out(false);
316 if (strpos($SESSION->wantsurl, $loginurlstr) === 0) {
317 // We do not want to return to alternate url.
318 $SESSION->wantsurl = null;
321 // If error code then add that to url.
322 if ($errorcode) {
323 $loginurl->param('errorcode', $errorcode);
326 redirect($loginurl->out(false));
329 /// Generate the login page with forms
331 if (!isset($frm) or !is_object($frm)) {
332 $frm = new stdClass();
335 if (empty($frm->username) && $authsequence[0] != 'shibboleth') { // See bug 5184
336 if (!empty($_GET["username"])) {
337 // we do not want data from _POST here
338 $frm->username = clean_param($_GET["username"], PARAM_RAW); // we do not want data from _POST here
339 } else {
340 $frm->username = get_moodle_cookie();
343 $frm->password = "";
346 if (!empty($SESSION->loginerrormsg)) {
347 // We had some errors before redirect, show them now.
348 $errormsg = $SESSION->loginerrormsg;
349 unset($SESSION->loginerrormsg);
351 } else if ($testsession) {
352 // No need to redirect here.
353 unset($SESSION->loginerrormsg);
355 } else if ($errormsg or !empty($frm->password)) {
356 // We must redirect after every password submission.
357 if ($errormsg) {
358 $SESSION->loginerrormsg = $errormsg;
360 redirect(new moodle_url('/login/index.php'));
363 $PAGE->set_title("$site->fullname: $loginsite");
364 $PAGE->set_heading("$site->fullname");
366 echo $OUTPUT->header();
368 if (isloggedin() and !isguestuser()) {
369 // prevent logging when already logged in, we do not want them to relogin by accident because sesskey would be changed
370 echo $OUTPUT->box_start();
371 $logout = new single_button(new moodle_url('/login/logout.php', array('sesskey'=>sesskey(),'loginpage'=>1)), get_string('logout'), 'post');
372 $continue = new single_button(new moodle_url('/'), get_string('cancel'), 'get');
373 echo $OUTPUT->confirm(get_string('alreadyloggedin', 'error', fullname($USER)), $logout, $continue);
374 echo $OUTPUT->box_end();
375 } else {
376 $loginform = new \core_auth\output\login($authsequence, $frm->username);
377 $loginform->set_error($errormsg);
378 echo $OUTPUT->render($loginform);
381 echo $OUTPUT->footer();