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, $wgRedirectOnLogin;
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->mReturnTo
= $request->getVal( 'returnto' );
97 $this->mReturnToQuery
= $request->getVal( 'returntoquery' );
98 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
99 $this->mPosted
= $request->wasPosted();
100 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' );
101 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
103 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
104 $this->mAction
= $request->getVal( 'action' );
105 $this->mRemember
= $request->getCheck( 'wpRemember' );
106 $this->mStickHTTPS
= $request->getCheck( 'wpStickHTTPS' );
107 $this->mLanguage
= $request->getText( 'uselang' );
108 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
109 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
111 if ( $wgRedirectOnLogin ) {
112 $this->mReturnTo
= $wgRedirectOnLogin;
113 $this->mReturnToQuery
= '';
116 if( $wgEnableEmail ) {
117 $this->mEmail
= $request->getText( 'wpEmail' );
121 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
122 $this->mRealName
= $request->getText( 'wpRealName' );
124 $this->mRealName
= '';
127 if( !$wgAuth->validDomain( $this->mDomain
) ) {
128 if ( isset( $_SESSION['wsDomain'] ) ) {
129 $this->mDomain
= $_SESSION['wsDomain'];
131 $this->mDomain
= 'invaliddomain';
134 $wgAuth->setDomain( $this->mDomain
);
136 # 1. When switching accounts, it sucks to get automatically logged out
137 # 2. Do not return to PasswordReset after a successful password change
138 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
139 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
140 if( is_object( $returnToTitle ) && (
141 $returnToTitle->isSpecial( 'Userlogout' )
142 ||
$returnToTitle->isSpecial( 'PasswordReset' ) ) ) {
143 $this->mReturnTo
= '';
144 $this->mReturnToQuery
= '';
148 function getDescription() {
149 return $this->msg( $this->getUser()->isAllowed( 'createaccount' ) ?
150 'userlogin' : 'userloginnocreate' )->text();
153 public function execute( $par ) {
154 if ( session_id() == '' ) {
161 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
162 $this->mType
= 'signup';
165 if ( !is_null( $this->mCookieCheck
) ) {
166 $this->onCookieRedirectCheck( $this->mCookieCheck
);
168 } elseif( $this->mPosted
) {
169 if( $this->mCreateaccount
) {
170 $this->addNewAccount();
172 } elseif ( $this->mCreateaccountMail
) {
173 $this->addNewAccountMailPassword();
175 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
176 $this->processLogin();
180 $this->mainLoginForm( '' );
186 function addNewAccountMailPassword() {
187 if ( $this->mEmail
== '' ) {
188 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
192 $u = $this->addNewaccountInternal();
198 // Wipe the initial password and mail a temporary one
199 $u->setPassword( null );
201 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
203 wfRunHooks( 'AddNewAccount', array( $u, true ) );
204 $u->addNewUserLogEntry( true, $this->mReason
);
206 $out = $this->getOutput();
207 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
209 if( !$result->isGood() ) {
210 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
212 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
213 $out->returnToMain( false );
221 function addNewAccount() {
222 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
224 # Create the account and abort if there's a problem doing so
225 $u = $this->addNewAccountInternal();
230 # If we showed up language selection links, and one was in use, be
231 # smart (and sensible) and save that language as the user's preference
232 if( $wgLoginLanguageSelector && $this->mLanguage
) {
233 $u->setOption( 'language', $this->mLanguage
);
236 $out = $this->getOutput();
238 # Send out an email authentication message if needed
239 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
240 $status = $u->sendConfirmationMail();
241 if( $status->isGood() ) {
242 $out->addWikiMsg( 'confirmemail_oncreate' );
244 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
248 # Save settings (including confirmation token)
251 # If not logged in, assume the new account as the current one and set
252 # session cookies then show a "welcome" message or a "need cookies"
254 if( $this->getUser()->isAnon() ) {
257 // This should set it for OutputPage and the Skin
258 // which is needed or the personal links will be
260 $this->getContext()->setUser( $u );
261 wfRunHooks( 'AddNewAccount', array( $u, false ) );
262 $u->addNewUserLogEntry();
263 if( $this->hasSessionCookie() ) {
264 $this->successfulCreation();
266 $this->cookieRedirectCheck( 'new' );
269 # Confirm that the account was created
270 $out->setPageTitle( $this->msg( 'accountcreated' ) );
271 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
272 $out->returnToMain( false, $this->getTitle() );
273 wfRunHooks( 'AddNewAccount', array( $u, false ) );
274 $u->addNewUserLogEntry( false, $this->mReason
);
283 function addNewAccountInternal() {
284 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
285 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
287 // If the user passes an invalid domain, something is fishy
288 if( !$wgAuth->validDomain( $this->mDomain
) ) {
289 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
293 // If we are not allowing users to login locally, we should be checking
294 // to see if the user is actually able to authenticate to the authenti-
295 // cation server before they create an account (otherwise, they can
296 // create a local account and login as any domain user). We only need
297 // to check this for domains that aren't local.
298 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
299 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername
)
300 ||
!$wgAuth->authenticate( $this->mUsername
, $this->mPassword
) ) ) {
301 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
306 if ( wfReadOnly() ) {
307 throw new ReadOnlyError
;
310 # Request forgery checks.
311 if ( !self
::getCreateaccountToken() ) {
312 self
::setCreateaccountToken();
313 $this->mainLoginForm( $this->msg( 'nocookiesfornew' )->parse() );
317 # The user didn't pass a createaccount token
318 if ( !$this->mToken
) {
319 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
323 # Validate the createaccount token
324 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
325 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
330 $currentUser = $this->getUser();
331 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
332 throw new PermissionsError( 'createaccount' );
333 } elseif ( $currentUser->isBlockedFromCreateAccount() ) {
334 $this->userBlockedMessage( $currentUser->isBlockedFromCreateAccount() );
338 $ip = $this->getRequest()->getIP();
339 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
340 $this->mainLoginForm( $this->msg( 'sorbs_create_account_reason' )->text() . ' ' . $this->msg( 'parentheses', $ip )->escaped() );
344 # Now create a dummy user ($u) and check if it is valid
345 $name = trim( $this->mUsername
);
346 $u = User
::newFromName( $name, 'creatable' );
347 if ( !is_object( $u ) ) {
348 $this->mainLoginForm( $this->msg( 'noname' )->text() );
352 if ( 0 != $u->idForName() ) {
353 $this->mainLoginForm( $this->msg( 'userexists' )->text() );
357 if ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
358 $this->mainLoginForm( $this->msg( 'badretype' )->text() );
362 # check for minimal password length
363 $valid = $u->getPasswordValidity( $this->mPassword
);
364 if ( $valid !== true ) {
365 if ( !$this->mCreateaccountMail
) {
366 if ( is_array( $valid ) ) {
367 $message = array_shift( $valid );
371 $params = array( $wgMinimalPasswordLength );
373 $this->mainLoginForm( $this->msg( $message, $params )->text() );
376 # do not force a password for account creation by email
377 # set invalid password, it will be replaced later by a random generated password
378 $this->mPassword
= null;
382 # if you need a confirmed email address to edit, then obviously you
383 # need an email address.
384 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
385 $this->mainLoginForm( $this->msg( 'noemailtitle' )->text() );
389 if( !empty( $this->mEmail
) && !Sanitizer
::validateEmail( $this->mEmail
) ) {
390 $this->mainLoginForm( $this->msg( 'invalidemailaddress' )->text() );
394 # Set some additional data so the AbortNewAccount hook can be used for
395 # more than just username validation
396 $u->setEmail( $this->mEmail
);
397 $u->setRealName( $this->mRealName
);
400 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
401 // Hook point to add extra creation throttles and blocks
402 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
403 $this->mainLoginForm( $abortError );
407 // Hook point to check for exempt from account creation throttle
408 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
409 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
411 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
412 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
413 $value = $wgMemc->get( $key );
415 $wgMemc->set( $key, 0, 86400 );
417 if ( $value >= $wgAccountCreationThrottle ) {
418 $this->throttleHit( $wgAccountCreationThrottle );
421 $wgMemc->incr( $key );
425 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
426 $this->mainLoginForm( $this->msg( 'externaldberror' )->text() );
430 self
::clearCreateaccountToken();
431 return $this->initUser( $u, false );
435 * Actually add a user to the database.
436 * Give it a User object that has been initialised with a name.
438 * @param $u User object.
439 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
440 * @return User object.
443 function initUser( $u, $autocreate ) {
448 if ( $wgAuth->allowPasswordChange() ) {
449 $u->setPassword( $this->mPassword
);
452 $u->setEmail( $this->mEmail
);
453 $u->setRealName( $this->mRealName
);
456 $wgAuth->initUser( $u, $autocreate );
458 if ( $this->mExtUser
) {
459 $this->mExtUser
->linkToLocal( $u->getId() );
460 $email = $this->mExtUser
->getPref( 'emailaddress' );
461 if ( $email && !$this->mEmail
) {
462 $u->setEmail( $email );
466 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
470 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
471 $ssUpdate->doUpdate();
477 * Internally authenticate the login request.
479 * This may create a local account as a side effect if the
480 * authentication plugin allows transparent local account
484 public function authenticateUserData() {
485 global $wgUser, $wgAuth;
489 if ( $this->mUsername
== '' ) {
490 return self
::NO_NAME
;
493 // We require a login token to prevent login CSRF
494 // Handle part of this before incrementing the throttle so
495 // token-less login attempts don't count towards the throttle
496 // but wrong-token attempts do.
498 // If the user doesn't have a login token yet, set one.
499 if ( !self
::getLoginToken() ) {
500 self
::setLoginToken();
501 return self
::NEED_TOKEN
;
503 // If the user didn't pass a login token, tell them we need one
504 if ( !$this->mToken
) {
505 return self
::NEED_TOKEN
;
508 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
509 if ( $throttleCount === true ) {
510 return self
::THROTTLED
;
513 // Validate the login token
514 if ( $this->mToken
!== self
::getLoginToken() ) {
515 return self
::WRONG_TOKEN
;
518 // Load the current user now, and check to see if we're logging in as
519 // the same name. This is necessary because loading the current user
520 // (say by calling getName()) calls the UserLoadFromSession hook, which
521 // potentially creates the user in the database. Until we load $wgUser,
522 // checking for user existence using User::newFromName($name)->getId() below
523 // will effectively be using stale data.
524 if ( $this->getUser()->getName() === $this->mUsername
) {
525 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
526 return self
::SUCCESS
;
529 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
531 # TODO: Allow some magic here for invalid external names, e.g., let the
532 # user choose a different wiki name.
533 $u = User
::newFromName( $this->mUsername
);
534 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
535 return self
::ILLEGAL
;
538 $isAutoCreated = false;
539 if ( 0 == $u->getID() ) {
540 $status = $this->attemptAutoCreate( $u );
541 if ( $status !== self
::SUCCESS
) {
544 $isAutoCreated = true;
547 global $wgExternalAuthType, $wgAutocreatePolicy;
548 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
549 && is_object( $this->mExtUser
)
550 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
551 # The external user and local user have the same name and
552 # password, so we assume they're the same.
553 $this->mExtUser
->linkToLocal( $u->getID() );
559 // Give general extensions, such as a captcha, a chance to abort logins
560 $abort = self
::ABORTED
;
561 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
565 global $wgBlockDisablesLogin;
566 if ( !$u->checkPassword( $this->mPassword
) ) {
567 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
568 // The e-mailed temporary password should not be used for actu-
569 // al logins; that's a very sloppy habit, and insecure if an
570 // attacker has a few seconds to click "search" on someone's o-
573 // Allow it to be used only to reset the password a single time
574 // to a new value, which won't be in the user's e-mail ar-
577 // For backwards compatibility, we'll still recognize it at the
578 // login form to minimize surprises for people who have been
579 // logging in with a temporary password for some time.
581 // As a side-effect, we can authenticate the user's e-mail ad-
582 // dress if it's not already done, since the temporary password
583 // was sent via e-mail.
584 if( !$u->isEmailConfirmed() ) {
589 // At this point we just return an appropriate code/ indicating
590 // that the UI should show a password reset form; bot inter-
591 // faces etc will probably just fail cleanly here.
592 $retval = self
::RESET_PASS
;
594 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
596 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
597 // If we've enabled it, make it so that a blocked user cannot login
598 $retval = self
::USER_BLOCKED
;
600 $wgAuth->updateUser( $u );
602 // This should set it for OutputPage and the Skin
603 // which is needed or the personal links will be
605 $this->getContext()->setUser( $u );
607 // Please reset throttle for successful logins, thanks!
608 if ( $throttleCount ) {
609 self
::clearLoginThrottle( $this->mUsername
);
612 if ( $isAutoCreated ) {
613 // Must be run after $wgUser is set, for correct new user log
614 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
617 $retval = self
::SUCCESS
;
619 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
624 * Increment the login attempt throttle hit count for the (username,current IP)
625 * tuple unless the throttle was already reached.
626 * @param $username string The user name
627 * @return Bool|Integer The integer hit count or True if it is already at the limit
629 public static function incLoginThrottle( $username ) {
630 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
631 $username = trim( $username ); // sanity
634 if ( is_array( $wgPasswordAttemptThrottle ) ) {
635 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
636 $count = $wgPasswordAttemptThrottle['count'];
637 $period = $wgPasswordAttemptThrottle['seconds'];
639 $throttleCount = $wgMemc->get( $throttleKey );
640 if ( !$throttleCount ) {
641 $wgMemc->add( $throttleKey, 1, $period ); // start counter
642 } elseif ( $throttleCount < $count ) {
643 $wgMemc->incr( $throttleKey );
644 } elseif ( $throttleCount >= $count ) {
649 return $throttleCount;
653 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
654 * @param $username string The user name
657 public static function clearLoginThrottle( $username ) {
658 global $wgMemc, $wgRequest;
659 $username = trim( $username ); // sanity
661 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
662 $wgMemc->delete( $throttleKey );
666 * Attempt to automatically create a user on login. Only succeeds if there
667 * is an external authentication method which allows it.
671 * @return integer Status code
673 function attemptAutoCreate( $user ) {
674 global $wgAuth, $wgAutocreatePolicy;
676 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
677 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
678 return self
::CREATE_BLOCKED
;
682 * If the external authentication plugin allows it, automatically cre-
683 * ate a new account for users that are externally defined but have not
686 if ( $this->mExtUser
) {
687 # mExtUser is neither null nor false, so use the new ExternalAuth
689 if ( $wgAutocreatePolicy == 'never' ) {
690 return self
::NOT_EXISTS
;
692 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
693 return self
::WRONG_PLUGIN_PASS
;
697 if ( !$wgAuth->autoCreate() ) {
698 return self
::NOT_EXISTS
;
700 if ( !$wgAuth->userExists( $user->getName() ) ) {
701 wfDebug( __METHOD__
. ": user does not exist\n" );
702 return self
::NOT_EXISTS
;
704 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
705 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
706 return self
::WRONG_PLUGIN_PASS
;
711 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
712 // Hook point to add extra creation throttles and blocks
713 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
714 $this->mAbortLoginErrorMsg
= $abortError;
715 return self
::ABORTED
;
718 wfDebug( __METHOD__
. ": creating account\n" );
719 $this->initUser( $user, true );
720 return self
::SUCCESS
;
723 function processLogin() {
724 global $wgMemc, $wgLang;
726 switch ( $this->authenticateUserData() ) {
728 # We've verified now, update the real record
729 $user = $this->getUser();
730 if( (bool)$this->mRemember
!= (bool)$user->getOption( 'rememberpassword' ) ) {
731 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
732 $user->saveSettings();
734 $user->invalidateCache();
737 self
::clearLoginToken();
739 // Reset the throttle
740 $request = $this->getRequest();
741 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
742 $wgMemc->delete( $key );
744 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
745 /* Replace the language object to provide user interface in
746 * correct language immediately on this first page load.
748 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
749 $userLang = Language
::factory( $code );
751 $this->getContext()->setLanguage( $userLang );
752 $this->successfulLogin();
754 $this->cookieRedirectCheck( 'login' );
758 case self
::NEED_TOKEN
:
759 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
761 case self
::WRONG_TOKEN
:
762 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
766 $this->mainLoginForm( $this->msg( 'noname' )->text() );
768 case self
::WRONG_PLUGIN_PASS
:
769 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
771 case self
::NOT_EXISTS
:
772 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
773 $this->mainLoginForm( $this->msg( 'nosuchuser',
774 wfEscapeWikiText( $this->mUsername
) )->parse() );
776 $this->mainLoginForm( $this->msg( 'nosuchusershort',
777 wfEscapeWikiText( $this->mUsername
) )->text() );
780 case self
::WRONG_PASS
:
781 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
783 case self
::EMPTY_PASS
:
784 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
786 case self
::RESET_PASS
:
787 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
789 case self
::CREATE_BLOCKED
:
790 $this->userBlockedMessage( $this->getUser()->mBlock
);
792 case self
::THROTTLED
:
793 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
795 case self
::USER_BLOCKED
:
796 $this->mainLoginForm( $this->msg( 'login-userblocked',
797 $this->mUsername
)->escaped() );
800 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
803 throw new MWException( 'Unhandled case value' );
807 function resetLoginForm( $error ) {
808 $this->getOutput()->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
809 $reset = new SpecialChangePassword();
810 $reset->setContext( $this->getContext() );
811 $reset->execute( null );
815 * @param $u User object
816 * @param $throttle Boolean
817 * @param $emailTitle String: message name of email title
818 * @param $emailText String: message name of email text
819 * @return Status object
821 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
822 global $wgServer, $wgScript, $wgNewPasswordExpiry;
824 if ( $u->getEmail() == '' ) {
825 return Status
::newFatal( 'noemail', $u->getName() );
827 $ip = $this->getRequest()->getIP();
829 return Status
::newFatal( 'badipaddress' );
832 $currentUser = $this->getUser();
833 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
835 $np = $u->randomPassword();
836 $u->setNewpassword( $np, $throttle );
838 $userLanguage = $u->getOption( 'language' );
839 $m = $this->msg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript,
840 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
841 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
848 * Run any hooks registered for logins, then HTTP redirect to
849 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
850 * nice message here, but that's really not as useful as just being sent to
851 * wherever you logged in from. It should be clear that the action was
852 * successful, given the lack of error messages plus the appearance of your
853 * name in the upper right.
857 function successfulLogin() {
858 # Run any hooks; display injected HTML if any, else redirect
859 $currentUser = $this->getUser();
861 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
863 if( $injected_html !== '' ) {
864 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
866 $titleObj = Title
::newFromText( $this->mReturnTo
);
867 if ( !$titleObj instanceof Title
) {
868 $titleObj = Title
::newMainPage();
870 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery
);
871 global $wgSecureLogin;
872 if( $wgSecureLogin && !$this->mStickHTTPS
) {
873 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
875 $this->getOutput()->redirect( $redirectUrl );
880 * Run any hooks registered for logins, then display a message welcoming
885 function successfulCreation() {
886 # Run any hooks; display injected HTML
887 $currentUser = $this->getUser();
889 $welcome_creation_msg = 'welcomecreation';
891 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
894 * Let any extensions change what message is shown.
895 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
898 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
900 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
904 * Display a "login successful" page.
905 * @param $msgname string
906 * @param $injected_html string
908 private function displaySuccessfulLogin( $msgname, $injected_html ) {
909 $out = $this->getOutput();
910 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
912 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
915 $out->addHTML( $injected_html );
917 if ( !empty( $this->mReturnTo
) ) {
918 $out->returnToMain( null, $this->mReturnTo
, $this->mReturnToQuery
);
920 $out->returnToMain( null );
925 * Output a message that informs the user that they cannot create an account because
926 * there is a block on them or their IP which prevents account creation. Note that
927 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
928 * setting on blocks (bug 13611).
929 * @param $block Block the block causing this error
931 function userBlockedMessage( Block
$block ) {
932 # Let's be nice about this, it's likely that this feature will be used
933 # for blocking large numbers of innocent people, e.g. range blocks on
934 # schools. Don't blame it on the user. There's a small chance that it
935 # really is the user's fault, i.e. the username is blocked and they
936 # haven't bothered to log out before trying to create an account to
937 # evade it, but we'll leave that to their guilty conscience to figure
940 $out = $this->getOutput();
941 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
943 $block_reason = $block->mReason
;
944 if ( strval( $block_reason ) === '' ) {
945 $block_reason = $this->msg( 'blockednoreason' )->text();
949 'cantcreateaccount-text',
955 $out->returnToMain( false );
961 function mainLoginForm( $msg, $msgtype = 'error' ) {
962 global $wgEnableEmail, $wgEnableUserEmail;
963 global $wgHiddenPrefs, $wgLoginLanguageSelector;
964 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
965 global $wgSecureLogin, $wgPasswordResetRoutes;
967 $titleObj = $this->getTitle();
968 $user = $this->getUser();
970 if ( $this->mType
== 'signup' ) {
971 // Block signup here if in readonly. Keeps user from
972 // going through the process (filling out data, etc)
973 // and being informed later.
974 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
975 if ( count( $permErrors ) ) {
976 throw new PermissionsError( 'createaccount', $permErrors );
977 } elseif ( $user->isBlockedFromCreateAccount() ) {
978 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
980 } elseif ( wfReadOnly() ) {
981 throw new ReadOnlyError
;
985 if ( $this->mUsername
== '' ) {
986 if ( $user->isLoggedIn() ) {
987 $this->mUsername
= $user->getName();
989 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
993 if ( $this->mType
== 'signup' ) {
994 $template = new UsercreateTemplate();
995 $q = 'action=submitlogin&type=signup';
996 $linkq = 'type=login';
997 $linkmsg = 'gotaccount';
999 $template = new UserloginTemplate();
1000 $q = 'action=submitlogin&type=login';
1001 $linkq = 'type=signup';
1002 $linkmsg = 'nologin';
1005 if ( !empty( $this->mReturnTo
) ) {
1006 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1007 if ( !empty( $this->mReturnToQuery
) ) {
1008 $returnto .= '&returntoquery=' .
1009 wfUrlencode( $this->mReturnToQuery
);
1012 $linkq .= $returnto;
1015 # Don't show a "create account" link if the user can't
1016 if( $this->showCreateOrLoginLink( $user ) ) {
1017 # Pass any language selection on to the mode switch link
1018 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1019 $linkq .= '&uselang=' . $this->mLanguage
;
1021 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1022 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1024 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1026 $template->set( 'link', '' );
1029 $resetLink = $this->mType
== 'signup'
1031 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1033 $template->set( 'header', '' );
1034 $template->set( 'name', $this->mUsername
);
1035 $template->set( 'password', $this->mPassword
);
1036 $template->set( 'retype', $this->mRetype
);
1037 $template->set( 'email', $this->mEmail
);
1038 $template->set( 'realname', $this->mRealName
);
1039 $template->set( 'domain', $this->mDomain
);
1040 $template->set( 'reason', $this->mReason
);
1042 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1043 $template->set( 'message', $msg );
1044 $template->set( 'messagetype', $msgtype );
1045 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1046 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1047 $template->set( 'useemail', $wgEnableEmail );
1048 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1049 $template->set( 'emailothers', $wgEnableUserEmail );
1050 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1051 $template->set( 'resetlink', $resetLink );
1052 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1053 $template->set( 'usereason', $user->isLoggedIn() );
1054 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1055 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1056 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1058 if ( $this->mType
== 'signup' ) {
1059 if ( !self
::getCreateaccountToken() ) {
1060 self
::setCreateaccountToken();
1062 $template->set( 'token', self
::getCreateaccountToken() );
1064 if ( !self
::getLoginToken() ) {
1065 self
::setLoginToken();
1067 $template->set( 'token', self
::getLoginToken() );
1070 # Prepare language selection links as needed
1071 if( $wgLoginLanguageSelector ) {
1072 $template->set( 'languages', $this->makeLanguageSelector() );
1073 if( $this->mLanguage
) {
1074 $template->set( 'uselang', $this->mLanguage
);
1078 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1079 // Ditto for signupend
1080 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1081 $loginendHTTPS = $this->msg( 'loginend-https' );
1082 $signupendHTTPS = $this->msg( 'signupend-https' );
1083 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1084 $template->set( 'loginend', $loginendHTTPS->parse() );
1086 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1088 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1089 $template->set( 'signupend', $signupendHTTPS->parse() );
1091 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1094 // Give authentication and captcha plugins a chance to modify the form
1095 $wgAuth->modifyUITemplate( $template, $this->mType
);
1096 if ( $this->mType
== 'signup' ) {
1097 wfRunHooks( 'UserCreateForm', array( &$template ) );
1099 wfRunHooks( 'UserLoginForm', array( &$template ) );
1102 $out = $this->getOutput();
1103 $out->disallowUserJs(); // just in case...
1104 $out->addTemplate( $template );
1114 function showCreateOrLoginLink( &$user ) {
1115 if( $this->mType
== 'signup' ) {
1117 } elseif( $user->isAllowed( 'createaccount' ) ) {
1125 * Check if a session cookie is present.
1127 * This will not pick up a cookie set during _this_ request, but is meant
1128 * to ensure that the client is returning the cookie which was set on a
1129 * previous pass through the system.
1134 function hasSessionCookie() {
1135 global $wgDisableCookieCheck;
1136 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1140 * Get the login token from the current session
1143 public static function getLoginToken() {
1145 return $wgRequest->getSessionData( 'wsLoginToken' );
1149 * Randomly generate a new login token and attach it to the current session
1151 public static function setLoginToken() {
1153 // Generate a token directly instead of using $user->editToken()
1154 // because the latter reuses $_SESSION['wsEditToken']
1155 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1159 * Remove any login token attached to the current session
1161 public static function clearLoginToken() {
1163 $wgRequest->setSessionData( 'wsLoginToken', null );
1167 * Get the createaccount token from the current session
1170 public static function getCreateaccountToken() {
1172 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1176 * Randomly generate a new createaccount token and attach it to the current session
1178 public static function setCreateaccountToken() {
1180 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1184 * Remove any createaccount token attached to the current session
1186 public static function clearCreateaccountToken() {
1188 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1194 function cookieRedirectCheck( $type ) {
1195 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1196 $query = array( 'wpCookieCheck' => $type );
1197 if ( $this->mReturnTo
) {
1198 $query['returnto'] = $this->mReturnTo
;
1200 $check = $titleObj->getFullURL( $query );
1202 $this->getOutput()->redirect( $check );
1208 function onCookieRedirectCheck( $type ) {
1209 if ( !$this->hasSessionCookie() ) {
1210 if ( $type == 'new' ) {
1211 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1212 } elseif ( $type == 'login' ) {
1213 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1216 $this->mainLoginForm( $this->msg( 'error' )->text() );
1219 $this->successfulLogin();
1226 function throttleHit( $limit ) {
1227 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1231 * Produce a bar of links which allow the user to select another language
1232 * during login/registration but retain "returnto"
1236 function makeLanguageSelector() {
1237 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1238 if( !$msg->isBlank() ) {
1239 $langs = explode( "\n", $msg->text() );
1241 foreach( $langs as $lang ) {
1242 $lang = trim( $lang, '* ' );
1243 $parts = explode( '|', $lang );
1244 if ( count( $parts ) >= 2 ) {
1245 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1248 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1249 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1256 * Create a language selector link for a particular language
1257 * Links back to this page preserving type and returnto
1259 * @param $text Link text
1260 * @param $lang Language code
1263 function makeLanguageSelectorLink( $text, $lang ) {
1264 $attr = array( 'uselang' => $lang );
1265 if( $this->mType
== 'signup' ) {
1266 $attr['type'] = 'signup';
1268 if( $this->mReturnTo
) {
1269 $attr['returnto'] = $this->mReturnTo
;
1271 return Linker
::linkKnown(
1273 htmlspecialchars( $text ),