Bug 32673: Keep the username in the input field if not existing
[lhc/web/wiklou.git] / includes / specials / SpecialUserlogin.php
1 <?php
2 /**
3 * Implements Special:UserLogin
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 * Implements Special:UserLogin
26 *
27 * @ingroup SpecialPage
28 */
29 class LoginForm extends SpecialPage {
30
31 const SUCCESS = 0;
32 const NO_NAME = 1;
33 const ILLEGAL = 2;
34 const WRONG_PLUGIN_PASS = 3;
35 const NOT_EXISTS = 4;
36 const WRONG_PASS = 5;
37 const EMPTY_PASS = 6;
38 const RESET_PASS = 7;
39 const ABORTED = 8;
40 const CREATE_BLOCKED = 9;
41 const THROTTLED = 10;
42 const USER_BLOCKED = 11;
43 const NEED_TOKEN = 12;
44 const WRONG_TOKEN = 13;
45
46 var $mUsername, $mPassword, $mRetype, $mReturnTo, $mCookieCheck, $mPosted;
47 var $mAction, $mCreateaccount, $mCreateaccountMail;
48 var $mLoginattempt, $mRemember, $mEmail, $mDomain, $mLanguage;
49 var $mSkipCookieCheck, $mReturnToQuery, $mToken, $mStickHTTPS;
50 var $mType, $mReason, $mRealName;
51 var $mAbortLoginErrorMsg = 'login-abort-generic';
52 private $mLoaded = false;
53
54 /**
55 * @var ExternalUser
56 */
57 private $mExtUser = null;
58
59 /**
60 * @ var WebRequest
61 */
62 private $mOverrideRequest = null;
63
64 /**
65 * @param WebRequest $request
66 */
67 public function __construct( $request = null ) {
68 parent::__construct( 'Userlogin' );
69
70 $this->mOverrideRequest = $request;
71 }
72
73 /**
74 * Loader
75 *
76 * @param $request WebRequest object
77 */
78 function load() {
79 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail, $wgRedirectOnLogin;
80
81 if ( $this->mLoaded ) {
82 return;
83 }
84 $this->mLoaded = true;
85
86 if ( $this->mOverrideRequest === null ) {
87 $request = $this->getRequest();
88 } else {
89 $request = $this->mOverrideRequest;
90 }
91
92 $this->mType = $request->getText( 'type' );
93 $this->mUsername = $request->getText( 'wpName' );
94 $this->mPassword = $request->getText( 'wpPassword' );
95 $this->mRetype = $request->getText( 'wpRetype' );
96 $this->mDomain = $request->getText( 'wpDomain' );
97 $this->mReason = $request->getText( 'wpReason' );
98 $this->mReturnTo = $request->getVal( 'returnto' );
99 $this->mReturnToQuery = $request->getVal( 'returntoquery' );
100 $this->mCookieCheck = $request->getVal( 'wpCookieCheck' );
101 $this->mPosted = $request->wasPosted();
102 $this->mCreateaccount = $request->getCheck( 'wpCreateaccount' );
103 $this->mCreateaccountMail = $request->getCheck( 'wpCreateaccountMail' )
104 && $wgEnableEmail;
105 $this->mLoginattempt = $request->getCheck( 'wpLoginattempt' );
106 $this->mAction = $request->getVal( 'action' );
107 $this->mRemember = $request->getCheck( 'wpRemember' );
108 $this->mStickHTTPS = $request->getCheck( 'wpStickHTTPS' );
109 $this->mLanguage = $request->getText( 'uselang' );
110 $this->mSkipCookieCheck = $request->getCheck( 'wpSkipCookieCheck' );
111 $this->mToken = ( $this->mType == 'signup' ) ? $request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
112
113 if ( $wgRedirectOnLogin ) {
114 $this->mReturnTo = $wgRedirectOnLogin;
115 $this->mReturnToQuery = '';
116 }
117
118 if( $wgEnableEmail ) {
119 $this->mEmail = $request->getText( 'wpEmail' );
120 } else {
121 $this->mEmail = '';
122 }
123 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
124 $this->mRealName = $request->getText( 'wpRealName' );
125 } else {
126 $this->mRealName = '';
127 }
128
129 if( !$wgAuth->validDomain( $this->mDomain ) ) {
130 $this->mDomain = 'invaliddomain';
131 }
132 $wgAuth->setDomain( $this->mDomain );
133
134 # When switching accounts, it sucks to get automatically logged out
135 $returnToTitle = Title::newFromText( $this->mReturnTo );
136 if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
137 $this->mReturnTo = '';
138 $this->mReturnToQuery = '';
139 }
140 }
141
142 function getDescription() {
143 return $this->msg( $this->getUser()->isAllowed( 'createaccount' ) ?
144 'userlogin' : 'userloginnocreate' )->text();
145 }
146
147 public function execute( $par ) {
148 if ( session_id() == '' ) {
149 wfSetupSession();
150 }
151
152 $this->load();
153 $this->setHeaders();
154
155 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
156 $this->mType = 'signup';
157 }
158
159 if ( !is_null( $this->mCookieCheck ) ) {
160 $this->onCookieRedirectCheck( $this->mCookieCheck );
161 return;
162 } elseif( $this->mPosted ) {
163 if( $this->mCreateaccount ) {
164 return $this->addNewAccount();
165 } elseif ( $this->mCreateaccountMail ) {
166 return $this->addNewAccountMailPassword();
167 } elseif ( ( 'submitlogin' == $this->mAction ) || $this->mLoginattempt ) {
168 return $this->processLogin();
169 }
170 }
171 $this->mainLoginForm( '' );
172 }
173
174 /**
175 * @private
176 */
177 function addNewAccountMailPassword() {
178 if ( $this->mEmail == '' ) {
179 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
180 return;
181 }
182
183 $u = $this->addNewaccountInternal();
184
185 if ( $u == null ) {
186 return;
187 }
188
189 // Wipe the initial password and mail a temporary one
190 $u->setPassword( null );
191 $u->saveSettings();
192 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
193
194 wfRunHooks( 'AddNewAccount', array( $u, true ) );
195 $u->addNewUserLogEntry( true, $this->mReason );
196
197 $out = $this->getOutput();
198 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
199
200 if( !$result->isGood() ) {
201 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
202 } else {
203 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
204 $out->returnToMain( false );
205 }
206 }
207
208 /**
209 * @private
210 */
211 function addNewAccount() {
212 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
213
214 # Create the account and abort if there's a problem doing so
215 $u = $this->addNewAccountInternal();
216 if( $u == null ) {
217 return;
218 }
219
220 # If we showed up language selection links, and one was in use, be
221 # smart (and sensible) and save that language as the user's preference
222 if( $wgLoginLanguageSelector && $this->mLanguage ) {
223 $u->setOption( 'language', $this->mLanguage );
224 }
225
226 $out = $this->getOutput();
227
228 # Send out an email authentication message if needed
229 if( $wgEmailAuthentication && Sanitizer::validateEmail( $u->getEmail() ) ) {
230 $status = $u->sendConfirmationMail();
231 if( $status->isGood() ) {
232 $out->addWikiMsg( 'confirmemail_oncreate' );
233 } else {
234 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
235 }
236 }
237
238 # Save settings (including confirmation token)
239 $u->saveSettings();
240
241 # If not logged in, assume the new account as the current one and set
242 # session cookies then show a "welcome" message or a "need cookies"
243 # message as needed
244 if( $this->getUser()->isAnon() ) {
245 $u->setCookies();
246 $wgUser = $u;
247 // This should set it for OutputPage and the Skin
248 // which is needed or the personal links will be
249 // wrong.
250 $this->getContext()->setUser( $u );
251 wfRunHooks( 'AddNewAccount', array( $u, false ) );
252 $u->addNewUserLogEntry();
253 if( $this->hasSessionCookie() ) {
254 return $this->successfulCreation();
255 } else {
256 return $this->cookieRedirectCheck( 'new' );
257 }
258 } else {
259 # Confirm that the account was created
260 $out->setPageTitle( $this->msg( 'accountcreated' ) );
261 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
262 $out->returnToMain( false, $this->getTitle() );
263 wfRunHooks( 'AddNewAccount', array( $u, false ) );
264 $u->addNewUserLogEntry( false, $this->mReason );
265 return true;
266 }
267 }
268
269 /**
270 * @private
271 */
272 function addNewAccountInternal() {
273 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
274 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
275
276 // If the user passes an invalid domain, something is fishy
277 if( !$wgAuth->validDomain( $this->mDomain ) ) {
278 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
279 return false;
280 }
281
282 // If we are not allowing users to login locally, we should be checking
283 // to see if the user is actually able to authenticate to the authenti-
284 // cation server before they create an account (otherwise, they can
285 // create a local account and login as any domain user). We only need
286 // to check this for domains that aren't local.
287 if( 'local' != $this->mDomain && $this->mDomain != '' ) {
288 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername )
289 || !$wgAuth->authenticate( $this->mUsername, $this->mPassword ) ) ) {
290 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
291 return false;
292 }
293 }
294
295 if ( wfReadOnly() ) {
296 throw new ReadOnlyError;
297 }
298
299 # Request forgery checks.
300 if ( !self::getCreateaccountToken() ) {
301 self::setCreateaccountToken();
302 $this->mainLoginForm( $this->msg( 'nocookiesfornew' )->parse() );
303 return false;
304 }
305
306 # The user didn't pass a createaccount token
307 if ( !$this->mToken ) {
308 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
309 return false;
310 }
311
312 # Validate the createaccount token
313 if ( $this->mToken !== self::getCreateaccountToken() ) {
314 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
315 return false;
316 }
317
318 # Check permissions
319 $currentUser = $this->getUser();
320 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
321 throw new PermissionsError( 'createaccount' );
322 } elseif ( $currentUser->isBlockedFromCreateAccount() ) {
323 $this->userBlockedMessage( $currentUser->isBlockedFromCreateAccount() );
324 return false;
325 }
326
327 $ip = $this->getRequest()->getIP();
328 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
329 $this->mainLoginForm( $this->msg( 'sorbs_create_account_reason' )->text() . ' (' . htmlspecialchars( $ip ) . ')' );
330 return false;
331 }
332
333 # Now create a dummy user ($u) and check if it is valid
334 $name = trim( $this->mUsername );
335 $u = User::newFromName( $name, 'creatable' );
336 if ( !is_object( $u ) ) {
337 $this->mainLoginForm( $this->msg( 'noname' )->text() );
338 return false;
339 }
340
341 if ( 0 != $u->idForName() ) {
342 $this->mainLoginForm( $this->msg( 'userexists' )->text() );
343 return false;
344 }
345
346 if ( 0 != strcmp( $this->mPassword, $this->mRetype ) ) {
347 $this->mainLoginForm( $this->msg( 'badretype' )->text() );
348 return false;
349 }
350
351 # check for minimal password length
352 $valid = $u->getPasswordValidity( $this->mPassword );
353 if ( $valid !== true ) {
354 if ( !$this->mCreateaccountMail ) {
355 if ( is_array( $valid ) ) {
356 $message = array_shift( $valid );
357 $params = $valid;
358 } else {
359 $message = $valid;
360 $params = array( $wgMinimalPasswordLength );
361 }
362 $this->mainLoginForm( $this->msg( $message, $params )->text() );
363 return false;
364 } else {
365 # do not force a password for account creation by email
366 # set invalid password, it will be replaced later by a random generated password
367 $this->mPassword = null;
368 }
369 }
370
371 # if you need a confirmed email address to edit, then obviously you
372 # need an email address.
373 if ( $wgEmailConfirmToEdit && empty( $this->mEmail ) ) {
374 $this->mainLoginForm( $this->msg( 'noemailtitle' )->text() );
375 return false;
376 }
377
378 if( !empty( $this->mEmail ) && !Sanitizer::validateEmail( $this->mEmail ) ) {
379 $this->mainLoginForm( $this->msg( 'invalidemailaddress' )->text() );
380 return false;
381 }
382
383 # Set some additional data so the AbortNewAccount hook can be used for
384 # more than just username validation
385 $u->setEmail( $this->mEmail );
386 $u->setRealName( $this->mRealName );
387
388 $abortError = '';
389 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
390 // Hook point to add extra creation throttles and blocks
391 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
392 $this->mainLoginForm( $abortError );
393 return false;
394 }
395
396 // Hook point to check for exempt from account creation throttle
397 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
398 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
399 } else {
400 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
401 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
402 $value = $wgMemc->get( $key );
403 if ( !$value ) {
404 $wgMemc->set( $key, 0, 86400 );
405 }
406 if ( $value >= $wgAccountCreationThrottle ) {
407 $this->throttleHit( $wgAccountCreationThrottle );
408 return false;
409 }
410 $wgMemc->incr( $key );
411 }
412 }
413
414 if( !$wgAuth->addUser( $u, $this->mPassword, $this->mEmail, $this->mRealName ) ) {
415 $this->mainLoginForm( $this->msg( 'externaldberror' )->text() );
416 return false;
417 }
418
419 self::clearCreateaccountToken();
420 return $this->initUser( $u, false );
421 }
422
423 /**
424 * Actually add a user to the database.
425 * Give it a User object that has been initialised with a name.
426 *
427 * @param $u User object.
428 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
429 * @return User object.
430 * @private
431 */
432 function initUser( $u, $autocreate ) {
433 global $wgAuth;
434
435 $u->addToDatabase();
436
437 if ( $wgAuth->allowPasswordChange() ) {
438 $u->setPassword( $this->mPassword );
439 }
440
441 $u->setEmail( $this->mEmail );
442 $u->setRealName( $this->mRealName );
443 $u->setToken();
444
445 $wgAuth->initUser( $u, $autocreate );
446
447 if ( $this->mExtUser ) {
448 $this->mExtUser->linkToLocal( $u->getId() );
449 $email = $this->mExtUser->getPref( 'emailaddress' );
450 if ( $email && !$this->mEmail ) {
451 $u->setEmail( $email );
452 }
453 }
454
455 $u->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
456 $u->saveSettings();
457
458 # Update user count
459 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
460 $ssUpdate->doUpdate();
461
462 return $u;
463 }
464
465 /**
466 * Internally authenticate the login request.
467 *
468 * This may create a local account as a side effect if the
469 * authentication plugin allows transparent local account
470 * creation.
471 */
472 public function authenticateUserData() {
473 global $wgUser, $wgAuth;
474
475 $this->load();
476
477 if ( $this->mUsername == '' ) {
478 wfRunHooks( 'LoginAuthenticateAudit', array( new User, $this->mPassword, self::NO_NAME ) );
479 return self::NO_NAME;
480 }
481
482 // We require a login token to prevent login CSRF
483 // Handle part of this before incrementing the throttle so
484 // token-less login attempts don't count towards the throttle
485 // but wrong-token attempts do.
486
487 // If the user doesn't have a login token yet, set one.
488 if ( !self::getLoginToken() ) {
489 self::setLoginToken();
490 wfRunHooks( 'LoginAuthenticateAudit', array( new User, $this->mPassword, self::NEED_TOKEN ) );
491 return self::NEED_TOKEN;
492 }
493 // If the user didn't pass a login token, tell them we need one
494 if ( !$this->mToken ) {
495 wfRunHooks( 'LoginAuthenticateAudit', array( new User, $this->mPassword, self::NEED_TOKEN ) );
496 return self::NEED_TOKEN;
497 }
498
499 $throttleCount = self::incLoginThrottle( $this->mUsername );
500 if ( $throttleCount === true ) {
501 wfRunHooks( 'LoginAuthenticateAudit', array( new User, $this->mPassword, self::THROTTLED ) );
502 return self::THROTTLED;
503 }
504
505 // Validate the login token
506 if ( $this->mToken !== self::getLoginToken() ) {
507 wfRunHooks( 'LoginAuthenticateAudit', array( new User, $this->mPassword, self::WRONG_TOKEN ) );
508 return self::WRONG_TOKEN;
509 }
510
511 // Load the current user now, and check to see if we're logging in as
512 // the same name. This is necessary because loading the current user
513 // (say by calling getName()) calls the UserLoadFromSession hook, which
514 // potentially creates the user in the database. Until we load $wgUser,
515 // checking for user existence using User::newFromName($name)->getId() below
516 // will effectively be using stale data.
517 if ( $this->getUser()->getName() === $this->mUsername ) {
518 wfDebug( __METHOD__ . ": already logged in as {$this->mUsername}\n" );
519 return self::SUCCESS;
520 }
521
522 $this->mExtUser = ExternalUser::newFromName( $this->mUsername );
523
524 # TODO: Allow some magic here for invalid external names, e.g., let the
525 # user choose a different wiki name.
526 $u = User::newFromName( $this->mUsername );
527 if( !( $u instanceof User ) || !User::isUsableName( $u->getName() ) ) {
528 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, self::ILLEGAL ) );
529 return self::ILLEGAL;
530 }
531
532 $isAutoCreated = false;
533 if ( 0 == $u->getID() ) {
534 $status = $this->attemptAutoCreate( $u );
535 if ( $status !== self::SUCCESS ) {
536 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $status ) );
537 return $status;
538 } else {
539 $isAutoCreated = true;
540 }
541 } else {
542 global $wgExternalAuthType, $wgAutocreatePolicy;
543 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
544 && is_object( $this->mExtUser )
545 && $this->mExtUser->authenticate( $this->mPassword ) ) {
546 # The external user and local user have the same name and
547 # password, so we assume they're the same.
548 $this->mExtUser->linkToLocal( $u->getID() );
549 }
550
551 $u->load();
552 }
553
554 // Give general extensions, such as a captcha, a chance to abort logins
555 $abort = self::ABORTED;
556 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword, &$abort, &$this->mAbortLoginErrorMsg ) ) ) {
557 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $abort ) );
558 return $abort;
559 }
560
561 global $wgBlockDisablesLogin;
562 if ( !$u->checkPassword( $this->mPassword ) ) {
563 if( $u->checkTemporaryPassword( $this->mPassword ) ) {
564 // The e-mailed temporary password should not be used for actu-
565 // al logins; that's a very sloppy habit, and insecure if an
566 // attacker has a few seconds to click "search" on someone's o-
567 // pen mail reader.
568 //
569 // Allow it to be used only to reset the password a single time
570 // to a new value, which won't be in the user's e-mail ar-
571 // chives.
572 //
573 // For backwards compatibility, we'll still recognize it at the
574 // login form to minimize surprises for people who have been
575 // logging in with a temporary password for some time.
576 //
577 // As a side-effect, we can authenticate the user's e-mail ad-
578 // dress if it's not already done, since the temporary password
579 // was sent via e-mail.
580 if( !$u->isEmailConfirmed() ) {
581 $u->confirmEmail();
582 $u->saveSettings();
583 }
584
585 // At this point we just return an appropriate code/ indicating
586 // that the UI should show a password reset form; bot inter-
587 // faces etc will probably just fail cleanly here.
588 $retval = self::RESET_PASS;
589 } else {
590 $retval = ( $this->mPassword == '' ) ? self::EMPTY_PASS : self::WRONG_PASS;
591 }
592 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
593 // If we've enabled it, make it so that a blocked user cannot login
594 $retval = self::USER_BLOCKED;
595 } else {
596 $wgAuth->updateUser( $u );
597 $wgUser = $u;
598 // This should set it for OutputPage and the Skin
599 // which is needed or the personal links will be
600 // wrong.
601 $this->getContext()->setUser( $u );
602
603 // Please reset throttle for successful logins, thanks!
604 if ( $throttleCount ) {
605 self::clearLoginThrottle( $this->mUsername );
606 }
607
608 if ( $isAutoCreated ) {
609 // Must be run after $wgUser is set, for correct new user log
610 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
611 }
612
613 $retval = self::SUCCESS;
614 }
615 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $retval ) );
616 return $retval;
617 }
618
619 /**
620 * Increment the login attempt throttle hit count for the (username,current IP)
621 * tuple unless the throttle was already reached.
622 * @param $username string The user name
623 * @return Bool|Integer The integer hit count or True if it is already at the limit
624 */
625 public static function incLoginThrottle( $username ) {
626 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
627 $username = trim( $username ); // sanity
628
629 $throttleCount = 0;
630 if ( is_array( $wgPasswordAttemptThrottle ) ) {
631 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
632 $count = $wgPasswordAttemptThrottle['count'];
633 $period = $wgPasswordAttemptThrottle['seconds'];
634
635 $throttleCount = $wgMemc->get( $throttleKey );
636 if ( !$throttleCount ) {
637 $wgMemc->add( $throttleKey, 1, $period ); // start counter
638 } elseif ( $throttleCount < $count ) {
639 $wgMemc->incr( $throttleKey );
640 } elseif ( $throttleCount >= $count ) {
641 return true;
642 }
643 }
644
645 return $throttleCount;
646 }
647
648 /**
649 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
650 * @param $username string The user name
651 * @return void
652 */
653 public static function clearLoginThrottle( $username ) {
654 global $wgMemc, $wgRequest;
655 $username = trim( $username ); // sanity
656
657 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
658 $wgMemc->delete( $throttleKey );
659 }
660
661 /**
662 * Attempt to automatically create a user on login. Only succeeds if there
663 * is an external authentication method which allows it.
664 *
665 * @param $user User
666 *
667 * @return integer Status code
668 */
669 function attemptAutoCreate( $user ) {
670 global $wgAuth, $wgAutocreatePolicy;
671
672 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
673 wfDebug( __METHOD__ . ": user is blocked from account creation\n" );
674 return self::CREATE_BLOCKED;
675 }
676
677 /**
678 * If the external authentication plugin allows it, automatically cre-
679 * ate a new account for users that are externally defined but have not
680 * yet logged in.
681 */
682 if ( $this->mExtUser ) {
683 # mExtUser is neither null nor false, so use the new ExternalAuth
684 # system.
685 if ( $wgAutocreatePolicy == 'never' ) {
686 return self::NOT_EXISTS;
687 }
688 if ( !$this->mExtUser->authenticate( $this->mPassword ) ) {
689 return self::WRONG_PLUGIN_PASS;
690 }
691 } else {
692 # Old AuthPlugin.
693 if ( !$wgAuth->autoCreate() ) {
694 return self::NOT_EXISTS;
695 }
696 if ( !$wgAuth->userExists( $user->getName() ) ) {
697 wfDebug( __METHOD__ . ": user does not exist\n" );
698 return self::NOT_EXISTS;
699 }
700 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
701 wfDebug( __METHOD__ . ": \$wgAuth->authenticate() returned false, aborting\n" );
702 return self::WRONG_PLUGIN_PASS;
703 }
704 }
705
706 $abortError = '';
707 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
708 // Hook point to add extra creation throttles and blocks
709 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
710 $this->mAbortLoginErrorMsg = $abortError;
711 return self::ABORTED;
712 }
713
714 wfDebug( __METHOD__ . ": creating account\n" );
715 $this->initUser( $user, true );
716 return self::SUCCESS;
717 }
718
719 function processLogin() {
720 global $wgMemc, $wgLang;
721
722 switch ( $this->authenticateUserData() ) {
723 case self::SUCCESS:
724 # We've verified now, update the real record
725 $user = $this->getUser();
726 if( (bool)$this->mRemember != (bool)$user->getOption( 'rememberpassword' ) ) {
727 $user->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
728 $user->saveSettings();
729 } else {
730 $user->invalidateCache();
731 }
732 $user->setCookies();
733 self::clearLoginToken();
734
735 // Reset the throttle
736 $request = $this->getRequest();
737 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername ) );
738 $wgMemc->delete( $key );
739
740 if( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
741 /* Replace the language object to provide user interface in
742 * correct language immediately on this first page load.
743 */
744 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
745 $userLang = Language::factory( $code );
746 $wgLang = $userLang;
747 $this->getContext()->setLanguage( $userLang );
748 return $this->successfulLogin();
749 } else {
750 return $this->cookieRedirectCheck( 'login' );
751 }
752 break;
753
754 case self::NEED_TOKEN:
755 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
756 break;
757 case self::WRONG_TOKEN:
758 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
759 break;
760 case self::NO_NAME:
761 case self::ILLEGAL:
762 $this->mainLoginForm( $this->msg( 'noname' )->text() );
763 break;
764 case self::WRONG_PLUGIN_PASS:
765 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
766 break;
767 case self::NOT_EXISTS:
768 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
769 $this->mainLoginForm( $this->msg( 'nosuchuser',
770 wfEscapeWikiText( $this->mUsername ) )->parse() );
771 } else {
772 $this->mainLoginForm( $this->msg( 'nosuchusershort',
773 wfEscapeWikiText( $this->mUsername ) )->text() );
774 }
775 break;
776 case self::WRONG_PASS:
777 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
778 break;
779 case self::EMPTY_PASS:
780 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
781 break;
782 case self::RESET_PASS:
783 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
784 break;
785 case self::CREATE_BLOCKED:
786 $this->userBlockedMessage( $this->getUser()->mBlock );
787 break;
788 case self::THROTTLED:
789 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
790 break;
791 case self::USER_BLOCKED:
792 $this->mainLoginForm( $this->msg( 'login-userblocked',
793 $this->mUsername )->escaped() );
794 break;
795 case self::ABORTED:
796 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg )->text() );
797 break;
798 default:
799 throw new MWException( 'Unhandled case value' );
800 }
801 }
802
803 function resetLoginForm( $error ) {
804 $this->getOutput()->addHTML( Xml::element('p', array( 'class' => 'error' ), $error ) );
805 $reset = new SpecialChangePassword();
806 $reset->setContext( $this );
807 $reset->execute( null );
808 }
809
810 /**
811 * @param $u User object
812 * @param $throttle Boolean
813 * @param $emailTitle String: message name of email title
814 * @param $emailText String: message name of email text
815 * @return Status object
816 */
817 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
818 global $wgServer, $wgScript, $wgNewPasswordExpiry;
819
820 if ( $u->getEmail() == '' ) {
821 return Status::newFatal( 'noemail', $u->getName() );
822 }
823 $ip = $this->getRequest()->getIP();
824 if( !$ip ) {
825 return Status::newFatal( 'badipaddress' );
826 }
827
828 $currentUser = $this->getUser();
829 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
830
831 $np = $u->randomPassword();
832 $u->setNewpassword( $np, $throttle );
833 $u->saveSettings();
834 $userLanguage = $u->getOption( 'language' );
835 $m = $this->msg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript,
836 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
837 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
838
839 return $result;
840 }
841
842
843 /**
844 * Run any hooks registered for logins, then HTTP redirect to
845 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
846 * nice message here, but that's really not as useful as just being sent to
847 * wherever you logged in from. It should be clear that the action was
848 * successful, given the lack of error messages plus the appearance of your
849 * name in the upper right.
850 *
851 * @private
852 */
853 function successfulLogin() {
854 # Run any hooks; display injected HTML if any, else redirect
855 $currentUser = $this->getUser();
856 $injected_html = '';
857 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
858
859 if( $injected_html !== '' ) {
860 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
861 } else {
862 $titleObj = Title::newFromText( $this->mReturnTo );
863 if ( !$titleObj instanceof Title ) {
864 $titleObj = Title::newMainPage();
865 }
866 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery );
867 global $wgSecureLogin;
868 if( $wgSecureLogin && !$this->mStickHTTPS ) {
869 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
870 }
871 $this->getOutput()->redirect( $redirectUrl );
872 }
873 }
874
875 /**
876 * Run any hooks registered for logins, then display a message welcoming
877 * the user.
878 *
879 * @private
880 */
881 function successfulCreation() {
882 # Run any hooks; display injected HTML
883 $currentUser = $this->getUser();
884 $injected_html = '';
885 $welcome_creation_msg = 'welcomecreation';
886
887 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
888
889 /**
890 * Let any extensions change what message is shown.
891 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
892 * @since 1.18
893 */
894 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
895
896 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
897 }
898
899 /**
900 * Display a "login successful" page.
901 */
902 private function displaySuccessfulLogin( $msgname, $injected_html ) {
903 $out = $this->getOutput();
904 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
905 if( $msgname ){
906 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
907 }
908
909 $out->addHTML( $injected_html );
910
911 if ( !empty( $this->mReturnTo ) ) {
912 $out->returnToMain( null, $this->mReturnTo, $this->mReturnToQuery );
913 } else {
914 $out->returnToMain( null );
915 }
916 }
917
918 /**
919 * Output a message that informs the user that they cannot create an account because
920 * there is a block on them or their IP which prevents account creation. Note that
921 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
922 * setting on blocks (bug 13611).
923 * @param $block Block the block causing this error
924 */
925 function userBlockedMessage( Block $block ) {
926 # Let's be nice about this, it's likely that this feature will be used
927 # for blocking large numbers of innocent people, e.g. range blocks on
928 # schools. Don't blame it on the user. There's a small chance that it
929 # really is the user's fault, i.e. the username is blocked and they
930 # haven't bothered to log out before trying to create an account to
931 # evade it, but we'll leave that to their guilty conscience to figure
932 # out.
933
934 $out = $this->getOutput();
935 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
936
937 $block_reason = $block->mReason;
938 if ( strval( $block_reason ) === '' ) {
939 $block_reason = $this->msg( 'blockednoreason' )->text();
940 }
941
942 $out->addWikiMsg(
943 'cantcreateaccount-text',
944 $block->getTarget(),
945 $block_reason,
946 $block->getByName()
947 );
948
949 $out->returnToMain( false );
950 }
951
952 /**
953 * @private
954 */
955 function mainLoginForm( $msg, $msgtype = 'error' ) {
956 global $wgEnableEmail, $wgEnableUserEmail;
957 global $wgHiddenPrefs, $wgLoginLanguageSelector;
958 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
959 global $wgSecureLogin, $wgPasswordResetRoutes;
960
961 $titleObj = $this->getTitle();
962 $user = $this->getUser();
963
964 if ( $this->mType == 'signup' ) {
965 // Block signup here if in readonly. Keeps user from
966 // going through the process (filling out data, etc)
967 // and being informed later.
968 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
969 if ( count( $permErrors ) ) {
970 throw new PermissionsError( 'createaccount', $permErrors );
971 } elseif ( $user->isBlockedFromCreateAccount() ) {
972 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
973 return;
974 } elseif ( wfReadOnly() ) {
975 throw new ReadOnlyError;
976 }
977 }
978
979 if ( $this->mUsername == '' ) {
980 if ( $user->isLoggedIn() ) {
981 $this->mUsername = $user->getName();
982 } else {
983 $this->mUsername = $this->getRequest()->getCookie( 'UserName' );
984 }
985 }
986
987 if ( $this->mType == 'signup' ) {
988 $template = new UsercreateTemplate();
989 $q = 'action=submitlogin&type=signup';
990 $linkq = 'type=login';
991 $linkmsg = 'gotaccount';
992 } else {
993 $template = new UserloginTemplate();
994 $q = 'action=submitlogin&type=login';
995 $linkq = 'type=signup';
996 $linkmsg = 'nologin';
997 }
998
999 if ( !empty( $this->mReturnTo ) ) {
1000 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
1001 if ( !empty( $this->mReturnToQuery ) ) {
1002 $returnto .= '&returntoquery=' .
1003 wfUrlencode( $this->mReturnToQuery );
1004 }
1005 $q .= $returnto;
1006 $linkq .= $returnto;
1007 }
1008
1009 # Don't show a "create account" link if the user can't
1010 if( $this->showCreateOrLoginLink( $user ) ) {
1011 # Pass any language selection on to the mode switch link
1012 if( $wgLoginLanguageSelector && $this->mLanguage ) {
1013 $linkq .= '&uselang=' . $this->mLanguage;
1014 }
1015 $link = Html::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1016 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1017
1018 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1019 } else {
1020 $template->set( 'link', '' );
1021 }
1022
1023 $resetLink = $this->mType == 'signup'
1024 ? null
1025 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1026
1027 $template->set( 'header', '' );
1028 $template->set( 'name', $this->mUsername );
1029 $template->set( 'password', $this->mPassword );
1030 $template->set( 'retype', $this->mRetype );
1031 $template->set( 'email', $this->mEmail );
1032 $template->set( 'realname', $this->mRealName );
1033 $template->set( 'domain', $this->mDomain );
1034 $template->set( 'reason', $this->mReason );
1035
1036 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1037 $template->set( 'message', $msg );
1038 $template->set( 'messagetype', $msgtype );
1039 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1040 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1041 $template->set( 'useemail', $wgEnableEmail );
1042 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1043 $template->set( 'emailothers', $wgEnableUserEmail );
1044 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1045 $template->set( 'resetlink', $resetLink );
1046 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1047 $template->set( 'usereason', $user->isLoggedIn() );
1048 $template->set( 'remember', $user->getOption( 'rememberpassword' ) || $this->mRemember );
1049 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1050 $template->set( 'stickHTTPS', $this->mStickHTTPS );
1051
1052 if ( $this->mType == 'signup' ) {
1053 if ( !self::getCreateaccountToken() ) {
1054 self::setCreateaccountToken();
1055 }
1056 $template->set( 'token', self::getCreateaccountToken() );
1057 } else {
1058 if ( !self::getLoginToken() ) {
1059 self::setLoginToken();
1060 }
1061 $template->set( 'token', self::getLoginToken() );
1062 }
1063
1064 # Prepare language selection links as needed
1065 if( $wgLoginLanguageSelector ) {
1066 $template->set( 'languages', $this->makeLanguageSelector() );
1067 if( $this->mLanguage )
1068 $template->set( 'uselang', $this->mLanguage );
1069 }
1070
1071 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1072 // Ditto for signupend
1073 $usingHTTPS = WebRequest::detectProtocol() == 'https';
1074 $loginendHTTPS = $this->msg( 'loginend-https' );
1075 $signupendHTTPS = $this->msg( 'signupend-https' );
1076 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1077 $template->set( 'loginend', $loginendHTTPS->parse() );
1078 } else {
1079 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1080 }
1081 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1082 $template->set( 'signupend', $signupendHTTPS->parse() );
1083 } else {
1084 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1085 }
1086
1087 // Give authentication and captcha plugins a chance to modify the form
1088 $wgAuth->modifyUITemplate( $template, $this->mType );
1089 if ( $this->mType == 'signup' ) {
1090 wfRunHooks( 'UserCreateForm', array( &$template ) );
1091 } else {
1092 wfRunHooks( 'UserLoginForm', array( &$template ) );
1093 }
1094
1095 $out = $this->getOutput();
1096 $out->disallowUserJs(); // just in case...
1097 $out->addTemplate( $template );
1098 }
1099
1100 /**
1101 * @private
1102 *
1103 * @param $user User
1104 *
1105 * @return Boolean
1106 */
1107 function showCreateOrLoginLink( &$user ) {
1108 if( $this->mType == 'signup' ) {
1109 return true;
1110 } elseif( $user->isAllowed( 'createaccount' ) ) {
1111 return true;
1112 } else {
1113 return false;
1114 }
1115 }
1116
1117 /**
1118 * Check if a session cookie is present.
1119 *
1120 * This will not pick up a cookie set during _this_ request, but is meant
1121 * to ensure that the client is returning the cookie which was set on a
1122 * previous pass through the system.
1123 *
1124 * @private
1125 */
1126 function hasSessionCookie() {
1127 global $wgDisableCookieCheck;
1128 return $wgDisableCookieCheck ? true : $this->getRequest()->checkSessionCookie();
1129 }
1130
1131 /**
1132 * Get the login token from the current session
1133 */
1134 public static function getLoginToken() {
1135 global $wgRequest;
1136 return $wgRequest->getSessionData( 'wsLoginToken' );
1137 }
1138
1139 /**
1140 * Randomly generate a new login token and attach it to the current session
1141 */
1142 public static function setLoginToken() {
1143 global $wgRequest;
1144 // Use User::generateToken() instead of $user->editToken()
1145 // because the latter reuses $_SESSION['wsEditToken']
1146 $wgRequest->setSessionData( 'wsLoginToken', User::generateToken() );
1147 }
1148
1149 /**
1150 * Remove any login token attached to the current session
1151 */
1152 public static function clearLoginToken() {
1153 global $wgRequest;
1154 $wgRequest->setSessionData( 'wsLoginToken', null );
1155 }
1156
1157 /**
1158 * Get the createaccount token from the current session
1159 */
1160 public static function getCreateaccountToken() {
1161 global $wgRequest;
1162 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1163 }
1164
1165 /**
1166 * Randomly generate a new createaccount token and attach it to the current session
1167 */
1168 public static function setCreateaccountToken() {
1169 global $wgRequest;
1170 $wgRequest->setSessionData( 'wsCreateaccountToken', User::generateToken() );
1171 }
1172
1173 /**
1174 * Remove any createaccount token attached to the current session
1175 */
1176 public static function clearCreateaccountToken() {
1177 global $wgRequest;
1178 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1179 }
1180
1181 /**
1182 * @private
1183 */
1184 function cookieRedirectCheck( $type ) {
1185 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
1186 $query = array( 'wpCookieCheck' => $type );
1187 if ( $this->mReturnTo ) {
1188 $query['returnto'] = $this->mReturnTo;
1189 }
1190 $check = $titleObj->getFullURL( $query );
1191
1192 return $this->getOutput()->redirect( $check );
1193 }
1194
1195 /**
1196 * @private
1197 */
1198 function onCookieRedirectCheck( $type ) {
1199 if ( !$this->hasSessionCookie() ) {
1200 if ( $type == 'new' ) {
1201 return $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1202 } elseif ( $type == 'login' ) {
1203 return $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1204 } else {
1205 # shouldn't happen
1206 return $this->mainLoginForm( $this->msg( 'error' )->text() );
1207 }
1208 } else {
1209 return $this->successfulLogin();
1210 }
1211 }
1212
1213 /**
1214 * @private
1215 */
1216 function throttleHit( $limit ) {
1217 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1218 }
1219
1220 /**
1221 * Produce a bar of links which allow the user to select another language
1222 * during login/registration but retain "returnto"
1223 *
1224 * @return string
1225 */
1226 function makeLanguageSelector() {
1227 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1228 if( !$msg->isBlank() ) {
1229 $langs = explode( "\n", $msg->text() );
1230 $links = array();
1231 foreach( $langs as $lang ) {
1232 $lang = trim( $lang, '* ' );
1233 $parts = explode( '|', $lang );
1234 if ( count( $parts ) >= 2 ) {
1235 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1236 }
1237 }
1238 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1239 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1240 } else {
1241 return '';
1242 }
1243 }
1244
1245 /**
1246 * Create a language selector link for a particular language
1247 * Links back to this page preserving type and returnto
1248 *
1249 * @param $text Link text
1250 * @param $lang Language code
1251 */
1252 function makeLanguageSelectorLink( $text, $lang ) {
1253 $attr = array( 'uselang' => $lang );
1254 if( $this->mType == 'signup' ) {
1255 $attr['type'] = 'signup';
1256 }
1257 if( $this->mReturnTo ) {
1258 $attr['returnto'] = $this->mReturnTo;
1259 }
1260 return Linker::linkKnown(
1261 $this->getTitle(),
1262 htmlspecialchars( $text ),
1263 array(),
1264 $attr
1265 );
1266 }
1267 }