on-demand release 3.7dev+
[moodle.git] / login / index.php
bloba04970acfffbc7ccca2fb72f2defbad0d7111af7
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 $context = context_system::instance();
38 $PAGE->set_url("$CFG->wwwroot/login/index.php");
39 $PAGE->set_context($context);
40 $PAGE->set_pagelayout('login');
42 /// Initialize variables
43 $errormsg = '';
44 $errorcode = 0;
46 // login page requested session test
47 if ($testsession) {
48 if ($testsession == $USER->id) {
49 if (isset($SESSION->wantsurl)) {
50 $urltogo = $SESSION->wantsurl;
51 } else {
52 $urltogo = $CFG->wwwroot.'/';
54 unset($SESSION->wantsurl);
55 redirect($urltogo);
56 } else {
57 // TODO: try to find out what is the exact reason why sessions do not work
58 $errormsg = get_string("cookiesnotenabled");
59 $errorcode = 1;
63 /// Check for timed out sessions
64 if (!empty($SESSION->has_timed_out)) {
65 $session_has_timed_out = true;
66 unset($SESSION->has_timed_out);
67 } else {
68 $session_has_timed_out = false;
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 // The auth plugin's loginpage_hook() can eventually set $frm and/or $user.
78 $authplugin->loginpage_hook();
82 /// Define variables used in page
83 $site = get_site();
85 // Ignore any active pages in the navigation/settings.
86 // We do this because there won't be an active page there, and by ignoring the active pages the
87 // navigation and settings won't be initialised unless something else needs them.
88 $PAGE->navbar->ignore_active();
89 $loginsite = get_string("loginsite");
90 $PAGE->navbar->add($loginsite);
92 if ($user !== false or $frm !== false or $errormsg !== '') {
93 // some auth plugin already supplied full user, fake form data or prevented user login with error message
95 } else if (!empty($SESSION->wantsurl) && file_exists($CFG->dirroot.'/login/weblinkauth.php')) {
96 // Handles the case of another Moodle site linking into a page on this site
97 //TODO: move weblink into own auth plugin
98 include($CFG->dirroot.'/login/weblinkauth.php');
99 if (function_exists('weblink_auth')) {
100 $user = weblink_auth($SESSION->wantsurl);
102 if ($user) {
103 $frm->username = $user->username;
104 } else {
105 $frm = data_submitted();
108 } else {
109 $frm = data_submitted();
112 // Restore the #anchor to the original wantsurl. Note that this
113 // will only work for internal auth plugins, SSO plugins such as
114 // SAML / CAS / OIDC will have to handle this correctly directly.
115 if ($anchor && isset($SESSION->wantsurl) && strpos($SESSION->wantsurl, '#') === false) {
116 $wantsurl = new moodle_url($SESSION->wantsurl);
117 $wantsurl->set_anchor(substr($anchor, 1));
118 $SESSION->wantsurl = $wantsurl->out();
121 /// Check if the user has actually submitted login data to us
123 if ($frm and isset($frm->username)) { // Login WITH cookies
125 $frm->username = trim(core_text::strtolower($frm->username));
127 if (is_enabled_auth('none') ) {
128 if ($frm->username !== core_user::clean_field($frm->username, 'username')) {
129 $errormsg = get_string('username').': '.get_string("invalidusername");
130 $errorcode = 2;
131 $user = null;
135 if ($user) {
136 // The auth plugin has already provided the user via the loginpage_hook() called above.
137 } else if (($frm->username == 'guest') and empty($CFG->guestloginbutton)) {
138 $user = false; /// Can't log in as guest if guest button is disabled
139 $frm = false;
140 } else {
141 if (empty($errormsg)) {
142 $logintoken = isset($frm->logintoken) ? $frm->logintoken : '';
143 $user = authenticate_user_login($frm->username, $frm->password, false, $errorcode, $logintoken);
147 // Intercept 'restored' users to provide them with info & reset password
148 if (!$user and $frm and is_restored_user($frm->username)) {
149 $PAGE->set_title(get_string('restoredaccount'));
150 $PAGE->set_heading($site->fullname);
151 echo $OUTPUT->header();
152 echo $OUTPUT->heading(get_string('restoredaccount'));
153 echo $OUTPUT->box(get_string('restoredaccountinfo'), 'generalbox boxaligncenter');
154 require_once('restored_password_form.php'); // Use our "supplanter" login_forgot_password_form. MDL-20846
155 $form = new login_forgot_password_form('forgot_password.php', array('username' => $frm->username));
156 $form->display();
157 echo $OUTPUT->footer();
158 die;
161 if ($user) {
163 // language setup
164 if (isguestuser($user)) {
165 // no predefined language for guests - use existing session or default site lang
166 unset($user->lang);
168 } else if (!empty($user->lang)) {
169 // unset previous session language - use user preference instead
170 unset($SESSION->lang);
173 if (empty($user->confirmed)) { // This account was never confirmed
174 $PAGE->set_title(get_string("mustconfirm"));
175 $PAGE->set_heading($site->fullname);
176 echo $OUTPUT->header();
177 echo $OUTPUT->heading(get_string("mustconfirm"));
178 if ($resendconfirmemail) {
179 if (!send_confirmation_email($user)) {
180 echo $OUTPUT->notification(get_string('emailconfirmsentfailure'), \core\output\notification::NOTIFY_ERROR);
181 } else {
182 echo $OUTPUT->notification(get_string('emailconfirmsentsuccess'), \core\output\notification::NOTIFY_SUCCESS);
185 echo $OUTPUT->box(get_string("emailconfirmsent", "", $user->email), "generalbox boxaligncenter");
186 $resendconfirmurl = new moodle_url('/login/index.php',
188 'username' => $frm->username,
189 'password' => $frm->password,
190 'resendconfirmemail' => true
193 echo $OUTPUT->single_button($resendconfirmurl, get_string('emailconfirmationresend'));
194 echo $OUTPUT->footer();
195 die;
198 /// Let's get them all set up.
199 complete_user_login($user);
201 \core\session\manager::apply_concurrent_login_limit($user->id, session_id());
203 // sets the username cookie
204 if (!empty($CFG->nolastloggedin)) {
205 // do not store last logged in user in cookie
206 // auth plugins can temporarily override this from loginpage_hook()
207 // do not save $CFG->nolastloggedin in database!
209 } else if (empty($CFG->rememberusername) or ($CFG->rememberusername == 2 and empty($frm->rememberusername))) {
210 // no permanent cookies, delete old one if exists
211 set_moodle_cookie('');
213 } else {
214 set_moodle_cookie($USER->username);
217 $urltogo = core_login_get_return_url();
219 /// check if user password has expired
220 /// Currently supported only for ldap-authentication module
221 $userauth = get_auth_plugin($USER->auth);
222 if (!isguestuser() and !empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
223 $externalchangepassword = false;
224 if ($userauth->can_change_password()) {
225 $passwordchangeurl = $userauth->change_password_url();
226 if (!$passwordchangeurl) {
227 $passwordchangeurl = $CFG->wwwroot.'/login/change_password.php';
228 } else {
229 $externalchangepassword = true;
231 } else {
232 $passwordchangeurl = $CFG->wwwroot.'/login/change_password.php';
234 $days2expire = $userauth->password_expire($USER->username);
235 $PAGE->set_title("$site->fullname: $loginsite");
236 $PAGE->set_heading("$site->fullname");
237 if (intval($days2expire) > 0 && intval($days2expire) < intval($userauth->config->expiration_warning)) {
238 echo $OUTPUT->header();
239 echo $OUTPUT->confirm(get_string('auth_passwordwillexpire', 'auth', $days2expire), $passwordchangeurl, $urltogo);
240 echo $OUTPUT->footer();
241 exit;
242 } elseif (intval($days2expire) < 0 ) {
243 if ($externalchangepassword) {
244 // We end the session if the change password form is external. This prevents access to the site
245 // until the password is correctly changed.
246 require_logout();
247 } else {
248 // If we use the standard change password form, this user preference will be reset when the password
249 // is changed. Until then it will prevent access to the site.
250 set_user_preference('auth_forcepasswordchange', 1, $USER);
252 echo $OUTPUT->header();
253 echo $OUTPUT->confirm(get_string('auth_passwordisexpired', 'auth'), $passwordchangeurl, $urltogo);
254 echo $OUTPUT->footer();
255 exit;
259 // Discard any errors before the last redirect.
260 unset($SESSION->loginerrormsg);
262 // test the session actually works by redirecting to self
263 $SESSION->wantsurl = $urltogo;
264 redirect(new moodle_url(get_login_url(), array('testsession'=>$USER->id)));
266 } else {
267 if (empty($errormsg)) {
268 if ($errorcode == AUTH_LOGIN_UNAUTHORISED) {
269 $errormsg = get_string("unauthorisedlogin", "", $frm->username);
270 } else {
271 $errormsg = get_string("invalidlogin");
272 $errorcode = 3;
278 /// Detect problems with timedout sessions
279 if ($session_has_timed_out and !data_submitted()) {
280 $errormsg = get_string('sessionerroruser', 'error');
281 $errorcode = 4;
284 /// First, let's remember where the user was trying to get to before they got here
286 if (empty($SESSION->wantsurl)) {
287 $SESSION->wantsurl = null;
288 $referer = get_local_referer(false);
289 if ($referer &&
290 $referer != $CFG->wwwroot &&
291 $referer != $CFG->wwwroot . '/' &&
292 $referer != $CFG->wwwroot . '/login/' &&
293 strpos($referer, $CFG->wwwroot . '/login/?') !== 0 &&
294 strpos($referer, $CFG->wwwroot . '/login/index.php') !== 0) { // There might be some extra params such as ?lang=.
295 $SESSION->wantsurl = $referer;
299 /// Redirect to alternative login URL if needed
300 if (!empty($CFG->alternateloginurl)) {
301 $loginurl = new moodle_url($CFG->alternateloginurl);
303 $loginurlstr = $loginurl->out(false);
305 if (strpos($SESSION->wantsurl, $loginurlstr) === 0) {
306 // We do not want to return to alternate url.
307 $SESSION->wantsurl = null;
310 // If error code then add that to url.
311 if ($errorcode) {
312 $loginurl->param('errorcode', $errorcode);
315 redirect($loginurl->out(false));
318 /// Generate the login page with forms
320 if (!isset($frm) or !is_object($frm)) {
321 $frm = new stdClass();
324 if (empty($frm->username) && $authsequence[0] != 'shibboleth') { // See bug 5184
325 if (!empty($_GET["username"])) {
326 // we do not want data from _POST here
327 $frm->username = clean_param($_GET["username"], PARAM_RAW); // we do not want data from _POST here
328 } else {
329 $frm->username = get_moodle_cookie();
332 $frm->password = "";
335 if (!empty($SESSION->loginerrormsg)) {
336 // We had some errors before redirect, show them now.
337 $errormsg = $SESSION->loginerrormsg;
338 unset($SESSION->loginerrormsg);
340 } else if ($testsession) {
341 // No need to redirect here.
342 unset($SESSION->loginerrormsg);
344 } else if ($errormsg or !empty($frm->password)) {
345 // We must redirect after every password submission.
346 if ($errormsg) {
347 $SESSION->loginerrormsg = $errormsg;
349 redirect(new moodle_url('/login/index.php'));
352 $PAGE->set_title("$site->fullname: $loginsite");
353 $PAGE->set_heading("$site->fullname");
355 echo $OUTPUT->header();
357 if (isloggedin() and !isguestuser()) {
358 // prevent logging when already logged in, we do not want them to relogin by accident because sesskey would be changed
359 echo $OUTPUT->box_start();
360 $logout = new single_button(new moodle_url('/login/logout.php', array('sesskey'=>sesskey(),'loginpage'=>1)), get_string('logout'), 'post');
361 $continue = new single_button(new moodle_url('/'), get_string('cancel'), 'get');
362 echo $OUTPUT->confirm(get_string('alreadyloggedin', 'error', fullname($USER)), $logout, $continue);
363 echo $OUTPUT->box_end();
364 } else {
365 $loginform = new \core_auth\output\login($authsequence, $frm->username);
366 $loginform->set_error($errormsg);
367 echo $OUTPUT->render($loginform);
370 echo $OUTPUT->footer();