MDL-23692 forgotpw: Coding style tidyups.

This commit is contained in:
Peter Bulmer 2013-08-05 14:14:55 +12:00
parent 92de749fc7
commit 2f0dd8d5bd
8 changed files with 177 additions and 120 deletions

View File

@ -71,13 +71,13 @@ if ($hassiteconfig) { // speedup for non-admins, add all caps used on this page
$temp->add(new admin_setting_configtext('minpasswordnonalphanum', new lang_string('minpasswordnonalphanum', 'admin'), new lang_string('configminpasswordnonalphanum', 'admin'), 1, PARAM_INT)); $temp->add(new admin_setting_configtext('minpasswordnonalphanum', new lang_string('minpasswordnonalphanum', 'admin'), new lang_string('configminpasswordnonalphanum', 'admin'), 1, PARAM_INT));
$temp->add(new admin_setting_configtext('maxconsecutiveidentchars', new lang_string('maxconsecutiveidentchars', 'admin'), new lang_string('configmaxconsecutiveidentchars', 'admin'), 0, PARAM_INT)); $temp->add(new admin_setting_configtext('maxconsecutiveidentchars', new lang_string('maxconsecutiveidentchars', 'admin'), new lang_string('configmaxconsecutiveidentchars', 'admin'), 0, PARAM_INT));
$pwresetoptions = array( $pwresetoptions = array(
300 => new lang_string('numminutes', '', 5), 300 => new lang_string('numminutes', '', 5),
900 => new lang_string('numminutes', '', 15), 900 => new lang_string('numminutes', '', 15),
1800 => new lang_string('numminutes', '', 30), 1800 => new lang_string('numminutes', '', 30),
2700 => new lang_string('numminutes', '', 45), 2700 => new lang_string('numminutes', '', 45),
3600 => new lang_string('numminutes', '', 60), 3600 => new lang_string('numminutes', '', 60),
7200 => new lang_string('numminutes', '', 120), 7200 => new lang_string('numminutes', '', 120),
14400 => new lang_string('numminutes', '', 240) 14400 => new lang_string('numminutes', '', 240)
); );
$adminsetting = new admin_setting_configselect( $adminsetting = new admin_setting_configselect(
'pwresettime', 'pwresettime',

View File

@ -535,7 +535,7 @@ $string['editthisactivity'] = 'Edit this activity';
$string['editthiscategory'] = 'Edit this category'; $string['editthiscategory'] = 'Edit this category';
$string['edituser'] = 'Edit user accounts'; $string['edituser'] = 'Edit user accounts';
$string['email'] = 'Email address'; $string['email'] = 'Email address';
$string['emailalreadysent'] = 'A Password reset email has already been sent. Please check your email.'; $string['emailalreadysent'] = 'A password reset email has already been sent. Please check your email.';
$string['emailactive'] = 'Email activated'; $string['emailactive'] = 'Email activated';
$string['emailagain'] = 'Email (again)'; $string['emailagain'] = 'Email (again)';
$string['emailconfirm'] = 'Confirm your account'; $string['emailconfirm'] = 'Confirm your account';
@ -1564,8 +1564,8 @@ $string['separateandconnectedinfo'] = 'The scale based on the theory of separate
$string['servererror'] = 'An error occurred whilst communicating with the server'; $string['servererror'] = 'An error occurred whilst communicating with the server';
$string['serverlocaltime'] = 'Server\'s local time'; $string['serverlocaltime'] = 'Server\'s local time';
$string['setcategorytheme'] = 'Set category theme'; $string['setcategorytheme'] = 'Set category theme';
$string['setpassword'] = 'Set Password'; $string['setpassword'] = 'Set password';
$string['setpasswordinstructions'] = 'Please enter and repeat your new password below, then click "Set Password". <br />Your new password will be saved, and you will be logged in.'; $string['setpasswordinstructions'] = 'Please enter and repeat your new password below, then click "Set password". <br />Your new password will be saved, and you will be logged in.';
$string['settings'] = 'Settings'; $string['settings'] = 'Settings';
$string['shortname'] = 'Short name'; // @deprecated MDL-34652 - use shortnamecourse or shortnameuser or some own context specific string $string['shortname'] = 'Short name'; // @deprecated MDL-34652 - use shortnamecourse or shortnameuser or some own context specific string
$string['shortnamecollisionwarning'] = '[*] = This shortname is already in use by a course and will need to be changed upon approval'; $string['shortnamecollisionwarning'] = '[*] = This shortname is already in use by a course and will need to be changed upon approval';

View File

@ -2575,6 +2575,5 @@ function xmldb_main_upgrade($oldversion) {
upgrade_main_savepoint(true, 2013092700.02); upgrade_main_savepoint(true, 2013092700.02);
} }
return true; return true;
} }

View File

@ -1,5 +1,4 @@
<?php <?php
// This file is part of Moodle - http://moodle.org/ // This file is part of Moodle - http://moodle.org/
// //
// Moodle is free software: you can redistribute it and/or modify // Moodle is free software: you can redistribute it and/or modify
@ -32,7 +31,7 @@ require_once(__DIR__ . '/lib.php');
require_once('forgot_password_form.php'); require_once('forgot_password_form.php');
require_once('set_password_form.php'); require_once('set_password_form.php');
$token = optional_param('token', false, PARAM_RAW); $token = optional_param('token', false, PARAM_ALPHANUM);
//HTTPS is required in this page when $CFG->loginhttps enabled //HTTPS is required in this page when $CFG->loginhttps enabled
$PAGE->https_required(); $PAGE->https_required();
@ -62,10 +61,10 @@ if (isloggedin() and !isguestuser()) {
if (empty($token)) { if (empty($token)) {
// This is a new password reset request. // This is a new password reset request.
// Process the request; identify the user & send confirmation email: // Process the request; identify the user & send confirmation email.
forgotpw_process_request(); core_login_process_password_reset_request();
} else { } else {
// User clicked on confirmation link in email message // User clicked on confirmation link in email message
// validate the token & set new password // validate the token & set new password
forgotpw_process_pwset($token); core_login_process_password_set($token);
} }

View File

@ -1,5 +1,4 @@
<?php <?php
// This file is part of Moodle - http://moodle.org/ // This file is part of Moodle - http://moodle.org/
// //
// Moodle is free software: you can redistribute it and/or modify // Moodle is free software: you can redistribute it and/or modify
@ -15,6 +14,18 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Forgot password page.
*
* @package core
* @subpackage auth
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/formslib.php');
/** /**
* Reset forgotten password form definition. * Reset forgotten password form definition.
* *
@ -23,13 +34,11 @@
* @copyright 2006 Petr Skoda {@link http://skodak.org} * @copyright 2006 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/ */
defined('MOODLE_INTERNAL') || die();
require_once $CFG->libdir.'/formslib.php';
class login_forgot_password_form extends moodleform { class login_forgot_password_form extends moodleform {
/**
* Define the forgot password form.
*/
function definition() { function definition() {
$mform = $this->_form; $mform = $this->_form;
$mform->setDisableShortforms(true); $mform->setDisableShortforms(true);
@ -51,6 +60,12 @@ class login_forgot_password_form extends moodleform {
$mform->addElement('submit', 'submitbuttonemail', $submitlabel); $mform->addElement('submit', 'submitbuttonemail', $submitlabel);
} }
/**
* Validate user input from the forgot password form.
* @param array $data array of submitted form fields.
* @param array $files submitted with the form.
* @return array errors occuring during validation.
*/
function validation($data, $files) { function validation($data, $files) {
global $CFG, $DB; global $CFG, $DB;

View File

@ -194,7 +194,7 @@ if ($frm and isset($frm->username)) { // Login WITH
set_moodle_cookie($USER->username); set_moodle_cookie($USER->username);
} }
$urltogo = get_postlogin_redirection(); $urltogo = core_login_get_return_url();
/// check if user password has expired /// check if user password has expired
/// Currently supported only for ldap-authentication module /// Currently supported only for ldap-authentication module

View File

@ -1,14 +1,40 @@
<?php <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
*
* Login library file of login/password related Moodle functions.
*
* @package core
* @subpackage lib
* @copyright Catalyst IT
* @copyright Peter Bulmer
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define('PWRESET_STATUS_NOEMAILSENT', 1); define('PWRESET_STATUS_NOEMAILSENT', 1);
define('PWRESET_STATUS_TOKENSENT', 2); define('PWRESET_STATUS_TOKENSENT', 2);
define('PWRESET_STATUS_OTHEREMAILSENT', 3); define('PWRESET_STATUS_OTHEREMAILSENT', 3);
define('PWRESET_STATUS_ALREADYSENT', 4); define('PWRESET_STATUS_ALREADYSENT', 4);
/* This function processes a user's request to set a new password in the event they forgot the old one. /**
If no user identifier has been supplied, it displays a form where they can submit their identifier. * Processes a user's request to set a new password in the event they forgot the old one.
Where they have supplied identifier, the function will check their status, and send email as appropriate. * If no user identifier has been supplied, it displays a form where they can submit their identifier.
*/ * Where they have supplied identifier, the function will check their status, and send email as appropriate.
function forgotpw_process_request() { */
function core_login_process_password_reset_request() {
global $DB, $OUTPUT, $CFG, $PAGE; global $DB, $OUTPUT, $CFG, $PAGE;
$systemcontext = context_system::instance(); $systemcontext = context_system::instance();
$mform = new login_forgot_password_form(); $mform = new login_forgot_password_form();
@ -18,25 +44,26 @@ function forgotpw_process_request() {
} else if ($data = $mform->get_data()) { } else if ($data = $mform->get_data()) {
// Requesting user has submitted form data. // Requesting user has submitted form data.
// Find the user account in the database which the requesting user claims to own: // Next find the user account in the database which the requesting user claims to own.
if (!empty($data->username)) { if (!empty($data->username)) {
// Username has been specified - load the user record based on that. // Username has been specified - load the user record based on that.
$username = core_text::strtolower($data->username); // mimic the login page process, if they forget username they need to use email for reset $username = core_text::strtolower($data->username); // Mimic the login page process.
$user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>0, 'suspended'=>0)); $userparams = array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 0, 'suspended' => 0);
$user = $DB->get_record('user', $userparams);
} else { } else {
// Try to load the user record based on email address: // Try to load the user record based on email address.
// this is tricky because // this is tricky because
// 1/ the email is not guaranteed to be unique - TODO: send email with all usernames to select the correct account for pw reset // 1/ the email is not guaranteed to be unique - TODO: send email with all usernames to select the account for pw reset
// 2/ mailbox may be case sensitive, the email domain is case insensitive - let's pretend it is all case-insensitive // 2/ mailbox may be case sensitive, the email domain is case insensitive - let's pretend it is all case-insensitive.
$select = $DB->sql_like('email', ':email', false, true, false, '|'). " AND mnethostid = :mnethostid AND deleted=0 AND suspended=0"; $select = $DB->sql_like('email', ':email', false, true, false, '|') .
$params = array('email'=>$DB->sql_like_escape($data->email, '|'), 'mnethostid'=>$CFG->mnet_localhost_id); " AND mnethostid = :mnethostid AND deleted=0 AND suspended=0";
$params = array('email' => $DB->sql_like_escape($data->email, '|'), 'mnethostid' => $CFG->mnet_localhost_id);
$user = $DB->get_record_select('user', $select, $params, '*', IGNORE_MULTIPLE); $user = $DB->get_record_select('user', $select, $params, '*', IGNORE_MULTIPLE);
} }
// Target user details have now been identified, or we know that there is no such account. // Target user details have now been identified, or we know that there is no such account.
// Send email address to account's email address if appropriate: // Send email address to account's email address if appropriate.
$pwresetstatus = PWRESET_STATUS_NOEMAILSENT; $pwresetstatus = PWRESET_STATUS_NOEMAILSENT;
if ($user and !empty($user->confirmed)) { if ($user and !empty($user->confirmed)) {
$userauth = get_auth_plugin($user->auth); $userauth = get_auth_plugin($user->auth);
@ -49,20 +76,20 @@ function forgotpw_process_request() {
} }
} else { } else {
// The account the requesting user claims to be is entitled to change their password. // The account the requesting user claims to be is entitled to change their password.
// Check if they have an existing password reset in progress: // Next, check if they have an existing password reset in progress.
$resetinprogress = $DB->get_record('user_password_resets', array('userid' => $user->id)); $resetinprogress = $DB->get_record('user_password_resets', array('userid' => $user->id));
if (empty($resetinprogress)) { if (empty($resetinprogress)) {
// Completely new reset request - common case // Completely new reset request - common case.
$resetrecord = create_reset_record($user); $resetrecord = core_login_generate_password_reset($user);
$sendemail = true; $sendemail = true;
} elseif ($resetinprogress->timerequested < (time() - $CFG->pwresettime)) { } else if ($resetinprogress->timerequested < (time() - $CFG->pwresettime)) {
// Preexisting, but expired request - delete old record & create new one. // Preexisting, but expired request - delete old record & create new one.
// Uncommon case - expired requests are cleaned up by cron. // Uncommon case - expired requests are cleaned up by cron.
$DB->delete_records('user_password_resets', array('id' => $resetinprogress->id)); $DB->delete_records('user_password_resets', array('id' => $resetinprogress->id));
$resetrecord = create_reset_record($user); $resetrecord = core_login_generate_password_reset($user);
$sendemail = true; $sendemail = true;
} elseif (empty($resetinprogress->timererequested)) { } else if (empty($resetinprogress->timererequested)) {
// Preexisting, valid request. This is the first time user has re-requested the reset // Preexisting, valid request. This is the first time user has re-requested the reset.
// Re-sending the same email once can actually help in certain circumstances // Re-sending the same email once can actually help in certain circumstances
// eg by reducing the delay caused by greylisting. // eg by reducing the delay caused by greylisting.
$resetinprogress->timererequested = time(); $resetinprogress->timererequested = time();
@ -87,53 +114,53 @@ function forgotpw_process_request() {
} }
// Any email has now been sent. // Any email has now been sent.
// Display results to requesting user if settings permit: // Next display results to requesting user if settings permit.
echo $OUTPUT->header(); echo $OUTPUT->header();
if (!empty($CFG->protectusernames)) { if (!empty($CFG->protectusernames)) {
// Neither confirm, nor deny existance of any username or email address in database. // Neither confirm, nor deny existance of any username or email address in database.
// Print general (non-commital) message // Print general (non-commital) message.
notice(get_string('emailpasswordconfirmmaybesent'), $CFG->wwwroot.'/index.php'); notice(get_string('emailpasswordconfirmmaybesent'), $CFG->wwwroot.'/index.php');
die; // never reached die; // Never reached.
} elseif (empty($user)) { } else if (empty($user)) {
// Protect usernames is off, and we couldn't find the user with details specified. // Protect usernames is off, and we couldn't find the user with details specified.
// Print failure advice: // Print failure advice.
notice(get_string('emailpasswordconfirmnotsent'), $CFG->wwwroot.'/forgot_password.php'); notice(get_string('emailpasswordconfirmnotsent'), $CFG->wwwroot.'/forgot_password.php');
die; // never reached die; // Never reached.
} elseif (empty($user->email)) { } else if (empty($user->email)) {
// User doesn't have an email set - can't send a password change confimation email. // User doesn't have an email set - can't send a password change confimation email.
notice(get_string('emailpasswordconfirmnoemail'), $CFG->wwwroot.'/index.php'); notice(get_string('emailpasswordconfirmnoemail'), $CFG->wwwroot.'/index.php');
die; // never reached. die; // Never reached.
} else if ($pwresetstatus == PWRESET_STATUS_ALREADYSENT) { } else if ($pwresetstatus == PWRESET_STATUS_ALREADYSENT) {
// User found, protectusernames is off, but user has already (re) requested a reset. // User found, protectusernames is off, but user has already (re) requested a reset.
// Don't send a 3rd reset email. // Don't send a 3rd reset email.
$stremailalreadysent = get_string('emailalreadysent'); $stremailalreadysent = get_string('emailalreadysent');
notice($stremailalreadysent, $CFG->wwwroot.'/index.php'); notice($stremailalreadysent, $CFG->wwwroot.'/index.php');
die; // never reached die; // Never reached.
} elseif ($pwresetstatus == PWRESET_STATUS_NOEMAILSENT) { } else if ($pwresetstatus == PWRESET_STATUS_NOEMAILSENT) {
// User found, protectusernames is off, but user is not confirmed // User found, protectusernames is off, but user is not confirmed.
// Pretend we sent them an email // Pretend we sent them an email.
// This is a big usability problem - need to tell users why we didn't send them an email // This is a big usability problem - need to tell users why we didn't send them an email.
$protectedemail = preg_replace('/([^@]*)@(.*)/', '******@$2', $user->email); // obfuscate the email address to protect privacy // Obfuscate email address to protect privacy.
$protectedemail = preg_replace('/([^@]*)@(.*)/', '******@$2', $user->email);
$stremailpasswordconfirmsent = get_string('emailpasswordconfirmsent', '', $protectedemail); $stremailpasswordconfirmsent = get_string('emailpasswordconfirmsent', '', $protectedemail);
notice($stremailpasswordconfirmsent, $CFG->wwwroot.'/index.php'); notice($stremailpasswordconfirmsent, $CFG->wwwroot.'/index.php');
die; // never reached die; // Never reached.
} else { } else {
// Confirm email sent // Confirm email sent. (Obfuscate email address to protect privacy).
$protectedemail = preg_replace('/([^@]*)@(.*)/', '******@$2', $user->email); // obfuscate the email address to protect privacy $protectedemail = preg_replace('/([^@]*)@(.*)/', '******@$2', $user->email);
// This is a small usability problem - may be obfuscating the email address which the user has just supplied. // This is a small usability problem - may be obfuscating the email address which the user has just supplied.
$stremailresetconfirmsent = get_string('emailresetconfirmsent', '', $protectedemail); $stremailresetconfirmsent = get_string('emailresetconfirmsent', '', $protectedemail);
notice($stremailresetconfirmsent, $CFG->wwwroot.'/index.php'); notice($stremailresetconfirmsent, $CFG->wwwroot.'/index.php');
die; // never reached die; // Never reached.
} }
die; // never reached die; // Never reached.
} }
// make sure we really are on the https page when https login required // Make sure we really are on the https page when https login required.
$PAGE->verify_https_required(); $PAGE->verify_https_required();
// DISPLAY FORM.
/// DISPLAY FORM
echo $OUTPUT->header(); echo $OUTPUT->header();
echo $OUTPUT->box(get_string('passwordforgotteninstructions2'), 'generalbox boxwidthnormal boxaligncenter'); echo $OUTPUT->box(get_string('passwordforgotteninstructions2'), 'generalbox boxwidthnormal boxaligncenter');
@ -142,45 +169,46 @@ function forgotpw_process_request() {
echo $OUTPUT->footer(); echo $OUTPUT->footer();
} }
/* This function processes a user's submitted token to validate the request to set a new password /** This function processes a user's submitted token to validate the request to set a new password.
If the user's token is validated, they are prompted to set a new password. * If the user's token is validated, they are prompted to set a new password.
* @param string $token the one-use identifier which should verify the password reset request as being valid * @param string $token the one-use identifier which should verify the password reset request as being valid.
*/ * @return null
function forgotpw_process_pwset($token) { */
function core_login_process_password_set($token) {
global $DB, $CFG, $OUTPUT, $PAGE, $SESSION; global $DB, $CFG, $OUTPUT, $PAGE, $SESSION;
$systemcontext = context_system::instance();
$pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800; $pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800;
$sql = 'SELECT u.*, upr.token, upr.timerequested, upr.id as tokenid FROM ' . $CFG->prefix . 'user u' . $sql = "SELECT u.*, upr.token, upr.timerequested, upr.id as tokenid
' INNER JOIN ' . $CFG->prefix . 'user_password_resets upr ON upr.userid = u.id ' . FROM {user} u
'WHERE upr.token = ?'; JOIN {user_password_resets} upr ON upr.userid = u.id
WHERE upr.token = ?";
$user = $DB->get_record_sql($sql, array($token)); $user = $DB->get_record_sql($sql, array($token));
$forgotpasswordurl = "{$CFG->httpswwwroot}/login/forgot_password.php"; $forgotpasswordurl = "{$CFG->httpswwwroot}/login/forgot_password.php";
if (empty($user) or ($user->timerequested < (time() - $pwresettime - DAYSECS))) { if (empty($user) or ($user->timerequested < (time() - $pwresettime - DAYSECS))) {
// There is no valid reset request record - not even a recently expired one. // There is no valid reset request record - not even a recently expired one.
// (suspicious) // (suspicious)
// Direct the user to the forgot password page to request a password reset // Direct the user to the forgot password page to request a password reset.
echo $OUTPUT->header(); echo $OUTPUT->header();
notice(get_string('noresetrecord'), $forgotpasswordurl); notice(get_string('noresetrecord'), $forgotpasswordurl);
die; // never reached die; // Never reached.
} }
if ($user->timerequested < (time() - $pwresettime)) { if ($user->timerequested < (time() - $pwresettime)) {
// There is a reset record, but it's expired // There is a reset record, but it's expired.
// Direct the user to the forgot password page to request a password reset // Direct the user to the forgot password page to request a password reset.
$pwresetmins = floor($pwresettime / MINSECS); $pwresetmins = floor($pwresettime / MINSECS);
echo $OUTPUT->header(); echo $OUTPUT->header();
notice(get_string('resetrecordexpired', '', $pwresetmins), $forgotpasswordurl); notice(get_string('resetrecordexpired', '', $pwresetmins), $forgotpasswordurl);
die; // never reached die; // Never reached.
} }
if ($user->auth === 'nologin' or !is_enabled_auth($user->auth)) { if ($user->auth === 'nologin' or !is_enabled_auth($user->auth)) {
// bad luck - user is not able to login, do not let them set password // Bad luck - user is not able to login, do not let them set password.
echo $OUTPUT->header(); echo $OUTPUT->header();
print_error('forgotteninvalidurl'); print_error('forgotteninvalidurl');
die; // never reached die; // Never reached.
} }
// check this isn't guest user // Check this isn't guest user.
if (isguestuser($user)) { if (isguestuser($user)) {
print_error('cannotresetguestpwd'); print_error('cannotresetguestpwd');
} }
@ -190,7 +218,7 @@ function forgotpw_process_pwset($token) {
$data = $mform->get_data(); $data = $mform->get_data();
if (empty($data)) { if (empty($data)) {
// User hasn't submitted form, they got here directly from email link. // User hasn't submitted form, they got here directly from email link.
// Display the form: // Next, display the form.
$setdata = new stdClass(); $setdata = new stdClass();
$setdata->username = $user->username; $setdata->username = $user->username;
$setdata->username2 = $user->username; $setdata->username2 = $user->username;
@ -204,38 +232,37 @@ function forgotpw_process_pwset($token) {
return; return;
} else { } else {
// User has submitted form. // User has submitted form.
// Delete this token so it can't be used again: // Delete this token so it can't be used again.
$DB->delete_records('user_password_resets', array('id' => $user->tokenid)); $DB->delete_records('user_password_resets', array('id' => $user->tokenid));
$userauth = get_auth_plugin($user->auth); $userauth = get_auth_plugin($user->auth);
if (!$userauth->user_update_password($user, $data->password)) { if (!$userauth->user_update_password($user, $data->password)) {
print_error('errorpasswordupdate', 'auth'); print_error('errorpasswordupdate', 'auth');
} }
add_to_log(SITEID, 'user', 'set password', "view.php?id=$user->id&amp;course=" . SITEID, $user->id); add_to_log(SITEID, 'user', 'set password', "view.php?id=$user->id&amp;course=" . SITEID, $user->id);
// Reset login lockout (if present) before a new password is set: // Reset login lockout (if present) before a new password is set.
login_unlock_account($user); login_unlock_account($user);
// Clear any requirement to change passwords // Clear any requirement to change passwords.
unset_user_preference('auth_forcepasswordchange', $user); unset_user_preference('auth_forcepasswordchange', $user);
unset_user_preference('create_password', $user); unset_user_preference('create_password', $user);
if (!empty($user->lang)) { if (!empty($user->lang)) {
// unset previous session language - use user preference instead // Unset previous session language - use user preference instead.
unset($SESSION->lang); unset($SESSION->lang);
} }
add_to_log(SITEID, 'user', 'login', "view.php?id=$user->id&course=".SITEID, $user->id, 0, $user->id); add_to_log(SITEID, 'user', 'login', "view.php?id=$user->id&course=".SITEID, $user->id, 0, $user->id);
complete_user_login($user); complete_user_login($user);
$urltogo = get_postlogin_redirection(); $urltogo = core_login_get_return_url();
unset($SESSION->wantsurl); unset($SESSION->wantsurl);
redirect($urltogo, get_string('passwordset'), 1); redirect($urltogo, get_string('passwordset'), 1);
} }
} }
/* /** Create a new record in the database to track a new password set request for user.
* Create a new record in the database to track a new password set request for user
* @param object $user the user record, the requester would like a new password set for. * @param object $user the user record, the requester would like a new password set for.
* @return record created * @return record created.
*/ */
function create_reset_record ($user) { function core_login_generate_password_reset ($user) {
global $CFG, $DB; global $DB;
$resetrecord = new stdClass(); $resetrecord = new stdClass();
$resetrecord->timerequested = time(); $resetrecord->timerequested = time();
$resetrecord->userid = $user->id; $resetrecord->userid = $user->id;
@ -244,29 +271,31 @@ function create_reset_record ($user) {
return $resetrecord; return $resetrecord;
} }
/* Determine where a user should be redirected after they have been logged in /** Determine where a user should be redirected after they have been logged in.
*/ * @return string url the user should be redirected to.
function get_postlogin_redirection() { */
function core_login_get_return_url() {
global $CFG, $SESSION, $USER; global $CFG, $SESSION, $USER;
/// Prepare redirection // Prepare redirection.
if (user_not_fully_set_up($USER)) { if (user_not_fully_set_up($USER)) {
$urltogo = $CFG->wwwroot.'/user/edit.php'; $urltogo = $CFG->wwwroot.'/user/edit.php';
// We don't delete $SESSION->wantsurl yet, so we get there later // We don't delete $SESSION->wantsurl yet, so we get there later.
} else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0 or strpos($SESSION->wantsurl, str_replace('http://', 'https://', $CFG->wwwroot)) === 0)) { } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0
$urltogo = $SESSION->wantsurl; /// Because it's an address in this site or strpos($SESSION->wantsurl, str_replace('http://', 'https://', $CFG->wwwroot)) === 0)) {
$urltogo = $SESSION->wantsurl; // Because it's an address in this site.
unset($SESSION->wantsurl); unset($SESSION->wantsurl);
} else { } else {
// no wantsurl stored or external - go to homepage // No wantsurl stored or external - go to homepage.
$urltogo = $CFG->wwwroot.'/'; $urltogo = $CFG->wwwroot.'/';
unset($SESSION->wantsurl); unset($SESSION->wantsurl);
} }
// If the url to go to is the same as the site page, check for default homepage. // If the url to go to is the same as the site page, check for default homepage.
if ($urltogo == ($CFG->wwwroot . '/')) { if ($urltogo == ($CFG->wwwroot . '/')) {
$home_page = get_home_page(); $homepage = get_home_page();
// Go to my-moodle page instead of site homepage if defaulthomepage set to homepage_my // Go to my-moodle page instead of site homepage if defaulthomepage set to homepage_my.
if ($home_page == HOMEPAGE_MY && !is_siteadmin() && !isguestuser()) { if ($homepage == HOMEPAGE_MY && !is_siteadmin() && !isguestuser()) {
if ($urltogo == $CFG->wwwroot or $urltogo == $CFG->wwwroot.'/' or $urltogo == $CFG->wwwroot.'/index.php') { if ($urltogo == $CFG->wwwroot or $urltogo == $CFG->wwwroot.'/' or $urltogo == $CFG->wwwroot.'/index.php') {
$urltogo = $CFG->wwwroot.'/my/'; $urltogo = $CFG->wwwroot.'/my/';
} }
@ -274,4 +303,3 @@ function get_postlogin_redirection() {
} }
return $urltogo; return $urltogo;
} }
?>

View File

@ -25,11 +25,23 @@
defined('MOODLE_INTERNAL') || die(); defined('MOODLE_INTERNAL') || die();
require_once $CFG->libdir.'/formslib.php'; require_once($CFG->libdir.'/formslib.php');
/**
* Set forgotten password form definition.
*
* @package core
* @subpackage auth
* @copyright 2006 Petr Skoda {@link http://skodak.org}
* @copyright 2013 Peter Bulmer
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class login_set_password_form extends moodleform { class login_set_password_form extends moodleform {
function definition() { /**
* Define the set password form.
*/
public function definition() {
global $USER, $CFG; global $USER, $CFG;
$mform = $this->_form; $mform = $this->_form;
@ -37,44 +49,48 @@ class login_set_password_form extends moodleform {
$mform->addElement('header', 'setpassword', get_string('setpassword'), ''); $mform->addElement('header', 'setpassword', get_string('setpassword'), '');
// Include the username in the form so browsers will recognise that a password is being set. // Include the username in the form so browsers will recognise that a password is being set.
$mform->addElement('text', 'username','','style="display: none;" autocomplete="on"'); $mform->addElement('text', 'username', '', 'style="display: none;" autocomplete="on"');
$mform->setType('username', PARAM_RAW); $mform->setType('username', PARAM_RAW);
// Token gives authority to change password. // Token gives authority to change password.
$mform->addElement('hidden', 'token', ''); $mform->addElement('hidden', 'token', '');
$mform->setType('token', PARAM_ALPHANUM); $mform->setType('token', PARAM_ALPHANUM);
// visible elements // Visible elements.
$mform->addElement('static', 'username2', get_string('username')); $mform->addElement('static', 'username2', get_string('username'));
if (!empty($CFG->passwordpolicy)){ if (!empty($CFG->passwordpolicy)) {
$mform->addElement('static', 'passwordpolicyinfo', '', print_password_policy()); $mform->addElement('static', 'passwordpolicyinfo', '', print_password_policy());
} }
$mform->addElement('password', 'password', get_string('newpassword'), 'autocomplete="on"'); $mform->addElement('password', 'password', get_string('newpassword'), 'autocomplete="on"');
$mform->addRule('password', get_string('required'), 'required', null, 'client'); $mform->addRule('password', get_string('required'), 'required', null, 'client');
$mform->setType('password', PARAM_RAW); $mform->setType('password', PARAM_RAW);
$mform->addElement('password', 'password2', get_string('newpassword').' ('.get_String('again').')', 'autocomplete="on"'); $strpasswordagain = get_string('newpassword') . ' (' . get_string('again') . ')';
$mform->addElement('password', 'password2', $strpasswordagain, 'autocomplete="on"');
$mform->addRule('password2', get_string('required'), 'required', null, 'client'); $mform->addRule('password2', get_string('required'), 'required', null, 'client');
$mform->setType('password2', PARAM_RAW); $mform->setType('password2', PARAM_RAW);
// buttons
$this->add_action_buttons(true); $this->add_action_buttons(true);
} }
// perform extra password change validation /**
function validation($data, $files) { * Perform extra password change validation.
* @param array $data submitted form fields.
* @param array $files submitted with the form.
* @return array errors occuring during validation.
*/
public function validation($data, $files) {
global $USER; global $USER;
$errors = parent::validation($data, $files); $errors = parent::validation($data, $files);
// Ignore submitted username. // Ignore submitted username.
// TODO: Validate submitted token. if ($data['password'] !== $data['password2']) {
if ($data['password'] <> $data['password2']) {
$errors['password'] = get_string('passwordsdiffer'); $errors['password'] = get_string('passwordsdiffer');
$errors['password2'] = get_string('passwordsdiffer'); $errors['password2'] = get_string('passwordsdiffer');
return $errors; return $errors;
} }
$errmsg = '';//prevents eclipse warnings $errmsg = ''; // Prevents eclipse warnings.
if (!check_password_policy($data['password'], $errmsg)) { if (!check_password_policy($data['password'], $errmsg)) {
$errors['password'] = $errmsg; $errors['password'] = $errmsg;
$errors['password2'] = $errmsg; $errors['password2'] = $errmsg;