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;
76 * @param $request WebRequest object
79 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail, $wgRedirectOnLogin;
81 if ( $this->mLoaded
) {
84 $this->mLoaded
= true;
86 if ( $this->mOverrideRequest
=== null ) {
87 $request = $this->getRequest();
89 $request = $this->mOverrideRequest
;
92 $this->mType
= $request->getText( 'type' );
93 $this->mUsername
= $request->getText( 'wpName' );
94 $this->mPassword
= $request->getText( 'wpPassword' );
95 $this->mRetype
= $request->getText( 'wpRetype' );
96 $this->mDomain
= $request->getText( 'wpDomain' );
97 $this->mReason
= $request->getText( 'wpReason' );
98 $this->mReturnTo
= $request->getVal( 'returnto' );
99 $this->mReturnToQuery
= $request->getVal( 'returntoquery' );
100 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
101 $this->mPosted
= $request->wasPosted();
102 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' );
103 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
105 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
106 $this->mAction
= $request->getVal( 'action' );
107 $this->mRemember
= $request->getCheck( 'wpRemember' );
108 $this->mStickHTTPS
= $request->getCheck( 'wpStickHTTPS' );
109 $this->mLanguage
= $request->getText( 'uselang' );
110 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
111 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
113 if ( $wgRedirectOnLogin ) {
114 $this->mReturnTo
= $wgRedirectOnLogin;
115 $this->mReturnToQuery
= '';
118 if( $wgEnableEmail ) {
119 $this->mEmail
= $request->getText( 'wpEmail' );
123 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
124 $this->mRealName
= $request->getText( 'wpRealName' );
126 $this->mRealName
= '';
129 if( !$wgAuth->validDomain( $this->mDomain
) ) {
130 $this->mDomain
= 'invaliddomain';
132 $wgAuth->setDomain( $this->mDomain
);
134 # When switching accounts, it sucks to get automatically logged out
135 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
136 if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
137 $this->mReturnTo
= '';
138 $this->mReturnToQuery
= '';
142 public function execute( $par ) {
143 if ( session_id() == '' ) {
149 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
150 $this->mType
= 'signup';
153 if ( !is_null( $this->mCookieCheck
) ) {
154 $this->onCookieRedirectCheck( $this->mCookieCheck
);
156 } elseif( $this->mPosted
) {
157 if( $this->mCreateaccount
) {
158 return $this->addNewAccount();
159 } elseif ( $this->mCreateaccountMail
) {
160 return $this->addNewAccountMailPassword();
161 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
162 return $this->processLogin();
165 $this->mainLoginForm( '' );
171 function addNewAccountMailPassword() {
172 if ( $this->mEmail
== '' ) {
173 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
177 $u = $this->addNewaccountInternal();
183 // Wipe the initial password and mail a temporary one
184 $u->setPassword( null );
186 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
188 wfRunHooks( 'AddNewAccount', array( $u, true ) );
189 $u->addNewUserLogEntry( true, $this->mReason
);
191 $out = $this->getOutput();
192 $out->setPageTitleMsg( 'accmailtitle' );
194 if( !$result->isGood() ) {
195 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
197 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
198 $out->returnToMain( false );
205 function addNewAccount() {
206 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
208 # Create the account and abort if there's a problem doing so
209 $u = $this->addNewAccountInternal();
214 # If we showed up language selection links, and one was in use, be
215 # smart (and sensible) and save that language as the user's preference
216 if( $wgLoginLanguageSelector && $this->mLanguage
) {
217 $u->setOption( 'language', $this->mLanguage
);
220 $out = $this->getOutput();
222 # Send out an email authentication message if needed
223 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
224 $status = $u->sendConfirmationMail();
225 if( $status->isGood() ) {
226 $out->addWikiMsg( 'confirmemail_oncreate' );
228 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
232 # Save settings (including confirmation token)
235 # If not logged in, assume the new account as the current one and set
236 # session cookies then show a "welcome" message or a "need cookies"
238 if( $this->getUser()->isAnon() ) {
241 // This should set it for OutputPage and the Skin
242 // which is needed or the personal links will be
244 $this->getContext()->setUser( $u );
245 wfRunHooks( 'AddNewAccount', array( $u, false ) );
246 $u->addNewUserLogEntry();
247 if( $this->hasSessionCookie() ) {
248 return $this->successfulCreation();
250 return $this->cookieRedirectCheck( 'new' );
253 # Confirm that the account was created
254 $out->setPageTitleMsg( 'accountcreated' );
255 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
256 $out->returnToMain( false, $this->getTitle() );
257 wfRunHooks( 'AddNewAccount', array( $u, false ) );
258 $u->addNewUserLogEntry( false, $this->mReason
);
266 function addNewAccountInternal() {
267 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
268 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
270 // If the user passes an invalid domain, something is fishy
271 if( !$wgAuth->validDomain( $this->mDomain
) ) {
272 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
276 // If we are not allowing users to login locally, we should be checking
277 // to see if the user is actually able to authenticate to the authenti-
278 // cation server before they create an account (otherwise, they can
279 // create a local account and login as any domain user). We only need
280 // to check this for domains that aren't local.
281 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
282 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername
)
283 ||
!$wgAuth->authenticate( $this->mUsername
, $this->mPassword
) ) ) {
284 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
289 if ( wfReadOnly() ) {
290 throw new ReadOnlyError
;
293 # Request forgery checks.
294 if ( !self
::getCreateaccountToken() ) {
295 self
::setCreateaccountToken();
296 $this->mainLoginForm( $this->msg( 'nocookiesfornew' )->parse() );
300 # The user didn't pass a createaccount token
301 if ( !$this->mToken
) {
302 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
306 # Validate the createaccount token
307 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
308 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
313 $currentUser = $this->getUser();
314 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
315 throw new PermissionsError( 'createaccount' );
316 } elseif ( $currentUser->isBlockedFromCreateAccount() ) {
317 $this->userBlockedMessage( $currentUser->isBlockedFromCreateAccount() );
321 $ip = $this->getRequest()->getIP();
322 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
323 $this->mainLoginForm( $this->msg( 'sorbs_create_account_reason' )->text() . ' (' . htmlspecialchars( $ip ) . ')' );
327 # Now create a dummy user ($u) and check if it is valid
328 $name = trim( $this->mUsername
);
329 $u = User
::newFromName( $name, 'creatable' );
330 if ( !is_object( $u ) ) {
331 $this->mainLoginForm( $this->msg( 'noname' )->text() );
335 if ( 0 != $u->idForName() ) {
336 $this->mainLoginForm( $this->msg( 'userexists' )->text() );
340 if ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
341 $this->mainLoginForm( $this->msg( 'badretype' )->text() );
345 # check for minimal password length
346 $valid = $u->getPasswordValidity( $this->mPassword
);
347 if ( $valid !== true ) {
348 if ( !$this->mCreateaccountMail
) {
349 if ( is_array( $valid ) ) {
350 $message = array_shift( $valid );
354 $params = array( $wgMinimalPasswordLength );
356 $this->mainLoginForm( $this->msg( $message, $params )->text() );
359 # do not force a password for account creation by email
360 # set invalid password, it will be replaced later by a random generated password
361 $this->mPassword
= null;
365 # if you need a confirmed email address to edit, then obviously you
366 # need an email address.
367 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
368 $this->mainLoginForm( $this->msg( 'noemailtitle' )->text() );
372 if( !empty( $this->mEmail
) && !Sanitizer
::validateEmail( $this->mEmail
) ) {
373 $this->mainLoginForm( $this->msg( 'invalidemailaddress' )->text() );
377 # Set some additional data so the AbortNewAccount hook can be used for
378 # more than just username validation
379 $u->setEmail( $this->mEmail
);
380 $u->setRealName( $this->mRealName
);
383 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
384 // Hook point to add extra creation throttles and blocks
385 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
386 $this->mainLoginForm( $abortError );
390 // Hook point to check for exempt from account creation throttle
391 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
392 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
394 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
395 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
396 $value = $wgMemc->get( $key );
398 $wgMemc->set( $key, 0, 86400 );
400 if ( $value >= $wgAccountCreationThrottle ) {
401 $this->throttleHit( $wgAccountCreationThrottle );
404 $wgMemc->incr( $key );
408 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
409 $this->mainLoginForm( $this->msg( 'externaldberror' )->text() );
413 self
::clearCreateaccountToken();
414 return $this->initUser( $u, false );
418 * Actually add a user to the database.
419 * Give it a User object that has been initialised with a name.
421 * @param $u User object.
422 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
423 * @return User object.
426 function initUser( $u, $autocreate ) {
431 if ( $wgAuth->allowPasswordChange() ) {
432 $u->setPassword( $this->mPassword
);
435 $u->setEmail( $this->mEmail
);
436 $u->setRealName( $this->mRealName
);
439 $wgAuth->initUser( $u, $autocreate );
441 if ( $this->mExtUser
) {
442 $this->mExtUser
->linkToLocal( $u->getId() );
443 $email = $this->mExtUser
->getPref( 'emailaddress' );
444 if ( $email && !$this->mEmail
) {
445 $u->setEmail( $email );
449 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
453 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
454 $ssUpdate->doUpdate();
460 * Internally authenticate the login request.
462 * This may create a local account as a side effect if the
463 * authentication plugin allows transparent local account
466 public function authenticateUserData() {
467 global $wgUser, $wgAuth;
471 if ( $this->mUsername
== '' ) {
472 return self
::NO_NAME
;
475 // We require a login token to prevent login CSRF
476 // Handle part of this before incrementing the throttle so
477 // token-less login attempts don't count towards the throttle
478 // but wrong-token attempts do.
480 // If the user doesn't have a login token yet, set one.
481 if ( !self
::getLoginToken() ) {
482 self
::setLoginToken();
483 return self
::NEED_TOKEN
;
485 // If the user didn't pass a login token, tell them we need one
486 if ( !$this->mToken
) {
487 return self
::NEED_TOKEN
;
490 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
491 if ( $throttleCount === true ) {
492 return self
::THROTTLED
;
495 // Validate the login token
496 if ( $this->mToken
!== self
::getLoginToken() ) {
497 return self
::WRONG_TOKEN
;
500 // Load the current user now, and check to see if we're logging in as
501 // the same name. This is necessary because loading the current user
502 // (say by calling getName()) calls the UserLoadFromSession hook, which
503 // potentially creates the user in the database. Until we load $wgUser,
504 // checking for user existence using User::newFromName($name)->getId() below
505 // will effectively be using stale data.
506 if ( $this->getUser()->getName() === $this->mUsername
) {
507 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
508 return self
::SUCCESS
;
511 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
513 # TODO: Allow some magic here for invalid external names, e.g., let the
514 # user choose a different wiki name.
515 $u = User
::newFromName( $this->mUsername
);
516 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
517 return self
::ILLEGAL
;
520 $isAutoCreated = false;
521 if ( 0 == $u->getID() ) {
522 $status = $this->attemptAutoCreate( $u );
523 if ( $status !== self
::SUCCESS
) {
526 $isAutoCreated = true;
529 global $wgExternalAuthType, $wgAutocreatePolicy;
530 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
531 && is_object( $this->mExtUser
)
532 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
533 # The external user and local user have the same name and
534 # password, so we assume they're the same.
535 $this->mExtUser
->linkToLocal( $u->getID() );
541 // Give general extensions, such as a captcha, a chance to abort logins
542 $abort = self
::ABORTED
;
543 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
547 global $wgBlockDisablesLogin;
548 if ( !$u->checkPassword( $this->mPassword
) ) {
549 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
550 // The e-mailed temporary password should not be used for actu-
551 // al logins; that's a very sloppy habit, and insecure if an
552 // attacker has a few seconds to click "search" on someone's o-
555 // Allow it to be used only to reset the password a single time
556 // to a new value, which won't be in the user's e-mail ar-
559 // For backwards compatibility, we'll still recognize it at the
560 // login form to minimize surprises for people who have been
561 // logging in with a temporary password for some time.
563 // As a side-effect, we can authenticate the user's e-mail ad-
564 // dress if it's not already done, since the temporary password
565 // was sent via e-mail.
566 if( !$u->isEmailConfirmed() ) {
571 // At this point we just return an appropriate code/ indicating
572 // that the UI should show a password reset form; bot inter-
573 // faces etc will probably just fail cleanly here.
574 $retval = self
::RESET_PASS
;
576 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
578 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
579 // If we've enabled it, make it so that a blocked user cannot login
580 $retval = self
::USER_BLOCKED
;
582 $wgAuth->updateUser( $u );
584 // This should set it for OutputPage and the Skin
585 // which is needed or the personal links will be
587 $this->getContext()->setUser( $u );
589 // Please reset throttle for successful logins, thanks!
590 if ( $throttleCount ) {
591 self
::clearLoginThrottle( $this->mUsername
);
594 if ( $isAutoCreated ) {
595 // Must be run after $wgUser is set, for correct new user log
596 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
599 $retval = self
::SUCCESS
;
601 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
606 * Increment the login attempt throttle hit count for the (username,current IP)
607 * tuple unless the throttle was already reached.
608 * @param $username string The user name
609 * @return Bool|Integer The integer hit count or True if it is already at the limit
611 public static function incLoginThrottle( $username ) {
612 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
613 $username = trim( $username ); // sanity
616 if ( is_array( $wgPasswordAttemptThrottle ) ) {
617 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
618 $count = $wgPasswordAttemptThrottle['count'];
619 $period = $wgPasswordAttemptThrottle['seconds'];
621 $throttleCount = $wgMemc->get( $throttleKey );
622 if ( !$throttleCount ) {
623 $wgMemc->add( $throttleKey, 1, $period ); // start counter
624 } elseif ( $throttleCount < $count ) {
625 $wgMemc->incr( $throttleKey );
626 } elseif ( $throttleCount >= $count ) {
631 return $throttleCount;
635 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
636 * @param $username string The user name
639 public static function clearLoginThrottle( $username ) {
640 global $wgMemc, $wgRequest;
641 $username = trim( $username ); // sanity
643 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
644 $wgMemc->delete( $throttleKey );
648 * Attempt to automatically create a user on login. Only succeeds if there
649 * is an external authentication method which allows it.
653 * @return integer Status code
655 function attemptAutoCreate( $user ) {
656 global $wgAuth, $wgAutocreatePolicy;
658 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
659 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
660 return self
::CREATE_BLOCKED
;
664 * If the external authentication plugin allows it, automatically cre-
665 * ate a new account for users that are externally defined but have not
668 if ( $this->mExtUser
) {
669 # mExtUser is neither null nor false, so use the new ExternalAuth
671 if ( $wgAutocreatePolicy == 'never' ) {
672 return self
::NOT_EXISTS
;
674 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
675 return self
::WRONG_PLUGIN_PASS
;
679 if ( !$wgAuth->autoCreate() ) {
680 return self
::NOT_EXISTS
;
682 if ( !$wgAuth->userExists( $user->getName() ) ) {
683 wfDebug( __METHOD__
. ": user does not exist\n" );
684 return self
::NOT_EXISTS
;
686 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
687 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
688 return self
::WRONG_PLUGIN_PASS
;
693 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
694 // Hook point to add extra creation throttles and blocks
695 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
696 $this->mAbortLoginErrorMsg
= $abortError;
697 return self
::ABORTED
;
700 wfDebug( __METHOD__
. ": creating account\n" );
701 $this->initUser( $user, true );
702 return self
::SUCCESS
;
705 function processLogin() {
706 global $wgMemc, $wgLang;
708 switch ( $this->authenticateUserData() ) {
710 # We've verified now, update the real record
711 $user = $this->getUser();
712 if( (bool)$this->mRemember
!= (bool)$user->getOption( 'rememberpassword' ) ) {
713 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
714 $user->saveSettings();
716 $user->invalidateCache();
719 self
::clearLoginToken();
721 // Reset the throttle
722 $request = $this->getRequest();
723 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
724 $wgMemc->delete( $key );
726 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
727 /* Replace the language object to provide user interface in
728 * correct language immediately on this first page load.
730 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
731 $userLang = Language
::factory( $code );
733 $this->getContext()->setLang( $userLang );
734 return $this->successfulLogin();
736 return $this->cookieRedirectCheck( 'login' );
740 case self
::NEED_TOKEN
:
741 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
743 case self
::WRONG_TOKEN
:
744 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
748 $this->mainLoginForm( $this->msg( 'noname' )->text() );
750 case self
::WRONG_PLUGIN_PASS
:
751 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
753 case self
::NOT_EXISTS
:
754 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
755 $this->mainLoginForm( $this->msg( 'nosuchuser',
756 wfEscapeWikiText( $this->mUsername
) )->parse() );
758 $this->mainLoginForm( $this->msg( 'nosuchusershort',
759 wfEscapeWikiText( $this->mUsername
) )->text() );
762 case self
::WRONG_PASS
:
763 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
765 case self
::EMPTY_PASS
:
766 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
768 case self
::RESET_PASS
:
769 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
771 case self
::CREATE_BLOCKED
:
772 $this->userBlockedMessage( $this->getUser()->mBlock
);
774 case self
::THROTTLED
:
775 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
777 case self
::USER_BLOCKED
:
778 $this->mainLoginForm( $this->msg( 'login-userblocked',
779 $this->mUsername
)->escaped() );
782 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
785 throw new MWException( 'Unhandled case value' );
789 function resetLoginForm( $error ) {
790 $this->getOutput()->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
791 $reset = new SpecialChangePassword();
792 $reset->setContext( $this );
793 $reset->execute( null );
797 * @param $u User object
798 * @param $throttle Boolean
799 * @param $emailTitle String: message name of email title
800 * @param $emailText String: message name of email text
801 * @return Status object
803 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
804 global $wgServer, $wgScript, $wgNewPasswordExpiry;
806 if ( $u->getEmail() == '' ) {
807 return Status
::newFatal( 'noemail', $u->getName() );
809 $ip = $this->getRequest()->getIP();
811 return Status
::newFatal( 'badipaddress' );
814 $currentUser = $this->getUser();
815 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
817 $np = $u->randomPassword();
818 $u->setNewpassword( $np, $throttle );
820 $userLanguage = $u->getOption( 'language' );
821 $m = $this->msg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript,
822 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
823 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
830 * Run any hooks registered for logins, then HTTP redirect to
831 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
832 * nice message here, but that's really not as useful as just being sent to
833 * wherever you logged in from. It should be clear that the action was
834 * successful, given the lack of error messages plus the appearance of your
835 * name in the upper right.
839 function successfulLogin() {
840 # Run any hooks; display injected HTML if any, else redirect
841 $currentUser = $this->getUser();
843 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
845 if( $injected_html !== '' ) {
846 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
848 $titleObj = Title
::newFromText( $this->mReturnTo
);
849 if ( !$titleObj instanceof Title
) {
850 $titleObj = Title
::newMainPage();
852 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery
);
853 global $wgSecureLogin;
854 if( $wgSecureLogin && !$this->mStickHTTPS
) {
855 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
857 $this->getOutput()->redirect( $redirectUrl );
862 * Run any hooks registered for logins, then display a message welcoming
867 function successfulCreation() {
868 # Run any hooks; display injected HTML
869 $currentUser = $this->getUser();
871 $welcome_creation_msg = 'welcomecreation';
873 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
875 //let any extensions change what message is shown
876 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
878 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
882 * Display a "login successful" page.
884 private function displaySuccessfulLogin( $msgname, $injected_html ) {
885 $out = $this->getOutput();
886 $out->setPageTitleMsg( 'loginsuccesstitle' );
888 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
891 $out->addHTML( $injected_html );
893 if ( !empty( $this->mReturnTo
) ) {
894 $out->returnToMain( null, $this->mReturnTo
, $this->mReturnToQuery
);
896 $out->returnToMain( null );
901 * Output a message that informs the user that they cannot create an account because
902 * there is a block on them or their IP which prevents account creation. Note that
903 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
904 * setting on blocks (bug 13611).
905 * @param $block Block the block causing this error
907 function userBlockedMessage( Block
$block ) {
908 # Let's be nice about this, it's likely that this feature will be used
909 # for blocking large numbers of innocent people, e.g. range blocks on
910 # schools. Don't blame it on the user. There's a small chance that it
911 # really is the user's fault, i.e. the username is blocked and they
912 # haven't bothered to log out before trying to create an account to
913 # evade it, but we'll leave that to their guilty conscience to figure
916 $out = $this->getOutput();
917 $out->setPageTitleMsg( 'cantcreateaccounttitle' );
919 $block_reason = $block->mReason
;
920 if ( strval( $block_reason ) === '' ) {
921 $block_reason = $this->msg( 'blockednoreason' )->text();
925 'cantcreateaccount-text',
928 $block->getBlocker()->getName()
931 $out->returnToMain( false );
937 function mainLoginForm( $msg, $msgtype = 'error' ) {
938 global $wgEnableEmail, $wgEnableUserEmail;
939 global $wgHiddenPrefs, $wgLoginLanguageSelector;
940 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
941 global $wgSecureLogin, $wgPasswordResetRoutes;
943 $titleObj = $this->getTitle();
944 $user = $this->getUser();
946 if ( $this->mType
== 'signup' ) {
947 // Block signup here if in readonly. Keeps user from
948 // going through the process (filling out data, etc)
949 // and being informed later.
950 if ( wfReadOnly() ) {
951 throw new ReadOnlyError
;
952 } elseif ( $user->isBlockedFromCreateAccount() ) {
953 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
955 } elseif ( count( $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true ) )>0 ) {
956 $this->getOutput()->showPermissionsErrorPage( $permErrors, 'createaccount' );
961 if ( $this->mUsername
== '' ) {
962 if ( $user->isLoggedIn() ) {
963 $this->mUsername
= $user->getName();
965 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
969 if ( $this->mType
== 'signup' ) {
970 $template = new UsercreateTemplate();
971 $q = 'action=submitlogin&type=signup';
972 $linkq = 'type=login';
973 $linkmsg = 'gotaccount';
975 $template = new UserloginTemplate();
976 $q = 'action=submitlogin&type=login';
977 $linkq = 'type=signup';
978 $linkmsg = 'nologin';
981 if ( !empty( $this->mReturnTo
) ) {
982 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
983 if ( !empty( $this->mReturnToQuery
) ) {
984 $returnto .= '&returntoquery=' .
985 wfUrlencode( $this->mReturnToQuery
);
991 # Don't show a "create account" link if the user can't
992 if( $this->showCreateOrLoginLink( $user ) ) {
993 # Pass any language selection on to the mode switch link
994 if( $wgLoginLanguageSelector && $this->mLanguage
) {
995 $linkq .= '&uselang=' . $this->mLanguage
;
997 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
998 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1000 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1002 $template->set( 'link', '' );
1005 $resetLink = $this->mType
== 'signup'
1007 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1009 $template->set( 'header', '' );
1010 $template->set( 'name', $this->mUsername
);
1011 $template->set( 'password', $this->mPassword
);
1012 $template->set( 'retype', $this->mRetype
);
1013 $template->set( 'email', $this->mEmail
);
1014 $template->set( 'realname', $this->mRealName
);
1015 $template->set( 'domain', $this->mDomain
);
1016 $template->set( 'reason', $this->mReason
);
1018 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1019 $template->set( 'message', $msg );
1020 $template->set( 'messagetype', $msgtype );
1021 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1022 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1023 $template->set( 'useemail', $wgEnableEmail );
1024 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1025 $template->set( 'emailothers', $wgEnableUserEmail );
1026 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1027 $template->set( 'resetlink', $resetLink );
1028 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1029 $template->set( 'usereason', $user->isLoggedIn() );
1030 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1031 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1032 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1034 if ( $this->mType
== 'signup' ) {
1035 if ( !self
::getCreateaccountToken() ) {
1036 self
::setCreateaccountToken();
1038 $template->set( 'token', self
::getCreateaccountToken() );
1040 if ( !self
::getLoginToken() ) {
1041 self
::setLoginToken();
1043 $template->set( 'token', self
::getLoginToken() );
1046 # Prepare language selection links as needed
1047 if( $wgLoginLanguageSelector ) {
1048 $template->set( 'languages', $this->makeLanguageSelector() );
1049 if( $this->mLanguage
)
1050 $template->set( 'uselang', $this->mLanguage
);
1053 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1054 // Ditto for signupend
1055 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1056 $loginendHTTPS = $this->msg( 'loginend-https' );
1057 $signupendHTTPS = $this->msg( 'signupend-https' );
1058 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1059 $template->set( 'loginend', $loginendHTTPS->parse() );
1061 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1063 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1064 $template->set( 'signupend', $signupendHTTPS->parse() );
1066 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1069 // Give authentication and captcha plugins a chance to modify the form
1070 $wgAuth->modifyUITemplate( $template, $this->mType
);
1071 if ( $this->mType
== 'signup' ) {
1072 wfRunHooks( 'UserCreateForm', array( &$template ) );
1074 wfRunHooks( 'UserLoginForm', array( &$template ) );
1077 // Changes the title depending on permissions for creating account
1078 $out = $this->getOutput();
1079 if ( $user->isAllowed( 'createaccount' ) ) {
1080 $out->setPageTitleMsg( 'userlogin' );
1082 $out->setPageTitleMsg( 'userloginnocreate' );
1085 $out->disallowUserJs(); // just in case...
1086 $out->addTemplate( $template );
1096 function showCreateOrLoginLink( &$user ) {
1097 if( $this->mType
== 'signup' ) {
1099 } elseif( $user->isAllowed( 'createaccount' ) ) {
1107 * Check if a session cookie is present.
1109 * This will not pick up a cookie set during _this_ request, but is meant
1110 * to ensure that the client is returning the cookie which was set on a
1111 * previous pass through the system.
1115 function hasSessionCookie() {
1116 global $wgDisableCookieCheck;
1117 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1121 * Get the login token from the current session
1123 public static function getLoginToken() {
1125 return $wgRequest->getSessionData( 'wsLoginToken' );
1129 * Randomly generate a new login token and attach it to the current session
1131 public static function setLoginToken() {
1133 // Use User::generateToken() instead of $user->editToken()
1134 // because the latter reuses $_SESSION['wsEditToken']
1135 $wgRequest->setSessionData( 'wsLoginToken', User
::generateToken() );
1139 * Remove any login token attached to the current session
1141 public static function clearLoginToken() {
1143 $wgRequest->setSessionData( 'wsLoginToken', null );
1147 * Get the createaccount token from the current session
1149 public static function getCreateaccountToken() {
1151 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1155 * Randomly generate a new createaccount token and attach it to the current session
1157 public static function setCreateaccountToken() {
1159 $wgRequest->setSessionData( 'wsCreateaccountToken', User
::generateToken() );
1163 * Remove any createaccount token attached to the current session
1165 public static function clearCreateaccountToken() {
1167 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1173 function cookieRedirectCheck( $type ) {
1174 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1175 $query = array( 'wpCookieCheck' => $type );
1176 if ( $this->mReturnTo
) {
1177 $query['returnto'] = $this->mReturnTo
;
1179 $check = $titleObj->getFullURL( $query );
1181 return $this->getOutput()->redirect( $check );
1187 function onCookieRedirectCheck( $type ) {
1188 if ( !$this->hasSessionCookie() ) {
1189 if ( $type == 'new' ) {
1190 return $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1191 } elseif ( $type == 'login' ) {
1192 return $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1195 return $this->mainLoginForm( $this->msg( 'error' )->text() );
1198 return $this->successfulLogin();
1205 function throttleHit( $limit ) {
1206 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1210 * Produce a bar of links which allow the user to select another language
1211 * during login/registration but retain "returnto"
1215 function makeLanguageSelector() {
1216 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1217 if( !$msg->isBlank() ) {
1218 $langs = explode( "\n", $msg->text() );
1220 foreach( $langs as $lang ) {
1221 $lang = trim( $lang, '* ' );
1222 $parts = explode( '|', $lang );
1223 if ( count( $parts ) >= 2 ) {
1224 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1227 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1228 $this->getLang()->pipeList( $links ) )->escaped() : '';
1235 * Create a language selector link for a particular language
1236 * Links back to this page preserving type and returnto
1238 * @param $text Link text
1239 * @param $lang Language code
1241 function makeLanguageSelectorLink( $text, $lang ) {
1242 $attr = array( 'uselang' => $lang );
1243 if( $this->mType
== 'signup' ) {
1244 $attr['type'] = 'signup';
1246 if( $this->mReturnTo
) {
1247 $attr['returnto'] = $this->mReturnTo
;
1249 return Linker
::linkKnown(
1251 htmlspecialchars( $text ),