Merge "Make Special:MediaStatistics show a total count of file sizes"
[lhc/web/wiklou.git] / includes / specials / SpecialPasswordReset.php
1 <?php
2 /**
3 * Implements Special:PasswordReset
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 /**
25 * Special page for requesting a password reset email
26 *
27 * @ingroup SpecialPage
28 */
29 class SpecialPasswordReset extends FormSpecialPage {
30 /**
31 * @var Message
32 */
33 private $email;
34
35 /**
36 * @var User
37 */
38 private $firstUser;
39
40 /**
41 * @var Status
42 */
43 private $result;
44
45 /**
46 * @var string $method Identifies which password reset field was specified by the user.
47 */
48 private $method;
49
50 public function __construct() {
51 parent::__construct( 'PasswordReset', 'editmyprivateinfo' );
52 }
53
54 public function userCanExecute( User $user ) {
55 return $this->canChangePassword( $user ) === true && parent::userCanExecute( $user );
56 }
57
58 public function checkExecutePermissions( User $user ) {
59 $error = $this->canChangePassword( $user );
60 if ( is_string( $error ) ) {
61 throw new ErrorPageError( 'internalerror', $error );
62 } elseif ( !$error ) {
63 throw new ErrorPageError( 'internalerror', 'resetpass_forbidden' );
64 }
65
66 parent::checkExecutePermissions( $user );
67 }
68
69 protected function getFormFields() {
70 global $wgAuth;
71 $resetRoutes = $this->getConfig()->get( 'PasswordResetRoutes' );
72 $a = array();
73 if ( isset( $resetRoutes['username'] ) && $resetRoutes['username'] ) {
74 $a['Username'] = array(
75 'type' => 'text',
76 'label-message' => 'passwordreset-username',
77 );
78
79 if ( $this->getUser()->isLoggedIn() ) {
80 $a['Username']['default'] = $this->getUser()->getName();
81 }
82 }
83
84 if ( isset( $resetRoutes['email'] ) && $resetRoutes['email'] ) {
85 $a['Email'] = array(
86 'type' => 'email',
87 'label-message' => 'passwordreset-email',
88 );
89 }
90
91 if ( isset( $resetRoutes['domain'] ) && $resetRoutes['domain'] ) {
92 $domains = $wgAuth->domainList();
93 $a['Domain'] = array(
94 'type' => 'select',
95 'options' => $domains,
96 'label-message' => 'passwordreset-domain',
97 );
98 }
99
100 if ( $this->getUser()->isAllowed( 'passwordreset' ) ) {
101 $a['Capture'] = array(
102 'type' => 'check',
103 'label-message' => 'passwordreset-capture',
104 'help-message' => 'passwordreset-capture-help',
105 );
106 }
107
108 return $a;
109 }
110
111 protected function getDisplayFormat() {
112 return 'ooui';
113 }
114
115 public function alterForm( HTMLForm $form ) {
116 $resetRoutes = $this->getConfig()->get( 'PasswordResetRoutes' );
117
118 $form->addHiddenFields( $this->getRequest()->getValues( 'returnto', 'returntoquery' ) );
119
120 $i = 0;
121 if ( isset( $resetRoutes['username'] ) && $resetRoutes['username'] ) {
122 $i++;
123 }
124 if ( isset( $resetRoutes['email'] ) && $resetRoutes['email'] ) {
125 $i++;
126 }
127 if ( isset( $resetRoutes['domain'] ) && $resetRoutes['domain'] ) {
128 $i++;
129 }
130
131 $message = ( $i > 1 ) ? 'passwordreset-text-many' : 'passwordreset-text-one';
132
133 $form->setHeaderText( $this->msg( $message, $i )->parseAsBlock() );
134 $form->setSubmitTextMsg( 'mailmypassword' );
135 }
136
137 /**
138 * Process the form. At this point we know that the user passes all the criteria in
139 * userCanExecute(), and if the data array contains 'Username', etc, then Username
140 * resets are allowed.
141 * @param array $data
142 * @throws MWException
143 * @throws ThrottledError|PermissionsError
144 * @return bool|array
145 */
146 public function onSubmit( array $data ) {
147 global $wgAuth, $wgMinimalPasswordLength;
148
149 if ( isset( $data['Domain'] ) ) {
150 if ( $wgAuth->validDomain( $data['Domain'] ) ) {
151 $wgAuth->setDomain( $data['Domain'] );
152 } else {
153 $wgAuth->setDomain( 'invaliddomain' );
154 }
155 }
156
157 if ( isset( $data['Capture'] ) && !$this->getUser()->isAllowed( 'passwordreset' ) ) {
158 // The user knows they don't have the passwordreset permission,
159 // but they tried to spoof the form. That's naughty
160 throw new PermissionsError( 'passwordreset' );
161 }
162
163 /**
164 * @var $firstUser User
165 * @var $users User[]
166 */
167
168 if ( isset( $data['Username'] ) && $data['Username'] !== '' ) {
169 $method = 'username';
170 $users = array( User::newFromName( $data['Username'] ) );
171 } elseif ( isset( $data['Email'] )
172 && $data['Email'] !== ''
173 && Sanitizer::validateEmail( $data['Email'] )
174 ) {
175 $method = 'email';
176 $res = wfGetDB( DB_SLAVE )->select(
177 'user',
178 User::selectFields(),
179 array( 'user_email' => $data['Email'] ),
180 __METHOD__
181 );
182
183 if ( $res ) {
184 $users = array();
185
186 foreach ( $res as $row ) {
187 $users[] = User::newFromRow( $row );
188 }
189 } else {
190 // Some sort of database error, probably unreachable
191 throw new MWException( 'Unknown database error in ' . __METHOD__ );
192 }
193 } else {
194 // The user didn't supply any data
195 return false;
196 }
197
198 // Check for hooks (captcha etc), and allow them to modify the users list
199 $error = array();
200 if ( !Hooks::run( 'SpecialPasswordResetOnSubmit', array( &$users, $data, &$error ) ) ) {
201 return array( $error );
202 }
203
204 $this->method = $method;
205
206 if ( count( $users ) == 0 ) {
207 if ( $method == 'email' ) {
208 // Don't reveal whether or not an email address is in use
209 return true;
210 } else {
211 return array( 'noname' );
212 }
213 }
214
215 $firstUser = $users[0];
216
217 if ( !$firstUser instanceof User || !$firstUser->getID() ) {
218 // Don't parse username as wikitext (bug 65501)
219 return array( array( 'nosuchuser', wfEscapeWikiText( $data['Username'] ) ) );
220 }
221
222 // Check against the rate limiter
223 if ( $this->getUser()->pingLimiter( 'mailpassword' ) ) {
224 throw new ThrottledError;
225 }
226
227 // Check against password throttle
228 foreach ( $users as $user ) {
229 if ( $user->isPasswordReminderThrottled() ) {
230
231 # Round the time in hours to 3 d.p., in case someone is specifying
232 # minutes or seconds.
233 return array( array(
234 'throttled-mailpassword',
235 round( $this->getConfig()->get( 'PasswordReminderResendTime' ), 3 )
236 ) );
237 }
238 }
239
240 // All the users will have the same email address
241 if ( $firstUser->getEmail() == '' ) {
242 // This won't be reachable from the email route, so safe to expose the username
243 return array( array( 'noemail', wfEscapeWikiText( $firstUser->getName() ) ) );
244 }
245
246 // We need to have a valid IP address for the hook, but per bug 18347, we should
247 // send the user's name if they're logged in.
248 $ip = $this->getRequest()->getIP();
249 if ( !$ip ) {
250 return array( 'badipaddress' );
251 }
252 $caller = $this->getUser();
253 Hooks::run( 'User::mailPasswordInternal', array( &$caller, &$ip, &$firstUser ) );
254 $username = $caller->getName();
255 $msg = IP::isValid( $username )
256 ? 'passwordreset-emailtext-ip'
257 : 'passwordreset-emailtext-user';
258
259 // Send in the user's language; which should hopefully be the same
260 $userLanguage = $firstUser->getOption( 'language' );
261
262 $passwords = array();
263 foreach ( $users as $user ) {
264 $password = PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
265 $user->setNewpassword( $password );
266 $user->saveSettings();
267 $passwords[] = $this->msg( 'passwordreset-emailelement', $user->getName(), $password )
268 ->inLanguage( $userLanguage )->text(); // We'll escape the whole thing later
269 }
270 $passwordBlock = implode( "\n\n", $passwords );
271
272 $this->email = $this->msg( $msg )->inLanguage( $userLanguage );
273 $this->email->params(
274 $username,
275 $passwordBlock,
276 count( $passwords ),
277 '<' . Title::newMainPage()->getCanonicalURL() . '>',
278 round( $this->getConfig()->get( 'NewPasswordExpiry' ) / 86400 )
279 );
280
281 $title = $this->msg( 'passwordreset-emailtitle' )->inLanguage( $userLanguage );
282
283 $this->result = $firstUser->sendMail( $title->text(), $this->email->text() );
284
285 if ( isset( $data['Capture'] ) && $data['Capture'] ) {
286 // Save the user, will be used if an error occurs when sending the email
287 $this->firstUser = $firstUser;
288 } else {
289 // Blank the email if the user is not supposed to see it
290 $this->email = null;
291 }
292
293 if ( $this->result->isGood() ) {
294 return true;
295 } elseif ( isset( $data['Capture'] ) && $data['Capture'] ) {
296 // The email didn't send, but maybe they knew that and that's why they captured it
297 return true;
298 } else {
299 // @todo FIXME: The email wasn't sent, but we have already set
300 // the password throttle timestamp, so they won't be able to try
301 // again until it expires... :(
302 return array( array( 'mailerror', $this->result->getMessage() ) );
303 }
304 }
305
306 public function onSuccess() {
307 if ( $this->getUser()->isAllowed( 'passwordreset' ) && $this->email != null ) {
308 // @todo Logging
309
310 if ( $this->result->isGood() ) {
311 $this->getOutput()->addWikiMsg( 'passwordreset-emailsent-capture' );
312 } else {
313 $this->getOutput()->addWikiMsg( 'passwordreset-emailerror-capture',
314 $this->result->getMessage(), $this->firstUser->getName() );
315 }
316
317 $this->getOutput()->addHTML( Html::rawElement( 'pre', array(), $this->email->escaped() ) );
318 }
319
320 if ( $this->method === 'email' ) {
321 $this->getOutput()->addWikiMsg( 'passwordreset-emailsentemail' );
322 } else {
323 $this->getOutput()->addWikiMsg( 'passwordreset-emailsentusername' );
324 }
325
326 $this->getOutput()->returnToMain();
327 }
328
329 protected function canChangePassword( User $user ) {
330 global $wgAuth;
331 $resetRoutes = $this->getConfig()->get( 'PasswordResetRoutes' );
332
333 // Maybe password resets are disabled, or there are no allowable routes
334 if ( !is_array( $resetRoutes ) ||
335 !in_array( true, array_values( $resetRoutes ) )
336 ) {
337 return 'passwordreset-disabled';
338 }
339
340 // Maybe the external auth plugin won't allow local password changes
341 if ( !$wgAuth->allowPasswordChange() ) {
342 return 'resetpass_forbidden';
343 }
344
345 // Maybe email features have been disabled
346 if ( !$this->getConfig()->get( 'EnableEmail' ) ) {
347 return 'passwordreset-emaildisabled';
348 }
349
350 // Maybe the user is blocked (check this here rather than relying on the parent
351 // method as we have a more specific error message to use here
352 if ( $user->isBlocked() ) {
353 return 'blocked-mailpassword';
354 }
355
356 return true;
357 }
358
359 /**
360 * Hide the password reset page if resets are disabled.
361 * @return bool
362 */
363 function isListed() {
364 if ( $this->canChangePassword( $this->getUser() ) === true ) {
365 return parent::isListed();
366 }
367
368 return false;
369 }
370
371 protected function getGroupName() {
372 return 'users';
373 }
374 }