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';
56 private $mExtUser = null;
61 private $mOverrideRequest = null;
64 * @param WebRequest $request
66 public function __construct( $request = null ) {
67 parent
::__construct( 'Userlogin' );
69 $this->mOverrideRequest
= $request;
75 * @param $request WebRequest object
77 function load( $request ) {
78 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail, $wgRedirectOnLogin;
80 $this->mType
= $request->getText( 'type' );
81 $this->mUsername
= $request->getText( 'wpName' );
82 $this->mPassword
= $request->getText( 'wpPassword' );
83 $this->mRetype
= $request->getText( 'wpRetype' );
84 $this->mDomain
= $request->getText( 'wpDomain' );
85 $this->mReason
= $request->getText( 'wpReason' );
86 $this->mReturnTo
= $request->getVal( 'returnto' );
87 $this->mReturnToQuery
= $request->getVal( 'returntoquery' );
88 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
89 $this->mPosted
= $request->wasPosted();
90 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' );
91 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
93 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
94 $this->mAction
= $request->getVal( 'action' );
95 $this->mRemember
= $request->getCheck( 'wpRemember' );
96 $this->mStickHTTPS
= $request->getCheck( 'wpStickHTTPS' );
97 $this->mLanguage
= $request->getText( 'uselang' );
98 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
99 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
101 if ( $wgRedirectOnLogin ) {
102 $this->mReturnTo
= $wgRedirectOnLogin;
103 $this->mReturnToQuery
= '';
106 if( $wgEnableEmail ) {
107 $this->mEmail
= $request->getText( 'wpEmail' );
111 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
112 $this->mRealName
= $request->getText( 'wpRealName' );
114 $this->mRealName
= '';
117 if( !$wgAuth->validDomain( $this->mDomain
) ) {
118 $this->mDomain
= 'invaliddomain';
120 $wgAuth->setDomain( $this->mDomain
);
122 # When switching accounts, it sucks to get automatically logged out
123 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
124 if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
125 $this->mReturnTo
= '';
126 $this->mReturnToQuery
= '';
130 public function execute( $par ) {
131 if ( session_id() == '' ) {
135 if ( $this->mOverrideRequest
=== null ) {
136 $request = $this->getRequest();
138 $request = $this->mOverrideRequest
;
140 $this->load( $request );
142 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
143 $this->mType
= 'signup';
146 if ( !is_null( $this->mCookieCheck
) ) {
147 $this->onCookieRedirectCheck( $this->mCookieCheck
);
149 } elseif( $this->mPosted
) {
150 if( $this->mCreateaccount
) {
151 return $this->addNewAccount();
152 } elseif ( $this->mCreateaccountMail
) {
153 return $this->addNewAccountMailPassword();
154 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
155 return $this->processLogin();
158 $this->mainLoginForm( '' );
164 function addNewAccountMailPassword() {
165 if ( $this->mEmail
== '' ) {
166 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
170 $u = $this->addNewaccountInternal();
176 // Wipe the initial password and mail a temporary one
177 $u->setPassword( null );
179 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
181 wfRunHooks( 'AddNewAccount', array( $u, true ) );
182 $u->addNewUserLogEntry( true, $this->mReason
);
184 $out = $this->getOutput();
185 $out->setPageTitle( $this->msg( 'accmailtitle' )->text() );
187 if( !$result->isGood() ) {
188 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
190 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
191 $out->returnToMain( false );
198 function addNewAccount() {
199 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
201 # Create the account and abort if there's a problem doing so
202 $u = $this->addNewAccountInternal();
207 # If we showed up language selection links, and one was in use, be
208 # smart (and sensible) and save that language as the user's preference
209 if( $wgLoginLanguageSelector && $this->mLanguage
) {
210 $u->setOption( 'language', $this->mLanguage
);
213 $out = $this->getOutput();
215 # Send out an email authentication message if needed
216 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
217 $status = $u->sendConfirmationMail();
218 if( $status->isGood() ) {
219 $out->addWikiMsg( 'confirmemail_oncreate' );
221 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
225 # Save settings (including confirmation token)
228 # If not logged in, assume the new account as the current one and set
229 # session cookies then show a "welcome" message or a "need cookies"
231 if( $this->getUser()->isAnon() ) {
234 // This should set it for OutputPage and the Skin
235 // which is needed or the personal links will be
237 $this->getContext()->setUser( $u );
238 wfRunHooks( 'AddNewAccount', array( $u, false ) );
239 $u->addNewUserLogEntry();
240 if( $this->hasSessionCookie() ) {
241 return $this->successfulCreation();
243 return $this->cookieRedirectCheck( 'new' );
246 # Confirm that the account was created
247 $out->setPageTitle( $this->msg( 'accountcreated' )->text() );
248 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
249 $out->returnToMain( false, $this->getTitle() );
250 wfRunHooks( 'AddNewAccount', array( $u, false ) );
251 $u->addNewUserLogEntry( false, $this->mReason
);
259 function addNewAccountInternal() {
260 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
261 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
263 // If the user passes an invalid domain, something is fishy
264 if( !$wgAuth->validDomain( $this->mDomain
) ) {
265 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
269 // If we are not allowing users to login locally, we should be checking
270 // to see if the user is actually able to authenticate to the authenti-
271 // cation server before they create an account (otherwise, they can
272 // create a local account and login as any domain user). We only need
273 // to check this for domains that aren't local.
274 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
275 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername
)
276 ||
!$wgAuth->authenticate( $this->mUsername
, $this->mPassword
) ) ) {
277 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
282 if ( wfReadOnly() ) {
283 throw new ReadOnlyError
;
286 # Request forgery checks.
287 if ( !self
::getCreateaccountToken() ) {
288 self
::setCreateaccountToken();
289 $this->mainLoginForm( $this->msg( 'nocookiesfornew' )->parse() );
293 # The user didn't pass a createaccount token
294 if ( !$this->mToken
) {
295 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
299 # Validate the createaccount token
300 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
301 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
306 $currentUser = $this->getUser();
307 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
308 throw new PermissionsError( 'createaccount' );
309 } elseif ( $currentUser->isBlockedFromCreateAccount() ) {
310 $this->userBlockedMessage( $currentUser->isBlockedFromCreateAccount() );
314 $ip = $this->getRequest()->getIP();
315 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
316 $this->mainLoginForm( $this->msg( 'sorbs_create_account_reason' )->text() . ' (' . htmlspecialchars( $ip ) . ')' );
320 # Now create a dummy user ($u) and check if it is valid
321 $name = trim( $this->mUsername
);
322 $u = User
::newFromName( $name, 'creatable' );
323 if ( !is_object( $u ) ) {
324 $this->mainLoginForm( $this->msg( 'noname' )->text() );
328 if ( 0 != $u->idForName() ) {
329 $this->mainLoginForm( $this->msg( 'userexists' )->text() );
333 if ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
334 $this->mainLoginForm( $this->msg( 'badretype' )->text() );
338 # check for minimal password length
339 $valid = $u->getPasswordValidity( $this->mPassword
);
340 if ( $valid !== true ) {
341 if ( !$this->mCreateaccountMail
) {
342 if ( is_array( $valid ) ) {
343 $message = array_shift( $valid );
347 $params = array( $wgMinimalPasswordLength );
349 $this->mainLoginForm( $this->msg( $message, $params )->text() );
352 # do not force a password for account creation by email
353 # set invalid password, it will be replaced later by a random generated password
354 $this->mPassword
= null;
358 # if you need a confirmed email address to edit, then obviously you
359 # need an email address.
360 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
361 $this->mainLoginForm( $this->msg( 'noemailtitle' )->text() );
365 if( !empty( $this->mEmail
) && !Sanitizer
::validateEmail( $this->mEmail
) ) {
366 $this->mainLoginForm( $this->msg( 'invalidemailaddress' )->text() );
370 # Set some additional data so the AbortNewAccount hook can be used for
371 # more than just username validation
372 $u->setEmail( $this->mEmail
);
373 $u->setRealName( $this->mRealName
);
376 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
377 // Hook point to add extra creation throttles and blocks
378 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
379 $this->mainLoginForm( $abortError );
383 // Hook point to check for exempt from account creation throttle
384 if ( !wfRunHooks( 'exemptFromAccountCreationThrottle', array( $ip ) ) ) {
385 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
387 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
388 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
389 $value = $wgMemc->get( $key );
391 $wgMemc->set( $key, 0, 86400 );
393 if ( $value >= $wgAccountCreationThrottle ) {
394 $this->throttleHit( $wgAccountCreationThrottle );
397 $wgMemc->incr( $key );
401 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
402 $this->mainLoginForm( $this->msg( 'externaldberror' )->text() );
406 self
::clearCreateaccountToken();
407 return $this->initUser( $u, false );
411 * Actually add a user to the database.
412 * Give it a User object that has been initialised with a name.
414 * @param $u User object.
415 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
416 * @return User object.
419 function initUser( $u, $autocreate ) {
424 if ( $wgAuth->allowPasswordChange() ) {
425 $u->setPassword( $this->mPassword
);
428 $u->setEmail( $this->mEmail
);
429 $u->setRealName( $this->mRealName
);
432 $wgAuth->initUser( $u, $autocreate );
434 if ( $this->mExtUser
) {
435 $this->mExtUser
->linkToLocal( $u->getId() );
436 $email = $this->mExtUser
->getPref( 'emailaddress' );
437 if ( $email && !$this->mEmail
) {
438 $u->setEmail( $email );
442 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
446 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
447 $ssUpdate->doUpdate();
453 * Internally authenticate the login request.
455 * This may create a local account as a side effect if the
456 * authentication plugin allows transparent local account
459 public function authenticateUserData() {
460 global $wgUser, $wgAuth;
462 if ( $this->mUsername
== '' ) {
463 return self
::NO_NAME
;
466 // We require a login token to prevent login CSRF
467 // Handle part of this before incrementing the throttle so
468 // token-less login attempts don't count towards the throttle
469 // but wrong-token attempts do.
471 // If the user doesn't have a login token yet, set one.
472 if ( !self
::getLoginToken() ) {
473 self
::setLoginToken();
474 return self
::NEED_TOKEN
;
476 // If the user didn't pass a login token, tell them we need one
477 if ( !$this->mToken
) {
478 return self
::NEED_TOKEN
;
481 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
482 if ( $throttleCount === true ) {
483 return self
::THROTTLED
;
486 // Validate the login token
487 if ( $this->mToken
!== self
::getLoginToken() ) {
488 return self
::WRONG_TOKEN
;
491 // Load the current user now, and check to see if we're logging in as
492 // the same name. This is necessary because loading the current user
493 // (say by calling getName()) calls the UserLoadFromSession hook, which
494 // potentially creates the user in the database. Until we load $wgUser,
495 // checking for user existence using User::newFromName($name)->getId() below
496 // will effectively be using stale data.
497 if ( $this->getUser()->getName() === $this->mUsername
) {
498 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
499 return self
::SUCCESS
;
502 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
504 # TODO: Allow some magic here for invalid external names, e.g., let the
505 # user choose a different wiki name.
506 $u = User
::newFromName( $this->mUsername
);
507 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
508 return self
::ILLEGAL
;
511 $isAutoCreated = false;
512 if ( 0 == $u->getID() ) {
513 $status = $this->attemptAutoCreate( $u );
514 if ( $status !== self
::SUCCESS
) {
517 $isAutoCreated = true;
520 global $wgExternalAuthType, $wgAutocreatePolicy;
521 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
522 && is_object( $this->mExtUser
)
523 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
524 # The external user and local user have the same name and
525 # password, so we assume they're the same.
526 $this->mExtUser
->linkToLocal( $u->getID() );
532 // Give general extensions, such as a captcha, a chance to abort logins
533 $abort = self
::ABORTED
;
534 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
538 global $wgBlockDisablesLogin;
539 if ( !$u->checkPassword( $this->mPassword
) ) {
540 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
541 // The e-mailed temporary password should not be used for actu-
542 // al logins; that's a very sloppy habit, and insecure if an
543 // attacker has a few seconds to click "search" on someone's o-
546 // Allow it to be used only to reset the password a single time
547 // to a new value, which won't be in the user's e-mail ar-
550 // For backwards compatibility, we'll still recognize it at the
551 // login form to minimize surprises for people who have been
552 // logging in with a temporary password for some time.
554 // As a side-effect, we can authenticate the user's e-mail ad-
555 // dress if it's not already done, since the temporary password
556 // was sent via e-mail.
557 if( !$u->isEmailConfirmed() ) {
562 // At this point we just return an appropriate code/ indicating
563 // that the UI should show a password reset form; bot inter-
564 // faces etc will probably just fail cleanly here.
565 $retval = self
::RESET_PASS
;
567 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
569 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
570 // If we've enabled it, make it so that a blocked user cannot login
571 $retval = self
::USER_BLOCKED
;
573 $wgAuth->updateUser( $u );
575 // This should set it for OutputPage and the Skin
576 // which is needed or the personal links will be
578 $this->getContext()->setUser( $u );
580 // Please reset throttle for successful logins, thanks!
581 if ( $throttleCount ) {
582 self
::clearLoginThrottle( $this->mUsername
);
585 if ( $isAutoCreated ) {
586 // Must be run after $wgUser is set, for correct new user log
587 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
590 $retval = self
::SUCCESS
;
592 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
597 * Increment the login attempt throttle hit count for the (username,current IP)
598 * tuple unless the throttle was already reached.
599 * @param $username string The user name
600 * @return Bool|Integer The integer hit count or True if it is already at the limit
602 public static function incLoginThrottle( $username ) {
603 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
604 $username = trim( $username ); // sanity
607 if ( is_array( $wgPasswordAttemptThrottle ) ) {
608 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
609 $count = $wgPasswordAttemptThrottle['count'];
610 $period = $wgPasswordAttemptThrottle['seconds'];
612 $throttleCount = $wgMemc->get( $throttleKey );
613 if ( !$throttleCount ) {
614 $wgMemc->add( $throttleKey, 1, $period ); // start counter
615 } elseif ( $throttleCount < $count ) {
616 $wgMemc->incr( $throttleKey );
617 } elseif ( $throttleCount >= $count ) {
622 return $throttleCount;
626 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
627 * @param $username string The user name
630 public static function clearLoginThrottle( $username ) {
631 global $wgMemc, $wgRequest;
632 $username = trim( $username ); // sanity
634 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
635 $wgMemc->delete( $throttleKey );
639 * Attempt to automatically create a user on login. Only succeeds if there
640 * is an external authentication method which allows it.
644 * @return integer Status code
646 function attemptAutoCreate( $user ) {
647 global $wgAuth, $wgAutocreatePolicy;
649 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
650 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
651 return self
::CREATE_BLOCKED
;
655 * If the external authentication plugin allows it, automatically cre-
656 * ate a new account for users that are externally defined but have not
659 if ( $this->mExtUser
) {
660 # mExtUser is neither null nor false, so use the new ExternalAuth
662 if ( $wgAutocreatePolicy == 'never' ) {
663 return self
::NOT_EXISTS
;
665 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
666 return self
::WRONG_PLUGIN_PASS
;
670 if ( !$wgAuth->autoCreate() ) {
671 return self
::NOT_EXISTS
;
673 if ( !$wgAuth->userExists( $user->getName() ) ) {
674 wfDebug( __METHOD__
. ": user does not exist\n" );
675 return self
::NOT_EXISTS
;
677 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
678 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
679 return self
::WRONG_PLUGIN_PASS
;
684 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
685 // Hook point to add extra creation throttles and blocks
686 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
687 $this->mAbortLoginErrorMsg
= $abortError;
688 return self
::ABORTED
;
691 wfDebug( __METHOD__
. ": creating account\n" );
692 $this->initUser( $user, true );
693 return self
::SUCCESS
;
696 function processLogin() {
697 global $wgMemc, $wgLang;
699 switch ( $this->authenticateUserData() ) {
701 # We've verified now, update the real record
702 $user = $this->getUser();
703 if( (bool)$this->mRemember
!= (bool)$user->getOption( 'rememberpassword' ) ) {
704 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
705 $user->saveSettings();
707 $user->invalidateCache();
710 self
::clearLoginToken();
712 // Reset the throttle
713 $request = $this->getRequest();
714 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
715 $wgMemc->delete( $key );
717 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
718 /* Replace the language object to provide user interface in
719 * correct language immediately on this first page load.
721 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
722 $userLang = Language
::factory( $code );
724 $this->getContext()->setLang( $userLang );
725 return $this->successfulLogin();
727 return $this->cookieRedirectCheck( 'login' );
731 case self
::NEED_TOKEN
:
732 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
734 case self
::WRONG_TOKEN
:
735 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
739 $this->mainLoginForm( $this->msg( 'noname' )->text() );
741 case self
::WRONG_PLUGIN_PASS
:
742 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
744 case self
::NOT_EXISTS
:
745 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
746 $this->mainLoginForm( $this->msg( 'nosuchuser',
747 wfEscapeWikiText( $this->mUsername
) )->parse() );
749 $this->mainLoginForm( $this->msg( 'nosuchusershort',
750 wfEscapeWikiText( $this->mUsername
) )->text() );
753 case self
::WRONG_PASS
:
754 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
756 case self
::EMPTY_PASS
:
757 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
759 case self
::RESET_PASS
:
760 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
762 case self
::CREATE_BLOCKED
:
763 $this->userBlockedMessage( $this->getUser()->mBlock
);
765 case self
::THROTTLED
:
766 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
768 case self
::USER_BLOCKED
:
769 $this->mainLoginForm( $this->msg( 'login-userblocked',
770 $this->mUsername
)->escaped() );
773 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
776 throw new MWException( 'Unhandled case value' );
780 function resetLoginForm( $error ) {
781 $this->getOutput()->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
782 $reset = new SpecialChangePassword();
783 $reset->setContext( $this );
784 $reset->execute( null );
788 * @param $u User object
789 * @param $throttle Boolean
790 * @param $emailTitle String: message name of email title
791 * @param $emailText String: message name of email text
792 * @return Status object
794 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
795 global $wgServer, $wgScript, $wgNewPasswordExpiry;
797 if ( $u->getEmail() == '' ) {
798 return Status
::newFatal( 'noemail', $u->getName() );
800 $ip = $this->getRequest()->getIP();
802 return Status
::newFatal( 'badipaddress' );
805 $currentUser = $this->getUser();
806 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
808 $np = $u->randomPassword();
809 $u->setNewpassword( $np, $throttle );
811 $userLanguage = $u->getOption( 'language' );
812 $m = $this->msg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript,
813 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
814 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
821 * Run any hooks registered for logins, then HTTP redirect to
822 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
823 * nice message here, but that's really not as useful as just being sent to
824 * wherever you logged in from. It should be clear that the action was
825 * successful, given the lack of error messages plus the appearance of your
826 * name in the upper right.
830 function successfulLogin() {
831 # Run any hooks; display injected HTML if any, else redirect
832 $currentUser = $this->getUser();
834 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
836 if( $injected_html !== '' ) {
837 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
839 $titleObj = Title
::newFromText( $this->mReturnTo
);
840 if ( !$titleObj instanceof Title
) {
841 $titleObj = Title
::newMainPage();
843 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery
);
844 global $wgSecureLogin;
845 if( $wgSecureLogin && !$this->mStickHTTPS
) {
846 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
848 $this->getOutput()->redirect( $redirectUrl );
853 * Run any hooks registered for logins, then display a message welcoming
858 function successfulCreation() {
859 # Run any hooks; display injected HTML
860 $currentUser = $this->getUser();
862 $welcome_creation_msg = 'welcomecreation';
864 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
866 //let any extensions change what message is shown
867 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
869 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
873 * Display a "login successful" page.
875 private function displaySuccessfulLogin( $msgname, $injected_html ) {
876 $out = $this->getOutput();
877 $out->setPageTitle( $this->msg( 'loginsuccesstitle' )->text() );
879 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
882 $out->addHTML( $injected_html );
884 if ( !empty( $this->mReturnTo
) ) {
885 $out->returnToMain( null, $this->mReturnTo
, $this->mReturnToQuery
);
887 $out->returnToMain( null );
892 * Output a message that informs the user that they cannot create an account because
893 * there is a block on them or their IP which prevents account creation. Note that
894 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
895 * setting on blocks (bug 13611).
896 * @param $block Block the block causing this error
898 function userBlockedMessage( Block
$block ) {
899 # Let's be nice about this, it's likely that this feature will be used
900 # for blocking large numbers of innocent people, e.g. range blocks on
901 # schools. Don't blame it on the user. There's a small chance that it
902 # really is the user's fault, i.e. the username is blocked and they
903 # haven't bothered to log out before trying to create an account to
904 # evade it, but we'll leave that to their guilty conscience to figure
907 $out = $this->getOutput();
908 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' )->text() );
910 $block_reason = $block->mReason
;
911 if ( strval( $block_reason ) === '' ) {
912 $block_reason = $this->msg( 'blockednoreason' )->text();
916 'cantcreateaccount-text',
919 $block->getBlocker()->getName()
922 $out->returnToMain( false );
928 function mainLoginForm( $msg, $msgtype = 'error' ) {
929 global $wgEnableEmail, $wgEnableUserEmail;
930 global $wgHiddenPrefs, $wgLoginLanguageSelector;
931 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
932 global $wgSecureLogin, $wgPasswordResetRoutes;
934 $titleObj = $this->getTitle();
935 $user = $this->getUser();
937 if ( $this->mType
== 'signup' ) {
938 // Block signup here if in readonly. Keeps user from
939 // going through the process (filling out data, etc)
940 // and being informed later.
941 if ( wfReadOnly() ) {
942 throw new ReadOnlyError
;
943 } elseif ( $user->isBlockedFromCreateAccount() ) {
944 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
946 } elseif ( count( $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true ) )>0 ) {
947 $this->getOutput()->showPermissionsErrorPage( $permErrors, 'createaccount' );
952 if ( $this->mUsername
== '' ) {
953 if ( $user->isLoggedIn() ) {
954 $this->mUsername
= $user->getName();
956 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
960 if ( $this->mType
== 'signup' ) {
961 $template = new UsercreateTemplate();
962 $q = 'action=submitlogin&type=signup';
963 $linkq = 'type=login';
964 $linkmsg = 'gotaccount';
966 $template = new UserloginTemplate();
967 $q = 'action=submitlogin&type=login';
968 $linkq = 'type=signup';
969 $linkmsg = 'nologin';
972 if ( !empty( $this->mReturnTo
) ) {
973 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
974 if ( !empty( $this->mReturnToQuery
) ) {
975 $returnto .= '&returntoquery=' .
976 wfUrlencode( $this->mReturnToQuery
);
982 # Don't show a "create account" link if the user can't
983 if( $this->showCreateOrLoginLink( $user ) ) {
984 # Pass any language selection on to the mode switch link
985 if( $wgLoginLanguageSelector && $this->mLanguage
) {
986 $linkq .= '&uselang=' . $this->mLanguage
;
988 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
989 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
991 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
993 $template->set( 'link', '' );
996 $resetLink = $this->mType
== 'signup'
998 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1000 $template->set( 'header', '' );
1001 $template->set( 'name', $this->mUsername
);
1002 $template->set( 'password', $this->mPassword
);
1003 $template->set( 'retype', $this->mRetype
);
1004 $template->set( 'email', $this->mEmail
);
1005 $template->set( 'realname', $this->mRealName
);
1006 $template->set( 'domain', $this->mDomain
);
1007 $template->set( 'reason', $this->mReason
);
1009 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1010 $template->set( 'message', $msg );
1011 $template->set( 'messagetype', $msgtype );
1012 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1013 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1014 $template->set( 'useemail', $wgEnableEmail );
1015 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1016 $template->set( 'emailothers', $wgEnableUserEmail );
1017 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1018 $template->set( 'resetlink', $resetLink );
1019 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1020 $template->set( 'usereason', $user->isLoggedIn() );
1021 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1022 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1023 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1025 if ( $this->mType
== 'signup' ) {
1026 if ( !self
::getCreateaccountToken() ) {
1027 self
::setCreateaccountToken();
1029 $template->set( 'token', self
::getCreateaccountToken() );
1031 if ( !self
::getLoginToken() ) {
1032 self
::setLoginToken();
1034 $template->set( 'token', self
::getLoginToken() );
1037 # Prepare language selection links as needed
1038 if( $wgLoginLanguageSelector ) {
1039 $template->set( 'languages', $this->makeLanguageSelector() );
1040 if( $this->mLanguage
)
1041 $template->set( 'uselang', $this->mLanguage
);
1044 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1045 // Ditto for signupend
1046 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1047 $loginendHTTPS = $this->msg( 'loginend-https' );
1048 $signupendHTTPS = $this->msg( 'signupend-https' );
1049 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1050 $template->set( 'loginend', $loginendHTTPS->parse() );
1052 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1054 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1055 $template->set( 'signupend', $signupendHTTPS->parse() );
1057 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1060 // Give authentication and captcha plugins a chance to modify the form
1061 $wgAuth->modifyUITemplate( $template, $this->mType
);
1062 if ( $this->mType
== 'signup' ) {
1063 wfRunHooks( 'UserCreateForm', array( &$template ) );
1065 wfRunHooks( 'UserLoginForm', array( &$template ) );
1068 // Changes the title depending on permissions for creating account
1069 $out = $this->getOutput();
1070 if ( $user->isAllowed( 'createaccount' ) ) {
1071 $out->setPageTitle( $this->msg( 'userlogin' )->text() );
1073 $out->setPageTitle( $this->msg( 'userloginnocreate' )->text() );
1076 $out->disallowUserJs(); // just in case...
1077 $out->addTemplate( $template );
1087 function showCreateOrLoginLink( &$user ) {
1088 if( $this->mType
== 'signup' ) {
1090 } elseif( $user->isAllowed( 'createaccount' ) ) {
1098 * Check if a session cookie is present.
1100 * This will not pick up a cookie set during _this_ request, but is meant
1101 * to ensure that the client is returning the cookie which was set on a
1102 * previous pass through the system.
1106 function hasSessionCookie() {
1107 global $wgDisableCookieCheck;
1108 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1112 * Get the login token from the current session
1114 public static function getLoginToken() {
1116 return $wgRequest->getSessionData( 'wsLoginToken' );
1120 * Randomly generate a new login token and attach it to the current session
1122 public static function setLoginToken() {
1124 // Use User::generateToken() instead of $user->editToken()
1125 // because the latter reuses $_SESSION['wsEditToken']
1126 $wgRequest->setSessionData( 'wsLoginToken', User
::generateToken() );
1130 * Remove any login token attached to the current session
1132 public static function clearLoginToken() {
1134 $wgRequest->setSessionData( 'wsLoginToken', null );
1138 * Get the createaccount token from the current session
1140 public static function getCreateaccountToken() {
1142 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1146 * Randomly generate a new createaccount token and attach it to the current session
1148 public static function setCreateaccountToken() {
1150 $wgRequest->setSessionData( 'wsCreateaccountToken', User
::generateToken() );
1154 * Remove any createaccount token attached to the current session
1156 public static function clearCreateaccountToken() {
1158 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1164 function cookieRedirectCheck( $type ) {
1165 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1166 $query = array( 'wpCookieCheck' => $type );
1167 if ( $this->mReturnTo
) {
1168 $query['returnto'] = $this->mReturnTo
;
1170 $check = $titleObj->getFullURL( $query );
1172 return $this->getOutput()->redirect( $check );
1178 function onCookieRedirectCheck( $type ) {
1179 if ( !$this->hasSessionCookie() ) {
1180 if ( $type == 'new' ) {
1181 return $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1182 } elseif ( $type == 'login' ) {
1183 return $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1186 return $this->mainLoginForm( $this->msg( 'error' )->text() );
1189 return $this->successfulLogin();
1196 function throttleHit( $limit ) {
1197 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1201 * Produce a bar of links which allow the user to select another language
1202 * during login/registration but retain "returnto"
1206 function makeLanguageSelector() {
1207 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1208 if( !$msg->isBlank() ) {
1209 $langs = explode( "\n", $msg->text() );
1211 foreach( $langs as $lang ) {
1212 $lang = trim( $lang, '* ' );
1213 $parts = explode( '|', $lang );
1214 if ( count( $parts ) >= 2 ) {
1215 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1218 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1219 $this->getLang()->pipeList( $links ) )->escaped() : '';
1226 * Create a language selector link for a particular language
1227 * Links back to this page preserving type and returnto
1229 * @param $text Link text
1230 * @param $lang Language code
1232 function makeLanguageSelectorLink( $text, $lang ) {
1233 $attr = array( 'uselang' => $lang );
1234 if( $this->mType
== 'signup' ) {
1235 $attr['type'] = 'signup';
1237 if( $this->mReturnTo
) {
1238 $attr['returnto'] = $this->mReturnTo
;
1240 return Linker
::linkKnown(
1242 htmlspecialchars( $text ),