MDL-65978 blog: Fix removing associations
[moodle.git] / login / index.php
blobe6b6087dcf4d41f22b63a4fa0e50d9ce7a8007eb
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 $loginredirect = optional_param('loginredirect', 1, PARAM_BOOL); // Used to bypass alternateloginurl.
36 $resendconfirmemail = optional_param('resendconfirmemail', false, PARAM_BOOL);
38 // It might be safe to do this for non-Behat sites, or there might
39 // be a security risk. For now we only allow it on Behat sites.
40 // If you wants to do the analysis, you may be able to remove the
41 // if (BEHAT_SITE_RUNNING).
42 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
43 $wantsurl = optional_param('wantsurl', '', PARAM_LOCALURL); // Overrides $SESSION->wantsurl if given.
44 if ($wantsurl !== '') {
45 $SESSION->wantsurl = (new moodle_url($wantsurl))->out(false);
49 $context = context_system::instance();
50 $PAGE->set_url("$CFG->wwwroot/login/index.php");
51 $PAGE->set_context($context);
52 $PAGE->set_pagelayout('login');
54 /// Initialize variables
55 $errormsg = '';
56 $infomsg = '';
57 $errorcode = 0;
59 // login page requested session test
60 if ($testsession) {
61 if ($testsession == $USER->id) {
62 if (isset($SESSION->wantsurl)) {
63 $urltogo = $SESSION->wantsurl;
64 } else {
65 $urltogo = $CFG->wwwroot.'/';
67 unset($SESSION->wantsurl);
68 redirect($urltogo);
69 } else {
70 // TODO: try to find out what is the exact reason why sessions do not work
71 $errormsg = get_string("cookiesnotenabled");
72 $errorcode = 1;
76 /// Check for timed out sessions
77 if (!empty($SESSION->has_timed_out)) {
78 $session_has_timed_out = true;
79 unset($SESSION->has_timed_out);
80 } else {
81 $session_has_timed_out = false;
84 $frm = false;
85 $user = false;
87 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
88 foreach($authsequence as $authname) {
89 $authplugin = get_auth_plugin($authname);
90 // The auth plugin's loginpage_hook() can eventually set $frm and/or $user.
91 $authplugin->loginpage_hook();
95 /// Define variables used in page
96 $site = get_site();
98 // Ignore any active pages in the navigation/settings.
99 // We do this because there won't be an active page there, and by ignoring the active pages the
100 // navigation and settings won't be initialised unless something else needs them.
101 $PAGE->navbar->ignore_active();
102 $loginsite = get_string("loginsite");
103 $PAGE->navbar->add($loginsite);
105 if ($user !== false or $frm !== false or $errormsg !== '') {
106 // some auth plugin already supplied full user, fake form data or prevented user login with error message
108 } else if (!empty($SESSION->wantsurl) && file_exists($CFG->dirroot.'/login/weblinkauth.php')) {
109 // Handles the case of another Moodle site linking into a page on this site
110 //TODO: move weblink into own auth plugin
111 include($CFG->dirroot.'/login/weblinkauth.php');
112 if (function_exists('weblink_auth')) {
113 $user = weblink_auth($SESSION->wantsurl);
115 if ($user) {
116 $frm->username = $user->username;
117 } else {
118 $frm = data_submitted();
121 } else {
122 $frm = data_submitted();
125 // Restore the #anchor to the original wantsurl. Note that this
126 // will only work for internal auth plugins, SSO plugins such as
127 // SAML / CAS / OIDC will have to handle this correctly directly.
128 if ($anchor && isset($SESSION->wantsurl) && strpos($SESSION->wantsurl, '#') === false) {
129 $wantsurl = new moodle_url($SESSION->wantsurl);
130 $wantsurl->set_anchor(substr($anchor, 1));
131 $SESSION->wantsurl = $wantsurl->out();
134 /// Check if the user has actually submitted login data to us
136 if ($frm and isset($frm->username)) { // Login WITH cookies
138 $frm->username = trim(core_text::strtolower($frm->username));
140 if (is_enabled_auth('none') ) {
141 if ($frm->username !== core_user::clean_field($frm->username, 'username')) {
142 $errormsg = get_string('username').': '.get_string("invalidusername");
143 $errorcode = 2;
144 $user = null;
148 if ($user) {
149 // The auth plugin has already provided the user via the loginpage_hook() called above.
150 } else if (($frm->username == 'guest') and empty($CFG->guestloginbutton)) {
151 $user = false; /// Can't log in as guest if guest button is disabled
152 $frm = false;
153 } else {
154 if (empty($errormsg)) {
155 $logintoken = isset($frm->logintoken) ? $frm->logintoken : '';
156 $loginrecaptcha = $frm->{'g-recaptcha-response'} ?? false;
157 $user = authenticate_user_login($frm->username, $frm->password, false, $errorcode, $logintoken, $loginrecaptcha);
161 // Intercept 'restored' users to provide them with info & reset password
162 if (!$user and $frm and is_restored_user($frm->username)) {
163 $PAGE->set_title(get_string('restoredaccount'));
164 $PAGE->set_heading($site->fullname);
165 echo $OUTPUT->header();
166 echo $OUTPUT->heading(get_string('restoredaccount'));
167 echo $OUTPUT->box(get_string('restoredaccountinfo'), 'generalbox boxaligncenter');
168 require_once('restored_password_form.php'); // Use our "supplanter" login_forgot_password_form. MDL-20846
169 $form = new login_forgot_password_form('forgot_password.php', array('username' => $frm->username));
170 $form->display();
171 echo $OUTPUT->footer();
172 die;
175 if ($user) {
177 // language setup
178 if (isguestuser($user)) {
179 // no predefined language for guests - use existing session or default site lang
180 unset($user->lang);
182 } else if (!empty($user->lang)) {
183 // unset previous session language - use user preference instead
184 unset($SESSION->lang);
187 if (empty($user->confirmed)) { // This account was never confirmed
188 $PAGE->set_title(get_string("mustconfirm"));
189 $PAGE->set_heading($site->fullname);
190 echo $OUTPUT->header();
191 echo $OUTPUT->heading(get_string("mustconfirm"));
192 if ($resendconfirmemail) {
193 if (!send_confirmation_email($user)) {
194 echo $OUTPUT->notification(get_string('emailconfirmsentfailure'), \core\output\notification::NOTIFY_ERROR);
195 } else {
196 echo $OUTPUT->notification(get_string('emailconfirmsentsuccess'), \core\output\notification::NOTIFY_SUCCESS);
199 echo $OUTPUT->box(get_string("emailconfirmsent", "", s($user->email)), "generalbox boxaligncenter");
200 $resendconfirmurl = new moodle_url('/login/index.php',
202 'username' => $frm->username,
203 'password' => $frm->password,
204 'resendconfirmemail' => true,
205 'logintoken' => \core\session\manager::get_login_token()
208 echo $OUTPUT->single_button($resendconfirmurl, get_string('emailconfirmationresend'));
209 echo $OUTPUT->footer();
210 die;
213 /// Let's get them all set up.
214 complete_user_login($user);
216 \core\session\manager::apply_concurrent_login_limit($user->id, session_id());
218 // sets the username cookie
219 if (!empty($CFG->nolastloggedin)) {
220 // do not store last logged in user in cookie
221 // auth plugins can temporarily override this from loginpage_hook()
222 // do not save $CFG->nolastloggedin in database!
224 } else if (empty($CFG->rememberusername)) {
225 // no permanent cookies, delete old one if exists
226 set_moodle_cookie('');
228 } else {
229 set_moodle_cookie($USER->username);
232 $urltogo = core_login_get_return_url();
234 /// check if user password has expired
235 /// Currently supported only for ldap-authentication module
236 $userauth = get_auth_plugin($USER->auth);
237 if (!isguestuser() and !empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
238 $externalchangepassword = false;
239 if ($userauth->can_change_password()) {
240 $passwordchangeurl = $userauth->change_password_url();
241 if (!$passwordchangeurl) {
242 $passwordchangeurl = $CFG->wwwroot.'/login/change_password.php';
243 } else {
244 $externalchangepassword = true;
246 } else {
247 $passwordchangeurl = $CFG->wwwroot.'/login/change_password.php';
249 $days2expire = $userauth->password_expire($USER->username);
250 $PAGE->set_title($loginsite);
251 $PAGE->set_heading("$site->fullname");
252 if (intval($days2expire) > 0 && intval($days2expire) < intval($userauth->config->expiration_warning)) {
253 echo $OUTPUT->header();
254 echo $OUTPUT->confirm(get_string('auth_passwordwillexpire', 'auth', $days2expire), $passwordchangeurl, $urltogo);
255 echo $OUTPUT->footer();
256 exit;
257 } elseif (intval($days2expire) < 0 ) {
258 if ($externalchangepassword) {
259 // We end the session if the change password form is external. This prevents access to the site
260 // until the password is correctly changed.
261 require_logout();
262 } else {
263 // If we use the standard change password form, this user preference will be reset when the password
264 // is changed. Until then it will prevent access to the site.
265 set_user_preference('auth_forcepasswordchange', 1, $USER);
267 echo $OUTPUT->header();
268 echo $OUTPUT->confirm(get_string('auth_passwordisexpired', 'auth'), $passwordchangeurl, $urltogo);
269 echo $OUTPUT->footer();
270 exit;
274 // Discard any errors before the last redirect.
275 unset($SESSION->loginerrormsg);
276 unset($SESSION->logininfomsg);
278 // Discard loginredirect if we are redirecting away.
279 unset($SESSION->loginredirect);
281 // test the session actually works by redirecting to self
282 $SESSION->wantsurl = $urltogo;
283 redirect(new moodle_url(get_login_url(), array('testsession'=>$USER->id)));
285 } else {
286 if (empty($errormsg)) {
287 if ($errorcode == AUTH_LOGIN_UNAUTHORISED) {
288 $errormsg = get_string("unauthorisedlogin", "", $frm->username);
289 } else if ($errorcode == AUTH_LOGIN_FAILED_RECAPTCHA) {
290 $errormsg = get_string('missingrecaptchachallengefield');
291 } else {
292 $errormsg = get_string("invalidlogin");
293 $errorcode = 3;
299 /// Detect problems with timedout sessions
300 if ($session_has_timed_out and !data_submitted()) {
301 $errormsg = get_string('sessionerroruser', 'error');
302 $errorcode = 4;
305 /// First, let's remember where the user was trying to get to before they got here
307 if (empty($SESSION->wantsurl)) {
308 $SESSION->wantsurl = null;
309 $referer = get_local_referer(false);
310 if ($referer &&
311 $referer != $CFG->wwwroot &&
312 $referer != $CFG->wwwroot . '/' &&
313 $referer != $CFG->wwwroot . '/login/' &&
314 strpos($referer, $CFG->wwwroot . '/login/?') !== 0 &&
315 strpos($referer, $CFG->wwwroot . '/login/index.php') !== 0) { // There might be some extra params such as ?lang=.
316 $SESSION->wantsurl = $referer;
320 // Check if loginredirect is set in the SESSION.
321 if ($errorcode && isset($SESSION->loginredirect)) {
322 $loginredirect = $SESSION->loginredirect;
324 $SESSION->loginredirect = $loginredirect;
326 /// Redirect to alternative login URL if needed
327 if (!empty($CFG->alternateloginurl) && $loginredirect) {
328 $loginurl = new moodle_url($CFG->alternateloginurl);
330 $loginurlstr = $loginurl->out(false);
332 if ($SESSION->wantsurl != '' && strpos($SESSION->wantsurl, $loginurlstr) === 0) {
333 // We do not want to return to alternate url.
334 $SESSION->wantsurl = null;
337 // If error code then add that to url.
338 if ($errorcode) {
339 $loginurl->param('errorcode', $errorcode);
342 redirect($loginurl->out(false));
345 /// Generate the login page with forms
347 if (!isset($frm) or !is_object($frm)) {
348 $frm = new stdClass();
351 if (empty($frm->username) && $authsequence[0] != 'shibboleth') { // See bug 5184
352 if (!empty($_GET["username"])) {
353 // we do not want data from _POST here
354 $frm->username = clean_param($_GET["username"], PARAM_RAW); // we do not want data from _POST here
355 } else {
356 $frm->username = get_moodle_cookie();
359 $frm->password = "";
362 if (!empty($SESSION->loginerrormsg) || !empty($SESSION->logininfomsg)) {
363 // We had some messages before redirect, show them now.
364 $errormsg = $SESSION->loginerrormsg ?? '';
365 $infomsg = $SESSION->logininfomsg ?? '';
366 unset($SESSION->loginerrormsg);
367 unset($SESSION->logininfomsg);
369 } else if ($testsession) {
370 // No need to redirect here.
371 unset($SESSION->loginerrormsg);
372 unset($SESSION->logininfomsg);
374 } else if ($errormsg or !empty($frm->password)) {
375 // We must redirect after every password submission.
376 if ($errormsg) {
377 $SESSION->loginerrormsg = $errormsg;
380 // Add redirect param to url.
381 $loginurl = new moodle_url('/login/index.php');
382 $loginurl->param('loginredirect', $SESSION->loginredirect);
384 redirect($loginurl->out(false));
387 $PAGE->set_title($loginsite);
388 $PAGE->set_heading("$site->fullname");
390 echo $OUTPUT->header();
392 if (isloggedin() and !isguestuser()) {
393 // prevent logging when already logged in, we do not want them to relogin by accident because sesskey would be changed
394 echo $OUTPUT->box_start();
395 $logout = new single_button(new moodle_url('/login/logout.php', array('sesskey'=>sesskey(),'loginpage'=>1)), get_string('logout'), 'post');
396 $continue = new single_button(new moodle_url('/'), get_string('cancel'), 'get');
397 echo $OUTPUT->confirm(get_string('alreadyloggedin', 'error', fullname($USER)), $logout, $continue);
398 echo $OUTPUT->box_end();
399 } else {
400 $loginform = new \core_auth\output\login($authsequence, $frm->username);
401 $loginform->set_error($errormsg);
402 $loginform->set_info($infomsg);
403 echo $OUTPUT->render($loginform);
406 echo $OUTPUT->footer();