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 ( 0 == $u->getID() ) {
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
) ) {
574 # The external user and local user have the same name and
575 # password, so we assume they're the same.
576 $this->mExtUser
->linkToLocal( $u->getID() );
582 // Give general extensions, such as a captcha, a chance to abort logins
583 $abort = self
::ABORTED
;
584 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
588 global $wgBlockDisablesLogin;
589 if ( !$u->checkPassword( $this->mPassword
) ) {
590 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
591 // The e-mailed temporary password should not be used for actu-
592 // al logins; that's a very sloppy habit, and insecure if an
593 // attacker has a few seconds to click "search" on someone's o-
596 // Allow it to be used only to reset the password a single time
597 // to a new value, which won't be in the user's e-mail ar-
600 // For backwards compatibility, we'll still recognize it at the
601 // login form to minimize surprises for people who have been
602 // logging in with a temporary password for some time.
604 // As a side-effect, we can authenticate the user's e-mail ad-
605 // dress if it's not already done, since the temporary password
606 // was sent via e-mail.
607 if( !$u->isEmailConfirmed() ) {
612 // At this point we just return an appropriate code/ indicating
613 // that the UI should show a password reset form; bot inter-
614 // faces etc will probably just fail cleanly here.
615 $retval = self
::RESET_PASS
;
617 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
619 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
620 // If we've enabled it, make it so that a blocked user cannot login
621 $retval = self
::USER_BLOCKED
;
623 $wgAuth->updateUser( $u );
625 // This should set it for OutputPage and the Skin
626 // which is needed or the personal links will be
628 $this->getContext()->setUser( $u );
630 // Please reset throttle for successful logins, thanks!
631 if ( $throttleCount ) {
632 self
::clearLoginThrottle( $this->mUsername
);
635 if ( $isAutoCreated ) {
636 // Must be run after $wgUser is set, for correct new user log
637 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
640 $retval = self
::SUCCESS
;
642 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
647 * Increment the login attempt throttle hit count for the (username,current IP)
648 * tuple unless the throttle was already reached.
649 * @param $username string The user name
650 * @return Bool|Integer The integer hit count or True if it is already at the limit
652 public static function incLoginThrottle( $username ) {
653 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
654 $username = trim( $username ); // sanity
657 if ( is_array( $wgPasswordAttemptThrottle ) ) {
658 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
659 $count = $wgPasswordAttemptThrottle['count'];
660 $period = $wgPasswordAttemptThrottle['seconds'];
662 $throttleCount = $wgMemc->get( $throttleKey );
663 if ( !$throttleCount ) {
664 $wgMemc->add( $throttleKey, 1, $period ); // start counter
665 } elseif ( $throttleCount < $count ) {
666 $wgMemc->incr( $throttleKey );
667 } elseif ( $throttleCount >= $count ) {
672 return $throttleCount;
676 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
677 * @param $username string The user name
680 public static function clearLoginThrottle( $username ) {
681 global $wgMemc, $wgRequest;
682 $username = trim( $username ); // sanity
684 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
685 $wgMemc->delete( $throttleKey );
689 * Attempt to automatically create a user on login. Only succeeds if there
690 * is an external authentication method which allows it.
694 * @return integer Status code
696 function attemptAutoCreate( $user ) {
697 global $wgAuth, $wgAutocreatePolicy;
699 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
700 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
701 return self
::CREATE_BLOCKED
;
705 * If the external authentication plugin allows it, automatically cre-
706 * ate a new account for users that are externally defined but have not
709 if ( $this->mExtUser
) {
710 # mExtUser is neither null nor false, so use the new ExternalAuth
712 if ( $wgAutocreatePolicy == 'never' ) {
713 return self
::NOT_EXISTS
;
715 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
716 return self
::WRONG_PLUGIN_PASS
;
720 if ( !$wgAuth->autoCreate() ) {
721 return self
::NOT_EXISTS
;
723 if ( !$wgAuth->userExists( $user->getName() ) ) {
724 wfDebug( __METHOD__
. ": user does not exist\n" );
725 return self
::NOT_EXISTS
;
727 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
728 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
729 return self
::WRONG_PLUGIN_PASS
;
734 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
735 // Hook point to add extra creation throttles and blocks
736 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
737 $this->mAbortLoginErrorMsg
= $abortError;
738 return self
::ABORTED
;
741 wfDebug( __METHOD__
. ": creating account\n" );
742 $status = $this->initUser( $user, true );
744 if ( !$status->isOK() ) {
745 $errors = $status->getErrorsByType( 'error' );
746 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
747 return self
::ABORTED
;
750 return self
::SUCCESS
;
753 function processLogin() {
754 global $wgMemc, $wgLang;
756 switch ( $this->authenticateUserData() ) {
758 global $wgSecureLogin;
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 $this->successfulLogin();
790 $this->cookieRedirectCheck( 'login' );
794 case self
::NEED_TOKEN
:
795 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
797 case self
::WRONG_TOKEN
:
798 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
802 $this->mainLoginForm( $this->msg( 'noname' )->text() );
804 case self
::WRONG_PLUGIN_PASS
:
805 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
807 case self
::NOT_EXISTS
:
808 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
809 $this->mainLoginForm( $this->msg( 'nosuchuser',
810 wfEscapeWikiText( $this->mUsername
) )->parse() );
812 $this->mainLoginForm( $this->msg( 'nosuchusershort',
813 wfEscapeWikiText( $this->mUsername
) )->text() );
816 case self
::WRONG_PASS
:
817 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
819 case self
::EMPTY_PASS
:
820 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
822 case self
::RESET_PASS
:
823 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
825 case self
::CREATE_BLOCKED
:
826 $this->userBlockedMessage( $this->getUser()->mBlock
);
828 case self
::THROTTLED
:
829 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
831 case self
::USER_BLOCKED
:
832 $this->mainLoginForm( $this->msg( 'login-userblocked',
833 $this->mUsername
)->escaped() );
836 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
839 throw new MWException( 'Unhandled case value' );
843 function resetLoginForm( $error ) {
844 $this->getOutput()->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
845 $reset = new SpecialChangePassword();
846 $reset->setContext( $this->getContext() );
847 $reset->execute( null );
851 * @param $u User object
852 * @param $throttle Boolean
853 * @param $emailTitle String: message name of email title
854 * @param $emailText String: message name of email text
855 * @return Status object
857 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
858 global $wgCanonicalServer, $wgScript, $wgNewPasswordExpiry;
860 if ( $u->getEmail() == '' ) {
861 return Status
::newFatal( 'noemail', $u->getName() );
863 $ip = $this->getRequest()->getIP();
865 return Status
::newFatal( 'badipaddress' );
868 $currentUser = $this->getUser();
869 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
871 $np = $u->randomPassword();
872 $u->setNewpassword( $np, $throttle );
874 $userLanguage = $u->getOption( 'language' );
875 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $wgCanonicalServer . $wgScript . '>',
876 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
877 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
884 * Run any hooks registered for logins, then HTTP redirect to
885 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
886 * nice message here, but that's really not as useful as just being sent to
887 * wherever you logged in from. It should be clear that the action was
888 * successful, given the lack of error messages plus the appearance of your
889 * name in the upper right.
893 function successfulLogin() {
894 # Run any hooks; display injected HTML if any, else redirect
895 $currentUser = $this->getUser();
897 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
899 if( $injected_html !== '' ) {
900 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
902 $this->executeReturnTo( 'successredirect' );
907 * Run any hooks registered for logins, then display a message welcoming
912 function successfulCreation() {
913 # Run any hooks; display injected HTML
914 $currentUser = $this->getUser();
916 $welcome_creation_msg = 'welcomecreation';
918 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
921 * Let any extensions change what message is shown.
922 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
925 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
927 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
931 * Display a "login successful" page.
932 * @param $msgname string
933 * @param $injected_html string
935 private function displaySuccessfulLogin( $msgname, $injected_html ) {
936 $out = $this->getOutput();
937 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
939 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
942 $out->addHTML( $injected_html );
944 $this->executeReturnTo( 'success' );
948 * Output a message that informs the user that they cannot create an account because
949 * there is a block on them or their IP which prevents account creation. Note that
950 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
951 * setting on blocks (bug 13611).
952 * @param $block Block the block causing this error
954 function userBlockedMessage( Block
$block ) {
955 # Let's be nice about this, it's likely that this feature will be used
956 # for blocking large numbers of innocent people, e.g. range blocks on
957 # schools. Don't blame it on the user. There's a small chance that it
958 # really is the user's fault, i.e. the username is blocked and they
959 # haven't bothered to log out before trying to create an account to
960 # evade it, but we'll leave that to their guilty conscience to figure
963 $out = $this->getOutput();
964 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
966 $block_reason = $block->mReason
;
967 if ( strval( $block_reason ) === '' ) {
968 $block_reason = $this->msg( 'blockednoreason' )->text();
972 'cantcreateaccount-text',
978 $this->executeReturnTo( 'error' );
982 * Add a "return to" link or redirect to it.
984 * @param $type string, one of the following:
985 * - error: display a return to link ignoring $wgRedirectOnLogin
986 * - success: display a return to link using $wgRedirectOnLogin if needed
987 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
989 private function executeReturnTo( $type ) {
990 global $wgRedirectOnLogin, $wgSecureLogin;
992 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
993 $returnTo = $wgRedirectOnLogin;
994 $returnToQuery = array();
996 $returnTo = $this->mReturnTo
;
997 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
1000 $returnToTitle = Title
::newFromText( $returnTo );
1001 if ( !$returnToTitle ) {
1002 $returnToTitle = Title
::newMainPage();
1005 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1006 $options = array( 'http' );
1007 $proto = PROTO_HTTP
;
1008 } elseif( $wgSecureLogin ) {
1009 $options = array( 'https' );
1010 $proto = PROTO_HTTPS
;
1013 $proto = PROTO_RELATIVE
;
1016 if ( $type == 'successredirect' ) {
1017 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1018 $this->getOutput()->redirect( $redirectUrl );
1020 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1027 function mainLoginForm( $msg, $msgtype = 'error' ) {
1028 global $wgEnableEmail, $wgEnableUserEmail;
1029 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1030 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
1031 global $wgSecureLogin, $wgPasswordResetRoutes;
1033 $titleObj = $this->getTitle();
1034 $user = $this->getUser();
1036 if ( $this->mType
== 'signup' ) {
1037 // Block signup here if in readonly. Keeps user from
1038 // going through the process (filling out data, etc)
1039 // and being informed later.
1040 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1041 if ( count( $permErrors ) ) {
1042 throw new PermissionsError( 'createaccount', $permErrors );
1043 } elseif ( $user->isBlockedFromCreateAccount() ) {
1044 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1046 } elseif ( wfReadOnly() ) {
1047 throw new ReadOnlyError
;
1051 if ( $this->mUsername
== '' ) {
1052 if ( $user->isLoggedIn() ) {
1053 $this->mUsername
= $user->getName();
1055 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1059 if ( $this->mType
== 'signup' ) {
1060 $template = new UsercreateTemplate();
1061 $q = 'action=submitlogin&type=signup';
1062 $linkq = 'type=login';
1063 $linkmsg = 'gotaccount';
1065 $template = new UserloginTemplate();
1066 $q = 'action=submitlogin&type=login';
1067 $linkq = 'type=signup';
1068 $linkmsg = 'nologin';
1071 if ( $this->mReturnTo
!== '' ) {
1072 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1073 if ( $this->mReturnToQuery
!== '' ) {
1074 $returnto .= '&returntoquery=' .
1075 wfUrlencode( $this->mReturnToQuery
);
1078 $linkq .= $returnto;
1081 # Don't show a "create account" link if the user can't
1082 if( $this->showCreateOrLoginLink( $user ) ) {
1083 # Pass any language selection on to the mode switch link
1084 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1085 $linkq .= '&uselang=' . $this->mLanguage
;
1087 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1088 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1090 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1092 $template->set( 'link', '' );
1095 $resetLink = $this->mType
== 'signup'
1097 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1099 $template->set( 'header', '' );
1100 $template->set( 'name', $this->mUsername
);
1101 $template->set( 'password', $this->mPassword
);
1102 $template->set( 'retype', $this->mRetype
);
1103 $template->set( 'email', $this->mEmail
);
1104 $template->set( 'realname', $this->mRealName
);
1105 $template->set( 'domain', $this->mDomain
);
1106 $template->set( 'reason', $this->mReason
);
1108 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1109 $template->set( 'message', $msg );
1110 $template->set( 'messagetype', $msgtype );
1111 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1112 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1113 $template->set( 'useemail', $wgEnableEmail );
1114 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1115 $template->set( 'emailothers', $wgEnableUserEmail );
1116 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1117 $template->set( 'resetlink', $resetLink );
1118 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1119 $template->set( 'usereason', $user->isLoggedIn() );
1120 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1121 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1122 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1124 if ( $this->mType
== 'signup' ) {
1125 if ( !self
::getCreateaccountToken() ) {
1126 self
::setCreateaccountToken();
1128 $template->set( 'token', self
::getCreateaccountToken() );
1130 if ( !self
::getLoginToken() ) {
1131 self
::setLoginToken();
1133 $template->set( 'token', self
::getLoginToken() );
1136 # Prepare language selection links as needed
1137 if( $wgLoginLanguageSelector ) {
1138 $template->set( 'languages', $this->makeLanguageSelector() );
1139 if( $this->mLanguage
) {
1140 $template->set( 'uselang', $this->mLanguage
);
1144 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1145 // Ditto for signupend
1146 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1147 $loginendHTTPS = $this->msg( 'loginend-https' );
1148 $signupendHTTPS = $this->msg( 'signupend-https' );
1149 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1150 $template->set( 'loginend', $loginendHTTPS->parse() );
1152 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1154 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1155 $template->set( 'signupend', $signupendHTTPS->parse() );
1157 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1160 // Give authentication and captcha plugins a chance to modify the form
1161 $wgAuth->modifyUITemplate( $template, $this->mType
);
1162 if ( $this->mType
== 'signup' ) {
1163 wfRunHooks( 'UserCreateForm', array( &$template ) );
1165 wfRunHooks( 'UserLoginForm', array( &$template ) );
1168 $out = $this->getOutput();
1169 $out->disallowUserJs(); // just in case...
1170 $out->addTemplate( $template );
1180 function showCreateOrLoginLink( &$user ) {
1181 if( $this->mType
== 'signup' ) {
1183 } elseif( $user->isAllowed( 'createaccount' ) ) {
1191 * Check if a session cookie is present.
1193 * This will not pick up a cookie set during _this_ request, but is meant
1194 * to ensure that the client is returning the cookie which was set on a
1195 * previous pass through the system.
1200 function hasSessionCookie() {
1201 global $wgDisableCookieCheck;
1202 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1206 * Get the login token from the current session
1209 public static function getLoginToken() {
1211 return $wgRequest->getSessionData( 'wsLoginToken' );
1215 * Randomly generate a new login token and attach it to the current session
1217 public static function setLoginToken() {
1219 // Generate a token directly instead of using $user->editToken()
1220 // because the latter reuses $_SESSION['wsEditToken']
1221 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1225 * Remove any login token attached to the current session
1227 public static function clearLoginToken() {
1229 $wgRequest->setSessionData( 'wsLoginToken', null );
1233 * Get the createaccount token from the current session
1236 public static function getCreateaccountToken() {
1238 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1242 * Randomly generate a new createaccount token and attach it to the current session
1244 public static function setCreateaccountToken() {
1246 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1250 * Remove any createaccount token attached to the current session
1252 public static function clearCreateaccountToken() {
1254 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1260 function cookieRedirectCheck( $type ) {
1261 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1262 $query = array( 'wpCookieCheck' => $type );
1263 if ( $this->mReturnTo
!== '' ) {
1264 $query['returnto'] = $this->mReturnTo
;
1265 $query['returntoquery'] = $this->mReturnToQuery
;
1267 $check = $titleObj->getFullURL( $query );
1269 $this->getOutput()->redirect( $check );
1275 function onCookieRedirectCheck( $type ) {
1276 if ( !$this->hasSessionCookie() ) {
1277 if ( $type == 'new' ) {
1278 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1279 } elseif ( $type == 'login' ) {
1280 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1283 $this->mainLoginForm( $this->msg( 'error' )->text() );
1286 $this->successfulLogin();
1293 function throttleHit( $limit ) {
1294 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1298 * Produce a bar of links which allow the user to select another language
1299 * during login/registration but retain "returnto"
1303 function makeLanguageSelector() {
1304 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1305 if( !$msg->isBlank() ) {
1306 $langs = explode( "\n", $msg->text() );
1308 foreach( $langs as $lang ) {
1309 $lang = trim( $lang, '* ' );
1310 $parts = explode( '|', $lang );
1311 if ( count( $parts ) >= 2 ) {
1312 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1315 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1316 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1323 * Create a language selector link for a particular language
1324 * Links back to this page preserving type and returnto
1326 * @param $text Link text
1327 * @param $lang Language code
1330 function makeLanguageSelectorLink( $text, $lang ) {
1331 if( $this->getLanguage()->getCode() == $lang ) {
1332 // no link for currently used language
1333 return htmlspecialchars( $text );
1335 $query = array( 'uselang' => $lang );
1336 if( $this->mType
== 'signup' ) {
1337 $query['type'] = 'signup';
1339 if( $this->mReturnTo
!== '' ) {
1340 $query['returnto'] = $this->mReturnTo
;
1341 $query['returntoquery'] = $this->mReturnToQuery
;
1345 $targetLanguage = Language
::factory( $lang );
1346 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1348 return Linker
::linkKnown(
1350 htmlspecialchars( $text ),