Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / specials / SpecialPasswordReset.php
bloba2dc2add28ea82050b085a63d807750d4ff8e873
1 <?php
2 /**
3 * Implements Special:PasswordReset
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup SpecialPage
24 /**
25 * Special page for requesting a password reset email
27 * @ingroup SpecialPage
29 class SpecialPasswordReset extends FormSpecialPage {
30 /**
31 * @var Message
33 private $email;
35 /**
36 * @var User
38 private $firstUser;
40 /**
41 * @var Status
43 private $result;
45 public function __construct() {
46 parent::__construct( 'PasswordReset', 'editmyprivateinfo' );
49 public function userCanExecute( User $user ) {
50 return $this->canChangePassword( $user ) === true && parent::userCanExecute( $user );
53 public function checkExecutePermissions( User $user ) {
54 $error = $this->canChangePassword( $user );
55 if ( is_string( $error ) ) {
56 throw new ErrorPageError( 'internalerror', $error );
57 } elseif ( !$error ) {
58 throw new ErrorPageError( 'internalerror', 'resetpass_forbidden' );
61 return parent::checkExecutePermissions( $user );
64 protected function getFormFields() {
65 global $wgAuth;
66 $resetRoutes = $this->getConfig()->get( 'PasswordResetRoutes' );
67 $a = array();
68 if ( isset( $resetRoutes['username'] ) && $resetRoutes['username'] ) {
69 $a['Username'] = array(
70 'type' => 'text',
71 'label-message' => 'passwordreset-username',
74 if ( $this->getUser()->isLoggedIn() ) {
75 $a['Username']['default'] = $this->getUser()->getName();
79 if ( isset( $resetRoutes['email'] ) && $resetRoutes['email'] ) {
80 $a['Email'] = array(
81 'type' => 'email',
82 'label-message' => 'passwordreset-email',
86 if ( isset( $resetRoutes['domain'] ) && $resetRoutes['domain'] ) {
87 $domains = $wgAuth->domainList();
88 $a['Domain'] = array(
89 'type' => 'select',
90 'options' => $domains,
91 'label-message' => 'passwordreset-domain',
95 if ( $this->getUser()->isAllowed( 'passwordreset' ) ) {
96 $a['Capture'] = array(
97 'type' => 'check',
98 'label-message' => 'passwordreset-capture',
99 'help-message' => 'passwordreset-capture-help',
103 return $a;
106 protected function getDisplayFormat() {
107 return 'vform';
110 public function alterForm( HTMLForm $form ) {
111 $resetRoutes = $this->getConfig()->get( 'PasswordResetRoutes' );
113 $form->addHiddenFields( $this->getRequest()->getValues( 'returnto', 'returntoquery' ) );
115 $i = 0;
116 if ( isset( $resetRoutes['username'] ) && $resetRoutes['username'] ) {
117 $i++;
119 if ( isset( $resetRoutes['email'] ) && $resetRoutes['email'] ) {
120 $i++;
122 if ( isset( $resetRoutes['domain'] ) && $resetRoutes['domain'] ) {
123 $i++;
126 $message = ( $i > 1 ) ? 'passwordreset-text-many' : 'passwordreset-text-one';
128 $form->setHeaderText( $this->msg( $message, $i )->parseAsBlock() );
129 $form->setSubmitTextMsg( 'mailmypassword' );
133 * Process the form. At this point we know that the user passes all the criteria in
134 * userCanExecute(), and if the data array contains 'Username', etc, then Username
135 * resets are allowed.
136 * @param array $data
137 * @throws MWException
138 * @throws ThrottledError|PermissionsError
139 * @return bool|array
141 public function onSubmit( array $data ) {
142 global $wgAuth;
144 if ( isset( $data['Domain'] ) ) {
145 if ( $wgAuth->validDomain( $data['Domain'] ) ) {
146 $wgAuth->setDomain( $data['Domain'] );
147 } else {
148 $wgAuth->setDomain( 'invaliddomain' );
152 if ( isset( $data['Capture'] ) && !$this->getUser()->isAllowed( 'passwordreset' ) ) {
153 // The user knows they don't have the passwordreset permission,
154 // but they tried to spoof the form. That's naughty
155 throw new PermissionsError( 'passwordreset' );
159 * @var $firstUser User
160 * @var $users User[]
163 if ( isset( $data['Username'] ) && $data['Username'] !== '' ) {
164 $method = 'username';
165 $users = array( User::newFromName( $data['Username'] ) );
166 } elseif ( isset( $data['Email'] )
167 && $data['Email'] !== ''
168 && Sanitizer::validateEmail( $data['Email'] )
170 $method = 'email';
171 $res = wfGetDB( DB_SLAVE )->select(
172 'user',
173 User::selectFields(),
174 array( 'user_email' => $data['Email'] ),
175 __METHOD__
178 if ( $res ) {
179 $users = array();
181 foreach ( $res as $row ) {
182 $users[] = User::newFromRow( $row );
184 } else {
185 // Some sort of database error, probably unreachable
186 throw new MWException( 'Unknown database error in ' . __METHOD__ );
188 } else {
189 // The user didn't supply any data
190 return false;
193 // Check for hooks (captcha etc), and allow them to modify the users list
194 $error = array();
195 if ( !Hooks::run( 'SpecialPasswordResetOnSubmit', array( &$users, $data, &$error ) ) ) {
196 return array( $error );
199 if ( count( $users ) == 0 ) {
200 if ( $method == 'email' ) {
201 // Don't reveal whether or not an email address is in use
202 return true;
203 } else {
204 return array( 'noname' );
208 $firstUser = $users[0];
210 if ( !$firstUser instanceof User || !$firstUser->getID() ) {
211 // Don't parse username as wikitext (bug 65501)
212 return array( array( 'nosuchuser', wfEscapeWikiText( $data['Username'] ) ) );
215 // Check against the rate limiter
216 if ( $this->getUser()->pingLimiter( 'mailpassword' ) ) {
217 throw new ThrottledError;
220 // Check against password throttle
221 foreach ( $users as $user ) {
222 if ( $user->isPasswordReminderThrottled() ) {
224 # Round the time in hours to 3 d.p., in case someone is specifying
225 # minutes or seconds.
226 return array( array(
227 'throttled-mailpassword',
228 round( $this->getConfig()->get( 'PasswordReminderResendTime' ), 3 )
229 ) );
233 // All the users will have the same email address
234 if ( $firstUser->getEmail() == '' ) {
235 // This won't be reachable from the email route, so safe to expose the username
236 return array( array( 'noemail', wfEscapeWikiText( $firstUser->getName() ) ) );
239 // We need to have a valid IP address for the hook, but per bug 18347, we should
240 // send the user's name if they're logged in.
241 $ip = $this->getRequest()->getIP();
242 if ( !$ip ) {
243 return array( 'badipaddress' );
245 $caller = $this->getUser();
246 Hooks::run( 'User::mailPasswordInternal', array( &$caller, &$ip, &$firstUser ) );
247 $username = $caller->getName();
248 $msg = IP::isValid( $username )
249 ? 'passwordreset-emailtext-ip'
250 : 'passwordreset-emailtext-user';
252 // Send in the user's language; which should hopefully be the same
253 $userLanguage = $firstUser->getOption( 'language' );
255 $passwords = array();
256 foreach ( $users as $user ) {
257 $password = $user->randomPassword();
258 $user->setNewpassword( $password );
259 $user->saveSettings();
260 $passwords[] = $this->msg( 'passwordreset-emailelement', $user->getName(), $password )
261 ->inLanguage( $userLanguage )->text(); // We'll escape the whole thing later
263 $passwordBlock = implode( "\n\n", $passwords );
265 $this->email = $this->msg( $msg )->inLanguage( $userLanguage );
266 $this->email->params(
267 $username,
268 $passwordBlock,
269 count( $passwords ),
270 '<' . Title::newMainPage()->getCanonicalURL() . '>',
271 round( $this->getConfig()->get( 'NewPasswordExpiry' ) / 86400 )
274 $title = $this->msg( 'passwordreset-emailtitle' );
276 $this->result = $firstUser->sendMail( $title->text(), $this->email->text() );
278 if ( isset( $data['Capture'] ) && $data['Capture'] ) {
279 // Save the user, will be used if an error occurs when sending the email
280 $this->firstUser = $firstUser;
281 } else {
282 // Blank the email if the user is not supposed to see it
283 $this->email = null;
286 if ( $this->result->isGood() ) {
287 return true;
288 } elseif ( isset( $data['Capture'] ) && $data['Capture'] ) {
289 // The email didn't send, but maybe they knew that and that's why they captured it
290 return true;
291 } else {
292 // @todo FIXME: The email wasn't sent, but we have already set
293 // the password throttle timestamp, so they won't be able to try
294 // again until it expires... :(
295 return array( array( 'mailerror', $this->result->getMessage() ) );
299 public function onSuccess() {
300 if ( $this->getUser()->isAllowed( 'passwordreset' ) && $this->email != null ) {
301 // @todo Logging
303 if ( $this->result->isGood() ) {
304 $this->getOutput()->addWikiMsg( 'passwordreset-emailsent-capture' );
305 } else {
306 $this->getOutput()->addWikiMsg( 'passwordreset-emailerror-capture',
307 $this->result->getMessage(), $this->firstUser->getName() );
310 $this->getOutput()->addHTML( Html::rawElement( 'pre', array(), $this->email->escaped() ) );
313 $this->getOutput()->addWikiMsg( 'passwordreset-emailsent' );
314 $this->getOutput()->returnToMain();
317 protected function canChangePassword( User $user ) {
318 global $wgAuth;
319 $resetRoutes = $this->getConfig()->get( 'PasswordResetRoutes' );
321 // Maybe password resets are disabled, or there are no allowable routes
322 if ( !is_array( $resetRoutes ) ||
323 !in_array( true, array_values( $resetRoutes ) )
325 return 'passwordreset-disabled';
328 // Maybe the external auth plugin won't allow local password changes
329 if ( !$wgAuth->allowPasswordChange() ) {
330 return 'resetpass_forbidden';
333 // Maybe email features have been disabled
334 if ( !$this->getConfig()->get( 'EnableEmail' ) ) {
335 return 'passwordreset-emaildisabled';
338 // Maybe the user is blocked (check this here rather than relying on the parent
339 // method as we have a more specific error message to use here
340 if ( $user->isBlocked() ) {
341 return 'blocked-mailpassword';
344 return true;
348 * Hide the password reset page if resets are disabled.
349 * @return bool
351 function isListed() {
352 if ( $this->canChangePassword( $this->getUser() ) === true ) {
353 return parent::isListed();
356 return false;
359 protected function getGroupName() {
360 return 'users';