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();
446 return $this->initUser( $u, false );
450 * Actually add a user to the database.
451 * Give it a User object that has been initialised with a name.
453 * @param $u User object.
454 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
455 * @return User object.
458 function initUser( $u, $autocreate ) {
463 if ( $wgAuth->allowPasswordChange() ) {
464 $u->setPassword( $this->mPassword
);
467 $u->setEmail( $this->mEmail
);
468 $u->setRealName( $this->mRealName
);
471 $wgAuth->initUser( $u, $autocreate );
473 if ( $this->mExtUser
) {
474 $this->mExtUser
->linkToLocal( $u->getId() );
475 $email = $this->mExtUser
->getPref( 'emailaddress' );
476 if ( $email && !$this->mEmail
) {
477 $u->setEmail( $email );
481 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
485 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
491 * Internally authenticate the login request.
493 * This may create a local account as a side effect if the
494 * authentication plugin allows transparent local account
498 public function authenticateUserData() {
499 global $wgUser, $wgAuth;
503 if ( $this->mUsername
== '' ) {
504 return self
::NO_NAME
;
507 // We require a login token to prevent login CSRF
508 // Handle part of this before incrementing the throttle so
509 // token-less login attempts don't count towards the throttle
510 // but wrong-token attempts do.
512 // If the user doesn't have a login token yet, set one.
513 if ( !self
::getLoginToken() ) {
514 self
::setLoginToken();
515 return self
::NEED_TOKEN
;
517 // If the user didn't pass a login token, tell them we need one
518 if ( !$this->mToken
) {
519 return self
::NEED_TOKEN
;
522 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
523 if ( $throttleCount === true ) {
524 return self
::THROTTLED
;
527 // Validate the login token
528 if ( $this->mToken
!== self
::getLoginToken() ) {
529 return self
::WRONG_TOKEN
;
532 // Load the current user now, and check to see if we're logging in as
533 // the same name. This is necessary because loading the current user
534 // (say by calling getName()) calls the UserLoadFromSession hook, which
535 // potentially creates the user in the database. Until we load $wgUser,
536 // checking for user existence using User::newFromName($name)->getId() below
537 // will effectively be using stale data.
538 if ( $this->getUser()->getName() === $this->mUsername
) {
539 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
540 return self
::SUCCESS
;
543 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
545 # TODO: Allow some magic here for invalid external names, e.g., let the
546 # user choose a different wiki name.
547 $u = User
::newFromName( $this->mUsername
);
548 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
549 return self
::ILLEGAL
;
552 $isAutoCreated = false;
553 if ( 0 == $u->getID() ) {
554 $status = $this->attemptAutoCreate( $u );
555 if ( $status !== self
::SUCCESS
) {
558 $isAutoCreated = true;
561 global $wgExternalAuthType, $wgAutocreatePolicy;
562 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
563 && is_object( $this->mExtUser
)
564 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
565 # The external user and local user have the same name and
566 # password, so we assume they're the same.
567 $this->mExtUser
->linkToLocal( $u->getID() );
573 // Give general extensions, such as a captcha, a chance to abort logins
574 $abort = self
::ABORTED
;
575 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
579 global $wgBlockDisablesLogin;
580 if ( !$u->checkPassword( $this->mPassword
) ) {
581 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
582 // The e-mailed temporary password should not be used for actu-
583 // al logins; that's a very sloppy habit, and insecure if an
584 // attacker has a few seconds to click "search" on someone's o-
587 // Allow it to be used only to reset the password a single time
588 // to a new value, which won't be in the user's e-mail ar-
591 // For backwards compatibility, we'll still recognize it at the
592 // login form to minimize surprises for people who have been
593 // logging in with a temporary password for some time.
595 // As a side-effect, we can authenticate the user's e-mail ad-
596 // dress if it's not already done, since the temporary password
597 // was sent via e-mail.
598 if( !$u->isEmailConfirmed() ) {
603 // At this point we just return an appropriate code/ indicating
604 // that the UI should show a password reset form; bot inter-
605 // faces etc will probably just fail cleanly here.
606 $retval = self
::RESET_PASS
;
608 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
610 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
611 // If we've enabled it, make it so that a blocked user cannot login
612 $retval = self
::USER_BLOCKED
;
614 $wgAuth->updateUser( $u );
616 // This should set it for OutputPage and the Skin
617 // which is needed or the personal links will be
619 $this->getContext()->setUser( $u );
621 // Please reset throttle for successful logins, thanks!
622 if ( $throttleCount ) {
623 self
::clearLoginThrottle( $this->mUsername
);
626 if ( $isAutoCreated ) {
627 // Must be run after $wgUser is set, for correct new user log
628 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
631 $retval = self
::SUCCESS
;
633 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
638 * Increment the login attempt throttle hit count for the (username,current IP)
639 * tuple unless the throttle was already reached.
640 * @param $username string The user name
641 * @return Bool|Integer The integer hit count or True if it is already at the limit
643 public static function incLoginThrottle( $username ) {
644 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
645 $username = trim( $username ); // sanity
648 if ( is_array( $wgPasswordAttemptThrottle ) ) {
649 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
650 $count = $wgPasswordAttemptThrottle['count'];
651 $period = $wgPasswordAttemptThrottle['seconds'];
653 $throttleCount = $wgMemc->get( $throttleKey );
654 if ( !$throttleCount ) {
655 $wgMemc->add( $throttleKey, 1, $period ); // start counter
656 } elseif ( $throttleCount < $count ) {
657 $wgMemc->incr( $throttleKey );
658 } elseif ( $throttleCount >= $count ) {
663 return $throttleCount;
667 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
668 * @param $username string The user name
671 public static function clearLoginThrottle( $username ) {
672 global $wgMemc, $wgRequest;
673 $username = trim( $username ); // sanity
675 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
676 $wgMemc->delete( $throttleKey );
680 * Attempt to automatically create a user on login. Only succeeds if there
681 * is an external authentication method which allows it.
685 * @return integer Status code
687 function attemptAutoCreate( $user ) {
688 global $wgAuth, $wgAutocreatePolicy;
690 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
691 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
692 return self
::CREATE_BLOCKED
;
696 * If the external authentication plugin allows it, automatically cre-
697 * ate a new account for users that are externally defined but have not
700 if ( $this->mExtUser
) {
701 # mExtUser is neither null nor false, so use the new ExternalAuth
703 if ( $wgAutocreatePolicy == 'never' ) {
704 return self
::NOT_EXISTS
;
706 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
707 return self
::WRONG_PLUGIN_PASS
;
711 if ( !$wgAuth->autoCreate() ) {
712 return self
::NOT_EXISTS
;
714 if ( !$wgAuth->userExists( $user->getName() ) ) {
715 wfDebug( __METHOD__
. ": user does not exist\n" );
716 return self
::NOT_EXISTS
;
718 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
719 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
720 return self
::WRONG_PLUGIN_PASS
;
725 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
726 // Hook point to add extra creation throttles and blocks
727 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
728 $this->mAbortLoginErrorMsg
= $abortError;
729 return self
::ABORTED
;
732 wfDebug( __METHOD__
. ": creating account\n" );
733 $this->initUser( $user, true );
734 return self
::SUCCESS
;
737 function processLogin() {
738 global $wgMemc, $wgLang;
740 switch ( $this->authenticateUserData() ) {
742 global $wgSecureLogin;
743 # We've verified now, update the real record
744 $user = $this->getUser();
745 if( (bool)$this->mRemember
!= (bool)$user->getOption( 'rememberpassword' ) ) {
746 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
747 $user->saveSettings();
749 $user->invalidateCache();
752 if( $wgSecureLogin && !$this->mStickHTTPS
) {
753 $user->setCookies( null, false );
757 self
::clearLoginToken();
759 // Reset the throttle
760 $request = $this->getRequest();
761 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
762 $wgMemc->delete( $key );
764 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
765 /* Replace the language object to provide user interface in
766 * correct language immediately on this first page load.
768 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
769 $userLang = Language
::factory( $code );
771 $this->getContext()->setLanguage( $userLang );
772 $this->successfulLogin();
774 $this->cookieRedirectCheck( 'login' );
778 case self
::NEED_TOKEN
:
779 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
781 case self
::WRONG_TOKEN
:
782 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
786 $this->mainLoginForm( $this->msg( 'noname' )->text() );
788 case self
::WRONG_PLUGIN_PASS
:
789 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
791 case self
::NOT_EXISTS
:
792 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
793 $this->mainLoginForm( $this->msg( 'nosuchuser',
794 wfEscapeWikiText( $this->mUsername
) )->parse() );
796 $this->mainLoginForm( $this->msg( 'nosuchusershort',
797 wfEscapeWikiText( $this->mUsername
) )->text() );
800 case self
::WRONG_PASS
:
801 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
803 case self
::EMPTY_PASS
:
804 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
806 case self
::RESET_PASS
:
807 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
809 case self
::CREATE_BLOCKED
:
810 $this->userBlockedMessage( $this->getUser()->mBlock
);
812 case self
::THROTTLED
:
813 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
815 case self
::USER_BLOCKED
:
816 $this->mainLoginForm( $this->msg( 'login-userblocked',
817 $this->mUsername
)->escaped() );
820 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
823 throw new MWException( 'Unhandled case value' );
827 function resetLoginForm( $error ) {
828 $this->getOutput()->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
829 $reset = new SpecialChangePassword();
830 $reset->setContext( $this->getContext() );
831 $reset->execute( null );
835 * @param $u User object
836 * @param $throttle Boolean
837 * @param $emailTitle String: message name of email title
838 * @param $emailText String: message name of email text
839 * @return Status object
841 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
842 global $wgServer, $wgScript, $wgNewPasswordExpiry;
844 if ( $u->getEmail() == '' ) {
845 return Status
::newFatal( 'noemail', $u->getName() );
847 $ip = $this->getRequest()->getIP();
849 return Status
::newFatal( 'badipaddress' );
852 $currentUser = $this->getUser();
853 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
855 $np = $u->randomPassword();
856 $u->setNewpassword( $np, $throttle );
858 $userLanguage = $u->getOption( 'language' );
859 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $wgServer . $wgScript . '>',
860 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
861 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
868 * Run any hooks registered for logins, then HTTP redirect to
869 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
870 * nice message here, but that's really not as useful as just being sent to
871 * wherever you logged in from. It should be clear that the action was
872 * successful, given the lack of error messages plus the appearance of your
873 * name in the upper right.
877 function successfulLogin() {
878 # Run any hooks; display injected HTML if any, else redirect
879 $currentUser = $this->getUser();
881 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
883 if( $injected_html !== '' ) {
884 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
886 $this->executeReturnTo( 'successredirect' );
891 * Run any hooks registered for logins, then display a message welcoming
896 function successfulCreation() {
897 # Run any hooks; display injected HTML
898 $currentUser = $this->getUser();
900 $welcome_creation_msg = 'welcomecreation';
902 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
905 * Let any extensions change what message is shown.
906 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
909 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
911 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
915 * Display a "login successful" page.
916 * @param $msgname string
917 * @param $injected_html string
919 private function displaySuccessfulLogin( $msgname, $injected_html ) {
920 $out = $this->getOutput();
921 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
923 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
926 $out->addHTML( $injected_html );
928 $this->executeReturnTo( 'success' );
932 * Output a message that informs the user that they cannot create an account because
933 * there is a block on them or their IP which prevents account creation. Note that
934 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
935 * setting on blocks (bug 13611).
936 * @param $block Block the block causing this error
938 function userBlockedMessage( Block
$block ) {
939 # Let's be nice about this, it's likely that this feature will be used
940 # for blocking large numbers of innocent people, e.g. range blocks on
941 # schools. Don't blame it on the user. There's a small chance that it
942 # really is the user's fault, i.e. the username is blocked and they
943 # haven't bothered to log out before trying to create an account to
944 # evade it, but we'll leave that to their guilty conscience to figure
947 $out = $this->getOutput();
948 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
950 $block_reason = $block->mReason
;
951 if ( strval( $block_reason ) === '' ) {
952 $block_reason = $this->msg( 'blockednoreason' )->text();
956 'cantcreateaccount-text',
962 $this->executeReturnTo( 'error' );
966 * Add a "return to" link or redirect to it.
968 * @param $type string, one of the following:
969 * - error: display a return to link ignoring $wgRedirectOnLogin
970 * - success: display a return to link using $wgRedirectOnLogin if needed
971 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
973 private function executeReturnTo( $type ) {
974 global $wgRedirectOnLogin, $wgSecureLogin;
976 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
977 $returnTo = $wgRedirectOnLogin;
978 $returnToQuery = array();
980 $returnTo = $this->mReturnTo
;
981 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
984 $returnToTitle = Title
::newFromText( $returnTo );
985 if ( !$returnToTitle ) {
986 $returnToTitle = Title
::newMainPage();
989 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
990 $options = array( 'http' );
993 $options = array( 'https' );
994 $proto = PROTO_HTTPS
;
997 if ( $type == 'successredirect' ) {
998 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
999 $this->getOutput()->redirect( $redirectUrl );
1001 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1008 function mainLoginForm( $msg, $msgtype = 'error' ) {
1009 global $wgEnableEmail, $wgEnableUserEmail;
1010 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1011 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
1012 global $wgSecureLogin, $wgPasswordResetRoutes;
1014 $titleObj = $this->getTitle();
1015 $user = $this->getUser();
1017 if ( $this->mType
== 'signup' ) {
1018 // Block signup here if in readonly. Keeps user from
1019 // going through the process (filling out data, etc)
1020 // and being informed later.
1021 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1022 if ( count( $permErrors ) ) {
1023 throw new PermissionsError( 'createaccount', $permErrors );
1024 } elseif ( $user->isBlockedFromCreateAccount() ) {
1025 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1027 } elseif ( wfReadOnly() ) {
1028 throw new ReadOnlyError
;
1032 if ( $this->mUsername
== '' ) {
1033 if ( $user->isLoggedIn() ) {
1034 $this->mUsername
= $user->getName();
1036 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1040 if ( $this->mType
== 'signup' ) {
1041 $template = new UsercreateTemplate();
1042 $q = 'action=submitlogin&type=signup';
1043 $linkq = 'type=login';
1044 $linkmsg = 'gotaccount';
1046 $template = new UserloginTemplate();
1047 $q = 'action=submitlogin&type=login';
1048 $linkq = 'type=signup';
1049 $linkmsg = 'nologin';
1052 if ( $this->mReturnTo
!== '' ) {
1053 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1054 if ( $this->mReturnToQuery
!== '' ) {
1055 $returnto .= '&returntoquery=' .
1056 wfUrlencode( $this->mReturnToQuery
);
1059 $linkq .= $returnto;
1062 # Don't show a "create account" link if the user can't
1063 if( $this->showCreateOrLoginLink( $user ) ) {
1064 # Pass any language selection on to the mode switch link
1065 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1066 $linkq .= '&uselang=' . $this->mLanguage
;
1068 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1069 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1071 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1073 $template->set( 'link', '' );
1076 $resetLink = $this->mType
== 'signup'
1078 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1080 $template->set( 'header', '' );
1081 $template->set( 'name', $this->mUsername
);
1082 $template->set( 'password', $this->mPassword
);
1083 $template->set( 'retype', $this->mRetype
);
1084 $template->set( 'email', $this->mEmail
);
1085 $template->set( 'realname', $this->mRealName
);
1086 $template->set( 'domain', $this->mDomain
);
1087 $template->set( 'reason', $this->mReason
);
1089 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1090 $template->set( 'message', $msg );
1091 $template->set( 'messagetype', $msgtype );
1092 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1093 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1094 $template->set( 'useemail', $wgEnableEmail );
1095 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1096 $template->set( 'emailothers', $wgEnableUserEmail );
1097 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1098 $template->set( 'resetlink', $resetLink );
1099 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1100 $template->set( 'usereason', $user->isLoggedIn() );
1101 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1102 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1103 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1105 if ( $this->mType
== 'signup' ) {
1106 if ( !self
::getCreateaccountToken() ) {
1107 self
::setCreateaccountToken();
1109 $template->set( 'token', self
::getCreateaccountToken() );
1111 if ( !self
::getLoginToken() ) {
1112 self
::setLoginToken();
1114 $template->set( 'token', self
::getLoginToken() );
1117 # Prepare language selection links as needed
1118 if( $wgLoginLanguageSelector ) {
1119 $template->set( 'languages', $this->makeLanguageSelector() );
1120 if( $this->mLanguage
) {
1121 $template->set( 'uselang', $this->mLanguage
);
1125 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1126 // Ditto for signupend
1127 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1128 $loginendHTTPS = $this->msg( 'loginend-https' );
1129 $signupendHTTPS = $this->msg( 'signupend-https' );
1130 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1131 $template->set( 'loginend', $loginendHTTPS->parse() );
1133 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1135 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1136 $template->set( 'signupend', $signupendHTTPS->parse() );
1138 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1141 // Give authentication and captcha plugins a chance to modify the form
1142 $wgAuth->modifyUITemplate( $template, $this->mType
);
1143 if ( $this->mType
== 'signup' ) {
1144 wfRunHooks( 'UserCreateForm', array( &$template ) );
1146 wfRunHooks( 'UserLoginForm', array( &$template ) );
1149 $out = $this->getOutput();
1150 $out->disallowUserJs(); // just in case...
1151 $out->addTemplate( $template );
1161 function showCreateOrLoginLink( &$user ) {
1162 if( $this->mType
== 'signup' ) {
1164 } elseif( $user->isAllowed( 'createaccount' ) ) {
1172 * Check if a session cookie is present.
1174 * This will not pick up a cookie set during _this_ request, but is meant
1175 * to ensure that the client is returning the cookie which was set on a
1176 * previous pass through the system.
1181 function hasSessionCookie() {
1182 global $wgDisableCookieCheck;
1183 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1187 * Get the login token from the current session
1190 public static function getLoginToken() {
1192 return $wgRequest->getSessionData( 'wsLoginToken' );
1196 * Randomly generate a new login token and attach it to the current session
1198 public static function setLoginToken() {
1200 // Generate a token directly instead of using $user->editToken()
1201 // because the latter reuses $_SESSION['wsEditToken']
1202 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1206 * Remove any login token attached to the current session
1208 public static function clearLoginToken() {
1210 $wgRequest->setSessionData( 'wsLoginToken', null );
1214 * Get the createaccount token from the current session
1217 public static function getCreateaccountToken() {
1219 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1223 * Randomly generate a new createaccount token and attach it to the current session
1225 public static function setCreateaccountToken() {
1227 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1231 * Remove any createaccount token attached to the current session
1233 public static function clearCreateaccountToken() {
1235 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1241 function cookieRedirectCheck( $type ) {
1242 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1243 $query = array( 'wpCookieCheck' => $type );
1244 if ( $this->mReturnTo
!== '' ) {
1245 $query['returnto'] = $this->mReturnTo
;
1246 $query['returntoquery'] = $this->mReturnToQuery
;
1248 $check = $titleObj->getFullURL( $query );
1250 $this->getOutput()->redirect( $check );
1256 function onCookieRedirectCheck( $type ) {
1257 if ( !$this->hasSessionCookie() ) {
1258 if ( $type == 'new' ) {
1259 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1260 } elseif ( $type == 'login' ) {
1261 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1264 $this->mainLoginForm( $this->msg( 'error' )->text() );
1267 $this->successfulLogin();
1274 function throttleHit( $limit ) {
1275 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1279 * Produce a bar of links which allow the user to select another language
1280 * during login/registration but retain "returnto"
1284 function makeLanguageSelector() {
1285 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1286 if( !$msg->isBlank() ) {
1287 $langs = explode( "\n", $msg->text() );
1289 foreach( $langs as $lang ) {
1290 $lang = trim( $lang, '* ' );
1291 $parts = explode( '|', $lang );
1292 if ( count( $parts ) >= 2 ) {
1293 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1296 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1297 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1304 * Create a language selector link for a particular language
1305 * Links back to this page preserving type and returnto
1307 * @param $text Link text
1308 * @param $lang Language code
1311 function makeLanguageSelectorLink( $text, $lang ) {
1312 if( $this->getLanguage()->getCode() == $lang ) {
1313 // no link for currently used language
1314 return htmlspecialchars( $text );
1316 $query = array( 'uselang' => $lang );
1317 if( $this->mType
== 'signup' ) {
1318 $query['type'] = 'signup';
1320 if( $this->mReturnTo
!== '' ) {
1321 $query['returnto'] = $this->mReturnTo
;
1322 $query['returntoquery'] = $this->mReturnToQuery
;
1326 $targetLanguage = Language
::factory( $lang );
1327 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1329 return Linker
::linkKnown(
1331 htmlspecialchars( $text ),