Merge branch 'MDL-68955' of https://github.com/Chocolate-lightning/moodle
[moodle.git] / login / lib.php
blobe0644050bdb2322629f32c44d16f0563e4cc1539
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
19 * Login library file of login/password related Moodle functions.
21 * @package core
22 * @subpackage lib
23 * @copyright Catalyst IT
24 * @copyright Peter Bulmer
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
30 define('PWRESET_STATUS_NOEMAILSENT', 1);
31 define('PWRESET_STATUS_TOKENSENT', 2);
32 define('PWRESET_STATUS_OTHEREMAILSENT', 3);
33 define('PWRESET_STATUS_ALREADYSENT', 4);
35 /**
36 * Processes a user's request to set a new password in the event they forgot the old one.
37 * If no user identifier has been supplied, it displays a form where they can submit their identifier.
38 * Where they have supplied identifier, the function will check their status, and send email as appropriate.
40 function core_login_process_password_reset_request() {
41 global $OUTPUT, $PAGE;
42 $mform = new login_forgot_password_form();
44 if ($mform->is_cancelled()) {
45 redirect(get_login_url());
47 } else if ($data = $mform->get_data()) {
49 $username = $email = '';
50 if (!empty($data->username)) {
51 $username = $data->username;
52 } else {
53 $email = $data->email;
55 list($status, $notice, $url) = core_login_process_password_reset($username, $email);
57 // Plugins can perform post forgot password actions once data has been validated.
58 core_login_post_forgot_password_requests($data);
60 // Any email has now been sent.
61 // Next display results to requesting user if settings permit.
62 echo $OUTPUT->header();
63 notice($notice, $url);
64 die; // Never reached.
67 // DISPLAY FORM.
69 echo $OUTPUT->header();
70 echo $OUTPUT->box(get_string('passwordforgotteninstructions2'), 'generalbox boxwidthnormal boxaligncenter');
71 $mform->display();
73 echo $OUTPUT->footer();
76 /**
77 * Process the password reset for the given user (via username or email).
79 * @param string $username the user name
80 * @param string $email the user email
81 * @return array an array containing fields indicating the reset status, a info notice and redirect URL.
82 * @since Moodle 3.4
84 function core_login_process_password_reset($username, $email) {
85 global $CFG, $DB;
87 if (empty($username) && empty($email)) {
88 print_error('cannotmailconfirm');
91 // Next find the user account in the database which the requesting user claims to own.
92 if (!empty($username)) {
93 // Username has been specified - load the user record based on that.
94 $username = core_text::strtolower($username); // Mimic the login page process.
95 $userparams = array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 0, 'suspended' => 0);
96 $user = $DB->get_record('user', $userparams);
97 } else {
98 // Try to load the user record based on email address.
99 // This is tricky because:
100 // 1/ the email is not guaranteed to be unique - TODO: send email with all usernames to select the account for pw reset
101 // 2/ mailbox may be case sensitive, the email domain is case insensitive - let's pretend it is all case-insensitive.
103 // The case-insensitive + accent-sensitive search may be expensive as some DBs such as MySQL cannot use the
104 // index in that case. For that reason, we first perform accent-insensitive search in a subselect for potential
105 // candidates (which can use the index) and only then perform the additional accent-sensitive search on this
106 // limited set of records in the outer select.
107 $sql = "SELECT *
108 FROM {user}
109 WHERE " . $DB->sql_equal('email', ':email1', false, true) . "
110 AND id IN (SELECT id
111 FROM {user}
112 WHERE mnethostid = :mnethostid
113 AND deleted = 0
114 AND suspended = 0
115 AND " . $DB->sql_equal('email', ':email2', false, false) . ")";
117 $params = array(
118 'email1' => $email,
119 'email2' => $email,
120 'mnethostid' => $CFG->mnet_localhost_id,
123 $user = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE);
126 // Target user details have now been identified, or we know that there is no such account.
127 // Send email address to account's email address if appropriate.
128 $pwresetstatus = PWRESET_STATUS_NOEMAILSENT;
129 if ($user and !empty($user->confirmed)) {
130 $systemcontext = context_system::instance();
132 $userauth = get_auth_plugin($user->auth);
133 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)
134 or !has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
135 if (send_password_change_info($user)) {
136 $pwresetstatus = PWRESET_STATUS_OTHEREMAILSENT;
137 } else {
138 print_error('cannotmailconfirm');
140 } else {
141 // The account the requesting user claims to be is entitled to change their password.
142 // Next, check if they have an existing password reset in progress.
143 $resetinprogress = $DB->get_record('user_password_resets', array('userid' => $user->id));
144 if (empty($resetinprogress)) {
145 // Completely new reset request - common case.
146 $resetrecord = core_login_generate_password_reset($user);
147 $sendemail = true;
148 } else if ($resetinprogress->timerequested < (time() - $CFG->pwresettime)) {
149 // Preexisting, but expired request - delete old record & create new one.
150 // Uncommon case - expired requests are cleaned up by cron.
151 $DB->delete_records('user_password_resets', array('id' => $resetinprogress->id));
152 $resetrecord = core_login_generate_password_reset($user);
153 $sendemail = true;
154 } else if (empty($resetinprogress->timererequested)) {
155 // Preexisting, valid request. This is the first time user has re-requested the reset.
156 // Re-sending the same email once can actually help in certain circumstances
157 // eg by reducing the delay caused by greylisting.
158 $resetinprogress->timererequested = time();
159 $DB->update_record('user_password_resets', $resetinprogress);
160 $resetrecord = $resetinprogress;
161 $sendemail = true;
162 } else {
163 // Preexisting, valid request. User has already re-requested email.
164 $pwresetstatus = PWRESET_STATUS_ALREADYSENT;
165 $sendemail = false;
168 if ($sendemail) {
169 $sendresult = send_password_change_confirmation_email($user, $resetrecord);
170 if ($sendresult) {
171 $pwresetstatus = PWRESET_STATUS_TOKENSENT;
172 } else {
173 print_error('cannotmailconfirm');
179 $url = $CFG->wwwroot.'/index.php';
180 if (!empty($CFG->protectusernames)) {
181 // Neither confirm, nor deny existance of any username or email address in database.
182 // Print general (non-commital) message.
183 $status = 'emailpasswordconfirmmaybesent';
184 $notice = get_string($status);
185 } else if (empty($user)) {
186 // Protect usernames is off, and we couldn't find the user with details specified.
187 // Print failure advice.
188 $status = 'emailpasswordconfirmnotsent';
189 $notice = get_string($status);
190 $url = $CFG->wwwroot.'/forgot_password.php';
191 } else if (empty($user->email)) {
192 // User doesn't have an email set - can't send a password change confimation email.
193 $status = 'emailpasswordconfirmnoemail';
194 $notice = get_string($status);
195 } else if ($pwresetstatus == PWRESET_STATUS_ALREADYSENT) {
196 // User found, protectusernames is off, but user has already (re) requested a reset.
197 // Don't send a 3rd reset email.
198 $status = 'emailalreadysent';
199 $notice = get_string($status);
200 } else if ($pwresetstatus == PWRESET_STATUS_NOEMAILSENT) {
201 // User found, protectusernames is off, but user is not confirmed.
202 // Pretend we sent them an email.
203 // This is a big usability problem - need to tell users why we didn't send them an email.
204 // Obfuscate email address to protect privacy.
205 $protectedemail = preg_replace('/([^@]*)@(.*)/', '******@$2', $user->email);
206 $status = 'emailpasswordconfirmsent';
207 $notice = get_string($status, '', $protectedemail);
208 } else {
209 // Confirm email sent. (Obfuscate email address to protect privacy).
210 $protectedemail = preg_replace('/([^@]*)@(.*)/', '******@$2', $user->email);
211 // This is a small usability problem - may be obfuscating the email address which the user has just supplied.
212 $status = 'emailresetconfirmsent';
213 $notice = get_string($status, '', $protectedemail);
215 return array($status, $notice, $url);
219 * This function processes a user's submitted token to validate the request to set a new password.
220 * If the user's token is validated, they are prompted to set a new password.
221 * @param string $token the one-use identifier which should verify the password reset request as being valid.
222 * @return void
224 function core_login_process_password_set($token) {
225 global $DB, $CFG, $OUTPUT, $PAGE, $SESSION;
226 require_once($CFG->dirroot.'/user/lib.php');
228 $pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800;
229 $sql = "SELECT u.*, upr.token, upr.timerequested, upr.id as tokenid
230 FROM {user} u
231 JOIN {user_password_resets} upr ON upr.userid = u.id
232 WHERE upr.token = ?";
233 $user = $DB->get_record_sql($sql, array($token));
235 $forgotpasswordurl = "{$CFG->wwwroot}/login/forgot_password.php";
236 if (empty($user) or ($user->timerequested < (time() - $pwresettime - DAYSECS))) {
237 // There is no valid reset request record - not even a recently expired one.
238 // (suspicious)
239 // Direct the user to the forgot password page to request a password reset.
240 echo $OUTPUT->header();
241 notice(get_string('noresetrecord'), $forgotpasswordurl);
242 die; // Never reached.
244 if ($user->timerequested < (time() - $pwresettime)) {
245 // There is a reset record, but it's expired.
246 // Direct the user to the forgot password page to request a password reset.
247 $pwresetmins = floor($pwresettime / MINSECS);
248 echo $OUTPUT->header();
249 notice(get_string('resetrecordexpired', '', $pwresetmins), $forgotpasswordurl);
250 die; // Never reached.
253 if ($user->auth === 'nologin' or !is_enabled_auth($user->auth)) {
254 // Bad luck - user is not able to login, do not let them set password.
255 echo $OUTPUT->header();
256 print_error('forgotteninvalidurl');
257 die; // Never reached.
260 // Check this isn't guest user.
261 if (isguestuser($user)) {
262 print_error('cannotresetguestpwd');
265 // Token is correct, and unexpired.
266 $mform = new login_set_password_form(null, $user);
267 $data = $mform->get_data();
268 if (empty($data)) {
269 // User hasn't submitted form, they got here directly from email link.
270 // Next, display the form.
271 $setdata = new stdClass();
272 $setdata->username = $user->username;
273 $setdata->username2 = $user->username;
274 $setdata->token = $user->token;
275 $mform->set_data($setdata);
276 echo $OUTPUT->header();
277 echo $OUTPUT->box(get_string('setpasswordinstructions'), 'generalbox boxwidthnormal boxaligncenter');
278 $mform->display();
279 echo $OUTPUT->footer();
280 return;
281 } else {
282 // User has submitted form.
283 // Delete this token so it can't be used again.
284 $DB->delete_records('user_password_resets', array('id' => $user->tokenid));
285 $userauth = get_auth_plugin($user->auth);
286 if (!$userauth->user_update_password($user, $data->password)) {
287 print_error('errorpasswordupdate', 'auth');
289 user_add_password_history($user->id, $data->password);
290 if (!empty($CFG->passwordchangelogout)) {
291 \core\session\manager::kill_user_sessions($user->id, session_id());
293 // Reset login lockout (if present) before a new password is set.
294 login_unlock_account($user);
295 // Clear any requirement to change passwords.
296 unset_user_preference('auth_forcepasswordchange', $user);
297 unset_user_preference('create_password', $user);
299 if (!empty($user->lang)) {
300 // Unset previous session language - use user preference instead.
301 unset($SESSION->lang);
303 complete_user_login($user); // Triggers the login event.
305 \core\session\manager::apply_concurrent_login_limit($user->id, session_id());
307 $urltogo = core_login_get_return_url();
308 unset($SESSION->wantsurl);
310 // Plugins can perform post set password actions once data has been validated.
311 core_login_post_set_password_requests($data, $user);
313 redirect($urltogo, get_string('passwordset'), 1);
317 /** Create a new record in the database to track a new password set request for user.
318 * @param object $user the user record, the requester would like a new password set for.
319 * @return record created.
321 function core_login_generate_password_reset ($user) {
322 global $DB;
323 $resetrecord = new stdClass();
324 $resetrecord->timerequested = time();
325 $resetrecord->userid = $user->id;
326 $resetrecord->token = random_string(32);
327 $resetrecord->id = $DB->insert_record('user_password_resets', $resetrecord);
328 return $resetrecord;
331 /** Determine where a user should be redirected after they have been logged in.
332 * @return string url the user should be redirected to.
334 function core_login_get_return_url() {
335 global $CFG, $SESSION, $USER;
336 // Prepare redirection.
337 if (user_not_fully_set_up($USER, true)) {
338 $urltogo = $CFG->wwwroot.'/user/edit.php';
339 // We don't delete $SESSION->wantsurl yet, so we get there later.
341 } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0
342 or strpos($SESSION->wantsurl, str_replace('http://', 'https://', $CFG->wwwroot)) === 0)) {
343 $urltogo = $SESSION->wantsurl; // Because it's an address in this site.
344 unset($SESSION->wantsurl);
345 } else {
346 // No wantsurl stored or external - go to homepage.
347 $urltogo = $CFG->wwwroot.'/';
348 unset($SESSION->wantsurl);
351 // If the url to go to is the same as the site page, check for default homepage.
352 if ($urltogo == ($CFG->wwwroot . '/')) {
353 $homepage = get_home_page();
354 // Go to my-moodle page instead of site homepage if defaulthomepage set to homepage_my.
355 if ($homepage == HOMEPAGE_MY && !is_siteadmin() && !isguestuser()) {
356 if ($urltogo == $CFG->wwwroot or $urltogo == $CFG->wwwroot.'/' or $urltogo == $CFG->wwwroot.'/index.php') {
357 $urltogo = $CFG->wwwroot.'/my/';
361 return $urltogo;
365 * Validates the forgot password form data.
367 * This is used by the forgot_password_form and by the core_auth_request_password_rest WS.
368 * @param array $data array containing the data to be validated (email and username)
369 * @return array array of errors compatible with mform
370 * @since Moodle 3.4
372 function core_login_validate_forgot_password_data($data) {
373 global $CFG, $DB;
375 $errors = array();
377 if ((!empty($data['username']) and !empty($data['email'])) or (empty($data['username']) and empty($data['email']))) {
378 $errors['username'] = get_string('usernameoremail');
379 $errors['email'] = get_string('usernameoremail');
381 } else if (!empty($data['email'])) {
382 if (!validate_email($data['email'])) {
383 $errors['email'] = get_string('invalidemail');
385 } else {
386 try {
387 $user = get_complete_user_data('email', $data['email'], null, true);
388 if (empty($user->confirmed)) {
389 send_confirmation_email($user);
390 $errors['email'] = get_string('confirmednot');
392 } catch (dml_missing_record_exception $missingexception) {
393 // User not found. Show error when $CFG->protectusernames is turned off.
394 if (empty($CFG->protectusernames)) {
395 $errors['email'] = get_string('emailnotfound');
397 } catch (dml_multiple_records_exception $multipleexception) {
398 // Multiple records found. Ask the user to enter a username instead.
399 $errors['email'] = get_string('forgottenduplicate');
403 } else {
404 if ($user = get_complete_user_data('username', $data['username'])) {
405 if (empty($user->confirmed)) {
406 send_confirmation_email($user);
407 $errors['email'] = get_string('confirmednot');
410 if (!$user and empty($CFG->protectusernames)) {
411 $errors['username'] = get_string('usernamenotfound');
415 return $errors;
419 * Plugins can create pre sign up requests.
421 function core_login_pre_signup_requests() {
422 $callbacks = get_plugins_with_function('pre_signup_requests');
423 foreach ($callbacks as $type => $plugins) {
424 foreach ($plugins as $plugin => $pluginfunction) {
425 $pluginfunction();
431 * Plugins can extend forms.
434 /** Inject form elements into change_password_form.
435 * @param mform $mform the form to inject elements into.
436 * @param stdClass $user the user object to use for context.
438 function core_login_extend_change_password_form($mform, $user) {
439 $callbacks = get_plugins_with_function('extend_change_password_form');
440 foreach ($callbacks as $type => $plugins) {
441 foreach ($plugins as $plugin => $pluginfunction) {
442 $pluginfunction($mform, $user);
447 /** Inject form elements into set_password_form.
448 * @param mform $mform the form to inject elements into.
449 * @param stdClass $user the user object to use for context.
451 function core_login_extend_set_password_form($mform, $user) {
452 $callbacks = get_plugins_with_function('extend_set_password_form');
453 foreach ($callbacks as $type => $plugins) {
454 foreach ($plugins as $plugin => $pluginfunction) {
455 $pluginfunction($mform, $user);
460 /** Inject form elements into forgot_password_form.
461 * @param mform $mform the form to inject elements into.
463 function core_login_extend_forgot_password_form($mform) {
464 $callbacks = get_plugins_with_function('extend_forgot_password_form');
465 foreach ($callbacks as $type => $plugins) {
466 foreach ($plugins as $plugin => $pluginfunction) {
467 $pluginfunction($mform);
472 /** Inject form elements into signup_form.
473 * @param mform $mform the form to inject elements into.
475 function core_login_extend_signup_form($mform) {
476 $callbacks = get_plugins_with_function('extend_signup_form');
477 foreach ($callbacks as $type => $plugins) {
478 foreach ($plugins as $plugin => $pluginfunction) {
479 $pluginfunction($mform);
485 * Plugins can add additional validation to forms.
488 /** Inject validation into change_password_form.
489 * @param array $data the data array from submitted form values.
490 * @param stdClass $user the user object to use for context.
491 * @return array $errors the updated array of errors from validation.
493 function core_login_validate_extend_change_password_form($data, $user) {
494 $pluginsfunction = get_plugins_with_function('validate_extend_change_password_form');
495 $errors = array();
496 foreach ($pluginsfunction as $plugintype => $plugins) {
497 foreach ($plugins as $pluginfunction) {
498 $pluginerrors = $pluginfunction($data, $user);
499 $errors = array_merge($errors, $pluginerrors);
502 return $errors;
505 /** Inject validation into set_password_form.
506 * @param array $data the data array from submitted form values.
507 * @param stdClass $user the user object to use for context.
508 * @return array $errors the updated array of errors from validation.
510 function core_login_validate_extend_set_password_form($data, $user) {
511 $pluginsfunction = get_plugins_with_function('validate_extend_set_password_form');
512 $errors = array();
513 foreach ($pluginsfunction as $plugintype => $plugins) {
514 foreach ($plugins as $pluginfunction) {
515 $pluginerrors = $pluginfunction($data, $user);
516 $errors = array_merge($errors, $pluginerrors);
519 return $errors;
522 /** Inject validation into forgot_password_form.
523 * @param array $data the data array from submitted form values.
524 * @return array $errors the updated array of errors from validation.
526 function core_login_validate_extend_forgot_password_form($data) {
527 $pluginsfunction = get_plugins_with_function('validate_extend_forgot_password_form');
528 $errors = array();
529 foreach ($pluginsfunction as $plugintype => $plugins) {
530 foreach ($plugins as $pluginfunction) {
531 $pluginerrors = $pluginfunction($data);
532 $errors = array_merge($errors, $pluginerrors);
535 return $errors;
538 /** Inject validation into signup_form.
539 * @param array $data the data array from submitted form values.
540 * @return array $errors the updated array of errors from validation.
542 function core_login_validate_extend_signup_form($data) {
543 $pluginsfunction = get_plugins_with_function('validate_extend_signup_form');
544 $errors = array();
545 foreach ($pluginsfunction as $plugintype => $plugins) {
546 foreach ($plugins as $pluginfunction) {
547 $pluginerrors = $pluginfunction($data);
548 $errors = array_merge($errors, $pluginerrors);
551 return $errors;
555 * Plugins can perform post submission actions.
558 /** Post change_password_form submission actions.
559 * @param stdClass $data the data object from the submitted form.
561 function core_login_post_change_password_requests($data) {
562 $pluginsfunction = get_plugins_with_function('post_change_password_requests');
563 foreach ($pluginsfunction as $plugintype => $plugins) {
564 foreach ($plugins as $pluginfunction) {
565 $pluginfunction($data);
570 /** Post set_password_form submission actions.
571 * @param stdClass $data the data object from the submitted form.
572 * @param stdClass $user the user object for set_password context.
574 function core_login_post_set_password_requests($data, $user) {
575 $pluginsfunction = get_plugins_with_function('post_set_password_requests');
576 foreach ($pluginsfunction as $plugintype => $plugins) {
577 foreach ($plugins as $pluginfunction) {
578 $pluginfunction($data, $user);
583 /** Post forgot_password_form submission actions.
584 * @param stdClass $data the data object from the submitted form.
586 function core_login_post_forgot_password_requests($data) {
587 $pluginsfunction = get_plugins_with_function('post_forgot_password_requests');
588 foreach ($pluginsfunction as $plugintype => $plugins) {
589 foreach ($plugins as $pluginfunction) {
590 $pluginfunction($data);
595 /** Post signup_form submission actions.
596 * @param stdClass $data the data object from the submitted form.
598 function core_login_post_signup_requests($data) {
599 $pluginsfunction = get_plugins_with_function('post_signup_requests');
600 foreach ($pluginsfunction as $plugintype => $plugins) {
601 foreach ($plugins as $pluginfunction) {
602 $pluginfunction($data);