Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
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.
14
//
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/>.
17
 
18
/**
19
 * Main login page.
20
 *
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
25
 */
26
 
27
require('../config.php');
28
require_once('lib.php');
29
 
30
redirect_if_major_upgrade_required();
31
 
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.
35
 
36
$resendconfirmemail = optional_param('resendconfirmemail', false, PARAM_BOOL);
37
 
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);
46
    }
47
}
48
 
49
$context = context_system::instance();
50
$PAGE->set_url("$CFG->wwwroot/login/index.php");
51
$PAGE->set_context($context);
52
$PAGE->set_pagelayout('login');
53
 
54
/// Initialize variables
55
$errormsg = '';
56
$infomsg = '';
57
$errorcode = 0;
58
 
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.'/';
66
        }
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;
73
    }
74
}
75
 
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;
82
}
83
 
84
$frm  = false;
85
$user = false;
86
 
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();
92
}
93
 
94
 
95
/// Define variables used in page
96
$site = get_site();
97
 
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);
104
 
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
107
 
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);
114
    }
115
    if ($user) {
116
        $frm->username = $user->username;
117
    } else {
118
        $frm = data_submitted();
119
    }
120
 
121
} else {
122
    $frm = data_submitted();
123
}
124
 
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();
132
}
133
 
134
/// Check if the user has actually submitted login data to us
135
 
136
if ($frm and isset($frm->username)) {                             // Login WITH cookies
137
 
138
    $frm->username = trim(core_text::strtolower($frm->username));
139
 
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;
145
        }
146
    }
147
 
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 = login_captcha_enabled() ? $frm->{'g-recaptcha-response'} ?? '' : false;
157
            $user = authenticate_user_login($frm->username, $frm->password, false, $errorcode, $logintoken, $loginrecaptcha);
158
        }
159
    }
160
 
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;
173
    }
174
 
175
    if ($user) {
176
 
177
        // language setup
178
        if (isguestuser($user)) {
179
            // no predefined language for guests - use existing session or default site lang
180
            unset($user->lang);
181
 
182
        } else if (!empty($user->lang)) {
183
            // unset previous session language - use user preference instead
184
            unset($SESSION->lang);
185
        }
186
 
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);
197
                }
198
            }
199
            echo $OUTPUT->box(get_string("emailconfirmsent", "", s($user->email)), "generalbox boxaligncenter");
200
            $resendconfirmurl = new moodle_url('/login/index.php',
201
                [
202
                    'username' => $frm->username,
203
                    'password' => $frm->password,
204
                    'resendconfirmemail' => true,
205
                    'logintoken' => \core\session\manager::get_login_token()
206
                ]
207
            );
208
            echo $OUTPUT->single_button($resendconfirmurl, get_string('emailconfirmationresend'));
209
            echo $OUTPUT->footer();
210
            die;
211
        }
212
 
213
    /// Let's get them all set up.
214
        complete_user_login($user);
215
 
216
        \core\session\manager::apply_concurrent_login_limit($user->id, session_id());
217
 
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!
223
 
224
        } else if (empty($CFG->rememberusername)) {
225
            // no permanent cookies, delete old one if exists
226
            set_moodle_cookie('');
227
 
228
        } else {
229
            set_moodle_cookie($USER->username);
230
        }
231
 
232
        $urltogo = core_login_get_return_url();
233
 
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;
245
                }
246
            } else {
247
                $passwordchangeurl = $CFG->wwwroot.'/login/change_password.php';
248
            }
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);
266
                }
267
                echo $OUTPUT->header();
268
                echo $OUTPUT->confirm(get_string('auth_passwordisexpired', 'auth'), $passwordchangeurl, $urltogo);
269
                echo $OUTPUT->footer();
270
                exit;
271
            }
272
        }
273
 
274
        // Discard any errors before the last redirect.
275
        unset($SESSION->loginerrormsg);
276
        unset($SESSION->logininfomsg);
277
 
278
        // Discard loginredirect if we are redirecting away.
279
        unset($SESSION->loginredirect);
280
 
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)));
284
 
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;
294
            }
295
        }
296
    }
297
}
298
 
299
/// Detect problems with timedout sessions
300
if ($session_has_timed_out and !data_submitted()) {
301
    $errormsg = get_string('sessionerroruser', 'error');
302
    $errorcode = 4;
303
}
304
 
305
/// First, let's remember where the user was trying to get to before they got here
306
 
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;
317
    }
318
}
319
 
320
// Check if loginredirect is set in the SESSION.
321
if ($errorcode && isset($SESSION->loginredirect)) {
322
    $loginredirect = $SESSION->loginredirect;
323
}
324
$SESSION->loginredirect = $loginredirect;
325
 
326
/// Redirect to alternative login URL if needed
327
if (!empty($CFG->alternateloginurl) && $loginredirect) {
328
    $loginurl = new moodle_url($CFG->alternateloginurl);
329
 
330
    $loginurlstr = $loginurl->out(false);
331
 
332
    if ($SESSION->wantsurl != '' && strpos($SESSION->wantsurl, $loginurlstr) === 0) {
333
        // We do not want to return to alternate url.
334
        $SESSION->wantsurl = null;
335
    }
336
 
337
    // If error code then add that to url.
338
    if ($errorcode) {
339
        $loginurl->param('errorcode', $errorcode);
340
    }
341
 
342
    redirect($loginurl->out(false));
343
}
344
 
345
/// Generate the login page with forms
346
 
347
if (!isset($frm) or !is_object($frm)) {
348
    $frm = new stdClass();
349
}
350
 
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();
357
    }
358
 
359
    $frm->password = "";
360
}
361
 
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);
368
 
369
} else if ($testsession) {
370
    // No need to redirect here.
371
    unset($SESSION->loginerrormsg);
372
    unset($SESSION->logininfomsg);
373
 
374
} else if ($errormsg or !empty($frm->password)) {
375
    // We must redirect after every password submission.
376
    if ($errormsg) {
377
        $SESSION->loginerrormsg = $errormsg;
378
    }
379
 
380
    // Add redirect param to url.
381
    $loginurl = new moodle_url('/login/index.php');
382
    $loginurl->param('loginredirect', $SESSION->loginredirect);
383
 
384
    redirect($loginurl->out(false));
385
}
386
 
387
$PAGE->set_title($loginsite);
388
$PAGE->set_heading("$site->fullname");
389
 
390
echo $OUTPUT->header();
391
 
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);
404
}
405
 
406
echo $OUTPUT->footer();