Merge branch 'MDL-70917-39' of git://github.com/paulholden/moodle into MOODLE_39_STABLE
[moodle.git] / login / lib.php
bloba00d1438da301ded555cb495370db130b655c054
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 if (empty($CFG->protectusernames)) {
391 $errors['email'] = get_string('confirmednot');
394 } catch (dml_missing_record_exception $missingexception) {
395 // User not found. Show error when $CFG->protectusernames is turned off.
396 if (empty($CFG->protectusernames)) {
397 $errors['email'] = get_string('emailnotfound');
399 } catch (dml_multiple_records_exception $multipleexception) {
400 // Multiple records found. Ask the user to enter a username instead.
401 if (empty($CFG->protectusernames)) {
402 $errors['email'] = get_string('forgottenduplicate');
407 } else {
408 if ($user = get_complete_user_data('username', $data['username'])) {
409 if (empty($user->confirmed)) {
410 send_confirmation_email($user);
411 if (empty($CFG->protectusernames)) {
412 $errors['username'] = get_string('confirmednot');
416 if (!$user and empty($CFG->protectusernames)) {
417 $errors['username'] = get_string('usernamenotfound');
421 return $errors;
425 * Plugins can create pre sign up requests.
427 function core_login_pre_signup_requests() {
428 $callbacks = get_plugins_with_function('pre_signup_requests');
429 foreach ($callbacks as $type => $plugins) {
430 foreach ($plugins as $plugin => $pluginfunction) {
431 $pluginfunction();
437 * Plugins can extend forms.
440 /** Inject form elements into change_password_form.
441 * @param mform $mform the form to inject elements into.
442 * @param stdClass $user the user object to use for context.
444 function core_login_extend_change_password_form($mform, $user) {
445 $callbacks = get_plugins_with_function('extend_change_password_form');
446 foreach ($callbacks as $type => $plugins) {
447 foreach ($plugins as $plugin => $pluginfunction) {
448 $pluginfunction($mform, $user);
453 /** Inject form elements into set_password_form.
454 * @param mform $mform the form to inject elements into.
455 * @param stdClass $user the user object to use for context.
457 function core_login_extend_set_password_form($mform, $user) {
458 $callbacks = get_plugins_with_function('extend_set_password_form');
459 foreach ($callbacks as $type => $plugins) {
460 foreach ($plugins as $plugin => $pluginfunction) {
461 $pluginfunction($mform, $user);
466 /** Inject form elements into forgot_password_form.
467 * @param mform $mform the form to inject elements into.
469 function core_login_extend_forgot_password_form($mform) {
470 $callbacks = get_plugins_with_function('extend_forgot_password_form');
471 foreach ($callbacks as $type => $plugins) {
472 foreach ($plugins as $plugin => $pluginfunction) {
473 $pluginfunction($mform);
478 /** Inject form elements into signup_form.
479 * @param mform $mform the form to inject elements into.
481 function core_login_extend_signup_form($mform) {
482 $callbacks = get_plugins_with_function('extend_signup_form');
483 foreach ($callbacks as $type => $plugins) {
484 foreach ($plugins as $plugin => $pluginfunction) {
485 $pluginfunction($mform);
491 * Plugins can add additional validation to forms.
494 /** Inject validation into change_password_form.
495 * @param array $data the data array from submitted form values.
496 * @param stdClass $user the user object to use for context.
497 * @return array $errors the updated array of errors from validation.
499 function core_login_validate_extend_change_password_form($data, $user) {
500 $pluginsfunction = get_plugins_with_function('validate_extend_change_password_form');
501 $errors = array();
502 foreach ($pluginsfunction as $plugintype => $plugins) {
503 foreach ($plugins as $pluginfunction) {
504 $pluginerrors = $pluginfunction($data, $user);
505 $errors = array_merge($errors, $pluginerrors);
508 return $errors;
511 /** Inject validation into set_password_form.
512 * @param array $data the data array from submitted form values.
513 * @param stdClass $user the user object to use for context.
514 * @return array $errors the updated array of errors from validation.
516 function core_login_validate_extend_set_password_form($data, $user) {
517 $pluginsfunction = get_plugins_with_function('validate_extend_set_password_form');
518 $errors = array();
519 foreach ($pluginsfunction as $plugintype => $plugins) {
520 foreach ($plugins as $pluginfunction) {
521 $pluginerrors = $pluginfunction($data, $user);
522 $errors = array_merge($errors, $pluginerrors);
525 return $errors;
528 /** Inject validation into forgot_password_form.
529 * @param array $data the data array from submitted form values.
530 * @return array $errors the updated array of errors from validation.
532 function core_login_validate_extend_forgot_password_form($data) {
533 $pluginsfunction = get_plugins_with_function('validate_extend_forgot_password_form');
534 $errors = array();
535 foreach ($pluginsfunction as $plugintype => $plugins) {
536 foreach ($plugins as $pluginfunction) {
537 $pluginerrors = $pluginfunction($data);
538 $errors = array_merge($errors, $pluginerrors);
541 return $errors;
544 /** Inject validation into signup_form.
545 * @param array $data the data array from submitted form values.
546 * @return array $errors the updated array of errors from validation.
548 function core_login_validate_extend_signup_form($data) {
549 $pluginsfunction = get_plugins_with_function('validate_extend_signup_form');
550 $errors = array();
551 foreach ($pluginsfunction as $plugintype => $plugins) {
552 foreach ($plugins as $pluginfunction) {
553 $pluginerrors = $pluginfunction($data);
554 $errors = array_merge($errors, $pluginerrors);
557 return $errors;
561 * Plugins can perform post submission actions.
564 /** Post change_password_form submission actions.
565 * @param stdClass $data the data object from the submitted form.
567 function core_login_post_change_password_requests($data) {
568 $pluginsfunction = get_plugins_with_function('post_change_password_requests');
569 foreach ($pluginsfunction as $plugintype => $plugins) {
570 foreach ($plugins as $pluginfunction) {
571 $pluginfunction($data);
576 /** Post set_password_form submission actions.
577 * @param stdClass $data the data object from the submitted form.
578 * @param stdClass $user the user object for set_password context.
580 function core_login_post_set_password_requests($data, $user) {
581 $pluginsfunction = get_plugins_with_function('post_set_password_requests');
582 foreach ($pluginsfunction as $plugintype => $plugins) {
583 foreach ($plugins as $pluginfunction) {
584 $pluginfunction($data, $user);
589 /** Post forgot_password_form submission actions.
590 * @param stdClass $data the data object from the submitted form.
592 function core_login_post_forgot_password_requests($data) {
593 $pluginsfunction = get_plugins_with_function('post_forgot_password_requests');
594 foreach ($pluginsfunction as $plugintype => $plugins) {
595 foreach ($plugins as $pluginfunction) {
596 $pluginfunction($data);
601 /** Post signup_form submission actions.
602 * @param stdClass $data the data object from the submitted form.
604 function core_login_post_signup_requests($data) {
605 $pluginsfunction = get_plugins_with_function('post_signup_requests');
606 foreach ($pluginsfunction as $plugintype => $plugins) {
607 foreach ($plugins as $pluginfunction) {
608 $pluginfunction($data);