8cad61683b44371cce24a21a266bd002e60ad892
[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 $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',
72 );
73
74 if ( $this->getUser()->isLoggedIn() ) {
75 $a['Username']['default'] = $this->getUser()->getName();
76 }
77 }
78
79 if ( isset( $resetRoutes['email'] ) && $resetRoutes['email'] ) {
80 $a['Email'] = array(
81 'type' => 'email',
82 'label-message' => 'passwordreset-email',
83 );
84 }
85
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',
92 );
93 }
94
95 if ( $this->getUser()->isAllowed( 'passwordreset' ) ) {
96 $a['Capture'] = array(
97 'type' => 'check',
98 'label-message' => 'passwordreset-capture',
99 'help-message' => 'passwordreset-capture-help',
100 );
101 }
102
103 return $a;
104 }
105
106 protected function getDisplayFormat() {
107 return 'ooui';
108 }
109
110 public function alterForm( HTMLForm $form ) {
111 $resetRoutes = $this->getConfig()->get( 'PasswordResetRoutes' );
112
113 $form->addHiddenFields( $this->getRequest()->getValues( 'returnto', 'returntoquery' ) );
114
115 $i = 0;
116 if ( isset( $resetRoutes['username'] ) && $resetRoutes['username'] ) {
117 $i++;
118 }
119 if ( isset( $resetRoutes['email'] ) && $resetRoutes['email'] ) {
120 $i++;
121 }
122 if ( isset( $resetRoutes['domain'] ) && $resetRoutes['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 array $data
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 ( !Hooks::run( '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 // Don't parse username as wikitext (bug 65501)
212 return array( array( 'nosuchuser', wfEscapeWikiText( $data['Username'] ) ) );
213 }
214
215 // Check against the rate limiter
216 if ( $this->getUser()->pingLimiter( 'mailpassword' ) ) {
217 throw new ThrottledError;
218 }
219
220 // Check against password throttle
221 foreach ( $users as $user ) {
222 if ( $user->isPasswordReminderThrottled() ) {
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( $this->getConfig()->get( 'PasswordReminderResendTime' ), 3 )
229 ) );
230 }
231 }
232
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() ) ) );
237 }
238
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' );
244 }
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';
251
252 // Send in the user's language; which should hopefully be the same
253 $userLanguage = $firstUser->getOption( 'language' );
254
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
262 }
263 $passwordBlock = implode( "\n\n", $passwords );
264
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 )
272 );
273
274 $title = $this->msg( 'passwordreset-emailtitle' );
275
276 $this->result = $firstUser->sendMail( $title->text(), $this->email->text() );
277
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;
284 }
285
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() ) );
296 }
297 }
298
299 public function onSuccess() {
300 if ( $this->getUser()->isAllowed( 'passwordreset' ) && $this->email != null ) {
301 // @todo Logging
302
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() );
308 }
309
310 $this->getOutput()->addHTML( Html::rawElement( 'pre', array(), $this->email->escaped() ) );
311 }
312
313 $this->getOutput()->addWikiMsg( 'passwordreset-emailsent' );
314 $this->getOutput()->returnToMain();
315 }
316
317 protected function canChangePassword( User $user ) {
318 global $wgAuth;
319 $resetRoutes = $this->getConfig()->get( 'PasswordResetRoutes' );
320
321 // Maybe password resets are disabled, or there are no allowable routes
322 if ( !is_array( $resetRoutes ) ||
323 !in_array( true, array_values( $resetRoutes ) )
324 ) {
325 return 'passwordreset-disabled';
326 }
327
328 // Maybe the external auth plugin won't allow local password changes
329 if ( !$wgAuth->allowPasswordChange() ) {
330 return 'resetpass_forbidden';
331 }
332
333 // Maybe email features have been disabled
334 if ( !$this->getConfig()->get( 'EnableEmail' ) ) {
335 return 'passwordreset-emaildisabled';
336 }
337
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';
342 }
343
344 return true;
345 }
346
347 /**
348 * Hide the password reset page if resets are disabled.
349 * @return bool
350 */
351 function isListed() {
352 if ( $this->canChangePassword( $this->getUser() ) === true ) {
353 return parent::isListed();
354 }
355
356 return false;
357 }
358
359 protected function getGroupName() {
360 return 'users';
361 }
362 }