Merge branch 'MDL-75137-master' of https://github.com/aanabit/moodle
[moodle.git] / login / lib.php
blobe30e178369e5e8a1f05188f3d78c6a93135c715f
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 throw new \moodle_exception('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 throw new \moodle_exception('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 throw new \moodle_exception('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 throw new \moodle_exception('forgotteninvalidurl');
257 die; // Never reached.
260 // Check this isn't guest user.
261 if (isguestuser($user)) {
262 throw new \moodle_exception('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 throw new \moodle_exception('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 && !isguestuser()) {
356 if ($urltogo == $CFG->wwwroot or $urltogo == $CFG->wwwroot.'/' or $urltogo == $CFG->wwwroot.'/index.php') {
357 $urltogo = $CFG->wwwroot.'/my/';
360 if ($homepage === HOMEPAGE_MYCOURSES && !isguestuser()) {
361 if ($urltogo == $CFG->wwwroot or $urltogo == $CFG->wwwroot.'/' or $urltogo == $CFG->wwwroot.'/index.php') {
362 $urltogo = $CFG->wwwroot.'/my/courses.php';
366 return $urltogo;
370 * Validates the forgot password form data.
372 * This is used by the forgot_password_form and by the core_auth_request_password_rest WS.
373 * @param array $data array containing the data to be validated (email and username)
374 * @return array array of errors compatible with mform
375 * @since Moodle 3.4
377 function core_login_validate_forgot_password_data($data) {
378 global $CFG, $DB;
380 $errors = array();
382 if ((!empty($data['username']) and !empty($data['email'])) or (empty($data['username']) and empty($data['email']))) {
383 $errors['username'] = get_string('usernameoremail');
384 $errors['email'] = get_string('usernameoremail');
386 } else if (!empty($data['email'])) {
387 if (!validate_email($data['email'])) {
388 $errors['email'] = get_string('invalidemail');
390 } else {
391 try {
392 $user = get_complete_user_data('email', $data['email'], null, true);
393 if (empty($user->confirmed)) {
394 send_confirmation_email($user);
395 if (empty($CFG->protectusernames)) {
396 $errors['email'] = get_string('confirmednot');
399 } catch (dml_missing_record_exception $missingexception) {
400 // User not found. Show error when $CFG->protectusernames is turned off.
401 if (empty($CFG->protectusernames)) {
402 $errors['email'] = get_string('emailnotfound');
404 } catch (dml_multiple_records_exception $multipleexception) {
405 // Multiple records found. Ask the user to enter a username instead.
406 if (empty($CFG->protectusernames)) {
407 $errors['email'] = get_string('forgottenduplicate');
412 } else {
413 if ($user = get_complete_user_data('username', $data['username'])) {
414 if (empty($user->confirmed)) {
415 send_confirmation_email($user);
416 if (empty($CFG->protectusernames)) {
417 $errors['username'] = get_string('confirmednot');
421 if (!$user and empty($CFG->protectusernames)) {
422 $errors['username'] = get_string('usernamenotfound');
426 return $errors;
430 * Plugins can create pre sign up requests.
432 function core_login_pre_signup_requests() {
433 $callbacks = get_plugins_with_function('pre_signup_requests');
434 foreach ($callbacks as $type => $plugins) {
435 foreach ($plugins as $plugin => $pluginfunction) {
436 $pluginfunction();
442 * Plugins can extend forms.
445 /** Inject form elements into change_password_form.
446 * @param mform $mform the form to inject elements into.
447 * @param stdClass $user the user object to use for context.
449 function core_login_extend_change_password_form($mform, $user) {
450 $callbacks = get_plugins_with_function('extend_change_password_form');
451 foreach ($callbacks as $type => $plugins) {
452 foreach ($plugins as $plugin => $pluginfunction) {
453 $pluginfunction($mform, $user);
458 /** Inject form elements into set_password_form.
459 * @param mform $mform the form to inject elements into.
460 * @param stdClass $user the user object to use for context.
462 function core_login_extend_set_password_form($mform, $user) {
463 $callbacks = get_plugins_with_function('extend_set_password_form');
464 foreach ($callbacks as $type => $plugins) {
465 foreach ($plugins as $plugin => $pluginfunction) {
466 $pluginfunction($mform, $user);
471 /** Inject form elements into forgot_password_form.
472 * @param mform $mform the form to inject elements into.
474 function core_login_extend_forgot_password_form($mform) {
475 $callbacks = get_plugins_with_function('extend_forgot_password_form');
476 foreach ($callbacks as $type => $plugins) {
477 foreach ($plugins as $plugin => $pluginfunction) {
478 $pluginfunction($mform);
483 /** Inject form elements into signup_form.
484 * @param mform $mform the form to inject elements into.
486 function core_login_extend_signup_form($mform) {
487 $callbacks = get_plugins_with_function('extend_signup_form');
488 foreach ($callbacks as $type => $plugins) {
489 foreach ($plugins as $plugin => $pluginfunction) {
490 $pluginfunction($mform);
496 * Plugins can add additional validation to forms.
499 /** Inject validation into change_password_form.
500 * @param array $data the data array from submitted form values.
501 * @param stdClass $user the user object to use for context.
502 * @return array $errors the updated array of errors from validation.
504 function core_login_validate_extend_change_password_form($data, $user) {
505 $pluginsfunction = get_plugins_with_function('validate_extend_change_password_form');
506 $errors = array();
507 foreach ($pluginsfunction as $plugintype => $plugins) {
508 foreach ($plugins as $pluginfunction) {
509 $pluginerrors = $pluginfunction($data, $user);
510 $errors = array_merge($errors, $pluginerrors);
513 return $errors;
516 /** Inject validation into set_password_form.
517 * @param array $data the data array from submitted form values.
518 * @param stdClass $user the user object to use for context.
519 * @return array $errors the updated array of errors from validation.
521 function core_login_validate_extend_set_password_form($data, $user) {
522 $pluginsfunction = get_plugins_with_function('validate_extend_set_password_form');
523 $errors = array();
524 foreach ($pluginsfunction as $plugintype => $plugins) {
525 foreach ($plugins as $pluginfunction) {
526 $pluginerrors = $pluginfunction($data, $user);
527 $errors = array_merge($errors, $pluginerrors);
530 return $errors;
533 /** Inject validation into forgot_password_form.
534 * @param array $data the data array from submitted form values.
535 * @return array $errors the updated array of errors from validation.
537 function core_login_validate_extend_forgot_password_form($data) {
538 $pluginsfunction = get_plugins_with_function('validate_extend_forgot_password_form');
539 $errors = array();
540 foreach ($pluginsfunction as $plugintype => $plugins) {
541 foreach ($plugins as $pluginfunction) {
542 $pluginerrors = $pluginfunction($data);
543 $errors = array_merge($errors, $pluginerrors);
546 return $errors;
549 /** Inject validation into signup_form.
550 * @param array $data the data array from submitted form values.
551 * @return array $errors the updated array of errors from validation.
553 function core_login_validate_extend_signup_form($data) {
554 $pluginsfunction = get_plugins_with_function('validate_extend_signup_form');
555 $errors = array();
556 foreach ($pluginsfunction as $plugintype => $plugins) {
557 foreach ($plugins as $pluginfunction) {
558 $pluginerrors = $pluginfunction($data);
559 $errors = array_merge($errors, $pluginerrors);
562 return $errors;
566 * Plugins can perform post submission actions.
569 /** Post change_password_form submission actions.
570 * @param stdClass $data the data object from the submitted form.
572 function core_login_post_change_password_requests($data) {
573 $pluginsfunction = get_plugins_with_function('post_change_password_requests');
574 foreach ($pluginsfunction as $plugintype => $plugins) {
575 foreach ($plugins as $pluginfunction) {
576 $pluginfunction($data);
581 /** Post set_password_form submission actions.
582 * @param stdClass $data the data object from the submitted form.
583 * @param stdClass $user the user object for set_password context.
585 function core_login_post_set_password_requests($data, $user) {
586 $pluginsfunction = get_plugins_with_function('post_set_password_requests');
587 foreach ($pluginsfunction as $plugintype => $plugins) {
588 foreach ($plugins as $pluginfunction) {
589 $pluginfunction($data, $user);
594 /** Post forgot_password_form submission actions.
595 * @param stdClass $data the data object from the submitted form.
597 function core_login_post_forgot_password_requests($data) {
598 $pluginsfunction = get_plugins_with_function('post_forgot_password_requests');
599 foreach ($pluginsfunction as $plugintype => $plugins) {
600 foreach ($plugins as $pluginfunction) {
601 $pluginfunction($data);
606 /** Post signup_form submission actions.
607 * @param stdClass $data the data object from the submitted form.
609 function core_login_post_signup_requests($data) {
610 $pluginsfunction = get_plugins_with_function('post_signup_requests');
611 foreach ($pluginsfunction as $plugintype => $plugins) {
612 foreach ($plugins as $pluginfunction) {
613 $pluginfunction($data);