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->mCreateaccount
= $request->getCheck( 'wpCreateaccount' );
99 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
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 $u = $this->addNewaccountInternal();
206 // Wipe the initial password and mail a temporary one
207 $u->setPassword( null );
209 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
211 wfRunHooks( 'AddNewAccount', array( $u, true ) );
212 $u->addNewUserLogEntry( true, $this->mReason
);
214 $out = $this->getOutput();
215 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
217 if( !$result->isGood() ) {
218 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
220 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
221 $this->executeReturnTo( 'success' );
229 function addNewAccount() {
230 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
232 # Create the account and abort if there's a problem doing so
233 $u = $this->addNewAccountInternal();
238 # If we showed up language selection links, and one was in use, be
239 # smart (and sensible) and save that language as the user's preference
240 if( $wgLoginLanguageSelector && $this->mLanguage
) {
241 $u->setOption( 'language', $this->mLanguage
);
244 $out = $this->getOutput();
246 # Send out an email authentication message if needed
247 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
248 $status = $u->sendConfirmationMail();
249 if( $status->isGood() ) {
250 $out->addWikiMsg( 'confirmemail_oncreate' );
252 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
256 # Save settings (including confirmation token)
259 # If not logged in, assume the new account as the current one and set
260 # session cookies then show a "welcome" message or a "need cookies"
262 if( $this->getUser()->isAnon() ) {
265 // This should set it for OutputPage and the Skin
266 // which is needed or the personal links will be
268 $this->getContext()->setUser( $u );
269 wfRunHooks( 'AddNewAccount', array( $u, false ) );
270 $u->addNewUserLogEntry();
271 if( $this->hasSessionCookie() ) {
272 $this->successfulCreation();
274 $this->cookieRedirectCheck( 'new' );
277 # Confirm that the account was created
278 $out->setPageTitle( $this->msg( 'accountcreated' ) );
279 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
280 $out->addReturnTo( $this->getTitle() );
281 wfRunHooks( 'AddNewAccount', array( $u, false ) );
282 $u->addNewUserLogEntry( false, $this->mReason
);
289 * @throws PermissionsError|ReadOnlyError
292 function addNewAccountInternal() {
293 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
294 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
296 // If the user passes an invalid domain, something is fishy
297 if( !$wgAuth->validDomain( $this->mDomain
) ) {
298 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
302 // If we are not allowing users to login locally, we should be checking
303 // to see if the user is actually able to authenticate to the authenti-
304 // cation server before they create an account (otherwise, they can
305 // create a local account and login as any domain user). We only need
306 // to check this for domains that aren't local.
307 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
308 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername
)
309 ||
!$wgAuth->authenticate( $this->mUsername
, $this->mPassword
) ) ) {
310 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
315 if ( wfReadOnly() ) {
316 throw new ReadOnlyError
;
319 # Request forgery checks.
320 if ( !self
::getCreateaccountToken() ) {
321 self
::setCreateaccountToken();
322 $this->mainLoginForm( $this->msg( 'nocookiesfornew' )->parse() );
326 # The user didn't pass a createaccount token
327 if ( !$this->mToken
) {
328 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
332 # Validate the createaccount token
333 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
334 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
339 $currentUser = $this->getUser();
340 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
341 throw new PermissionsError( 'createaccount' );
342 } elseif ( $currentUser->isBlockedFromCreateAccount() ) {
343 $this->userBlockedMessage( $currentUser->isBlockedFromCreateAccount() );
347 # Include checks that will include GlobalBlocking (Bug 38333)
348 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'createaccount', $currentUser, true );
349 if ( count( $permErrors ) ) {
350 throw new PermissionsError( 'createaccount', $permErrors );
353 $ip = $this->getRequest()->getIP();
354 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
355 $this->mainLoginForm( $this->msg( 'sorbs_create_account_reason' )->text() . ' ' . $this->msg( 'parentheses', $ip )->escaped() );
359 # Now create a dummy user ($u) and check if it is valid
360 $name = trim( $this->mUsername
);
361 $u = User
::newFromName( $name, 'creatable' );
362 if ( !is_object( $u ) ) {
363 $this->mainLoginForm( $this->msg( 'noname' )->text() );
367 if ( 0 != $u->idForName() ) {
368 $this->mainLoginForm( $this->msg( 'userexists' )->text() );
372 if ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
373 $this->mainLoginForm( $this->msg( 'badretype' )->text() );
377 # check for minimal password length
378 $valid = $u->getPasswordValidity( $this->mPassword
);
379 if ( $valid !== true ) {
380 if ( !$this->mCreateaccountMail
) {
381 if ( is_array( $valid ) ) {
382 $message = array_shift( $valid );
386 $params = array( $wgMinimalPasswordLength );
388 $this->mainLoginForm( $this->msg( $message, $params )->text() );
391 # do not force a password for account creation by email
392 # set invalid password, it will be replaced later by a random generated password
393 $this->mPassword
= null;
397 # if you need a confirmed email address to edit, then obviously you
398 # need an email address.
399 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
400 $this->mainLoginForm( $this->msg( 'noemailtitle' )->text() );
404 if( !empty( $this->mEmail
) && !Sanitizer
::validateEmail( $this->mEmail
) ) {
405 $this->mainLoginForm( $this->msg( 'invalidemailaddress' )->text() );
409 # Set some additional data so the AbortNewAccount hook can be used for
410 # more than just username validation
411 $u->setEmail( $this->mEmail
);
412 $u->setRealName( $this->mRealName
);
415 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
416 // Hook point to add extra creation throttles and blocks
417 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
418 $this->mainLoginForm( $abortError );
422 // Hook point to check for exempt from account creation throttle
423 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
424 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
426 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
427 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
428 $value = $wgMemc->get( $key );
430 $wgMemc->set( $key, 0, 86400 );
432 if ( $value >= $wgAccountCreationThrottle ) {
433 $this->throttleHit( $wgAccountCreationThrottle );
436 $wgMemc->incr( $key );
440 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
441 $this->mainLoginForm( $this->msg( 'externaldberror' )->text() );
445 self
::clearCreateaccountToken();
447 $status = $this->initUser( $u, false );
448 if ( !$status->isOK() ) {
449 $this->mainLoginForm( $status->getHTML() );
452 return $status->value
;
456 * Actually add a user to the database.
457 * Give it a User object that has been initialised with a name.
459 * @param $u User object.
460 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
461 * @return Status object, with the User object in the value member on success
464 function initUser( $u, $autocreate ) {
467 $status = $u->addToDatabase();
468 if ( !$status->isOK() ) {
472 if ( $wgAuth->allowPasswordChange() ) {
473 $u->setPassword( $this->mPassword
);
476 $u->setEmail( $this->mEmail
);
477 $u->setRealName( $this->mRealName
);
480 $wgAuth->initUser( $u, $autocreate );
482 if ( $this->mExtUser
) {
483 $this->mExtUser
->linkToLocal( $u->getId() );
484 $email = $this->mExtUser
->getPref( 'emailaddress' );
485 if ( $email && !$this->mEmail
) {
486 $u->setEmail( $email );
490 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
494 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
496 return Status
::newGood( $u );
500 * Internally authenticate the login request.
502 * This may create a local account as a side effect if the
503 * authentication plugin allows transparent local account
507 public function authenticateUserData() {
508 global $wgUser, $wgAuth;
512 if ( $this->mUsername
== '' ) {
513 return self
::NO_NAME
;
516 // We require a login token to prevent login CSRF
517 // Handle part of this before incrementing the throttle so
518 // token-less login attempts don't count towards the throttle
519 // but wrong-token attempts do.
521 // If the user doesn't have a login token yet, set one.
522 if ( !self
::getLoginToken() ) {
523 self
::setLoginToken();
524 return self
::NEED_TOKEN
;
526 // If the user didn't pass a login token, tell them we need one
527 if ( !$this->mToken
) {
528 return self
::NEED_TOKEN
;
531 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
532 if ( $throttleCount === true ) {
533 return self
::THROTTLED
;
536 // Validate the login token
537 if ( $this->mToken
!== self
::getLoginToken() ) {
538 return self
::WRONG_TOKEN
;
541 // Load the current user now, and check to see if we're logging in as
542 // the same name. This is necessary because loading the current user
543 // (say by calling getName()) calls the UserLoadFromSession hook, which
544 // potentially creates the user in the database. Until we load $wgUser,
545 // checking for user existence using User::newFromName($name)->getId() below
546 // will effectively be using stale data.
547 if ( $this->getUser()->getName() === $this->mUsername
) {
548 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
549 return self
::SUCCESS
;
552 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
554 # TODO: Allow some magic here for invalid external names, e.g., let the
555 # user choose a different wiki name.
556 $u = User
::newFromName( $this->mUsername
);
557 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
558 return self
::ILLEGAL
;
561 $isAutoCreated = false;
562 if ( $u->getID() == 0 ) {
563 $status = $this->attemptAutoCreate( $u );
564 if ( $status !== self
::SUCCESS
) {
567 $isAutoCreated = true;
570 global $wgExternalAuthType, $wgAutocreatePolicy;
571 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
572 && is_object( $this->mExtUser
)
573 && $this->mExtUser
->authenticate( $this->mPassword
)
575 # The external user and local user have the same name and
576 # password, so we assume they're the same.
577 $this->mExtUser
->linkToLocal( $u->getID() );
583 // Give general extensions, such as a captcha, a chance to abort logins
584 $abort = self
::ABORTED
;
585 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
589 global $wgBlockDisablesLogin;
590 if ( !$u->checkPassword( $this->mPassword
) ) {
591 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
592 // The e-mailed temporary password should not be used for actu-
593 // al logins; that's a very sloppy habit, and insecure if an
594 // attacker has a few seconds to click "search" on someone's o-
597 // Allow it to be used only to reset the password a single time
598 // to a new value, which won't be in the user's e-mail ar-
601 // For backwards compatibility, we'll still recognize it at the
602 // login form to minimize surprises for people who have been
603 // logging in with a temporary password for some time.
605 // As a side-effect, we can authenticate the user's e-mail ad-
606 // dress if it's not already done, since the temporary password
607 // was sent via e-mail.
608 if( !$u->isEmailConfirmed() ) {
613 // At this point we just return an appropriate code/ indicating
614 // that the UI should show a password reset form; bot inter-
615 // faces etc will probably just fail cleanly here.
616 $retval = self
::RESET_PASS
;
618 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
620 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
621 // If we've enabled it, make it so that a blocked user cannot login
622 $retval = self
::USER_BLOCKED
;
624 $wgAuth->updateUser( $u );
626 // This should set it for OutputPage and the Skin
627 // which is needed or the personal links will be
629 $this->getContext()->setUser( $u );
631 // Please reset throttle for successful logins, thanks!
632 if ( $throttleCount ) {
633 self
::clearLoginThrottle( $this->mUsername
);
636 if ( $isAutoCreated ) {
637 // Must be run after $wgUser is set, for correct new user log
638 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
641 $retval = self
::SUCCESS
;
643 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
648 * Increment the login attempt throttle hit count for the (username,current IP)
649 * tuple unless the throttle was already reached.
650 * @param $username string The user name
651 * @return Bool|Integer The integer hit count or True if it is already at the limit
653 public static function incLoginThrottle( $username ) {
654 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
655 $username = trim( $username ); // sanity
658 if ( is_array( $wgPasswordAttemptThrottle ) ) {
659 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
660 $count = $wgPasswordAttemptThrottle['count'];
661 $period = $wgPasswordAttemptThrottle['seconds'];
663 $throttleCount = $wgMemc->get( $throttleKey );
664 if ( !$throttleCount ) {
665 $wgMemc->add( $throttleKey, 1, $period ); // start counter
666 } elseif ( $throttleCount < $count ) {
667 $wgMemc->incr( $throttleKey );
668 } elseif ( $throttleCount >= $count ) {
673 return $throttleCount;
677 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
678 * @param $username string The user name
681 public static function clearLoginThrottle( $username ) {
682 global $wgMemc, $wgRequest;
683 $username = trim( $username ); // sanity
685 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
686 $wgMemc->delete( $throttleKey );
690 * Attempt to automatically create a user on login. Only succeeds if there
691 * is an external authentication method which allows it.
695 * @return integer Status code
697 function attemptAutoCreate( $user ) {
698 global $wgAuth, $wgAutocreatePolicy;
700 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
701 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
702 return self
::CREATE_BLOCKED
;
706 * If the external authentication plugin allows it, automatically cre-
707 * ate a new account for users that are externally defined but have not
710 if ( $this->mExtUser
) {
711 # mExtUser is neither null nor false, so use the new ExternalAuth
713 if ( $wgAutocreatePolicy == 'never' ) {
714 return self
::NOT_EXISTS
;
716 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
717 return self
::WRONG_PLUGIN_PASS
;
721 if ( !$wgAuth->autoCreate() ) {
722 return self
::NOT_EXISTS
;
724 if ( !$wgAuth->userExists( $user->getName() ) ) {
725 wfDebug( __METHOD__
. ": user does not exist\n" );
726 return self
::NOT_EXISTS
;
728 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
729 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
730 return self
::WRONG_PLUGIN_PASS
;
735 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
736 // Hook point to add extra creation throttles and blocks
737 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
738 $this->mAbortLoginErrorMsg
= $abortError;
739 return self
::ABORTED
;
742 wfDebug( __METHOD__
. ": creating account\n" );
743 $status = $this->initUser( $user, true );
745 if ( !$status->isOK() ) {
746 $errors = $status->getErrorsByType( 'error' );
747 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
748 return self
::ABORTED
;
751 return self
::SUCCESS
;
754 function processLogin() {
755 global $wgMemc, $wgLang, $wgSecureLogin;
757 switch ( $this->authenticateUserData() ) {
759 # We've verified now, update the real record
760 $user = $this->getUser();
761 if( (bool)$this->mRemember
!= (bool)$user->getOption( 'rememberpassword' ) ) {
762 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
763 $user->saveSettings();
765 $user->invalidateCache();
768 if( $wgSecureLogin && !$this->mStickHTTPS
) {
769 $user->setCookies( null, false );
773 self
::clearLoginToken();
775 // Reset the throttle
776 $request = $this->getRequest();
777 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
778 $wgMemc->delete( $key );
780 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
781 /* Replace the language object to provide user interface in
782 * correct language immediately on this first page load.
784 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
785 $userLang = Language
::factory( $code );
787 $this->getContext()->setLanguage( $userLang );
788 // Reset SessionID on Successful login (bug 40995)
789 $this->renewSessionId();
790 $this->successfulLogin();
792 $this->cookieRedirectCheck( 'login' );
796 case self
::NEED_TOKEN
:
797 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
799 case self
::WRONG_TOKEN
:
800 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
804 $this->mainLoginForm( $this->msg( 'noname' )->text() );
806 case self
::WRONG_PLUGIN_PASS
:
807 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
809 case self
::NOT_EXISTS
:
810 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
811 $this->mainLoginForm( $this->msg( 'nosuchuser',
812 wfEscapeWikiText( $this->mUsername
) )->parse() );
814 $this->mainLoginForm( $this->msg( 'nosuchusershort',
815 wfEscapeWikiText( $this->mUsername
) )->text() );
818 case self
::WRONG_PASS
:
819 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
821 case self
::EMPTY_PASS
:
822 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
824 case self
::RESET_PASS
:
825 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
827 case self
::CREATE_BLOCKED
:
828 $this->userBlockedMessage( $this->getUser()->mBlock
);
830 case self
::THROTTLED
:
831 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
833 case self
::USER_BLOCKED
:
834 $this->mainLoginForm( $this->msg( 'login-userblocked',
835 $this->mUsername
)->escaped() );
838 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
841 throw new MWException( 'Unhandled case value' );
845 function resetLoginForm( $error ) {
846 $this->getOutput()->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
847 $reset = new SpecialChangePassword();
848 $reset->setContext( $this->getContext() );
849 $reset->execute( null );
853 * @param $u User object
854 * @param $throttle Boolean
855 * @param $emailTitle String: message name of email title
856 * @param $emailText String: message name of email text
857 * @return Status object
859 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
860 global $wgCanonicalServer, $wgScript, $wgNewPasswordExpiry;
862 if ( $u->getEmail() == '' ) {
863 return Status
::newFatal( 'noemail', $u->getName() );
865 $ip = $this->getRequest()->getIP();
867 return Status
::newFatal( 'badipaddress' );
870 $currentUser = $this->getUser();
871 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
873 $np = $u->randomPassword();
874 $u->setNewpassword( $np, $throttle );
876 $userLanguage = $u->getOption( 'language' );
877 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $wgCanonicalServer . $wgScript . '>',
878 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
879 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
886 * Run any hooks registered for logins, then HTTP redirect to
887 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
888 * nice message here, but that's really not as useful as just being sent to
889 * wherever you logged in from. It should be clear that the action was
890 * successful, given the lack of error messages plus the appearance of your
891 * name in the upper right.
895 function successfulLogin() {
896 # Run any hooks; display injected HTML if any, else redirect
897 $currentUser = $this->getUser();
899 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
901 if( $injected_html !== '' ) {
902 $this->displaySuccessfulAction( $this->msg( 'loginsuccesstitle' ),
903 'loginsuccess', $injected_html );
905 $this->executeReturnTo( 'successredirect' );
910 * Run any hooks registered for logins, then display a message welcoming
915 function successfulCreation() {
916 # Run any hooks; display injected HTML
917 $currentUser = $this->getUser();
919 $welcome_creation_msg = 'welcomecreation-msg';
921 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
924 * Let any extensions change what message is shown.
925 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
928 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
930 $this->displaySuccessfulAction( $this->msg( 'welcomeuser', $this->getUser()->getName() ),
931 $welcome_creation_msg, $injected_html );
935 * Display an "successful action" page.
937 * @param $title string|Message page's title
938 * @param $msgname string
939 * @param $injected_html string
941 private function displaySuccessfulAction( $title, $msgname, $injected_html ) {
942 $out = $this->getOutput();
943 $out->setPageTitle( $title );
945 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
948 $out->addHTML( $injected_html );
950 $this->executeReturnTo( 'success' );
954 * Output a message that informs the user that they cannot create an account because
955 * there is a block on them or their IP which prevents account creation. Note that
956 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
957 * setting on blocks (bug 13611).
958 * @param $block Block the block causing this error
960 function userBlockedMessage( Block
$block ) {
961 # Let's be nice about this, it's likely that this feature will be used
962 # for blocking large numbers of innocent people, e.g. range blocks on
963 # schools. Don't blame it on the user. There's a small chance that it
964 # really is the user's fault, i.e. the username is blocked and they
965 # haven't bothered to log out before trying to create an account to
966 # evade it, but we'll leave that to their guilty conscience to figure
969 $out = $this->getOutput();
970 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
972 $block_reason = $block->mReason
;
973 if ( strval( $block_reason ) === '' ) {
974 $block_reason = $this->msg( 'blockednoreason' )->text();
978 'cantcreateaccount-text',
984 $this->executeReturnTo( 'error' );
988 * Add a "return to" link or redirect to it.
990 * @param $type string, one of the following:
991 * - error: display a return to link ignoring $wgRedirectOnLogin
992 * - success: display a return to link using $wgRedirectOnLogin if needed
993 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
995 private function executeReturnTo( $type ) {
996 global $wgRedirectOnLogin, $wgSecureLogin;
998 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
999 $returnTo = $wgRedirectOnLogin;
1000 $returnToQuery = array();
1002 $returnTo = $this->mReturnTo
;
1003 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
1006 $returnToTitle = Title
::newFromText( $returnTo );
1007 if ( !$returnToTitle ) {
1008 $returnToTitle = Title
::newMainPage();
1011 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1012 $options = array( 'http' );
1013 $proto = PROTO_HTTP
;
1014 } elseif( $wgSecureLogin ) {
1015 $options = array( 'https' );
1016 $proto = PROTO_HTTPS
;
1019 $proto = PROTO_RELATIVE
;
1022 if ( $type == 'successredirect' ) {
1023 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1024 $this->getOutput()->redirect( $redirectUrl );
1026 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1033 function mainLoginForm( $msg, $msgtype = 'error' ) {
1034 global $wgEnableEmail, $wgEnableUserEmail;
1035 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1036 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
1037 global $wgSecureLogin, $wgPasswordResetRoutes;
1039 $titleObj = $this->getTitle();
1040 $user = $this->getUser();
1042 if ( $this->mType
== 'signup' ) {
1043 // Block signup here if in readonly. Keeps user from
1044 // going through the process (filling out data, etc)
1045 // and being informed later.
1046 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1047 if ( count( $permErrors ) ) {
1048 throw new PermissionsError( 'createaccount', $permErrors );
1049 } elseif ( $user->isBlockedFromCreateAccount() ) {
1050 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1052 } elseif ( wfReadOnly() ) {
1053 throw new ReadOnlyError
;
1057 if ( $this->mUsername
== '' ) {
1058 if ( $user->isLoggedIn() ) {
1059 $this->mUsername
= $user->getName();
1061 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1065 if ( $this->mType
== 'signup' ) {
1066 $template = new UsercreateTemplate();
1067 $q = 'action=submitlogin&type=signup';
1068 $linkq = 'type=login';
1069 $linkmsg = 'gotaccount';
1071 $template = new UserloginTemplate();
1072 $q = 'action=submitlogin&type=login';
1073 $linkq = 'type=signup';
1074 $linkmsg = 'nologin';
1077 if ( $this->mReturnTo
!== '' ) {
1078 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1079 if ( $this->mReturnToQuery
!== '' ) {
1080 $returnto .= '&returntoquery=' .
1081 wfUrlencode( $this->mReturnToQuery
);
1084 $linkq .= $returnto;
1087 # Don't show a "create account" link if the user can't
1088 if( $this->showCreateOrLoginLink( $user ) ) {
1089 # Pass any language selection on to the mode switch link
1090 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1091 $linkq .= '&uselang=' . $this->mLanguage
;
1093 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1094 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1096 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1098 $template->set( 'link', '' );
1101 $resetLink = $this->mType
== 'signup'
1103 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1105 $template->set( 'header', '' );
1106 $template->set( 'name', $this->mUsername
);
1107 $template->set( 'password', $this->mPassword
);
1108 $template->set( 'retype', $this->mRetype
);
1109 $template->set( 'email', $this->mEmail
);
1110 $template->set( 'realname', $this->mRealName
);
1111 $template->set( 'domain', $this->mDomain
);
1112 $template->set( 'reason', $this->mReason
);
1114 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1115 $template->set( 'message', $msg );
1116 $template->set( 'messagetype', $msgtype );
1117 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1118 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1119 $template->set( 'useemail', $wgEnableEmail );
1120 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1121 $template->set( 'emailothers', $wgEnableUserEmail );
1122 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1123 $template->set( 'resetlink', $resetLink );
1124 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1125 $template->set( 'usereason', $user->isLoggedIn() );
1126 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1127 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1128 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1130 if ( $this->mType
== 'signup' ) {
1131 if ( !self
::getCreateaccountToken() ) {
1132 self
::setCreateaccountToken();
1134 $template->set( 'token', self
::getCreateaccountToken() );
1136 if ( !self
::getLoginToken() ) {
1137 self
::setLoginToken();
1139 $template->set( 'token', self
::getLoginToken() );
1142 # Prepare language selection links as needed
1143 if( $wgLoginLanguageSelector ) {
1144 $template->set( 'languages', $this->makeLanguageSelector() );
1145 if( $this->mLanguage
) {
1146 $template->set( 'uselang', $this->mLanguage
);
1150 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1151 // Ditto for signupend
1152 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1153 $loginendHTTPS = $this->msg( 'loginend-https' );
1154 $signupendHTTPS = $this->msg( 'signupend-https' );
1155 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1156 $template->set( 'loginend', $loginendHTTPS->parse() );
1158 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1160 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1161 $template->set( 'signupend', $signupendHTTPS->parse() );
1163 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1166 // Give authentication and captcha plugins a chance to modify the form
1167 $wgAuth->modifyUITemplate( $template, $this->mType
);
1168 if ( $this->mType
== 'signup' ) {
1169 wfRunHooks( 'UserCreateForm', array( &$template ) );
1171 wfRunHooks( 'UserLoginForm', array( &$template ) );
1174 $out = $this->getOutput();
1175 $out->disallowUserJs(); // just in case...
1176 $out->addTemplate( $template );
1186 function showCreateOrLoginLink( &$user ) {
1187 if( $this->mType
== 'signup' ) {
1189 } elseif( $user->isAllowed( 'createaccount' ) ) {
1197 * Check if a session cookie is present.
1199 * This will not pick up a cookie set during _this_ request, but is meant
1200 * to ensure that the client is returning the cookie which was set on a
1201 * previous pass through the system.
1206 function hasSessionCookie() {
1207 global $wgDisableCookieCheck;
1208 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1212 * Get the login token from the current session
1215 public static function getLoginToken() {
1217 return $wgRequest->getSessionData( 'wsLoginToken' );
1221 * Randomly generate a new login token and attach it to the current session
1223 public static function setLoginToken() {
1225 // Generate a token directly instead of using $user->editToken()
1226 // because the latter reuses $_SESSION['wsEditToken']
1227 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1231 * Remove any login token attached to the current session
1233 public static function clearLoginToken() {
1235 $wgRequest->setSessionData( 'wsLoginToken', null );
1239 * Get the createaccount token from the current session
1242 public static function getCreateaccountToken() {
1244 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1248 * Randomly generate a new createaccount token and attach it to the current session
1250 public static function setCreateaccountToken() {
1252 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1256 * Remove any createaccount token attached to the current session
1258 public static function clearCreateaccountToken() {
1260 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1264 * Renew the user's session id, using strong entropy
1266 private function renewSessionId() {
1267 if ( wfCheckEntropy() ) {
1268 session_regenerate_id( false );
1270 //If we don't trust PHP's entropy, we have to replace the session manually
1273 session_write_close();
1274 session_id( MWCryptRand
::generateHex( 32 ) );
1283 function cookieRedirectCheck( $type ) {
1284 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1285 $query = array( 'wpCookieCheck' => $type );
1286 if ( $this->mReturnTo
!== '' ) {
1287 $query['returnto'] = $this->mReturnTo
;
1288 $query['returntoquery'] = $this->mReturnToQuery
;
1290 $check = $titleObj->getFullURL( $query );
1292 $this->getOutput()->redirect( $check );
1298 function onCookieRedirectCheck( $type ) {
1299 if ( !$this->hasSessionCookie() ) {
1300 if ( $type == 'new' ) {
1301 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1302 } elseif ( $type == 'login' ) {
1303 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1306 $this->mainLoginForm( $this->msg( 'error' )->text() );
1309 $this->successfulLogin();
1316 function throttleHit( $limit ) {
1317 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1321 * Produce a bar of links which allow the user to select another language
1322 * during login/registration but retain "returnto"
1326 function makeLanguageSelector() {
1327 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1328 if( !$msg->isBlank() ) {
1329 $langs = explode( "\n", $msg->text() );
1331 foreach( $langs as $lang ) {
1332 $lang = trim( $lang, '* ' );
1333 $parts = explode( '|', $lang );
1334 if ( count( $parts ) >= 2 ) {
1335 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1338 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1339 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1346 * Create a language selector link for a particular language
1347 * Links back to this page preserving type and returnto
1349 * @param $text Link text
1350 * @param $lang Language code
1353 function makeLanguageSelectorLink( $text, $lang ) {
1354 if( $this->getLanguage()->getCode() == $lang ) {
1355 // no link for currently used language
1356 return htmlspecialchars( $text );
1358 $query = array( 'uselang' => $lang );
1359 if( $this->mType
== 'signup' ) {
1360 $query['type'] = 'signup';
1362 if( $this->mReturnTo
!== '' ) {
1363 $query['returnto'] = $this->mReturnTo
;
1364 $query['returntoquery'] = $this->mReturnToQuery
;
1368 $targetLanguage = Language
::factory( $lang );
1369 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1371 return Linker
::linkKnown(
1373 htmlspecialchars( $text ),