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 if ( isset( $_SESSION['wsDomain'] ) ) {
131 $this->mDomain
= $_SESSION['wsDomain'];
133 $this->mDomain
= 'invaliddomain';
136 $wgAuth->setDomain( $this->mDomain
);
138 # When switching accounts, it sucks to get automatically logged out
139 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
140 if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
141 $this->mReturnTo
= '';
142 $this->mReturnToQuery
= '';
146 function getDescription() {
147 return $this->msg( $this->getUser()->isAllowed( 'createaccount' ) ?
148 'userlogin' : 'userloginnocreate' )->text();
151 public function execute( $par ) {
152 if ( session_id() == '' ) {
159 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
160 $this->mType
= 'signup';
163 if ( !is_null( $this->mCookieCheck
) ) {
164 $this->onCookieRedirectCheck( $this->mCookieCheck
);
166 } elseif( $this->mPosted
) {
167 if( $this->mCreateaccount
) {
168 return $this->addNewAccount();
169 } elseif ( $this->mCreateaccountMail
) {
170 return $this->addNewAccountMailPassword();
171 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
172 return $this->processLogin();
175 $this->mainLoginForm( '' );
181 function addNewAccountMailPassword() {
182 if ( $this->mEmail
== '' ) {
183 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
187 $u = $this->addNewaccountInternal();
193 // Wipe the initial password and mail a temporary one
194 $u->setPassword( null );
196 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
198 wfRunHooks( 'AddNewAccount', array( $u, true ) );
199 $u->addNewUserLogEntry( true, $this->mReason
);
201 $out = $this->getOutput();
202 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
204 if( !$result->isGood() ) {
205 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
207 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
208 $out->returnToMain( false );
215 function addNewAccount() {
216 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
218 # Create the account and abort if there's a problem doing so
219 $u = $this->addNewAccountInternal();
224 # If we showed up language selection links, and one was in use, be
225 # smart (and sensible) and save that language as the user's preference
226 if( $wgLoginLanguageSelector && $this->mLanguage
) {
227 $u->setOption( 'language', $this->mLanguage
);
230 $out = $this->getOutput();
232 # Send out an email authentication message if needed
233 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
234 $status = $u->sendConfirmationMail();
235 if( $status->isGood() ) {
236 $out->addWikiMsg( 'confirmemail_oncreate' );
238 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
242 # Save settings (including confirmation token)
245 # If not logged in, assume the new account as the current one and set
246 # session cookies then show a "welcome" message or a "need cookies"
248 if( $this->getUser()->isAnon() ) {
251 // This should set it for OutputPage and the Skin
252 // which is needed or the personal links will be
254 $this->getContext()->setUser( $u );
255 wfRunHooks( 'AddNewAccount', array( $u, false ) );
256 $u->addNewUserLogEntry();
257 if( $this->hasSessionCookie() ) {
258 return $this->successfulCreation();
260 return $this->cookieRedirectCheck( 'new' );
263 # Confirm that the account was created
264 $out->setPageTitle( $this->msg( 'accountcreated' ) );
265 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
266 $out->returnToMain( false, $this->getTitle() );
267 wfRunHooks( 'AddNewAccount', array( $u, false ) );
268 $u->addNewUserLogEntry( false, $this->mReason
);
276 function addNewAccountInternal() {
277 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
278 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
280 // If the user passes an invalid domain, something is fishy
281 if( !$wgAuth->validDomain( $this->mDomain
) ) {
282 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
286 // If we are not allowing users to login locally, we should be checking
287 // to see if the user is actually able to authenticate to the authenti-
288 // cation server before they create an account (otherwise, they can
289 // create a local account and login as any domain user). We only need
290 // to check this for domains that aren't local.
291 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
292 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername
)
293 ||
!$wgAuth->authenticate( $this->mUsername
, $this->mPassword
) ) ) {
294 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
299 if ( wfReadOnly() ) {
300 throw new ReadOnlyError
;
303 # Request forgery checks.
304 if ( !self
::getCreateaccountToken() ) {
305 self
::setCreateaccountToken();
306 $this->mainLoginForm( $this->msg( 'nocookiesfornew' )->parse() );
310 # The user didn't pass a createaccount token
311 if ( !$this->mToken
) {
312 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
316 # Validate the createaccount token
317 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
318 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
323 $currentUser = $this->getUser();
324 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
325 throw new PermissionsError( 'createaccount' );
326 } elseif ( $currentUser->isBlockedFromCreateAccount() ) {
327 $this->userBlockedMessage( $currentUser->isBlockedFromCreateAccount() );
331 $ip = $this->getRequest()->getIP();
332 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
333 $this->mainLoginForm( $this->msg( 'sorbs_create_account_reason' )->text() . ' (' . htmlspecialchars( $ip ) . ')' );
337 # Now create a dummy user ($u) and check if it is valid
338 $name = trim( $this->mUsername
);
339 $u = User
::newFromName( $name, 'creatable' );
340 if ( !is_object( $u ) ) {
341 $this->mainLoginForm( $this->msg( 'noname' )->text() );
345 if ( 0 != $u->idForName() ) {
346 $this->mainLoginForm( $this->msg( 'userexists' )->text() );
350 if ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
351 $this->mainLoginForm( $this->msg( 'badretype' )->text() );
355 # check for minimal password length
356 $valid = $u->getPasswordValidity( $this->mPassword
);
357 if ( $valid !== true ) {
358 if ( !$this->mCreateaccountMail
) {
359 if ( is_array( $valid ) ) {
360 $message = array_shift( $valid );
364 $params = array( $wgMinimalPasswordLength );
366 $this->mainLoginForm( $this->msg( $message, $params )->text() );
369 # do not force a password for account creation by email
370 # set invalid password, it will be replaced later by a random generated password
371 $this->mPassword
= null;
375 # if you need a confirmed email address to edit, then obviously you
376 # need an email address.
377 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
378 $this->mainLoginForm( $this->msg( 'noemailtitle' )->text() );
382 if( !empty( $this->mEmail
) && !Sanitizer
::validateEmail( $this->mEmail
) ) {
383 $this->mainLoginForm( $this->msg( 'invalidemailaddress' )->text() );
387 # Set some additional data so the AbortNewAccount hook can be used for
388 # more than just username validation
389 $u->setEmail( $this->mEmail
);
390 $u->setRealName( $this->mRealName
);
393 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
394 // Hook point to add extra creation throttles and blocks
395 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
396 $this->mainLoginForm( $abortError );
400 // Hook point to check for exempt from account creation throttle
401 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
402 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
404 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
405 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
406 $value = $wgMemc->get( $key );
408 $wgMemc->set( $key, 0, 86400 );
410 if ( $value >= $wgAccountCreationThrottle ) {
411 $this->throttleHit( $wgAccountCreationThrottle );
414 $wgMemc->incr( $key );
418 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
419 $this->mainLoginForm( $this->msg( 'externaldberror' )->text() );
423 self
::clearCreateaccountToken();
424 return $this->initUser( $u, false );
428 * Actually add a user to the database.
429 * Give it a User object that has been initialised with a name.
431 * @param $u User object.
432 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
433 * @return User object.
436 function initUser( $u, $autocreate ) {
441 if ( $wgAuth->allowPasswordChange() ) {
442 $u->setPassword( $this->mPassword
);
445 $u->setEmail( $this->mEmail
);
446 $u->setRealName( $this->mRealName
);
449 $wgAuth->initUser( $u, $autocreate );
451 if ( $this->mExtUser
) {
452 $this->mExtUser
->linkToLocal( $u->getId() );
453 $email = $this->mExtUser
->getPref( 'emailaddress' );
454 if ( $email && !$this->mEmail
) {
455 $u->setEmail( $email );
459 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
463 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
464 $ssUpdate->doUpdate();
470 * Internally authenticate the login request.
472 * This may create a local account as a side effect if the
473 * authentication plugin allows transparent local account
476 public function authenticateUserData() {
477 global $wgUser, $wgAuth;
481 if ( $this->mUsername
== '' ) {
482 wfRunHooks( 'LoginAuthenticateAudit', array( new User
, $this->mPassword
, self
::NO_NAME
) );
483 return self
::NO_NAME
;
486 // We require a login token to prevent login CSRF
487 // Handle part of this before incrementing the throttle so
488 // token-less login attempts don't count towards the throttle
489 // but wrong-token attempts do.
491 // If the user doesn't have a login token yet, set one.
492 if ( !self
::getLoginToken() ) {
493 self
::setLoginToken();
494 wfRunHooks( 'LoginAuthenticateAudit', array( new User
, $this->mPassword
, self
::NEED_TOKEN
) );
495 return self
::NEED_TOKEN
;
497 // If the user didn't pass a login token, tell them we need one
498 if ( !$this->mToken
) {
499 wfRunHooks( 'LoginAuthenticateAudit', array( new User
, $this->mPassword
, self
::NEED_TOKEN
) );
500 return self
::NEED_TOKEN
;
503 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
504 if ( $throttleCount === true ) {
505 wfRunHooks( 'LoginAuthenticateAudit', array( new User
, $this->mPassword
, self
::THROTTLED
) );
506 return self
::THROTTLED
;
509 // Validate the login token
510 if ( $this->mToken
!== self
::getLoginToken() ) {
511 wfRunHooks( 'LoginAuthenticateAudit', array( new User
, $this->mPassword
, self
::WRONG_TOKEN
) );
512 return self
::WRONG_TOKEN
;
515 // Load the current user now, and check to see if we're logging in as
516 // the same name. This is necessary because loading the current user
517 // (say by calling getName()) calls the UserLoadFromSession hook, which
518 // potentially creates the user in the database. Until we load $wgUser,
519 // checking for user existence using User::newFromName($name)->getId() below
520 // will effectively be using stale data.
521 if ( $this->getUser()->getName() === $this->mUsername
) {
522 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
523 return self
::SUCCESS
;
526 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
528 # TODO: Allow some magic here for invalid external names, e.g., let the
529 # user choose a different wiki name.
530 $u = User
::newFromName( $this->mUsername
);
531 if( !( $u instanceof User
) ) {
532 wfRunHooks( 'LoginAuthenticateAudit', array( new User
, $this->mPassword
, self
::ILLEGAL
) );
533 return self
::ILLEGAL
;
535 if( !User
::isUsableName( $u->getName() ) ) {
536 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, self
::ILLEGAL
) );
537 return self
::ILLEGAL
;
540 $isAutoCreated = false;
541 if ( 0 == $u->getID() ) {
542 $status = $this->attemptAutoCreate( $u );
543 if ( $status !== self
::SUCCESS
) {
544 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $status ) );
547 $isAutoCreated = true;
550 global $wgExternalAuthType, $wgAutocreatePolicy;
551 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
552 && is_object( $this->mExtUser
)
553 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
554 # The external user and local user have the same name and
555 # password, so we assume they're the same.
556 $this->mExtUser
->linkToLocal( $u->getID() );
562 // Give general extensions, such as a captcha, a chance to abort logins
563 $abort = self
::ABORTED
;
564 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
565 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $abort ) );
569 global $wgBlockDisablesLogin;
570 if ( !$u->checkPassword( $this->mPassword
) ) {
571 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
572 // The e-mailed temporary password should not be used for actu-
573 // al logins; that's a very sloppy habit, and insecure if an
574 // attacker has a few seconds to click "search" on someone's o-
577 // Allow it to be used only to reset the password a single time
578 // to a new value, which won't be in the user's e-mail ar-
581 // For backwards compatibility, we'll still recognize it at the
582 // login form to minimize surprises for people who have been
583 // logging in with a temporary password for some time.
585 // As a side-effect, we can authenticate the user's e-mail ad-
586 // dress if it's not already done, since the temporary password
587 // was sent via e-mail.
588 if( !$u->isEmailConfirmed() ) {
593 // At this point we just return an appropriate code/ indicating
594 // that the UI should show a password reset form; bot inter-
595 // faces etc will probably just fail cleanly here.
596 $retval = self
::RESET_PASS
;
598 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
600 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
601 // If we've enabled it, make it so that a blocked user cannot login
602 $retval = self
::USER_BLOCKED
;
604 $wgAuth->updateUser( $u );
606 // This should set it for OutputPage and the Skin
607 // which is needed or the personal links will be
609 $this->getContext()->setUser( $u );
611 // Please reset throttle for successful logins, thanks!
612 if ( $throttleCount ) {
613 self
::clearLoginThrottle( $this->mUsername
);
616 if ( $isAutoCreated ) {
617 // Must be run after $wgUser is set, for correct new user log
618 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
621 $retval = self
::SUCCESS
;
623 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
628 * Increment the login attempt throttle hit count for the (username,current IP)
629 * tuple unless the throttle was already reached.
630 * @param $username string The user name
631 * @return Bool|Integer The integer hit count or True if it is already at the limit
633 public static function incLoginThrottle( $username ) {
634 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
635 $username = trim( $username ); // sanity
638 if ( is_array( $wgPasswordAttemptThrottle ) ) {
639 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
640 $count = $wgPasswordAttemptThrottle['count'];
641 $period = $wgPasswordAttemptThrottle['seconds'];
643 $throttleCount = $wgMemc->get( $throttleKey );
644 if ( !$throttleCount ) {
645 $wgMemc->add( $throttleKey, 1, $period ); // start counter
646 } elseif ( $throttleCount < $count ) {
647 $wgMemc->incr( $throttleKey );
648 } elseif ( $throttleCount >= $count ) {
653 return $throttleCount;
657 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
658 * @param $username string The user name
661 public static function clearLoginThrottle( $username ) {
662 global $wgMemc, $wgRequest;
663 $username = trim( $username ); // sanity
665 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
666 $wgMemc->delete( $throttleKey );
670 * Attempt to automatically create a user on login. Only succeeds if there
671 * is an external authentication method which allows it.
675 * @return integer Status code
677 function attemptAutoCreate( $user ) {
678 global $wgAuth, $wgAutocreatePolicy;
680 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
681 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
682 return self
::CREATE_BLOCKED
;
686 * If the external authentication plugin allows it, automatically cre-
687 * ate a new account for users that are externally defined but have not
690 if ( $this->mExtUser
) {
691 # mExtUser is neither null nor false, so use the new ExternalAuth
693 if ( $wgAutocreatePolicy == 'never' ) {
694 return self
::NOT_EXISTS
;
696 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
697 return self
::WRONG_PLUGIN_PASS
;
701 if ( !$wgAuth->autoCreate() ) {
702 return self
::NOT_EXISTS
;
704 if ( !$wgAuth->userExists( $user->getName() ) ) {
705 wfDebug( __METHOD__
. ": user does not exist\n" );
706 return self
::NOT_EXISTS
;
708 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
709 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
710 return self
::WRONG_PLUGIN_PASS
;
715 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
716 // Hook point to add extra creation throttles and blocks
717 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
718 $this->mAbortLoginErrorMsg
= $abortError;
719 return self
::ABORTED
;
722 wfDebug( __METHOD__
. ": creating account\n" );
723 $this->initUser( $user, true );
724 return self
::SUCCESS
;
727 function processLogin() {
728 global $wgMemc, $wgLang;
730 switch ( $this->authenticateUserData() ) {
732 # We've verified now, update the real record
733 $user = $this->getUser();
734 if( (bool)$this->mRemember
!= (bool)$user->getOption( 'rememberpassword' ) ) {
735 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
736 $user->saveSettings();
738 $user->invalidateCache();
741 self
::clearLoginToken();
743 // Reset the throttle
744 $request = $this->getRequest();
745 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
746 $wgMemc->delete( $key );
748 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
749 /* Replace the language object to provide user interface in
750 * correct language immediately on this first page load.
752 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
753 $userLang = Language
::factory( $code );
755 $this->getContext()->setLanguage( $userLang );
756 return $this->successfulLogin();
758 return $this->cookieRedirectCheck( 'login' );
762 case self
::NEED_TOKEN
:
763 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
765 case self
::WRONG_TOKEN
:
766 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
770 $this->mainLoginForm( $this->msg( 'noname' )->text() );
772 case self
::WRONG_PLUGIN_PASS
:
773 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
775 case self
::NOT_EXISTS
:
776 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
777 $this->mainLoginForm( $this->msg( 'nosuchuser',
778 wfEscapeWikiText( $this->mUsername
) )->parse() );
780 $this->mainLoginForm( $this->msg( 'nosuchusershort',
781 wfEscapeWikiText( $this->mUsername
) )->text() );
784 case self
::WRONG_PASS
:
785 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
787 case self
::EMPTY_PASS
:
788 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
790 case self
::RESET_PASS
:
791 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
793 case self
::CREATE_BLOCKED
:
794 $this->userBlockedMessage( $this->getUser()->mBlock
);
796 case self
::THROTTLED
:
797 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
799 case self
::USER_BLOCKED
:
800 $this->mainLoginForm( $this->msg( 'login-userblocked',
801 $this->mUsername
)->escaped() );
804 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
807 throw new MWException( 'Unhandled case value' );
811 function resetLoginForm( $error ) {
812 $this->getOutput()->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
813 $reset = new SpecialChangePassword();
814 $reset->setContext( $this );
815 $reset->execute( null );
819 * @param $u User object
820 * @param $throttle Boolean
821 * @param $emailTitle String: message name of email title
822 * @param $emailText String: message name of email text
823 * @return Status object
825 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
826 global $wgServer, $wgScript, $wgNewPasswordExpiry;
828 if ( $u->getEmail() == '' ) {
829 return Status
::newFatal( 'noemail', $u->getName() );
831 $ip = $this->getRequest()->getIP();
833 return Status
::newFatal( 'badipaddress' );
836 $currentUser = $this->getUser();
837 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
839 $np = $u->randomPassword();
840 $u->setNewpassword( $np, $throttle );
842 $userLanguage = $u->getOption( 'language' );
843 $m = $this->msg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript,
844 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
845 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
852 * Run any hooks registered for logins, then HTTP redirect to
853 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
854 * nice message here, but that's really not as useful as just being sent to
855 * wherever you logged in from. It should be clear that the action was
856 * successful, given the lack of error messages plus the appearance of your
857 * name in the upper right.
861 function successfulLogin() {
862 # Run any hooks; display injected HTML if any, else redirect
863 $currentUser = $this->getUser();
865 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
867 if( $injected_html !== '' ) {
868 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
870 $titleObj = Title
::newFromText( $this->mReturnTo
);
871 if ( !$titleObj instanceof Title
) {
872 $titleObj = Title
::newMainPage();
874 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery
);
875 global $wgSecureLogin;
876 if( $wgSecureLogin && !$this->mStickHTTPS
) {
877 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
879 $this->getOutput()->redirect( $redirectUrl );
884 * Run any hooks registered for logins, then display a message welcoming
889 function successfulCreation() {
890 # Run any hooks; display injected HTML
891 $currentUser = $this->getUser();
893 $welcome_creation_msg = 'welcomecreation';
895 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
898 * Let any extensions change what message is shown.
899 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
902 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
904 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
908 * Display a "login successful" page.
910 private function displaySuccessfulLogin( $msgname, $injected_html ) {
911 $out = $this->getOutput();
912 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
914 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
917 $out->addHTML( $injected_html );
919 if ( !empty( $this->mReturnTo
) ) {
920 $out->returnToMain( null, $this->mReturnTo
, $this->mReturnToQuery
);
922 $out->returnToMain( null );
927 * Output a message that informs the user that they cannot create an account because
928 * there is a block on them or their IP which prevents account creation. Note that
929 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
930 * setting on blocks (bug 13611).
931 * @param $block Block the block causing this error
933 function userBlockedMessage( Block
$block ) {
934 # Let's be nice about this, it's likely that this feature will be used
935 # for blocking large numbers of innocent people, e.g. range blocks on
936 # schools. Don't blame it on the user. There's a small chance that it
937 # really is the user's fault, i.e. the username is blocked and they
938 # haven't bothered to log out before trying to create an account to
939 # evade it, but we'll leave that to their guilty conscience to figure
942 $out = $this->getOutput();
943 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
945 $block_reason = $block->mReason
;
946 if ( strval( $block_reason ) === '' ) {
947 $block_reason = $this->msg( 'blockednoreason' )->text();
951 'cantcreateaccount-text',
957 $out->returnToMain( false );
963 function mainLoginForm( $msg, $msgtype = 'error' ) {
964 global $wgEnableEmail, $wgEnableUserEmail;
965 global $wgHiddenPrefs, $wgLoginLanguageSelector;
966 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
967 global $wgSecureLogin, $wgPasswordResetRoutes;
969 $titleObj = $this->getTitle();
970 $user = $this->getUser();
972 if ( $this->mType
== 'signup' ) {
973 // Block signup here if in readonly. Keeps user from
974 // going through the process (filling out data, etc)
975 // and being informed later.
976 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
977 if ( count( $permErrors ) ) {
978 throw new PermissionsError( 'createaccount', $permErrors );
979 } elseif ( $user->isBlockedFromCreateAccount() ) {
980 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
982 } elseif ( wfReadOnly() ) {
983 throw new ReadOnlyError
;
987 if ( $this->mUsername
== '' ) {
988 if ( $user->isLoggedIn() ) {
989 $this->mUsername
= $user->getName();
991 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
995 if ( $this->mType
== 'signup' ) {
996 $template = new UsercreateTemplate();
997 $q = 'action=submitlogin&type=signup';
998 $linkq = 'type=login';
999 $linkmsg = 'gotaccount';
1001 $template = new UserloginTemplate();
1002 $q = 'action=submitlogin&type=login';
1003 $linkq = 'type=signup';
1004 $linkmsg = 'nologin';
1007 if ( !empty( $this->mReturnTo
) ) {
1008 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1009 if ( !empty( $this->mReturnToQuery
) ) {
1010 $returnto .= '&returntoquery=' .
1011 wfUrlencode( $this->mReturnToQuery
);
1014 $linkq .= $returnto;
1017 # Don't show a "create account" link if the user can't
1018 if( $this->showCreateOrLoginLink( $user ) ) {
1019 # Pass any language selection on to the mode switch link
1020 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1021 $linkq .= '&uselang=' . $this->mLanguage
;
1023 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1024 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1026 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1028 $template->set( 'link', '' );
1031 $resetLink = $this->mType
== 'signup'
1033 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1035 $template->set( 'header', '' );
1036 $template->set( 'name', $this->mUsername
);
1037 $template->set( 'password', $this->mPassword
);
1038 $template->set( 'retype', $this->mRetype
);
1039 $template->set( 'email', $this->mEmail
);
1040 $template->set( 'realname', $this->mRealName
);
1041 $template->set( 'domain', $this->mDomain
);
1042 $template->set( 'reason', $this->mReason
);
1044 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1045 $template->set( 'message', $msg );
1046 $template->set( 'messagetype', $msgtype );
1047 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1048 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1049 $template->set( 'useemail', $wgEnableEmail );
1050 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1051 $template->set( 'emailothers', $wgEnableUserEmail );
1052 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1053 $template->set( 'resetlink', $resetLink );
1054 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1055 $template->set( 'usereason', $user->isLoggedIn() );
1056 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1057 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1058 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1060 if ( $this->mType
== 'signup' ) {
1061 if ( !self
::getCreateaccountToken() ) {
1062 self
::setCreateaccountToken();
1064 $template->set( 'token', self
::getCreateaccountToken() );
1066 if ( !self
::getLoginToken() ) {
1067 self
::setLoginToken();
1069 $template->set( 'token', self
::getLoginToken() );
1072 # Prepare language selection links as needed
1073 if( $wgLoginLanguageSelector ) {
1074 $template->set( 'languages', $this->makeLanguageSelector() );
1075 if( $this->mLanguage
) {
1076 $template->set( 'uselang', $this->mLanguage
);
1080 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1081 // Ditto for signupend
1082 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1083 $loginendHTTPS = $this->msg( 'loginend-https' );
1084 $signupendHTTPS = $this->msg( 'signupend-https' );
1085 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1086 $template->set( 'loginend', $loginendHTTPS->parse() );
1088 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1090 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1091 $template->set( 'signupend', $signupendHTTPS->parse() );
1093 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1096 // Give authentication and captcha plugins a chance to modify the form
1097 $wgAuth->modifyUITemplate( $template, $this->mType
);
1098 if ( $this->mType
== 'signup' ) {
1099 wfRunHooks( 'UserCreateForm', array( &$template ) );
1101 wfRunHooks( 'UserLoginForm', array( &$template ) );
1104 $out = $this->getOutput();
1105 $out->disallowUserJs(); // just in case...
1106 $out->addTemplate( $template );
1116 function showCreateOrLoginLink( &$user ) {
1117 if( $this->mType
== 'signup' ) {
1119 } elseif( $user->isAllowed( 'createaccount' ) ) {
1127 * Check if a session cookie is present.
1129 * This will not pick up a cookie set during _this_ request, but is meant
1130 * to ensure that the client is returning the cookie which was set on a
1131 * previous pass through the system.
1135 function hasSessionCookie() {
1136 global $wgDisableCookieCheck;
1137 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1141 * 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 // Use User::generateToken() instead of $user->editToken()
1154 // because the latter reuses $_SESSION['wsEditToken']
1155 $wgRequest->setSessionData( 'wsLoginToken', User
::generateToken() );
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
1169 public static function getCreateaccountToken() {
1171 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1175 * Randomly generate a new createaccount token and attach it to the current session
1177 public static function setCreateaccountToken() {
1179 $wgRequest->setSessionData( 'wsCreateaccountToken', User
::generateToken() );
1183 * Remove any createaccount token attached to the current session
1185 public static function clearCreateaccountToken() {
1187 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1193 function cookieRedirectCheck( $type ) {
1194 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1195 $query = array( 'wpCookieCheck' => $type );
1196 if ( $this->mReturnTo
) {
1197 $query['returnto'] = $this->mReturnTo
;
1199 $check = $titleObj->getFullURL( $query );
1201 return $this->getOutput()->redirect( $check );
1207 function onCookieRedirectCheck( $type ) {
1208 if ( !$this->hasSessionCookie() ) {
1209 if ( $type == 'new' ) {
1210 return $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1211 } elseif ( $type == 'login' ) {
1212 return $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1215 return $this->mainLoginForm( $this->msg( 'error' )->text() );
1218 return $this->successfulLogin();
1225 function throttleHit( $limit ) {
1226 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1230 * Produce a bar of links which allow the user to select another language
1231 * during login/registration but retain "returnto"
1235 function makeLanguageSelector() {
1236 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1237 if( !$msg->isBlank() ) {
1238 $langs = explode( "\n", $msg->text() );
1240 foreach( $langs as $lang ) {
1241 $lang = trim( $lang, '* ' );
1242 $parts = explode( '|', $lang );
1243 if ( count( $parts ) >= 2 ) {
1244 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1247 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1248 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1255 * Create a language selector link for a particular language
1256 * Links back to this page preserving type and returnto
1258 * @param $text Link text
1259 * @param $lang Language code
1261 function makeLanguageSelectorLink( $text, $lang ) {
1262 $attr = array( 'uselang' => $lang );
1263 if( $this->mType
== 'signup' ) {
1264 $attr['type'] = 'signup';
1266 if( $this->mReturnTo
) {
1267 $attr['returnto'] = $this->mReturnTo
;
1269 return Linker
::linkKnown(
1271 htmlspecialchars( $text ),