3 * Implements Special:UserLogin
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
25 * Implements Special:UserLogin
27 * @ingroup SpecialPage
29 class LoginForm
extends SpecialPage
{
34 const WRONG_PLUGIN_PASS
= 3;
40 const CREATE_BLOCKED
= 9;
42 const USER_BLOCKED
= 11;
43 const NEED_TOKEN
= 12;
44 const WRONG_TOKEN
= 13;
46 var $mUsername, $mPassword, $mRetype, $mReturnTo, $mCookieCheck, $mPosted;
47 var $mAction, $mCreateaccount, $mCreateaccountMail;
48 var $mLoginattempt, $mRemember, $mEmail, $mDomain, $mLanguage;
49 var $mSkipCookieCheck, $mReturnToQuery, $mToken, $mStickHTTPS;
50 var $mType, $mReason, $mRealName;
51 var $mAbortLoginErrorMsg = 'login-abort-generic';
52 private $mLoaded = false;
57 private $mExtUser = null;
62 private $mOverrideRequest = null;
65 * @param WebRequest $request
67 public function __construct( $request = null ) {
68 parent
::__construct( 'Userlogin' );
70 $this->mOverrideRequest
= $request;
77 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
79 if ( $this->mLoaded
) {
82 $this->mLoaded
= true;
84 if ( $this->mOverrideRequest
=== null ) {
85 $request = $this->getRequest();
87 $request = $this->mOverrideRequest
;
90 $this->mType
= $request->getText( 'type' );
91 $this->mUsername
= $request->getText( 'wpName' );
92 $this->mPassword
= $request->getText( 'wpPassword' );
93 $this->mRetype
= $request->getText( 'wpRetype' );
94 $this->mDomain
= $request->getText( 'wpDomain' );
95 $this->mReason
= $request->getText( 'wpReason' );
96 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
97 $this->mPosted
= $request->wasPosted();
98 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' );
99 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
101 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
102 $this->mAction
= $request->getVal( 'action' );
103 $this->mRemember
= $request->getCheck( 'wpRemember' );
104 $this->mStickHTTPS
= $request->getCheck( 'wpStickHTTPS' );
105 $this->mLanguage
= $request->getText( 'uselang' );
106 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
107 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
109 $this->mReturnTo
= $request->getVal( 'returnto', '' );
110 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
112 if( $wgEnableEmail ) {
113 $this->mEmail
= $request->getText( 'wpEmail' );
117 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
118 $this->mRealName
= $request->getText( 'wpRealName' );
120 $this->mRealName
= '';
123 if( !$wgAuth->validDomain( $this->mDomain
) ) {
124 $this->mDomain
= $wgAuth->getDomain();
126 $wgAuth->setDomain( $this->mDomain
);
128 # 1. When switching accounts, it sucks to get automatically logged out
129 # 2. Do not return to PasswordReset after a successful password change
130 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
131 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
132 if( is_object( $returnToTitle ) && (
133 $returnToTitle->isSpecial( 'Userlogout' )
134 ||
$returnToTitle->isSpecial( 'PasswordReset' ) ) ) {
135 $this->mReturnTo
= '';
136 $this->mReturnToQuery
= '';
140 function getDescription() {
141 return $this->msg( $this->getUser()->isAllowed( 'createaccount' ) ?
142 'userlogin' : 'userloginnocreate' )->text();
145 public function execute( $par ) {
146 if ( session_id() == '' ) {
153 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
154 $this->mType
= 'signup';
157 if ( !is_null( $this->mCookieCheck
) ) {
158 $this->onCookieRedirectCheck( $this->mCookieCheck
);
160 } elseif( $this->mPosted
) {
161 if( $this->mCreateaccount
) {
162 $this->addNewAccount();
164 } elseif ( $this->mCreateaccountMail
) {
165 $this->addNewAccountMailPassword();
167 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
168 $this->processLogin();
172 $this->mainLoginForm( '' );
178 function addNewAccountMailPassword() {
179 if ( $this->mEmail
== '' ) {
180 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
184 $u = $this->addNewaccountInternal();
190 // Wipe the initial password and mail a temporary one
191 $u->setPassword( null );
193 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
195 wfRunHooks( 'AddNewAccount', array( $u, true ) );
196 $u->addNewUserLogEntry( true, $this->mReason
);
198 $out = $this->getOutput();
199 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
201 if( !$result->isGood() ) {
202 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
204 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
205 $this->executeReturnTo( 'success' );
213 function addNewAccount() {
214 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
216 # Create the account and abort if there's a problem doing so
217 $u = $this->addNewAccountInternal();
222 # If we showed up language selection links, and one was in use, be
223 # smart (and sensible) and save that language as the user's preference
224 if( $wgLoginLanguageSelector && $this->mLanguage
) {
225 $u->setOption( 'language', $this->mLanguage
);
228 $out = $this->getOutput();
230 # Send out an email authentication message if needed
231 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
232 $status = $u->sendConfirmationMail();
233 if( $status->isGood() ) {
234 $out->addWikiMsg( 'confirmemail_oncreate' );
236 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
240 # Save settings (including confirmation token)
243 # If not logged in, assume the new account as the current one and set
244 # session cookies then show a "welcome" message or a "need cookies"
246 if( $this->getUser()->isAnon() ) {
249 // This should set it for OutputPage and the Skin
250 // which is needed or the personal links will be
252 $this->getContext()->setUser( $u );
253 wfRunHooks( 'AddNewAccount', array( $u, false ) );
254 $u->addNewUserLogEntry();
255 if( $this->hasSessionCookie() ) {
256 $this->successfulCreation();
258 $this->cookieRedirectCheck( 'new' );
261 # Confirm that the account was created
262 $out->setPageTitle( $this->msg( 'accountcreated' ) );
263 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
264 $out->addReturnTo( $this->getTitle() );
265 wfRunHooks( 'AddNewAccount', array( $u, false ) );
266 $u->addNewUserLogEntry( false, $this->mReason
);
275 function addNewAccountInternal() {
276 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
277 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
279 // If the user passes an invalid domain, something is fishy
280 if( !$wgAuth->validDomain( $this->mDomain
) ) {
281 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
285 // If we are not allowing users to login locally, we should be checking
286 // to see if the user is actually able to authenticate to the authenti-
287 // cation server before they create an account (otherwise, they can
288 // create a local account and login as any domain user). We only need
289 // to check this for domains that aren't local.
290 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
291 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername
)
292 ||
!$wgAuth->authenticate( $this->mUsername
, $this->mPassword
) ) ) {
293 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
298 if ( wfReadOnly() ) {
299 throw new ReadOnlyError
;
302 # Request forgery checks.
303 if ( !self
::getCreateaccountToken() ) {
304 self
::setCreateaccountToken();
305 $this->mainLoginForm( $this->msg( 'nocookiesfornew' )->parse() );
309 # The user didn't pass a createaccount token
310 if ( !$this->mToken
) {
311 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
315 # Validate the createaccount token
316 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
317 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
322 $currentUser = $this->getUser();
323 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
324 throw new PermissionsError( 'createaccount' );
325 } elseif ( $currentUser->isBlockedFromCreateAccount() ) {
326 $this->userBlockedMessage( $currentUser->isBlockedFromCreateAccount() );
330 # Include checks that will include GlobalBlocking (Bug 38333)
331 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'createaccount', $currentUser, true );
332 if ( count( $permErrors ) ) {
333 throw new PermissionsError( 'createaccount', $permErrors );
336 $ip = $this->getRequest()->getIP();
337 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
338 $this->mainLoginForm( $this->msg( 'sorbs_create_account_reason' )->text() . ' ' . $this->msg( 'parentheses', $ip )->escaped() );
342 # Now create a dummy user ($u) and check if it is valid
343 $name = trim( $this->mUsername
);
344 $u = User
::newFromName( $name, 'creatable' );
345 if ( !is_object( $u ) ) {
346 $this->mainLoginForm( $this->msg( 'noname' )->text() );
350 if ( 0 != $u->idForName() ) {
351 $this->mainLoginForm( $this->msg( 'userexists' )->text() );
355 if ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
356 $this->mainLoginForm( $this->msg( 'badretype' )->text() );
360 # check for minimal password length
361 $valid = $u->getPasswordValidity( $this->mPassword
);
362 if ( $valid !== true ) {
363 if ( !$this->mCreateaccountMail
) {
364 if ( is_array( $valid ) ) {
365 $message = array_shift( $valid );
369 $params = array( $wgMinimalPasswordLength );
371 $this->mainLoginForm( $this->msg( $message, $params )->text() );
374 # do not force a password for account creation by email
375 # set invalid password, it will be replaced later by a random generated password
376 $this->mPassword
= null;
380 # if you need a confirmed email address to edit, then obviously you
381 # need an email address.
382 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
383 $this->mainLoginForm( $this->msg( 'noemailtitle' )->text() );
387 if( !empty( $this->mEmail
) && !Sanitizer
::validateEmail( $this->mEmail
) ) {
388 $this->mainLoginForm( $this->msg( 'invalidemailaddress' )->text() );
392 # Set some additional data so the AbortNewAccount hook can be used for
393 # more than just username validation
394 $u->setEmail( $this->mEmail
);
395 $u->setRealName( $this->mRealName
);
398 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
399 // Hook point to add extra creation throttles and blocks
400 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
401 $this->mainLoginForm( $abortError );
405 // Hook point to check for exempt from account creation throttle
406 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
407 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
409 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
410 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
411 $value = $wgMemc->get( $key );
413 $wgMemc->set( $key, 0, 86400 );
415 if ( $value >= $wgAccountCreationThrottle ) {
416 $this->throttleHit( $wgAccountCreationThrottle );
419 $wgMemc->incr( $key );
423 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
424 $this->mainLoginForm( $this->msg( 'externaldberror' )->text() );
428 self
::clearCreateaccountToken();
429 return $this->initUser( $u, false );
433 * Actually add a user to the database.
434 * Give it a User object that has been initialised with a name.
436 * @param $u User object.
437 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
438 * @return User object.
441 function initUser( $u, $autocreate ) {
446 if ( $wgAuth->allowPasswordChange() ) {
447 $u->setPassword( $this->mPassword
);
450 $u->setEmail( $this->mEmail
);
451 $u->setRealName( $this->mRealName
);
454 $wgAuth->initUser( $u, $autocreate );
456 if ( $this->mExtUser
) {
457 $this->mExtUser
->linkToLocal( $u->getId() );
458 $email = $this->mExtUser
->getPref( 'emailaddress' );
459 if ( $email && !$this->mEmail
) {
460 $u->setEmail( $email );
464 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
468 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
469 $ssUpdate->doUpdate();
475 * Internally authenticate the login request.
477 * This may create a local account as a side effect if the
478 * authentication plugin allows transparent local account
482 public function authenticateUserData() {
483 global $wgUser, $wgAuth;
487 if ( $this->mUsername
== '' ) {
488 return self
::NO_NAME
;
491 // We require a login token to prevent login CSRF
492 // Handle part of this before incrementing the throttle so
493 // token-less login attempts don't count towards the throttle
494 // but wrong-token attempts do.
496 // If the user doesn't have a login token yet, set one.
497 if ( !self
::getLoginToken() ) {
498 self
::setLoginToken();
499 return self
::NEED_TOKEN
;
501 // If the user didn't pass a login token, tell them we need one
502 if ( !$this->mToken
) {
503 return self
::NEED_TOKEN
;
506 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
507 if ( $throttleCount === true ) {
508 return self
::THROTTLED
;
511 // Validate the login token
512 if ( $this->mToken
!== self
::getLoginToken() ) {
513 return self
::WRONG_TOKEN
;
516 // Load the current user now, and check to see if we're logging in as
517 // the same name. This is necessary because loading the current user
518 // (say by calling getName()) calls the UserLoadFromSession hook, which
519 // potentially creates the user in the database. Until we load $wgUser,
520 // checking for user existence using User::newFromName($name)->getId() below
521 // will effectively be using stale data.
522 if ( $this->getUser()->getName() === $this->mUsername
) {
523 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
524 return self
::SUCCESS
;
527 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
529 # TODO: Allow some magic here for invalid external names, e.g., let the
530 # user choose a different wiki name.
531 $u = User
::newFromName( $this->mUsername
);
532 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
533 return self
::ILLEGAL
;
536 $isAutoCreated = false;
537 if ( 0 == $u->getID() ) {
538 $status = $this->attemptAutoCreate( $u );
539 if ( $status !== self
::SUCCESS
) {
542 $isAutoCreated = true;
545 global $wgExternalAuthType, $wgAutocreatePolicy;
546 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
547 && is_object( $this->mExtUser
)
548 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
549 # The external user and local user have the same name and
550 # password, so we assume they're the same.
551 $this->mExtUser
->linkToLocal( $u->getID() );
557 // Give general extensions, such as a captcha, a chance to abort logins
558 $abort = self
::ABORTED
;
559 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
563 global $wgBlockDisablesLogin;
564 if ( !$u->checkPassword( $this->mPassword
) ) {
565 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
566 // The e-mailed temporary password should not be used for actu-
567 // al logins; that's a very sloppy habit, and insecure if an
568 // attacker has a few seconds to click "search" on someone's o-
571 // Allow it to be used only to reset the password a single time
572 // to a new value, which won't be in the user's e-mail ar-
575 // For backwards compatibility, we'll still recognize it at the
576 // login form to minimize surprises for people who have been
577 // logging in with a temporary password for some time.
579 // As a side-effect, we can authenticate the user's e-mail ad-
580 // dress if it's not already done, since the temporary password
581 // was sent via e-mail.
582 if( !$u->isEmailConfirmed() ) {
587 // At this point we just return an appropriate code/ indicating
588 // that the UI should show a password reset form; bot inter-
589 // faces etc will probably just fail cleanly here.
590 $retval = self
::RESET_PASS
;
592 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
594 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
595 // If we've enabled it, make it so that a blocked user cannot login
596 $retval = self
::USER_BLOCKED
;
598 $wgAuth->updateUser( $u );
600 // This should set it for OutputPage and the Skin
601 // which is needed or the personal links will be
603 $this->getContext()->setUser( $u );
605 // Please reset throttle for successful logins, thanks!
606 if ( $throttleCount ) {
607 self
::clearLoginThrottle( $this->mUsername
);
610 if ( $isAutoCreated ) {
611 // Must be run after $wgUser is set, for correct new user log
612 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
615 $retval = self
::SUCCESS
;
617 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
622 * Increment the login attempt throttle hit count for the (username,current IP)
623 * tuple unless the throttle was already reached.
624 * @param $username string The user name
625 * @return Bool|Integer The integer hit count or True if it is already at the limit
627 public static function incLoginThrottle( $username ) {
628 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
629 $username = trim( $username ); // sanity
632 if ( is_array( $wgPasswordAttemptThrottle ) ) {
633 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
634 $count = $wgPasswordAttemptThrottle['count'];
635 $period = $wgPasswordAttemptThrottle['seconds'];
637 $throttleCount = $wgMemc->get( $throttleKey );
638 if ( !$throttleCount ) {
639 $wgMemc->add( $throttleKey, 1, $period ); // start counter
640 } elseif ( $throttleCount < $count ) {
641 $wgMemc->incr( $throttleKey );
642 } elseif ( $throttleCount >= $count ) {
647 return $throttleCount;
651 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
652 * @param $username string The user name
655 public static function clearLoginThrottle( $username ) {
656 global $wgMemc, $wgRequest;
657 $username = trim( $username ); // sanity
659 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
660 $wgMemc->delete( $throttleKey );
664 * Attempt to automatically create a user on login. Only succeeds if there
665 * is an external authentication method which allows it.
669 * @return integer Status code
671 function attemptAutoCreate( $user ) {
672 global $wgAuth, $wgAutocreatePolicy;
674 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
675 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
676 return self
::CREATE_BLOCKED
;
680 * If the external authentication plugin allows it, automatically cre-
681 * ate a new account for users that are externally defined but have not
684 if ( $this->mExtUser
) {
685 # mExtUser is neither null nor false, so use the new ExternalAuth
687 if ( $wgAutocreatePolicy == 'never' ) {
688 return self
::NOT_EXISTS
;
690 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
691 return self
::WRONG_PLUGIN_PASS
;
695 if ( !$wgAuth->autoCreate() ) {
696 return self
::NOT_EXISTS
;
698 if ( !$wgAuth->userExists( $user->getName() ) ) {
699 wfDebug( __METHOD__
. ": user does not exist\n" );
700 return self
::NOT_EXISTS
;
702 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
703 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
704 return self
::WRONG_PLUGIN_PASS
;
709 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
710 // Hook point to add extra creation throttles and blocks
711 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
712 $this->mAbortLoginErrorMsg
= $abortError;
713 return self
::ABORTED
;
716 wfDebug( __METHOD__
. ": creating account\n" );
717 $this->initUser( $user, true );
718 return self
::SUCCESS
;
721 function processLogin() {
722 global $wgMemc, $wgLang;
724 switch ( $this->authenticateUserData() ) {
726 # We've verified now, update the real record
727 $user = $this->getUser();
728 if( (bool)$this->mRemember
!= (bool)$user->getOption( 'rememberpassword' ) ) {
729 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
730 $user->saveSettings();
732 $user->invalidateCache();
735 self
::clearLoginToken();
737 // Reset the throttle
738 $request = $this->getRequest();
739 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
740 $wgMemc->delete( $key );
742 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
743 /* Replace the language object to provide user interface in
744 * correct language immediately on this first page load.
746 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
747 $userLang = Language
::factory( $code );
749 $this->getContext()->setLanguage( $userLang );
750 $this->successfulLogin();
752 $this->cookieRedirectCheck( 'login' );
756 case self
::NEED_TOKEN
:
757 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
759 case self
::WRONG_TOKEN
:
760 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
764 $this->mainLoginForm( $this->msg( 'noname' )->text() );
766 case self
::WRONG_PLUGIN_PASS
:
767 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
769 case self
::NOT_EXISTS
:
770 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
771 $this->mainLoginForm( $this->msg( 'nosuchuser',
772 wfEscapeWikiText( $this->mUsername
) )->parse() );
774 $this->mainLoginForm( $this->msg( 'nosuchusershort',
775 wfEscapeWikiText( $this->mUsername
) )->text() );
778 case self
::WRONG_PASS
:
779 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
781 case self
::EMPTY_PASS
:
782 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
784 case self
::RESET_PASS
:
785 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
787 case self
::CREATE_BLOCKED
:
788 $this->userBlockedMessage( $this->getUser()->mBlock
);
790 case self
::THROTTLED
:
791 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
793 case self
::USER_BLOCKED
:
794 $this->mainLoginForm( $this->msg( 'login-userblocked',
795 $this->mUsername
)->escaped() );
798 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
801 throw new MWException( 'Unhandled case value' );
805 function resetLoginForm( $error ) {
806 $this->getOutput()->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
807 $reset = new SpecialChangePassword();
808 $reset->setContext( $this->getContext() );
809 $reset->execute( null );
813 * @param $u User object
814 * @param $throttle Boolean
815 * @param $emailTitle String: message name of email title
816 * @param $emailText String: message name of email text
817 * @return Status object
819 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
820 global $wgServer, $wgScript, $wgNewPasswordExpiry;
822 if ( $u->getEmail() == '' ) {
823 return Status
::newFatal( 'noemail', $u->getName() );
825 $ip = $this->getRequest()->getIP();
827 return Status
::newFatal( 'badipaddress' );
830 $currentUser = $this->getUser();
831 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
833 $np = $u->randomPassword();
834 $u->setNewpassword( $np, $throttle );
836 $userLanguage = $u->getOption( 'language' );
837 $m = $this->msg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript,
838 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
839 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
846 * Run any hooks registered for logins, then HTTP redirect to
847 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
848 * nice message here, but that's really not as useful as just being sent to
849 * wherever you logged in from. It should be clear that the action was
850 * successful, given the lack of error messages plus the appearance of your
851 * name in the upper right.
855 function successfulLogin() {
856 # Run any hooks; display injected HTML if any, else redirect
857 $currentUser = $this->getUser();
859 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
861 if( $injected_html !== '' ) {
862 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
864 $this->executeReturnTo( 'successredirect' );
869 * Run any hooks registered for logins, then display a message welcoming
874 function successfulCreation() {
875 # Run any hooks; display injected HTML
876 $currentUser = $this->getUser();
878 $welcome_creation_msg = 'welcomecreation';
880 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
883 * Let any extensions change what message is shown.
884 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
887 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
889 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
893 * Display a "login successful" page.
894 * @param $msgname string
895 * @param $injected_html string
897 private function displaySuccessfulLogin( $msgname, $injected_html ) {
898 $out = $this->getOutput();
899 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
901 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
904 $out->addHTML( $injected_html );
906 $this->executeReturnTo( 'success' );
910 * Output a message that informs the user that they cannot create an account because
911 * there is a block on them or their IP which prevents account creation. Note that
912 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
913 * setting on blocks (bug 13611).
914 * @param $block Block the block causing this error
916 function userBlockedMessage( Block
$block ) {
917 # Let's be nice about this, it's likely that this feature will be used
918 # for blocking large numbers of innocent people, e.g. range blocks on
919 # schools. Don't blame it on the user. There's a small chance that it
920 # really is the user's fault, i.e. the username is blocked and they
921 # haven't bothered to log out before trying to create an account to
922 # evade it, but we'll leave that to their guilty conscience to figure
925 $out = $this->getOutput();
926 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
928 $block_reason = $block->mReason
;
929 if ( strval( $block_reason ) === '' ) {
930 $block_reason = $this->msg( 'blockednoreason' )->text();
934 'cantcreateaccount-text',
940 $this->executeReturnTo( 'error' );
944 * Add a "return to" link or redirect to it.
946 * @param $type string, one of the following:
947 * - error: display a return to link ignoring $wgRedirectOnLogin
948 * - success: display a return to link using $wgRedirectOnLogin if needed
949 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
951 private function executeReturnTo( $type ) {
952 global $wgRedirectOnLogin, $wgSecureLogin;
954 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
955 $returnTo = $wgRedirectOnLogin;
956 $returnToQuery = array();
958 $returnTo = $this->mReturnTo
;
959 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
962 $returnToTitle = Title
::newFromText( $returnTo );
963 if ( !$returnToTitle ) {
964 $returnToTitle = Title
::newMainPage();
967 if ( $type == 'successredirect' ) {
968 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery );
969 if( $wgSecureLogin && !$this->mStickHTTPS
) {
970 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
972 $this->getOutput()->redirect( $redirectUrl );
974 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery );
981 function mainLoginForm( $msg, $msgtype = 'error' ) {
982 global $wgEnableEmail, $wgEnableUserEmail;
983 global $wgHiddenPrefs, $wgLoginLanguageSelector;
984 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
985 global $wgSecureLogin, $wgPasswordResetRoutes;
987 $titleObj = $this->getTitle();
988 $user = $this->getUser();
990 if ( $this->mType
== 'signup' ) {
991 // Block signup here if in readonly. Keeps user from
992 // going through the process (filling out data, etc)
993 // and being informed later.
994 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
995 if ( count( $permErrors ) ) {
996 throw new PermissionsError( 'createaccount', $permErrors );
997 } elseif ( $user->isBlockedFromCreateAccount() ) {
998 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1000 } elseif ( wfReadOnly() ) {
1001 throw new ReadOnlyError
;
1005 if ( $this->mUsername
== '' ) {
1006 if ( $user->isLoggedIn() ) {
1007 $this->mUsername
= $user->getName();
1009 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1013 if ( $this->mType
== 'signup' ) {
1014 $template = new UsercreateTemplate();
1015 $q = 'action=submitlogin&type=signup';
1016 $linkq = 'type=login';
1017 $linkmsg = 'gotaccount';
1019 $template = new UserloginTemplate();
1020 $q = 'action=submitlogin&type=login';
1021 $linkq = 'type=signup';
1022 $linkmsg = 'nologin';
1025 if ( $this->mReturnTo
!== '' ) {
1026 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1027 if ( $this->mReturnToQuery
!== '' ) {
1028 $returnto .= '&returntoquery=' .
1029 wfUrlencode( $this->mReturnToQuery
);
1032 $linkq .= $returnto;
1035 # Don't show a "create account" link if the user can't
1036 if( $this->showCreateOrLoginLink( $user ) ) {
1037 # Pass any language selection on to the mode switch link
1038 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1039 $linkq .= '&uselang=' . $this->mLanguage
;
1041 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1042 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1044 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1046 $template->set( 'link', '' );
1049 $resetLink = $this->mType
== 'signup'
1051 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1053 $template->set( 'header', '' );
1054 $template->set( 'name', $this->mUsername
);
1055 $template->set( 'password', $this->mPassword
);
1056 $template->set( 'retype', $this->mRetype
);
1057 $template->set( 'email', $this->mEmail
);
1058 $template->set( 'realname', $this->mRealName
);
1059 $template->set( 'domain', $this->mDomain
);
1060 $template->set( 'reason', $this->mReason
);
1062 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1063 $template->set( 'message', $msg );
1064 $template->set( 'messagetype', $msgtype );
1065 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1066 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1067 $template->set( 'useemail', $wgEnableEmail );
1068 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1069 $template->set( 'emailothers', $wgEnableUserEmail );
1070 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1071 $template->set( 'resetlink', $resetLink );
1072 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1073 $template->set( 'usereason', $user->isLoggedIn() );
1074 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1075 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1076 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1078 if ( $this->mType
== 'signup' ) {
1079 if ( !self
::getCreateaccountToken() ) {
1080 self
::setCreateaccountToken();
1082 $template->set( 'token', self
::getCreateaccountToken() );
1084 if ( !self
::getLoginToken() ) {
1085 self
::setLoginToken();
1087 $template->set( 'token', self
::getLoginToken() );
1090 # Prepare language selection links as needed
1091 if( $wgLoginLanguageSelector ) {
1092 $template->set( 'languages', $this->makeLanguageSelector() );
1093 if( $this->mLanguage
) {
1094 $template->set( 'uselang', $this->mLanguage
);
1098 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1099 // Ditto for signupend
1100 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1101 $loginendHTTPS = $this->msg( 'loginend-https' );
1102 $signupendHTTPS = $this->msg( 'signupend-https' );
1103 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1104 $template->set( 'loginend', $loginendHTTPS->parse() );
1106 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1108 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1109 $template->set( 'signupend', $signupendHTTPS->parse() );
1111 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1114 // Give authentication and captcha plugins a chance to modify the form
1115 $wgAuth->modifyUITemplate( $template, $this->mType
);
1116 if ( $this->mType
== 'signup' ) {
1117 wfRunHooks( 'UserCreateForm', array( &$template ) );
1119 wfRunHooks( 'UserLoginForm', array( &$template ) );
1122 $out = $this->getOutput();
1123 $out->disallowUserJs(); // just in case...
1124 $out->addTemplate( $template );
1134 function showCreateOrLoginLink( &$user ) {
1135 if( $this->mType
== 'signup' ) {
1137 } elseif( $user->isAllowed( 'createaccount' ) ) {
1145 * Check if a session cookie is present.
1147 * This will not pick up a cookie set during _this_ request, but is meant
1148 * to ensure that the client is returning the cookie which was set on a
1149 * previous pass through the system.
1154 function hasSessionCookie() {
1155 global $wgDisableCookieCheck;
1156 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1160 * Get the login token from the current session
1163 public static function getLoginToken() {
1165 return $wgRequest->getSessionData( 'wsLoginToken' );
1169 * Randomly generate a new login token and attach it to the current session
1171 public static function setLoginToken() {
1173 // Generate a token directly instead of using $user->editToken()
1174 // because the latter reuses $_SESSION['wsEditToken']
1175 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1179 * Remove any login token attached to the current session
1181 public static function clearLoginToken() {
1183 $wgRequest->setSessionData( 'wsLoginToken', null );
1187 * Get the createaccount token from the current session
1190 public static function getCreateaccountToken() {
1192 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1196 * Randomly generate a new createaccount token and attach it to the current session
1198 public static function setCreateaccountToken() {
1200 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1204 * Remove any createaccount token attached to the current session
1206 public static function clearCreateaccountToken() {
1208 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1214 function cookieRedirectCheck( $type ) {
1215 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1216 $query = array( 'wpCookieCheck' => $type );
1217 if ( $this->mReturnTo
!== '' ) {
1218 $query['returnto'] = $this->mReturnTo
;
1219 $query['returntoquery'] = $this->mReturnToQuery
;
1221 $check = $titleObj->getFullURL( $query );
1223 $this->getOutput()->redirect( $check );
1229 function onCookieRedirectCheck( $type ) {
1230 if ( !$this->hasSessionCookie() ) {
1231 if ( $type == 'new' ) {
1232 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1233 } elseif ( $type == 'login' ) {
1234 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1237 $this->mainLoginForm( $this->msg( 'error' )->text() );
1240 $this->successfulLogin();
1247 function throttleHit( $limit ) {
1248 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1252 * Produce a bar of links which allow the user to select another language
1253 * during login/registration but retain "returnto"
1257 function makeLanguageSelector() {
1258 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1259 if( !$msg->isBlank() ) {
1260 $langs = explode( "\n", $msg->text() );
1262 foreach( $langs as $lang ) {
1263 $lang = trim( $lang, '* ' );
1264 $parts = explode( '|', $lang );
1265 if ( count( $parts ) >= 2 ) {
1266 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1269 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1270 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1277 * Create a language selector link for a particular language
1278 * Links back to this page preserving type and returnto
1280 * @param $text Link text
1281 * @param $lang Language code
1284 function makeLanguageSelectorLink( $text, $lang ) {
1285 if( $this->getLanguage()->getCode() == $lang ) {
1286 // no link for currently used language
1287 return htmlspecialchars( $text );
1289 $query = array( 'uselang' => $lang );
1290 if( $this->mType
== 'signup' ) {
1291 $query['type'] = 'signup';
1293 if( $this->mReturnTo
!== '' ) {
1294 $query['returnto'] = $this->mReturnTo
;
1295 $query['returntoquery'] = $this->mReturnToQuery
;
1299 $targetLanguage = Language
::factory( $lang );
1300 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1302 return Linker
::linkKnown(
1304 htmlspecialchars( $text ),