3 * Implements Special:UserLogin
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.
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.
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
21 * @ingroup SpecialPage
25 * Implements Special:UserLogin
27 * @ingroup SpecialPage
29 class LoginForm
extends SpecialPage
{
34 const WRONG_PLUGIN_PASS
= 3;
40 const CREATE_BLOCKED
= 9;
42 const USER_BLOCKED
= 11;
43 const NEED_TOKEN
= 12;
44 const WRONG_TOKEN
= 13;
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;
57 private $mExtUser = null;
62 private $mOverrideRequest = null;
65 * @param WebRequest $request
67 public function __construct( $request = null ) {
68 parent
::__construct( 'Userlogin' );
70 $this->mOverrideRequest
= $request;
77 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
79 if ( $this->mLoaded
) {
82 $this->mLoaded
= true;
84 if ( $this->mOverrideRequest
=== null ) {
85 $request = $this->getRequest();
87 $request = $this->mOverrideRequest
;
90 $this->mType
= $request->getText( 'type' );
91 $this->mUsername
= $request->getText( 'wpName' );
92 $this->mPassword
= $request->getText( 'wpPassword' );
93 $this->mRetype
= $request->getText( 'wpRetype' );
94 $this->mDomain
= $request->getText( 'wpDomain' );
95 $this->mReason
= $request->getText( 'wpReason' );
96 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
97 $this->mPosted
= $request->wasPosted();
98 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
100 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' ) && !$this->mCreateaccountMail
;
101 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
102 $this->mAction
= $request->getVal( 'action' );
103 $this->mRemember
= $request->getCheck( 'wpRemember' );
104 $this->mStickHTTPS
= $request->getCheck( 'wpStickHTTPS' );
105 $this->mLanguage
= $request->getText( 'uselang' );
106 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
107 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
108 $this->mReturnTo
= $request->getVal( 'returnto', '' );
109 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
111 if( $wgEnableEmail ) {
112 $this->mEmail
= $request->getText( 'wpEmail' );
116 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
117 $this->mRealName
= $request->getText( 'wpRealName' );
119 $this->mRealName
= '';
122 if( !$wgAuth->validDomain( $this->mDomain
) ) {
123 $this->mDomain
= $wgAuth->getDomain();
125 $wgAuth->setDomain( $this->mDomain
);
127 # 1. When switching accounts, it sucks to get automatically logged out
128 # 2. Do not return to PasswordReset after a successful password change
129 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
130 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
131 if( is_object( $returnToTitle ) && (
132 $returnToTitle->isSpecial( 'Userlogout' )
133 ||
$returnToTitle->isSpecial( 'PasswordReset' ) ) ) {
134 $this->mReturnTo
= '';
135 $this->mReturnToQuery
= '';
139 function getDescription() {
140 return $this->msg( $this->getUser()->isAllowed( 'createaccount' ) ?
141 'userlogin' : 'userloginnocreate' )->text();
144 public function execute( $par ) {
145 if ( session_id() == '' ) {
152 global $wgSecureLogin;
154 $this->mType
!== 'signup' &&
156 WebRequest
::detectProtocol() !== 'https'
158 $title = $this->getFullTitle();
160 'returnto' => $this->mReturnTo
,
161 'returntoquery' => $this->mReturnToQuery
,
162 'wpStickHTTPS' => $this->mStickHTTPS
164 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
165 $this->getOutput()->redirect( $url );
169 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
170 $this->mType
= 'signup';
173 if ( !is_null( $this->mCookieCheck
) ) {
174 $this->onCookieRedirectCheck( $this->mCookieCheck
);
176 } elseif( $this->mPosted
) {
177 if( $this->mCreateaccount
) {
178 $this->addNewAccount();
180 } elseif ( $this->mCreateaccountMail
) {
181 $this->addNewAccountMailPassword();
183 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
184 $this->processLogin();
188 $this->mainLoginForm( '' );
194 function addNewAccountMailPassword() {
195 if ( $this->mEmail
== '' ) {
196 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
200 $status = $this->addNewaccountInternal();
201 if( !$status->isGood() ) {
202 $error = $this->getOutput()->parse( $status->getWikiText() );
203 $this->mainLoginForm( $error );
207 $u = $status->getValue();
209 // Wipe the initial password and mail a temporary one
210 $u->setPassword( null );
212 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
214 wfRunHooks( 'AddNewAccount', array( $u, true ) );
215 $u->addNewUserLogEntry( 'byemail', $this->mReason
);
217 $out = $this->getOutput();
218 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
220 if( !$result->isGood() ) {
221 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
223 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
224 $this->executeReturnTo( 'success' );
232 function addNewAccount() {
233 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
235 # Create the account and abort if there's a problem doing so
236 $status = $this->addNewAccountInternal();
237 if( !$status->isGood() ) {
238 $error = $this->getOutput()->parse( $status->getWikiText() );
239 $this->mainLoginForm( $error );
243 $u = $status->getValue();
245 # If we showed up language selection links, and one was in use, be
246 # smart (and sensible) and save that language as the user's preference
247 if( $wgLoginLanguageSelector && $this->mLanguage
) {
248 $u->setOption( 'language', $this->mLanguage
);
251 $out = $this->getOutput();
253 # Send out an email authentication message if needed
254 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
255 $status = $u->sendConfirmationMail();
256 if( $status->isGood() ) {
257 $out->addWikiMsg( 'confirmemail_oncreate' );
259 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
263 # Save settings (including confirmation token)
266 # If not logged in, assume the new account as the current one and set
267 # session cookies then show a "welcome" message or a "need cookies"
269 if( $this->getUser()->isAnon() ) {
272 // This should set it for OutputPage and the Skin
273 // which is needed or the personal links will be
275 $this->getContext()->setUser( $u );
276 wfRunHooks( 'AddNewAccount', array( $u, false ) );
277 $u->addNewUserLogEntry( 'create' );
278 if( $this->hasSessionCookie() ) {
279 $this->successfulCreation();
281 $this->cookieRedirectCheck( 'new' );
284 # Confirm that the account was created
285 $out->setPageTitle( $this->msg( 'accountcreated' ) );
286 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
287 $out->addReturnTo( $this->getTitle() );
288 wfRunHooks( 'AddNewAccount', array( $u, false ) );
289 $u->addNewUserLogEntry( 'create2', $this->mReason
);
295 * Make a new user account using the loaded data.
297 * @throws PermissionsError|ReadOnlyError
300 public function addNewAccountInternal() {
301 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
302 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
304 // If the user passes an invalid domain, something is fishy
305 if( !$wgAuth->validDomain( $this->mDomain
) ) {
306 return Status
::newFatal( 'wrongpassword' );
309 // If we are not allowing users to login locally, we should be checking
310 // to see if the user is actually able to authenticate to the authenti-
311 // cation server before they create an account (otherwise, they can
312 // create a local account and login as any domain user). We only need
313 // to check this for domains that aren't local.
314 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
316 !$wgAuth->canCreateAccounts() &&
317 ( !$wgAuth->userExists( $this->mUsername ||
318 !$wgAuth->authenticate( $this->mUsername
, $this->mPassword
) ) )
320 return Status
::newFatal( 'wrongpassword' );
324 if ( wfReadOnly() ) {
325 throw new ReadOnlyError
;
328 # Request forgery checks.
329 if ( !self
::getCreateaccountToken() ) {
330 self
::setCreateaccountToken();
331 return Status
::newFatal( 'nocookiesfornew' );
334 # The user didn't pass a createaccount token
335 if ( !$this->mToken
) {
336 return Status
::newFatal( 'sessionfailure' );
339 # Validate the createaccount token
340 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
341 return Status
::newFatal( 'sessionfailure' );
345 $currentUser = $this->getUser();
346 $creationBlock = $currentUser->isBlockedFromCreateAccount();
347 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
348 throw new PermissionsError( 'createaccount' );
349 } elseif ( $creationBlock instanceof Block
) {
350 // Throws an ErrorPageError.
351 $this->userBlockedMessage( $creationBlock );
352 // This should never be reached.
356 # Include checks that will include GlobalBlocking (Bug 38333)
357 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'createaccount', $currentUser, true );
358 if ( count( $permErrors ) ) {
359 throw new PermissionsError( 'createaccount', $permErrors );
362 $ip = $this->getRequest()->getIP();
363 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
364 return Status
::newFatal( 'sorbs_create_account_reason' );
367 # Now create a dummy user ($u) and check if it is valid
368 $name = trim( $this->mUsername
);
369 $u = User
::newFromName( $name, 'creatable' );
370 if ( !is_object( $u ) ) {
371 return Status
::newFatal( 'noname' );
372 } elseif ( 0 != $u->idForName() ) {
373 return Status
::newFatal( 'userexists' );
374 } elseif ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
375 return Status
::newFatal( 'badretype' );
378 # check for minimal password length
379 $valid = $u->getPasswordValidity( $this->mPassword
);
380 if ( $valid !== true ) {
381 if ( !$this->mCreateaccountMail
) {
382 if ( !is_array( $valid ) ) {
383 $valid = array( $valid, $wgMinimalPasswordLength );
385 return call_user_func_array( 'Status::newFatal', $valid );
387 # do not force a password for account creation by email
388 # set invalid password, it will be replaced later by a random generated password
389 $this->mPassword
= null;
393 # if you need a confirmed email address to edit, then obviously you
394 # need an email address.
395 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
396 return Status
::newFatal( 'noemailtitle' );
399 if( !empty( $this->mEmail
) && !Sanitizer
::validateEmail( $this->mEmail
) ) {
400 return Status
::newFatal( 'invalidemailaddress' );
403 # Set some additional data so the AbortNewAccount hook can be used for
404 # more than just username validation
405 $u->setEmail( $this->mEmail
);
406 $u->setRealName( $this->mRealName
);
409 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
410 // Hook point to add extra creation throttles and blocks
411 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
412 return Status
::newFatal( new RawMessage( $abortError ) );
415 // Hook point to check for exempt from account creation throttle
416 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
417 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
419 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
420 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
421 $value = $wgMemc->get( $key );
423 $wgMemc->set( $key, 0, 86400 );
425 if ( $value >= $wgAccountCreationThrottle ) {
426 return Status
::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
428 $wgMemc->incr( $key );
432 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
433 return Status
::newFatal( 'externaldberror' );
436 self
::clearCreateaccountToken();
437 return $this->initUser( $u, false );
441 * Actually add a user to the database.
442 * Give it a User object that has been initialised with a name.
444 * @param $u User object.
445 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
446 * @return Status object, with the User object in the value member on success
449 function initUser( $u, $autocreate ) {
452 $status = $u->addToDatabase();
453 if ( !$status->isOK() ) {
457 if ( $wgAuth->allowPasswordChange() ) {
458 $u->setPassword( $this->mPassword
);
461 $u->setEmail( $this->mEmail
);
462 $u->setRealName( $this->mRealName
);
465 $wgAuth->initUser( $u, $autocreate );
467 if ( $this->mExtUser
) {
468 $this->mExtUser
->linkToLocal( $u->getId() );
469 $email = $this->mExtUser
->getPref( 'emailaddress' );
470 if ( $email && !$this->mEmail
) {
471 $u->setEmail( $email );
475 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
479 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
481 return Status
::newGood( $u );
485 * Internally authenticate the login request.
487 * This may create a local account as a side effect if the
488 * authentication plugin allows transparent local account
492 public function authenticateUserData() {
493 global $wgUser, $wgAuth;
497 if ( $this->mUsername
== '' ) {
498 return self
::NO_NAME
;
501 // We require a login token to prevent login CSRF
502 // Handle part of this before incrementing the throttle so
503 // token-less login attempts don't count towards the throttle
504 // but wrong-token attempts do.
506 // If the user doesn't have a login token yet, set one.
507 if ( !self
::getLoginToken() ) {
508 self
::setLoginToken();
509 return self
::NEED_TOKEN
;
511 // If the user didn't pass a login token, tell them we need one
512 if ( !$this->mToken
) {
513 return self
::NEED_TOKEN
;
516 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
517 if ( $throttleCount === true ) {
518 return self
::THROTTLED
;
521 // Validate the login token
522 if ( $this->mToken
!== self
::getLoginToken() ) {
523 return self
::WRONG_TOKEN
;
526 // Load the current user now, and check to see if we're logging in as
527 // the same name. This is necessary because loading the current user
528 // (say by calling getName()) calls the UserLoadFromSession hook, which
529 // potentially creates the user in the database. Until we load $wgUser,
530 // checking for user existence using User::newFromName($name)->getId() below
531 // will effectively be using stale data.
532 if ( $this->getUser()->getName() === $this->mUsername
) {
533 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
534 return self
::SUCCESS
;
537 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
539 # TODO: Allow some magic here for invalid external names, e.g., let the
540 # user choose a different wiki name.
541 $u = User
::newFromName( $this->mUsername
);
542 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
543 return self
::ILLEGAL
;
546 $isAutoCreated = false;
547 if ( $u->getID() == 0 ) {
548 $status = $this->attemptAutoCreate( $u );
549 if ( $status !== self
::SUCCESS
) {
552 $isAutoCreated = true;
555 global $wgExternalAuthType, $wgAutocreatePolicy;
556 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
557 && is_object( $this->mExtUser
)
558 && $this->mExtUser
->authenticate( $this->mPassword
)
560 # The external user and local user have the same name and
561 # password, so we assume they're the same.
562 $this->mExtUser
->linkToLocal( $u->getID() );
568 // Give general extensions, such as a captcha, a chance to abort logins
569 $abort = self
::ABORTED
;
570 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
574 global $wgBlockDisablesLogin;
575 if ( !$u->checkPassword( $this->mPassword
) ) {
576 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
577 // The e-mailed temporary password should not be used for actu-
578 // al logins; that's a very sloppy habit, and insecure if an
579 // attacker has a few seconds to click "search" on someone's o-
582 // Allow it to be used only to reset the password a single time
583 // to a new value, which won't be in the user's e-mail ar-
586 // For backwards compatibility, we'll still recognize it at the
587 // login form to minimize surprises for people who have been
588 // logging in with a temporary password for some time.
590 // As a side-effect, we can authenticate the user's e-mail ad-
591 // dress if it's not already done, since the temporary password
592 // was sent via e-mail.
593 if( !$u->isEmailConfirmed() ) {
598 // At this point we just return an appropriate code/ indicating
599 // that the UI should show a password reset form; bot inter-
600 // faces etc will probably just fail cleanly here.
601 $retval = self
::RESET_PASS
;
603 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
605 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
606 // If we've enabled it, make it so that a blocked user cannot login
607 $retval = self
::USER_BLOCKED
;
609 $wgAuth->updateUser( $u );
611 // This should set it for OutputPage and the Skin
612 // which is needed or the personal links will be
614 $this->getContext()->setUser( $u );
616 // Please reset throttle for successful logins, thanks!
617 if ( $throttleCount ) {
618 self
::clearLoginThrottle( $this->mUsername
);
621 if ( $isAutoCreated ) {
622 // Must be run after $wgUser is set, for correct new user log
623 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
626 $retval = self
::SUCCESS
;
628 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
633 * Increment the login attempt throttle hit count for the (username,current IP)
634 * tuple unless the throttle was already reached.
635 * @param $username string The user name
636 * @return Bool|Integer The integer hit count or True if it is already at the limit
638 public static function incLoginThrottle( $username ) {
639 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
640 $username = trim( $username ); // sanity
643 if ( is_array( $wgPasswordAttemptThrottle ) ) {
644 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
645 $count = $wgPasswordAttemptThrottle['count'];
646 $period = $wgPasswordAttemptThrottle['seconds'];
648 $throttleCount = $wgMemc->get( $throttleKey );
649 if ( !$throttleCount ) {
650 $wgMemc->add( $throttleKey, 1, $period ); // start counter
651 } elseif ( $throttleCount < $count ) {
652 $wgMemc->incr( $throttleKey );
653 } elseif ( $throttleCount >= $count ) {
658 return $throttleCount;
662 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
663 * @param $username string The user name
666 public static function clearLoginThrottle( $username ) {
667 global $wgMemc, $wgRequest;
668 $username = trim( $username ); // sanity
670 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
671 $wgMemc->delete( $throttleKey );
675 * Attempt to automatically create a user on login. Only succeeds if there
676 * is an external authentication method which allows it.
680 * @return integer Status code
682 function attemptAutoCreate( $user ) {
683 global $wgAuth, $wgAutocreatePolicy;
685 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
686 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
687 return self
::CREATE_BLOCKED
;
691 * If the external authentication plugin allows it, automatically cre-
692 * ate a new account for users that are externally defined but have not
695 if ( $this->mExtUser
) {
696 # mExtUser is neither null nor false, so use the new ExternalAuth
698 if ( $wgAutocreatePolicy == 'never' ) {
699 return self
::NOT_EXISTS
;
701 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
702 return self
::WRONG_PLUGIN_PASS
;
706 if ( !$wgAuth->autoCreate() ) {
707 return self
::NOT_EXISTS
;
709 if ( !$wgAuth->userExists( $user->getName() ) ) {
710 wfDebug( __METHOD__
. ": user does not exist\n" );
711 return self
::NOT_EXISTS
;
713 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
714 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
715 return self
::WRONG_PLUGIN_PASS
;
720 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
721 // Hook point to add extra creation throttles and blocks
722 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
723 $this->mAbortLoginErrorMsg
= $abortError;
724 return self
::ABORTED
;
727 wfDebug( __METHOD__
. ": creating account\n" );
728 $status = $this->initUser( $user, true );
730 if ( !$status->isOK() ) {
731 $errors = $status->getErrorsByType( 'error' );
732 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
733 return self
::ABORTED
;
736 return self
::SUCCESS
;
739 function processLogin() {
740 global $wgMemc, $wgLang, $wgSecureLogin;
742 switch ( $this->authenticateUserData() ) {
744 # We've verified now, update the real record
745 $user = $this->getUser();
746 if( (bool)$this->mRemember
!= (bool)$user->getOption( 'rememberpassword' ) ) {
747 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
748 $user->saveSettings();
750 $user->invalidateCache();
753 if( $wgSecureLogin && !$this->mStickHTTPS
) {
754 $user->setCookies( null, false );
758 self
::clearLoginToken();
760 // Reset the throttle
761 $request = $this->getRequest();
762 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
763 $wgMemc->delete( $key );
765 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
766 /* Replace the language object to provide user interface in
767 * correct language immediately on this first page load.
769 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
770 $userLang = Language
::factory( $code );
772 $this->getContext()->setLanguage( $userLang );
773 // Reset SessionID on Successful login (bug 40995)
774 $this->renewSessionId();
775 $this->successfulLogin();
777 $this->cookieRedirectCheck( 'login' );
781 case self
::NEED_TOKEN
:
782 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
784 case self
::WRONG_TOKEN
:
785 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
789 $this->mainLoginForm( $this->msg( 'noname' )->text() );
791 case self
::WRONG_PLUGIN_PASS
:
792 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
794 case self
::NOT_EXISTS
:
795 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
796 $this->mainLoginForm( $this->msg( 'nosuchuser',
797 wfEscapeWikiText( $this->mUsername
) )->parse() );
799 $this->mainLoginForm( $this->msg( 'nosuchusershort',
800 wfEscapeWikiText( $this->mUsername
) )->text() );
803 case self
::WRONG_PASS
:
804 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
806 case self
::EMPTY_PASS
:
807 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
809 case self
::RESET_PASS
:
810 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
812 case self
::CREATE_BLOCKED
:
813 $this->userBlockedMessage( $this->getUser()->mBlock
);
815 case self
::THROTTLED
:
816 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
818 case self
::USER_BLOCKED
:
819 $this->mainLoginForm( $this->msg( 'login-userblocked',
820 $this->mUsername
)->escaped() );
823 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
826 throw new MWException( 'Unhandled case value' );
830 function resetLoginForm( $error ) {
831 $this->getOutput()->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
832 $reset = new SpecialChangePassword();
833 $reset->setContext( $this->getContext() );
834 $reset->execute( null );
838 * @param $u User object
839 * @param $throttle Boolean
840 * @param $emailTitle String: message name of email title
841 * @param $emailText String: message name of email text
842 * @return Status object
844 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
845 global $wgCanonicalServer, $wgScript, $wgNewPasswordExpiry;
847 if ( $u->getEmail() == '' ) {
848 return Status
::newFatal( 'noemail', $u->getName() );
850 $ip = $this->getRequest()->getIP();
852 return Status
::newFatal( 'badipaddress' );
855 $currentUser = $this->getUser();
856 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
858 $np = $u->randomPassword();
859 $u->setNewpassword( $np, $throttle );
861 $userLanguage = $u->getOption( 'language' );
862 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $wgCanonicalServer . $wgScript . '>',
863 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
864 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
871 * Run any hooks registered for logins, then HTTP redirect to
872 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
873 * nice message here, but that's really not as useful as just being sent to
874 * wherever you logged in from. It should be clear that the action was
875 * successful, given the lack of error messages plus the appearance of your
876 * name in the upper right.
880 function successfulLogin() {
881 # Run any hooks; display injected HTML if any, else redirect
882 $currentUser = $this->getUser();
884 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
886 if( $injected_html !== '' ) {
887 $this->displaySuccessfulAction( $this->msg( 'loginsuccesstitle' ),
888 'loginsuccess', $injected_html );
890 $this->executeReturnTo( 'successredirect' );
895 * Run any hooks registered for logins, then display a message welcoming
900 function successfulCreation() {
901 # Run any hooks; display injected HTML
902 $currentUser = $this->getUser();
904 $welcome_creation_msg = 'welcomecreation-msg';
906 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
909 * Let any extensions change what message is shown.
910 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
913 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
915 $this->displaySuccessfulAction( $this->msg( 'welcomeuser', $this->getUser()->getName() ),
916 $welcome_creation_msg, $injected_html );
920 * Display an "successful action" page.
922 * @param $title string|Message page's title
923 * @param $msgname string
924 * @param $injected_html string
926 private function displaySuccessfulAction( $title, $msgname, $injected_html ) {
927 $out = $this->getOutput();
928 $out->setPageTitle( $title );
930 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
933 $out->addHTML( $injected_html );
935 $this->executeReturnTo( 'success' );
939 * Output a message that informs the user that they cannot create an account because
940 * there is a block on them or their IP which prevents account creation. Note that
941 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
942 * setting on blocks (bug 13611).
943 * @param $block Block the block causing this error
945 function userBlockedMessage( Block
$block ) {
946 # Let's be nice about this, it's likely that this feature will be used
947 # for blocking large numbers of innocent people, e.g. range blocks on
948 # schools. Don't blame it on the user. There's a small chance that it
949 # really is the user's fault, i.e. the username is blocked and they
950 # haven't bothered to log out before trying to create an account to
951 # evade it, but we'll leave that to their guilty conscience to figure
953 throw new ErrorPageError(
954 'cantcreateaccounttitle',
955 'cantcreateaccount-text',
958 $block->mReason ?
$block->mReason
: $this->msg( 'blockednoreason' )->text(),
965 * Add a "return to" link or redirect to it.
967 * @param $type string, one of the following:
968 * - error: display a return to link ignoring $wgRedirectOnLogin
969 * - success: display a return to link using $wgRedirectOnLogin if needed
970 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
972 private function executeReturnTo( $type ) {
973 global $wgRedirectOnLogin, $wgSecureLogin;
975 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
976 $returnTo = $wgRedirectOnLogin;
977 $returnToQuery = array();
979 $returnTo = $this->mReturnTo
;
980 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
983 $returnToTitle = Title
::newFromText( $returnTo );
984 if ( !$returnToTitle ) {
985 $returnToTitle = Title
::newMainPage();
988 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
989 $options = array( 'http' );
991 } elseif( $wgSecureLogin ) {
992 $options = array( 'https' );
993 $proto = PROTO_HTTPS
;
996 $proto = PROTO_RELATIVE
;
999 if ( $type == 'successredirect' ) {
1000 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1001 $this->getOutput()->redirect( $redirectUrl );
1003 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1010 function mainLoginForm( $msg, $msgtype = 'error' ) {
1011 global $wgEnableEmail, $wgEnableUserEmail;
1012 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1013 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
1014 global $wgSecureLogin, $wgPasswordResetRoutes;
1016 $titleObj = $this->getTitle();
1017 $user = $this->getUser();
1019 if ( $this->mType
== 'signup' ) {
1020 // Block signup here if in readonly. Keeps user from
1021 // going through the process (filling out data, etc)
1022 // and being informed later.
1023 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1024 if ( count( $permErrors ) ) {
1025 throw new PermissionsError( 'createaccount', $permErrors );
1026 } elseif ( $user->isBlockedFromCreateAccount() ) {
1027 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1029 } elseif ( wfReadOnly() ) {
1030 throw new ReadOnlyError
;
1034 if ( $this->mUsername
== '' ) {
1035 if ( $user->isLoggedIn() ) {
1036 $this->mUsername
= $user->getName();
1038 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1042 if ( $this->mType
== 'signup' ) {
1043 $template = new UsercreateTemplate();
1044 $q = 'action=submitlogin&type=signup';
1045 $linkq = 'type=login';
1046 $linkmsg = 'gotaccount';
1047 $this->getOutput()->addModules( 'mediawiki.special.userlogin.signup' );
1049 $template = new UserloginTemplate();
1050 $q = 'action=submitlogin&type=login';
1051 $linkq = 'type=signup';
1052 $linkmsg = 'nologin';
1055 if ( $this->mReturnTo
!== '' ) {
1056 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1057 if ( $this->mReturnToQuery
!== '' ) {
1058 $returnto .= '&returntoquery=' .
1059 wfUrlencode( $this->mReturnToQuery
);
1062 $linkq .= $returnto;
1065 # Don't show a "create account" link if the user can't
1066 if( $this->showCreateOrLoginLink( $user ) ) {
1067 # Pass any language selection on to the mode switch link
1068 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1069 $linkq .= '&uselang=' . $this->mLanguage
;
1071 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1072 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1074 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1076 $template->set( 'link', '' );
1079 $resetLink = $this->mType
== 'signup'
1081 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1083 $template->set( 'header', '' );
1084 $template->set( 'name', $this->mUsername
);
1085 $template->set( 'password', $this->mPassword
);
1086 $template->set( 'retype', $this->mRetype
);
1087 $template->set( 'createemailset', $this->mCreateaccountMail
);
1088 $template->set( 'email', $this->mEmail
);
1089 $template->set( 'realname', $this->mRealName
);
1090 $template->set( 'domain', $this->mDomain
);
1091 $template->set( 'reason', $this->mReason
);
1093 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1094 $template->set( 'message', $msg );
1095 $template->set( 'messagetype', $msgtype );
1096 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1097 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1098 $template->set( 'useemail', $wgEnableEmail );
1099 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1100 $template->set( 'emailothers', $wgEnableUserEmail );
1101 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1102 $template->set( 'resetlink', $resetLink );
1103 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1104 $template->set( 'usereason', $user->isLoggedIn() );
1105 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1106 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1107 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1109 if ( $this->mType
== 'signup' ) {
1110 if ( !self
::getCreateaccountToken() ) {
1111 self
::setCreateaccountToken();
1113 $template->set( 'token', self
::getCreateaccountToken() );
1115 if ( !self
::getLoginToken() ) {
1116 self
::setLoginToken();
1118 $template->set( 'token', self
::getLoginToken() );
1121 # Prepare language selection links as needed
1122 if( $wgLoginLanguageSelector ) {
1123 $template->set( 'languages', $this->makeLanguageSelector() );
1124 if( $this->mLanguage
) {
1125 $template->set( 'uselang', $this->mLanguage
);
1129 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1130 // Ditto for signupend
1131 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1132 $loginendHTTPS = $this->msg( 'loginend-https' );
1133 $signupendHTTPS = $this->msg( 'signupend-https' );
1134 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1135 $template->set( 'loginend', $loginendHTTPS->parse() );
1137 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1139 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1140 $template->set( 'signupend', $signupendHTTPS->parse() );
1142 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1145 // Give authentication and captcha plugins a chance to modify the form
1146 $wgAuth->modifyUITemplate( $template, $this->mType
);
1147 if ( $this->mType
== 'signup' ) {
1148 wfRunHooks( 'UserCreateForm', array( &$template ) );
1150 wfRunHooks( 'UserLoginForm', array( &$template ) );
1153 $out = $this->getOutput();
1154 $out->disallowUserJs(); // just in case...
1155 $out->addTemplate( $template );
1165 function showCreateOrLoginLink( &$user ) {
1166 if( $this->mType
== 'signup' ) {
1168 } elseif( $user->isAllowed( 'createaccount' ) ) {
1176 * Check if a session cookie is present.
1178 * This will not pick up a cookie set during _this_ request, but is meant
1179 * to ensure that the client is returning the cookie which was set on a
1180 * previous pass through the system.
1185 function hasSessionCookie() {
1186 global $wgDisableCookieCheck;
1187 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1191 * Get the login token from the current session
1194 public static function getLoginToken() {
1196 return $wgRequest->getSessionData( 'wsLoginToken' );
1200 * Randomly generate a new login token and attach it to the current session
1202 public static function setLoginToken() {
1204 // Generate a token directly instead of using $user->editToken()
1205 // because the latter reuses $_SESSION['wsEditToken']
1206 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1210 * Remove any login token attached to the current session
1212 public static function clearLoginToken() {
1214 $wgRequest->setSessionData( 'wsLoginToken', null );
1218 * Get the createaccount token from the current session
1221 public static function getCreateaccountToken() {
1223 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1227 * Randomly generate a new createaccount token and attach it to the current session
1229 public static function setCreateaccountToken() {
1231 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1235 * Remove any createaccount token attached to the current session
1237 public static function clearCreateaccountToken() {
1239 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1243 * Renew the user's session id, using strong entropy
1245 private function renewSessionId() {
1246 global $wgSecureLogin, $wgCookieSecure;
1247 if( $wgSecureLogin && !$this->mStickHTTPS
) {
1248 $wgCookieSecure = false;
1251 // If either we don't trust PHP's entropy, or if we need
1252 // to change cookie settings when logging in because of
1253 // wpStickHTTPS, then change the session ID manually.
1254 $cookieParams = session_get_cookie_params();
1255 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
1256 session_regenerate_id( false );
1260 wfSetupSession( MWCryptRand
::generateHex( 32 ) );
1268 function cookieRedirectCheck( $type ) {
1269 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1270 $query = array( 'wpCookieCheck' => $type );
1271 if ( $this->mReturnTo
!== '' ) {
1272 $query['returnto'] = $this->mReturnTo
;
1273 $query['returntoquery'] = $this->mReturnToQuery
;
1275 $check = $titleObj->getFullURL( $query );
1277 $this->getOutput()->redirect( $check );
1283 function onCookieRedirectCheck( $type ) {
1284 if ( !$this->hasSessionCookie() ) {
1285 if ( $type == 'new' ) {
1286 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1287 } elseif ( $type == 'login' ) {
1288 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1291 $this->mainLoginForm( $this->msg( 'error' )->text() );
1294 $this->successfulLogin();
1299 * Produce a bar of links which allow the user to select another language
1300 * during login/registration but retain "returnto"
1304 function makeLanguageSelector() {
1305 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1306 if( !$msg->isBlank() ) {
1307 $langs = explode( "\n", $msg->text() );
1309 foreach( $langs as $lang ) {
1310 $lang = trim( $lang, '* ' );
1311 $parts = explode( '|', $lang );
1312 if ( count( $parts ) >= 2 ) {
1313 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1316 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1317 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1324 * Create a language selector link for a particular language
1325 * Links back to this page preserving type and returnto
1327 * @param $text Link text
1328 * @param $lang Language code
1331 function makeLanguageSelectorLink( $text, $lang ) {
1332 if( $this->getLanguage()->getCode() == $lang ) {
1333 // no link for currently used language
1334 return htmlspecialchars( $text );
1336 $query = array( 'uselang' => $lang );
1337 if( $this->mType
== 'signup' ) {
1338 $query['type'] = 'signup';
1340 if( $this->mReturnTo
!== '' ) {
1341 $query['returnto'] = $this->mReturnTo
;
1342 $query['returntoquery'] = $this->mReturnToQuery
;
1346 $targetLanguage = Language
::factory( $lang );
1347 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1349 return Linker
::linkKnown(
1351 htmlspecialchars( $text ),