Merge "deleteEqualMessages: Exclude messages that are empty by default"
[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 public function __construct() {
46 parent::__construct( 'PasswordReset', 'editmyprivateinfo' );
47 }
48
49 public function userCanExecute( User $user ) {
50 return $this->canChangePassword( $user ) === true && parent::userCanExecute( $user );
51 }
52
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' );
59 }
60
61 return parent::checkExecutePermissions( $user );
62 }
63
64 protected function getFormFields() {
65 global $wgPasswordResetRoutes, $wgAuth;
66 $a = array();
67 if ( isset( $wgPasswordResetRoutes['username'] ) && $wgPasswordResetRoutes['username'] ) {
68 $a['Username'] = array(
69 'type' => 'text',
70 'label-message' => 'passwordreset-username',
71 );
72
73 if ( $this->getUser()->isLoggedIn() ) {
74 $a['Username']['default'] = $this->getUser()->getName();
75 }
76 }
77
78 if ( isset( $wgPasswordResetRoutes['email'] ) && $wgPasswordResetRoutes['email'] ) {
79 $a['Email'] = array(
80 'type' => 'email',
81 'label-message' => 'passwordreset-email',
82 );
83 }
84
85 if ( isset( $wgPasswordResetRoutes['domain'] ) && $wgPasswordResetRoutes['domain'] ) {
86 $domains = $wgAuth->domainList();
87 $a['Domain'] = array(
88 'type' => 'select',
89 'options' => $domains,
90 'label-message' => 'passwordreset-domain',
91 );
92 }
93
94 if ( $this->getUser()->isAllowed( 'passwordreset' ) ) {
95 $a['Capture'] = array(
96 'type' => 'check',
97 'label-message' => 'passwordreset-capture',
98 'help-message' => 'passwordreset-capture-help',
99 );
100 }
101
102 return $a;
103 }
104
105 public function alterForm( HTMLForm $form ) {
106 global $wgPasswordResetRoutes;
107
108 $form->setDisplayFormat( 'vform' );
109 // Turn the old-school line around the form off.
110 // XXX This wouldn't be necessary here if we could set the format of
111 // the HTMLForm to 'vform' at its creation, but there's no way to do so
112 // from a FormSpecialPage class.
113 $form->setWrapperLegend( false );
114
115 $i = 0;
116 if ( isset( $wgPasswordResetRoutes['username'] ) && $wgPasswordResetRoutes['username'] ) {
117 $i++;
118 }
119 if ( isset( $wgPasswordResetRoutes['email'] ) && $wgPasswordResetRoutes['email'] ) {
120 $i++;
121 }
122 if ( isset( $wgPasswordResetRoutes['domain'] ) && $wgPasswordResetRoutes['domain'] ) {
123 $i++;
124 }
125
126 $message = ( $i > 1 ) ? 'passwordreset-text-many' : 'passwordreset-text-one';
127
128 $form->setHeaderText( $this->msg( $message, $i )->parseAsBlock() );
129 $form->setSubmitTextMsg( 'mailmypassword' );
130 }
131
132 /**
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 $data array
137 * @throws MWException
138 * @throws ThrottledError|PermissionsError
139 * @return Bool|Array
140 */
141 public function onSubmit( array $data ) {
142 global $wgAuth;
143
144 if ( isset( $data['Domain'] ) ) {
145 if ( $wgAuth->validDomain( $data['Domain'] ) ) {
146 $wgAuth->setDomain( $data['Domain'] );
147 } else {
148 $wgAuth->setDomain( 'invaliddomain' );
149 }
150 }
151
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' );
156 }
157
158 /**
159 * @var $firstUser User
160 * @var $users User[]
161 */
162
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'] )
169 ) {
170 $method = 'email';
171 $res = wfGetDB( DB_SLAVE )->select(
172 'user',
173 User::selectFields(),
174 array( 'user_email' => $data['Email'] ),
175 __METHOD__
176 );
177
178 if ( $res ) {
179 $users = array();
180
181 foreach ( $res as $row ) {
182 $users[] = User::newFromRow( $row );
183 }
184 } else {
185 // Some sort of database error, probably unreachable
186 throw new MWException( 'Unknown database error in ' . __METHOD__ );
187 }
188 } else {
189 // The user didn't supply any data
190 return false;
191 }
192
193 // Check for hooks (captcha etc), and allow them to modify the users list
194 $error = array();
195 if ( !wfRunHooks( 'SpecialPasswordResetOnSubmit', array( &$users, $data, &$error ) ) ) {
196 return array( $error );
197 }
198
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' );
205 }
206 }
207
208 $firstUser = $users[0];
209
210 if ( !$firstUser instanceof User || !$firstUser->getID() ) {
211 return array( array( 'nosuchuser', $data['Username'] ) );
212 }
213
214 // Check against the rate limiter
215 if ( $this->getUser()->pingLimiter( 'mailpassword' ) ) {
216 throw new ThrottledError;
217 }
218
219 // Check against password throttle
220 foreach ( $users as $user ) {
221 if ( $user->isPasswordReminderThrottled() ) {
222 global $wgPasswordReminderResendTime;
223
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( $wgPasswordReminderResendTime, 3 )
229 ) );
230 }
231 }
232
233 global $wgNewPasswordExpiry;
234
235 // All the users will have the same email address
236 if ( $firstUser->getEmail() == '' ) {
237 // This won't be reachable from the email route, so safe to expose the username
238 return array( array( 'noemail', $firstUser->getName() ) );
239 }
240
241 // We need to have a valid IP address for the hook, but per bug 18347, we should
242 // send the user's name if they're logged in.
243 $ip = $this->getRequest()->getIP();
244 if ( !$ip ) {
245 return array( 'badipaddress' );
246 }
247 $caller = $this->getUser();
248 wfRunHooks( 'User::mailPasswordInternal', array( &$caller, &$ip, &$firstUser ) );
249 $username = $caller->getName();
250 $msg = IP::isValid( $username )
251 ? 'passwordreset-emailtext-ip'
252 : 'passwordreset-emailtext-user';
253
254 // Send in the user's language; which should hopefully be the same
255 $userLanguage = $firstUser->getOption( 'language' );
256
257 $passwords = array();
258 foreach ( $users as $user ) {
259 $password = $user->randomPassword();
260 $user->setNewpassword( $password );
261 $user->saveSettings();
262 $passwords[] = $this->msg( 'passwordreset-emailelement', $user->getName(), $password )
263 ->inLanguage( $userLanguage )->text(); // We'll escape the whole thing later
264 }
265 $passwordBlock = implode( "\n\n", $passwords );
266
267 $this->email = $this->msg( $msg )->inLanguage( $userLanguage );
268 $this->email->params(
269 $username,
270 $passwordBlock,
271 count( $passwords ),
272 '<' . Title::newMainPage()->getCanonicalURL() . '>',
273 round( $wgNewPasswordExpiry / 86400 )
274 );
275
276 $title = $this->msg( 'passwordreset-emailtitle' );
277
278 $this->result = $firstUser->sendMail( $title->escaped(), $this->email->text() );
279
280 if ( isset( $data['Capture'] ) && $data['Capture'] ) {
281 // Save the user, will be used if an error occurs when sending the email
282 $this->firstUser = $firstUser;
283 } else {
284 // Blank the email if the user is not supposed to see it
285 $this->email = null;
286 }
287
288 if ( $this->result->isGood() ) {
289 return true;
290 } elseif ( isset( $data['Capture'] ) && $data['Capture'] ) {
291 // The email didn't send, but maybe they knew that and that's why they captured it
292 return true;
293 } else {
294 // @todo FIXME: The email wasn't sent, but we have already set
295 // the password throttle timestamp, so they won't be able to try
296 // again until it expires... :(
297 return array( array( 'mailerror', $this->result->getMessage() ) );
298 }
299 }
300
301 public function onSuccess() {
302 if ( $this->getUser()->isAllowed( 'passwordreset' ) && $this->email != null ) {
303 // @todo Logging
304
305 if ( $this->result->isGood() ) {
306 $this->getOutput()->addWikiMsg( 'passwordreset-emailsent-capture' );
307 } else {
308 $this->getOutput()->addWikiMsg( 'passwordreset-emailerror-capture',
309 $this->result->getMessage(), $this->firstUser->getName() );
310 }
311
312 $this->getOutput()->addHTML( Html::rawElement( 'pre', array(), $this->email->escaped() ) );
313 }
314
315 $this->getOutput()->addWikiMsg( 'passwordreset-emailsent' );
316 $this->getOutput()->returnToMain();
317 }
318
319 protected function canChangePassword( User $user ) {
320 global $wgPasswordResetRoutes, $wgEnableEmail, $wgAuth;
321
322 // Maybe password resets are disabled, or there are no allowable routes
323 if ( !is_array( $wgPasswordResetRoutes ) ||
324 !in_array( true, array_values( $wgPasswordResetRoutes ) )
325 ) {
326 return 'passwordreset-disabled';
327 }
328
329 // Maybe the external auth plugin won't allow local password changes
330 if ( !$wgAuth->allowPasswordChange() ) {
331 return 'resetpass_forbidden';
332 }
333
334 // Maybe email features have been disabled
335 if ( !$wgEnableEmail ) {
336 return 'passwordreset-emaildisabled';
337 }
338
339 // Maybe the user is blocked (check this here rather than relying on the parent
340 // method as we have a more specific error message to use here
341 if ( $user->isBlocked() ) {
342 return 'blocked-mailpassword';
343 }
344
345 return true;
346 }
347
348 /**
349 * Hide the password reset page if resets are disabled.
350 * @return Bool
351 */
352 function isListed() {
353 if ( $this->canChangePassword( $this->getUser() ) === true ) {
354 return parent::isListed();
355 }
356
357 return false;
358 }
359
360 protected function getGroupName() {
361 return 'users';
362 }
363 }