Merge branch 'MDL-61355' of git://github.com/danmarsden/moodle
[moodle.git] / login / lib.php
blobeb29ae1fcac40af835d33b33be5d4f942a7f226c
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
27 define('PWRESET_STATUS_NOEMAILSENT', 1);
28 define('PWRESET_STATUS_TOKENSENT', 2);
29 define('PWRESET_STATUS_OTHEREMAILSENT', 3);
30 define('PWRESET_STATUS_ALREADYSENT', 4);
32 /**
33 * Processes a user's request to set a new password in the event they forgot the old one.
34 * If no user identifier has been supplied, it displays a form where they can submit their identifier.
35 * Where they have supplied identifier, the function will check their status, and send email as appropriate.
37 function core_login_process_password_reset_request() {
38 global $OUTPUT, $PAGE;
39 $mform = new login_forgot_password_form();
41 if ($mform->is_cancelled()) {
42 redirect(get_login_url());
44 } else if ($data = $mform->get_data()) {
46 $username = $email = '';
47 if (!empty($data->username)) {
48 $username = $data->username;
49 } else {
50 $email = $data->email;
52 list($status, $notice, $url) = core_login_process_password_reset($username, $email);
54 // Any email has now been sent.
55 // Next display results to requesting user if settings permit.
56 echo $OUTPUT->header();
57 notice($notice, $url);
58 die; // Never reached.
61 // DISPLAY FORM.
63 echo $OUTPUT->header();
64 echo $OUTPUT->box(get_string('passwordforgotteninstructions2'), 'generalbox boxwidthnormal boxaligncenter');
65 $mform->display();
67 echo $OUTPUT->footer();
70 /**
71 * Process the password reset for the given user (via username or email).
73 * @param string $username the user name
74 * @param string $email the user email
75 * @return array an array containing fields indicating the reset status, a info notice and redirect URL.
76 * @since Moodle 3.4
78 function core_login_process_password_reset($username, $email) {
79 global $CFG, $DB;
81 if (empty($username) && empty($email)) {
82 print_error('cannotmailconfirm');
85 // Next find the user account in the database which the requesting user claims to own.
86 if (!empty($username)) {
87 // Username has been specified - load the user record based on that.
88 $username = core_text::strtolower($username); // Mimic the login page process.
89 $userparams = array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 0, 'suspended' => 0);
90 $user = $DB->get_record('user', $userparams);
91 } else {
92 // Try to load the user record based on email address.
93 // this is tricky because
94 // 1/ the email is not guaranteed to be unique - TODO: send email with all usernames to select the account for pw reset
95 // 2/ mailbox may be case sensitive, the email domain is case insensitive - let's pretend it is all case-insensitive.
97 $select = $DB->sql_like('email', ':email', false, true, false, '|') .
98 " AND mnethostid = :mnethostid AND deleted=0 AND suspended=0";
99 $params = array('email' => $DB->sql_like_escape($email, '|'), 'mnethostid' => $CFG->mnet_localhost_id);
100 $user = $DB->get_record_select('user', $select, $params, '*', IGNORE_MULTIPLE);
103 // Target user details have now been identified, or we know that there is no such account.
104 // Send email address to account's email address if appropriate.
105 $pwresetstatus = PWRESET_STATUS_NOEMAILSENT;
106 if ($user and !empty($user->confirmed)) {
107 $systemcontext = context_system::instance();
109 $userauth = get_auth_plugin($user->auth);
110 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)
111 or !has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
112 if (send_password_change_info($user)) {
113 $pwresetstatus = PWRESET_STATUS_OTHEREMAILSENT;
114 } else {
115 print_error('cannotmailconfirm');
117 } else {
118 // The account the requesting user claims to be is entitled to change their password.
119 // Next, check if they have an existing password reset in progress.
120 $resetinprogress = $DB->get_record('user_password_resets', array('userid' => $user->id));
121 if (empty($resetinprogress)) {
122 // Completely new reset request - common case.
123 $resetrecord = core_login_generate_password_reset($user);
124 $sendemail = true;
125 } else if ($resetinprogress->timerequested < (time() - $CFG->pwresettime)) {
126 // Preexisting, but expired request - delete old record & create new one.
127 // Uncommon case - expired requests are cleaned up by cron.
128 $DB->delete_records('user_password_resets', array('id' => $resetinprogress->id));
129 $resetrecord = core_login_generate_password_reset($user);
130 $sendemail = true;
131 } else if (empty($resetinprogress->timererequested)) {
132 // Preexisting, valid request. This is the first time user has re-requested the reset.
133 // Re-sending the same email once can actually help in certain circumstances
134 // eg by reducing the delay caused by greylisting.
135 $resetinprogress->timererequested = time();
136 $DB->update_record('user_password_resets', $resetinprogress);
137 $resetrecord = $resetinprogress;
138 $sendemail = true;
139 } else {
140 // Preexisting, valid request. User has already re-requested email.
141 $pwresetstatus = PWRESET_STATUS_ALREADYSENT;
142 $sendemail = false;
145 if ($sendemail) {
146 $sendresult = send_password_change_confirmation_email($user, $resetrecord);
147 if ($sendresult) {
148 $pwresetstatus = PWRESET_STATUS_TOKENSENT;
149 } else {
150 print_error('cannotmailconfirm');
156 $url = $CFG->wwwroot.'/index.php';
157 if (!empty($CFG->protectusernames)) {
158 // Neither confirm, nor deny existance of any username or email address in database.
159 // Print general (non-commital) message.
160 $status = 'emailpasswordconfirmmaybesent';
161 $notice = get_string($status);
162 } else if (empty($user)) {
163 // Protect usernames is off, and we couldn't find the user with details specified.
164 // Print failure advice.
165 $status = 'emailpasswordconfirmnotsent';
166 $notice = get_string($status);
167 $url = $CFG->wwwroot.'/forgot_password.php';
168 } else if (empty($user->email)) {
169 // User doesn't have an email set - can't send a password change confimation email.
170 $status = 'emailpasswordconfirmnoemail';
171 $notice = get_string($status);
172 } else if ($pwresetstatus == PWRESET_STATUS_ALREADYSENT) {
173 // User found, protectusernames is off, but user has already (re) requested a reset.
174 // Don't send a 3rd reset email.
175 $status = 'emailalreadysent';
176 $notice = get_string($status);
177 } else if ($pwresetstatus == PWRESET_STATUS_NOEMAILSENT) {
178 // User found, protectusernames is off, but user is not confirmed.
179 // Pretend we sent them an email.
180 // This is a big usability problem - need to tell users why we didn't send them an email.
181 // Obfuscate email address to protect privacy.
182 $protectedemail = preg_replace('/([^@]*)@(.*)/', '******@$2', $user->email);
183 $status = 'emailpasswordconfirmsent';
184 $notice = get_string($status, '', $protectedemail);
185 } else {
186 // Confirm email sent. (Obfuscate email address to protect privacy).
187 $protectedemail = preg_replace('/([^@]*)@(.*)/', '******@$2', $user->email);
188 // This is a small usability problem - may be obfuscating the email address which the user has just supplied.
189 $status = 'emailresetconfirmsent';
190 $notice = get_string($status, '', $protectedemail);
192 return array($status, $notice, $url);
196 * This function processes a user's submitted token to validate the request to set a new password.
197 * If the user's token is validated, they are prompted to set a new password.
198 * @param string $token the one-use identifier which should verify the password reset request as being valid.
199 * @return void
201 function core_login_process_password_set($token) {
202 global $DB, $CFG, $OUTPUT, $PAGE, $SESSION;
203 require_once($CFG->dirroot.'/user/lib.php');
205 $pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800;
206 $sql = "SELECT u.*, upr.token, upr.timerequested, upr.id as tokenid
207 FROM {user} u
208 JOIN {user_password_resets} upr ON upr.userid = u.id
209 WHERE upr.token = ?";
210 $user = $DB->get_record_sql($sql, array($token));
212 $forgotpasswordurl = "{$CFG->wwwroot}/login/forgot_password.php";
213 if (empty($user) or ($user->timerequested < (time() - $pwresettime - DAYSECS))) {
214 // There is no valid reset request record - not even a recently expired one.
215 // (suspicious)
216 // Direct the user to the forgot password page to request a password reset.
217 echo $OUTPUT->header();
218 notice(get_string('noresetrecord'), $forgotpasswordurl);
219 die; // Never reached.
221 if ($user->timerequested < (time() - $pwresettime)) {
222 // There is a reset record, but it's expired.
223 // Direct the user to the forgot password page to request a password reset.
224 $pwresetmins = floor($pwresettime / MINSECS);
225 echo $OUTPUT->header();
226 notice(get_string('resetrecordexpired', '', $pwresetmins), $forgotpasswordurl);
227 die; // Never reached.
230 if ($user->auth === 'nologin' or !is_enabled_auth($user->auth)) {
231 // Bad luck - user is not able to login, do not let them set password.
232 echo $OUTPUT->header();
233 print_error('forgotteninvalidurl');
234 die; // Never reached.
237 // Check this isn't guest user.
238 if (isguestuser($user)) {
239 print_error('cannotresetguestpwd');
242 // Token is correct, and unexpired.
243 $mform = new login_set_password_form(null, $user);
244 $data = $mform->get_data();
245 if (empty($data)) {
246 // User hasn't submitted form, they got here directly from email link.
247 // Next, display the form.
248 $setdata = new stdClass();
249 $setdata->username = $user->username;
250 $setdata->username2 = $user->username;
251 $setdata->token = $user->token;
252 $mform->set_data($setdata);
253 echo $OUTPUT->header();
254 echo $OUTPUT->box(get_string('setpasswordinstructions'), 'generalbox boxwidthnormal boxaligncenter');
255 $mform->display();
256 echo $OUTPUT->footer();
257 return;
258 } else {
259 // User has submitted form.
260 // Delete this token so it can't be used again.
261 $DB->delete_records('user_password_resets', array('id' => $user->tokenid));
262 $userauth = get_auth_plugin($user->auth);
263 if (!$userauth->user_update_password($user, $data->password)) {
264 print_error('errorpasswordupdate', 'auth');
266 user_add_password_history($user->id, $data->password);
267 if (!empty($CFG->passwordchangelogout)) {
268 \core\session\manager::kill_user_sessions($user->id, session_id());
270 // Reset login lockout (if present) before a new password is set.
271 login_unlock_account($user);
272 // Clear any requirement to change passwords.
273 unset_user_preference('auth_forcepasswordchange', $user);
274 unset_user_preference('create_password', $user);
276 if (!empty($user->lang)) {
277 // Unset previous session language - use user preference instead.
278 unset($SESSION->lang);
280 complete_user_login($user); // Triggers the login event.
282 \core\session\manager::apply_concurrent_login_limit($user->id, session_id());
284 $urltogo = core_login_get_return_url();
285 unset($SESSION->wantsurl);
286 redirect($urltogo, get_string('passwordset'), 1);
290 /** Create a new record in the database to track a new password set request for user.
291 * @param object $user the user record, the requester would like a new password set for.
292 * @return record created.
294 function core_login_generate_password_reset ($user) {
295 global $DB;
296 $resetrecord = new stdClass();
297 $resetrecord->timerequested = time();
298 $resetrecord->userid = $user->id;
299 $resetrecord->token = random_string(32);
300 $resetrecord->id = $DB->insert_record('user_password_resets', $resetrecord);
301 return $resetrecord;
304 /** Determine where a user should be redirected after they have been logged in.
305 * @return string url the user should be redirected to.
307 function core_login_get_return_url() {
308 global $CFG, $SESSION, $USER;
309 // Prepare redirection.
310 if (user_not_fully_set_up($USER, true)) {
311 $urltogo = $CFG->wwwroot.'/user/edit.php';
312 // We don't delete $SESSION->wantsurl yet, so we get there later.
314 } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0
315 or strpos($SESSION->wantsurl, str_replace('http://', 'https://', $CFG->wwwroot)) === 0)) {
316 $urltogo = $SESSION->wantsurl; // Because it's an address in this site.
317 unset($SESSION->wantsurl);
318 } else {
319 // No wantsurl stored or external - go to homepage.
320 $urltogo = $CFG->wwwroot.'/';
321 unset($SESSION->wantsurl);
324 // If the url to go to is the same as the site page, check for default homepage.
325 if ($urltogo == ($CFG->wwwroot . '/')) {
326 $homepage = get_home_page();
327 // Go to my-moodle page instead of site homepage if defaulthomepage set to homepage_my.
328 if ($homepage == HOMEPAGE_MY && !is_siteadmin() && !isguestuser()) {
329 if ($urltogo == $CFG->wwwroot or $urltogo == $CFG->wwwroot.'/' or $urltogo == $CFG->wwwroot.'/index.php') {
330 $urltogo = $CFG->wwwroot.'/my/';
334 return $urltogo;
338 * Validates the forgot password form data.
340 * This is used by the forgot_password_form and by the core_auth_request_password_rest WS.
341 * @param array $data array containing the data to be validated (email and username)
342 * @return array array of errors compatible with mform
343 * @since Moodle 3.4
345 function core_login_validate_forgot_password_data($data) {
346 global $CFG, $DB;
348 $errors = array();
350 if ((!empty($data['username']) and !empty($data['email'])) or (empty($data['username']) and empty($data['email']))) {
351 $errors['username'] = get_string('usernameoremail');
352 $errors['email'] = get_string('usernameoremail');
354 } else if (!empty($data['email'])) {
355 if (!validate_email($data['email'])) {
356 $errors['email'] = get_string('invalidemail');
358 } else if ($DB->count_records('user', array('email' => $data['email'])) > 1) {
359 $errors['email'] = get_string('forgottenduplicate');
361 } else {
362 if ($user = get_complete_user_data('email', $data['email'])) {
363 if (empty($user->confirmed)) {
364 send_confirmation_email($user);
365 $errors['email'] = get_string('confirmednot');
368 if (!$user and empty($CFG->protectusernames)) {
369 $errors['email'] = get_string('emailnotfound');
373 } else {
374 if ($user = get_complete_user_data('username', $data['username'])) {
375 if (empty($user->confirmed)) {
376 send_confirmation_email($user);
377 $errors['email'] = get_string('confirmednot');
380 if (!$user and empty($CFG->protectusernames)) {
381 $errors['username'] = get_string('usernamenotfound');
385 return $errors;
389 * Plugins can create pre sign up requests.
391 function core_login_pre_signup_requests() {
392 $callbacks = get_plugins_with_function('pre_signup_requests');
393 foreach ($callbacks as $type => $plugins) {
394 foreach ($plugins as $plugin => $pluginfunction) {
395 $pluginfunction();