Merge branch 'MDL-61355' of git://github.com/danmarsden/moodle
[moodle.git] / login / index.php
blob923cb438263b31131d275ffefaf2244c4f2e4681
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.
34 $resendconfirmemail = optional_param('resendconfirmemail', false, PARAM_BOOL);
36 $context = context_system::instance();
37 $PAGE->set_url("$CFG->wwwroot/login/index.php");
38 $PAGE->set_context($context);
39 $PAGE->set_pagelayout('login');
41 /// Initialize variables
42 $errormsg = '';
43 $errorcode = 0;
45 // login page requested session test
46 if ($testsession) {
47 if ($testsession == $USER->id) {
48 if (isset($SESSION->wantsurl)) {
49 $urltogo = $SESSION->wantsurl;
50 } else {
51 $urltogo = $CFG->wwwroot.'/';
53 unset($SESSION->wantsurl);
54 redirect($urltogo);
55 } else {
56 // TODO: try to find out what is the exact reason why sessions do not work
57 $errormsg = get_string("cookiesnotenabled");
58 $errorcode = 1;
62 /// Check for timed out sessions
63 if (!empty($SESSION->has_timed_out)) {
64 $session_has_timed_out = true;
65 unset($SESSION->has_timed_out);
66 } else {
67 $session_has_timed_out = false;
70 /// auth plugins may override these - SSO anyone?
71 $frm = false;
72 $user = false;
74 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
75 foreach($authsequence as $authname) {
76 $authplugin = get_auth_plugin($authname);
77 $authplugin->loginpage_hook();
81 /// Define variables used in page
82 $site = get_site();
84 // Ignore any active pages in the navigation/settings.
85 // We do this because there won't be an active page there, and by ignoring the active pages the
86 // navigation and settings won't be initialised unless something else needs them.
87 $PAGE->navbar->ignore_active();
88 $loginsite = get_string("loginsite");
89 $PAGE->navbar->add($loginsite);
91 if ($user !== false or $frm !== false or $errormsg !== '') {
92 // some auth plugin already supplied full user, fake form data or prevented user login with error message
94 } else if (!empty($SESSION->wantsurl) && file_exists($CFG->dirroot.'/login/weblinkauth.php')) {
95 // Handles the case of another Moodle site linking into a page on this site
96 //TODO: move weblink into own auth plugin
97 include($CFG->dirroot.'/login/weblinkauth.php');
98 if (function_exists('weblink_auth')) {
99 $user = weblink_auth($SESSION->wantsurl);
101 if ($user) {
102 $frm->username = $user->username;
103 } else {
104 $frm = data_submitted();
107 } else {
108 $frm = data_submitted();
111 // Restore the #anchor to the original wantsurl. Note that this
112 // will only work for internal auth plugins, SSO plugins such as
113 // SAML / CAS / OIDC will have to handle this correctly directly.
114 if ($anchor && isset($SESSION->wantsurl) && strpos($SESSION->wantsurl, '#') === false) {
115 $wantsurl = new moodle_url($SESSION->wantsurl);
116 $wantsurl->set_anchor(substr($anchor, 1));
117 $SESSION->wantsurl = $wantsurl->out();
120 /// Check if the user has actually submitted login data to us
122 if ($frm and isset($frm->username)) { // Login WITH cookies
124 $frm->username = trim(core_text::strtolower($frm->username));
126 if (is_enabled_auth('none') ) {
127 if ($frm->username !== core_user::clean_field($frm->username, 'username')) {
128 $errormsg = get_string('username').': '.get_string("invalidusername");
129 $errorcode = 2;
130 $user = null;
134 if ($user) {
135 //user already supplied by aut plugin prelogin hook
136 } else if (($frm->username == 'guest') and empty($CFG->guestloginbutton)) {
137 $user = false; /// Can't log in as guest if guest button is disabled
138 $frm = false;
139 } else {
140 if (empty($errormsg)) {
141 $user = authenticate_user_login($frm->username, $frm->password, false, $errorcode);
145 // Intercept 'restored' users to provide them with info & reset password
146 if (!$user and $frm and is_restored_user($frm->username)) {
147 $PAGE->set_title(get_string('restoredaccount'));
148 $PAGE->set_heading($site->fullname);
149 echo $OUTPUT->header();
150 echo $OUTPUT->heading(get_string('restoredaccount'));
151 echo $OUTPUT->box(get_string('restoredaccountinfo'), 'generalbox boxaligncenter');
152 require_once('restored_password_form.php'); // Use our "supplanter" login_forgot_password_form. MDL-20846
153 $form = new login_forgot_password_form('forgot_password.php', array('username' => $frm->username));
154 $form->display();
155 echo $OUTPUT->footer();
156 die;
159 if ($user) {
161 // language setup
162 if (isguestuser($user)) {
163 // no predefined language for guests - use existing session or default site lang
164 unset($user->lang);
166 } else if (!empty($user->lang)) {
167 // unset previous session language - use user preference instead
168 unset($SESSION->lang);
171 if (empty($user->confirmed)) { // This account was never confirmed
172 $PAGE->set_title(get_string("mustconfirm"));
173 $PAGE->set_heading($site->fullname);
174 echo $OUTPUT->header();
175 echo $OUTPUT->heading(get_string("mustconfirm"));
176 if ($resendconfirmemail) {
177 if (!send_confirmation_email($user)) {
178 echo $OUTPUT->notification(get_string('emailconfirmsentfailure'), \core\output\notification::NOTIFY_ERROR);
179 } else {
180 echo $OUTPUT->notification(get_string('emailconfirmsentsuccess'), \core\output\notification::NOTIFY_SUCCESS);
183 echo $OUTPUT->box(get_string("emailconfirmsent", "", $user->email), "generalbox boxaligncenter");
184 $resendconfirmurl = new moodle_url('/login/index.php',
186 'username' => $frm->username,
187 'password' => $frm->password,
188 'resendconfirmemail' => true
191 echo $OUTPUT->single_button($resendconfirmurl, get_string('emailconfirmationresend'));
192 echo $OUTPUT->footer();
193 die;
196 /// Let's get them all set up.
197 complete_user_login($user);
199 \core\session\manager::apply_concurrent_login_limit($user->id, session_id());
201 // sets the username cookie
202 if (!empty($CFG->nolastloggedin)) {
203 // do not store last logged in user in cookie
204 // auth plugins can temporarily override this from loginpage_hook()
205 // do not save $CFG->nolastloggedin in database!
207 } else if (empty($CFG->rememberusername) or ($CFG->rememberusername == 2 and empty($frm->rememberusername))) {
208 // no permanent cookies, delete old one if exists
209 set_moodle_cookie('');
211 } else {
212 set_moodle_cookie($USER->username);
215 $urltogo = core_login_get_return_url();
217 /// check if user password has expired
218 /// Currently supported only for ldap-authentication module
219 $userauth = get_auth_plugin($USER->auth);
220 if (!isguestuser() and !empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
221 $externalchangepassword = false;
222 if ($userauth->can_change_password()) {
223 $passwordchangeurl = $userauth->change_password_url();
224 if (!$passwordchangeurl) {
225 $passwordchangeurl = $CFG->wwwroot.'/login/change_password.php';
226 } else {
227 $externalchangepassword = true;
229 } else {
230 $passwordchangeurl = $CFG->wwwroot.'/login/change_password.php';
232 $days2expire = $userauth->password_expire($USER->username);
233 $PAGE->set_title("$site->fullname: $loginsite");
234 $PAGE->set_heading("$site->fullname");
235 if (intval($days2expire) > 0 && intval($days2expire) < intval($userauth->config->expiration_warning)) {
236 echo $OUTPUT->header();
237 echo $OUTPUT->confirm(get_string('auth_passwordwillexpire', 'auth', $days2expire), $passwordchangeurl, $urltogo);
238 echo $OUTPUT->footer();
239 exit;
240 } elseif (intval($days2expire) < 0 ) {
241 if ($externalchangepassword) {
242 // We end the session if the change password form is external. This prevents access to the site
243 // until the password is correctly changed.
244 require_logout();
245 } else {
246 // If we use the standard change password form, this user preference will be reset when the password
247 // is changed. Until then it will prevent access to the site.
248 set_user_preference('auth_forcepasswordchange', 1, $USER);
250 echo $OUTPUT->header();
251 echo $OUTPUT->confirm(get_string('auth_passwordisexpired', 'auth'), $passwordchangeurl, $urltogo);
252 echo $OUTPUT->footer();
253 exit;
257 // Discard any errors before the last redirect.
258 unset($SESSION->loginerrormsg);
260 // test the session actually works by redirecting to self
261 $SESSION->wantsurl = $urltogo;
262 redirect(new moodle_url(get_login_url(), array('testsession'=>$USER->id)));
264 } else {
265 if (empty($errormsg)) {
266 if ($errorcode == AUTH_LOGIN_UNAUTHORISED) {
267 $errormsg = get_string("unauthorisedlogin", "", $frm->username);
268 } else {
269 $errormsg = get_string("invalidlogin");
270 $errorcode = 3;
276 /// Detect problems with timedout sessions
277 if ($session_has_timed_out and !data_submitted()) {
278 $errormsg = get_string('sessionerroruser', 'error');
279 $errorcode = 4;
282 /// First, let's remember where the user was trying to get to before they got here
284 if (empty($SESSION->wantsurl)) {
285 $SESSION->wantsurl = null;
286 $referer = get_local_referer(false);
287 if ($referer &&
288 $referer != $CFG->wwwroot &&
289 $referer != $CFG->wwwroot . '/' &&
290 $referer != $CFG->wwwroot . '/login/' &&
291 strpos($referer, $CFG->wwwroot . '/login/?') !== 0 &&
292 strpos($referer, $CFG->wwwroot . '/login/index.php') !== 0) { // There might be some extra params such as ?lang=.
293 $SESSION->wantsurl = $referer;
297 /// Redirect to alternative login URL if needed
298 if (!empty($CFG->alternateloginurl)) {
299 $loginurl = new moodle_url($CFG->alternateloginurl);
301 $loginurlstr = $loginurl->out(false);
303 if (strpos($SESSION->wantsurl, $loginurlstr) === 0) {
304 // We do not want to return to alternate url.
305 $SESSION->wantsurl = null;
308 // If error code then add that to url.
309 if ($errorcode) {
310 $loginurl->param('errorcode', $errorcode);
313 redirect($loginurl->out(false));
316 /// Generate the login page with forms
318 if (!isset($frm) or !is_object($frm)) {
319 $frm = new stdClass();
322 if (empty($frm->username) && $authsequence[0] != 'shibboleth') { // See bug 5184
323 if (!empty($_GET["username"])) {
324 // we do not want data from _POST here
325 $frm->username = clean_param($_GET["username"], PARAM_RAW); // we do not want data from _POST here
326 } else {
327 $frm->username = get_moodle_cookie();
330 $frm->password = "";
333 if (!empty($SESSION->loginerrormsg)) {
334 // We had some errors before redirect, show them now.
335 $errormsg = $SESSION->loginerrormsg;
336 unset($SESSION->loginerrormsg);
338 } else if ($testsession) {
339 // No need to redirect here.
340 unset($SESSION->loginerrormsg);
342 } else if ($errormsg or !empty($frm->password)) {
343 // We must redirect after every password submission.
344 if ($errormsg) {
345 $SESSION->loginerrormsg = $errormsg;
347 redirect(new moodle_url('/login/index.php'));
350 $PAGE->set_title("$site->fullname: $loginsite");
351 $PAGE->set_heading("$site->fullname");
353 echo $OUTPUT->header();
355 if (isloggedin() and !isguestuser()) {
356 // prevent logging when already logged in, we do not want them to relogin by accident because sesskey would be changed
357 echo $OUTPUT->box_start();
358 $logout = new single_button(new moodle_url('/login/logout.php', array('sesskey'=>sesskey(),'loginpage'=>1)), get_string('logout'), 'post');
359 $continue = new single_button(new moodle_url('/'), get_string('cancel'), 'get');
360 echo $OUTPUT->confirm(get_string('alreadyloggedin', 'error', fullname($USER)), $logout, $continue);
361 echo $OUTPUT->box_end();
362 } else {
363 $loginform = new \core_auth\output\login($authsequence, $frm->username);
364 $loginform->set_error($errormsg);
365 echo $OUTPUT->render($loginform);
368 echo $OUTPUT->footer();