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