Merge branch 'wip-MDL-57234-master' of https://github.com/Beedell/moodle
[moodle.git] / login / index.php
blob20d3a4761b9f86ebccecc8792297c41721521967
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 // Try to prevent searching for sites that allow sign-up.
31 if (!isset($CFG->additionalhtmlhead)) {
32 $CFG->additionalhtmlhead = '';
34 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
36 redirect_if_major_upgrade_required();
38 $testsession = optional_param('testsession', 0, PARAM_INT); // test session works properly
39 $cancel = optional_param('cancel', 0, PARAM_BOOL); // redirect to frontpage, needed for loginhttps
40 $anchor = optional_param('anchor', '', PARAM_RAW); // Used to restore hash anchor to wantsurl.
42 if ($cancel) {
43 redirect(new moodle_url('/'));
46 //HTTPS is required in this page when $CFG->loginhttps enabled
47 $PAGE->https_required();
49 $context = context_system::instance();
50 $PAGE->set_url("$CFG->httpswwwroot/login/index.php");
51 $PAGE->set_context($context);
52 $PAGE->set_pagelayout('login');
54 /// Initialize variables
55 $errormsg = '';
56 $errorcode = 0;
58 // login page requested session test
59 if ($testsession) {
60 if ($testsession == $USER->id) {
61 if (isset($SESSION->wantsurl)) {
62 $urltogo = $SESSION->wantsurl;
63 } else {
64 $urltogo = $CFG->wwwroot.'/';
66 unset($SESSION->wantsurl);
67 redirect($urltogo);
68 } else {
69 // TODO: try to find out what is the exact reason why sessions do not work
70 $errormsg = get_string("cookiesnotenabled");
71 $errorcode = 1;
75 /// Check for timed out sessions
76 if (!empty($SESSION->has_timed_out)) {
77 $session_has_timed_out = true;
78 unset($SESSION->has_timed_out);
79 } else {
80 $session_has_timed_out = false;
83 /// auth plugins may override these - SSO anyone?
84 $frm = false;
85 $user = false;
87 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
88 foreach($authsequence as $authname) {
89 $authplugin = get_auth_plugin($authname);
90 $authplugin->loginpage_hook();
94 /// Define variables used in page
95 $site = get_site();
97 // Ignore any active pages in the navigation/settings.
98 // We do this because there won't be an active page there, and by ignoring the active pages the
99 // navigation and settings won't be initialised unless something else needs them.
100 $PAGE->navbar->ignore_active();
101 $loginsite = get_string("loginsite");
102 $PAGE->navbar->add($loginsite);
104 if ($user !== false or $frm !== false or $errormsg !== '') {
105 // some auth plugin already supplied full user, fake form data or prevented user login with error message
107 } else if (!empty($SESSION->wantsurl) && file_exists($CFG->dirroot.'/login/weblinkauth.php')) {
108 // Handles the case of another Moodle site linking into a page on this site
109 //TODO: move weblink into own auth plugin
110 include($CFG->dirroot.'/login/weblinkauth.php');
111 if (function_exists('weblink_auth')) {
112 $user = weblink_auth($SESSION->wantsurl);
114 if ($user) {
115 $frm->username = $user->username;
116 } else {
117 $frm = data_submitted();
120 } else {
121 $frm = data_submitted();
124 // Restore the #anchor to the original wantsurl. Note that this
125 // will only work for internal auth plugins, SSO plugins such as
126 // SAML / CAS / OIDC will have to handle this correctly directly.
127 if ($anchor && isset($SESSION->wantsurl) && strpos($SESSION->wantsurl, '#') === false) {
128 $wantsurl = new moodle_url($SESSION->wantsurl);
129 $wantsurl->set_anchor(substr($anchor, 1));
130 $SESSION->wantsurl = $wantsurl->out();
133 /// Check if the user has actually submitted login data to us
135 if ($frm and isset($frm->username)) { // Login WITH cookies
137 $frm->username = trim(core_text::strtolower($frm->username));
139 if (is_enabled_auth('none') ) {
140 if ($frm->username !== core_user::clean_field($frm->username, 'username')) {
141 $errormsg = get_string('username').': '.get_string("invalidusername");
142 $errorcode = 2;
143 $user = null;
147 if ($user) {
148 //user already supplied by aut plugin prelogin hook
149 } else if (($frm->username == 'guest') and empty($CFG->guestloginbutton)) {
150 $user = false; /// Can't log in as guest if guest button is disabled
151 $frm = false;
152 } else {
153 if (empty($errormsg)) {
154 $user = authenticate_user_login($frm->username, $frm->password, false, $errorcode);
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 echo $OUTPUT->box(get_string("emailconfirmsent", "", $user->email), "generalbox boxaligncenter");
190 echo $OUTPUT->footer();
191 die;
194 /// Let's get them all set up.
195 complete_user_login($user);
197 \core\session\manager::apply_concurrent_login_limit($user->id, session_id());
199 // sets the username cookie
200 if (!empty($CFG->nolastloggedin)) {
201 // do not store last logged in user in cookie
202 // auth plugins can temporarily override this from loginpage_hook()
203 // do not save $CFG->nolastloggedin in database!
205 } else if (empty($CFG->rememberusername) or ($CFG->rememberusername == 2 and empty($frm->rememberusername))) {
206 // no permanent cookies, delete old one if exists
207 set_moodle_cookie('');
209 } else {
210 set_moodle_cookie($USER->username);
213 $urltogo = core_login_get_return_url();
215 /// check if user password has expired
216 /// Currently supported only for ldap-authentication module
217 $userauth = get_auth_plugin($USER->auth);
218 if (!isguestuser() and !empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
219 if ($userauth->can_change_password()) {
220 $passwordchangeurl = $userauth->change_password_url();
221 if (!$passwordchangeurl) {
222 $passwordchangeurl = $CFG->httpswwwroot.'/login/change_password.php';
224 } else {
225 $passwordchangeurl = $CFG->httpswwwroot.'/login/change_password.php';
227 $days2expire = $userauth->password_expire($USER->username);
228 $PAGE->set_title("$site->fullname: $loginsite");
229 $PAGE->set_heading("$site->fullname");
230 if (intval($days2expire) > 0 && intval($days2expire) < intval($userauth->config->expiration_warning)) {
231 echo $OUTPUT->header();
232 echo $OUTPUT->confirm(get_string('auth_passwordwillexpire', 'auth', $days2expire), $passwordchangeurl, $urltogo);
233 echo $OUTPUT->footer();
234 exit;
235 } elseif (intval($days2expire) < 0 ) {
236 echo $OUTPUT->header();
237 echo $OUTPUT->confirm(get_string('auth_passwordisexpired', 'auth'), $passwordchangeurl, $urltogo);
238 echo $OUTPUT->footer();
239 exit;
243 // Discard any errors before the last redirect.
244 unset($SESSION->loginerrormsg);
246 // test the session actually works by redirecting to self
247 $SESSION->wantsurl = $urltogo;
248 redirect(new moodle_url(get_login_url(), array('testsession'=>$USER->id)));
250 } else {
251 if (empty($errormsg)) {
252 if ($errorcode == AUTH_LOGIN_UNAUTHORISED) {
253 $errormsg = get_string("unauthorisedlogin", "", $frm->username);
254 } else {
255 $errormsg = get_string("invalidlogin");
256 $errorcode = 3;
262 /// Detect problems with timedout sessions
263 if ($session_has_timed_out and !data_submitted()) {
264 $errormsg = get_string('sessionerroruser', 'error');
265 $errorcode = 4;
268 /// First, let's remember where the user was trying to get to before they got here
270 if (empty($SESSION->wantsurl)) {
271 $SESSION->wantsurl = null;
272 $referer = get_local_referer(false);
273 if ($referer &&
274 $referer != $CFG->wwwroot &&
275 $referer != $CFG->wwwroot . '/' &&
276 $referer != $CFG->httpswwwroot . '/login/' &&
277 strpos($referer, $CFG->httpswwwroot . '/login/?') !== 0 &&
278 strpos($referer, $CFG->httpswwwroot . '/login/index.php') !== 0) { // There might be some extra params such as ?lang=.
279 $SESSION->wantsurl = $referer;
283 /// Redirect to alternative login URL if needed
284 if (!empty($CFG->alternateloginurl)) {
285 $loginurl = new moodle_url($CFG->alternateloginurl);
287 $loginurlstr = $loginurl->out(false);
289 if (strpos($SESSION->wantsurl, $loginurlstr) === 0) {
290 // We do not want to return to alternate url.
291 $SESSION->wantsurl = null;
294 // If error code then add that to url.
295 if ($errorcode) {
296 $loginurl->param('errorcode', $errorcode);
299 redirect($loginurl->out(false));
302 // make sure we really are on the https page when https login required
303 $PAGE->verify_https_required();
305 /// Generate the login page with forms
307 if (!isset($frm) or !is_object($frm)) {
308 $frm = new stdClass();
311 if (empty($frm->username) && $authsequence[0] != 'shibboleth') { // See bug 5184
312 if (!empty($_GET["username"])) {
313 // we do not want data from _POST here
314 $frm->username = clean_param($_GET["username"], PARAM_RAW); // we do not want data from _POST here
315 } else {
316 $frm->username = get_moodle_cookie();
319 $frm->password = "";
322 if (!empty($SESSION->loginerrormsg)) {
323 // We had some errors before redirect, show them now.
324 $errormsg = $SESSION->loginerrormsg;
325 unset($SESSION->loginerrormsg);
327 } else if ($testsession) {
328 // No need to redirect here.
329 unset($SESSION->loginerrormsg);
331 } else if ($errormsg or !empty($frm->password)) {
332 // We must redirect after every password submission.
333 if ($errormsg) {
334 $SESSION->loginerrormsg = $errormsg;
336 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
339 $PAGE->set_title("$site->fullname: $loginsite");
340 $PAGE->set_heading("$site->fullname");
342 echo $OUTPUT->header();
344 if (isloggedin() and !isguestuser()) {
345 // prevent logging when already logged in, we do not want them to relogin by accident because sesskey would be changed
346 echo $OUTPUT->box_start();
347 $logout = new single_button(new moodle_url($CFG->httpswwwroot.'/login/logout.php', array('sesskey'=>sesskey(),'loginpage'=>1)), get_string('logout'), 'post');
348 $continue = new single_button(new moodle_url($CFG->httpswwwroot.'/login/index.php', array('cancel'=>1)), get_string('cancel'), 'get');
349 echo $OUTPUT->confirm(get_string('alreadyloggedin', 'error', fullname($USER)), $logout, $continue);
350 echo $OUTPUT->box_end();
351 } else {
352 $loginform = new \core_auth\output\login($authsequence, $frm->username);
353 $loginform->set_error($errormsg);
354 echo $OUTPUT->render($loginform);
357 echo $OUTPUT->footer();