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
23 use MediaWiki\Logger\LoggerFactory
;
26 * Implements Special:UserLogin
28 * @ingroup SpecialPage
30 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;
45 const USER_MIGRATED
= 14;
48 * Valid error and warning messages
50 * Special:Userlogin can show an error or warning message on the form when
51 * coming from another page. This is done via the ?error= or ?warning= GET
54 * This array is the list of valid message keys. All other values will be
60 public static $validErrorMessages = array(
61 'exception-nologin-text',
63 'changeemail-no-info',
65 'confirmemail_needlogin',
69 public $mAbortLoginErrorMsg = null;
75 protected $mCookieCheck;
78 protected $mCreateaccount;
79 protected $mCreateaccountMail;
80 protected $mLoginattempt;
85 protected $mSkipCookieCheck;
86 protected $mReturnToQuery;
88 protected $mStickHTTPS;
92 protected $mEntryError = '';
93 protected $mEntryErrorType = 'error';
95 private $mTempPasswordUsed;
96 private $mLoaded = false;
97 private $mSecureLoginUrl;
99 /** @var WebRequest */
100 private $mOverrideRequest = null;
102 /** @var WebRequest Effective request; set at the beginning of load */
103 private $mRequest = null;
106 * @param WebRequest $request
108 public function __construct( $request = null ) {
109 global $wgUseMediaWikiUIEverywhere;
110 parent
::__construct( 'Userlogin' );
112 $this->mOverrideRequest
= $request;
113 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
114 $wgUseMediaWikiUIEverywhere = true;
118 * Returns an array of all valid error messages.
122 public static function getValidErrorMessages() {
123 static $messages = null;
125 $messages = self
::$validErrorMessages;
126 Hooks
::run( 'LoginFormValidErrorMessages', array( &$messages ) );
136 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
138 if ( $this->mLoaded
) {
141 $this->mLoaded
= true;
143 if ( $this->mOverrideRequest
=== null ) {
144 $request = $this->getRequest();
146 $request = $this->mOverrideRequest
;
148 $this->mRequest
= $request;
150 $this->mType
= $request->getText( 'type' );
151 $this->mUsername
= $request->getText( 'wpName' );
152 $this->mPassword
= $request->getText( 'wpPassword' );
153 $this->mRetype
= $request->getText( 'wpRetype' );
154 $this->mDomain
= $request->getText( 'wpDomain' );
155 $this->mReason
= $request->getText( 'wpReason' );
156 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
157 $this->mPosted
= $request->wasPosted();
158 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
160 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' ) && !$this->mCreateaccountMail
;
161 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
162 $this->mAction
= $request->getVal( 'action' );
163 $this->mRemember
= $request->getCheck( 'wpRemember' );
164 $this->mFromHTTP
= $request->getBool( 'fromhttp', false )
165 ||
$request->getBool( 'wpFromhttp', false );
166 $this->mStickHTTPS
= ( !$this->mFromHTTP
&& $request->getProtocol() === 'https' )
167 ||
$request->getBool( 'wpForceHttps', false );
168 $this->mLanguage
= $request->getText( 'uselang' );
169 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
170 $this->mToken
= $this->mType
== 'signup'
171 ?
$request->getVal( 'wpCreateaccountToken' )
172 : $request->getVal( 'wpLoginToken' );
173 $this->mReturnTo
= $request->getVal( 'returnto', '' );
174 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
176 // Show an error or warning passed on from a previous page
177 $entryError = $this->msg( $request->getVal( 'error', '' ) );
178 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
179 // bc: provide login link as a parameter for messages where the translation
181 $loginreqlink = Linker
::linkKnown(
182 $this->getPageTitle(),
183 $this->msg( 'loginreqlink' )->escaped(),
186 'returnto' => $this->mReturnTo
,
187 'returntoquery' => $this->mReturnToQuery
,
188 'uselang' => $this->mLanguage
,
189 'fromhttp' => $this->mFromHTTP ?
'1' : '0',
193 // Only show valid error or warning messages.
194 if ( $entryError->exists()
195 && in_array( $entryError->getKey(), self
::getValidErrorMessages() )
197 $this->mEntryErrorType
= 'error';
198 $this->mEntryError
= $entryError->rawParams( $loginreqlink )->parse();
200 } elseif ( $entryWarning->exists()
201 && in_array( $entryWarning->getKey(), self
::getValidErrorMessages() )
203 $this->mEntryErrorType
= 'warning';
204 $this->mEntryError
= $entryWarning->rawParams( $loginreqlink )->parse();
207 if ( $wgEnableEmail ) {
208 $this->mEmail
= $request->getText( 'wpEmail' );
212 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
213 $this->mRealName
= $request->getText( 'wpRealName' );
215 $this->mRealName
= '';
218 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
219 $this->mDomain
= $wgAuth->getDomain();
221 $wgAuth->setDomain( $this->mDomain
);
223 # 1. When switching accounts, it sucks to get automatically logged out
224 # 2. Do not return to PasswordReset after a successful password change
225 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
226 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
227 if ( is_object( $returnToTitle )
228 && ( $returnToTitle->isSpecial( 'Userlogout' )
229 ||
$returnToTitle->isSpecial( 'PasswordReset' ) )
231 $this->mReturnTo
= '';
232 $this->mReturnToQuery
= '';
236 function getDescription() {
237 if ( $this->mType
=== 'signup' ) {
238 return $this->msg( 'createaccount' )->text();
240 return $this->msg( 'login' )->text();
245 * @param string|null $subPage
247 public function execute( $subPage ) {
248 if ( session_id() == '' ) {
254 // Check for [[Special:Userlogin/signup]]. This affects form display and
256 if ( $subPage == 'signup' ) {
257 $this->mType
= 'signup';
261 // In the case where the user is already logged in, and was redirected to the login form from a
262 // page that requires login, do not show the login page. The use case scenario for this is when
263 // a user opens a large number of tabs, is redirected to the login page on all of them, and then
264 // logs in on one, expecting all the others to work properly.
266 // However, do show the form if it was visited intentionally (no 'returnto' is present). People
267 // who often switch between several accounts have grown accustomed to this behavior.
269 $this->mType
!== 'signup' &&
271 $this->getUser()->isLoggedIn() &&
272 ( $this->mReturnTo
!== '' ||
$this->mReturnToQuery
!== '' )
274 $this->successfulLogin();
277 // If logging in and not on HTTPS, either redirect to it or offer a link.
278 global $wgSecureLogin;
279 if ( $this->mRequest
->getProtocol() !== 'https' ) {
280 $title = $this->getFullTitle();
282 'returnto' => $this->mReturnTo
!== '' ?
$this->mReturnTo
: null,
283 'returntoquery' => $this->mReturnToQuery
!== '' ?
284 $this->mReturnToQuery
: null,
286 ( $this->mEntryErrorType
=== 'error' ?
'error' : 'warning' ) => $this->mEntryError
,
287 ) +
$this->mRequest
->getQueryValues();
288 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
290 && wfCanIPUseHTTPS( $this->getRequest()->getIP() )
291 && !$this->mFromHTTP
) // Avoid infinite redirect
293 $url = wfAppendQuery( $url, 'fromhttp=1' );
294 $this->getOutput()->redirect( $url );
295 // Since we only do this redir to change proto, always vary
296 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
300 // A wiki without HTTPS login support should set $wgServer to
301 // http://somehost, in which case the secure URL generated
302 // above won't actually start with https://
303 if ( substr( $url, 0, 8 ) === 'https://' ) {
304 $this->mSecureLoginUrl
= $url;
309 if ( !is_null( $this->mCookieCheck
) ) {
310 $this->onCookieRedirectCheck( $this->mCookieCheck
);
313 } elseif ( $this->mPosted
) {
314 if ( $this->mCreateaccount
) {
315 $this->addNewAccount();
318 } elseif ( $this->mCreateaccountMail
) {
319 $this->addNewAccountMailPassword();
322 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
323 $this->processLogin();
328 $this->mainLoginForm( $this->mEntryError
, $this->mEntryErrorType
);
334 function addNewAccountMailPassword() {
335 if ( $this->mEmail
== '' ) {
336 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
341 $status = $this->addNewAccountInternal();
342 LoggerFactory
::getInstance( 'authmanager' )->info( 'Account creation attempt with mailed password', array(
343 'event' => 'accountcreation',
346 if ( !$status->isGood() ) {
347 $error = $status->getMessage();
348 $this->mainLoginForm( $error->toString() );
353 $u = $status->getValue();
355 // Wipe the initial password and mail a temporary one
356 $u->setPassword( null );
358 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
360 Hooks
::run( 'AddNewAccount', array( $u, true ) );
361 $u->addNewUserLogEntry( 'byemail', $this->mReason
);
363 $out = $this->getOutput();
364 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
366 if ( !$result->isGood() ) {
367 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
369 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
370 $this->executeReturnTo( 'success' );
378 function addNewAccount() {
379 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
381 # Create the account and abort if there's a problem doing so
382 $status = $this->addNewAccountInternal();
383 LoggerFactory
::getInstance( 'authmanager' )->info( 'Account creation attempt', array(
384 'event' => 'accountcreation',
388 if ( !$status->isGood() ) {
389 $error = $status->getMessage();
390 $this->mainLoginForm( $error->toString() );
395 $u = $status->getValue();
397 # Only save preferences if the user is not creating an account for someone else.
398 if ( $this->getUser()->isAnon() ) {
399 # If we showed up language selection links, and one was in use, be
400 # smart (and sensible) and save that language as the user's preference
401 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
402 $u->setOption( 'language', $this->mLanguage
);
405 # Otherwise the user's language preference defaults to $wgContLang,
406 # but it may be better to set it to their preferred $wgContLang variant,
407 # based on browser preferences or URL parameters.
408 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
410 if ( $wgContLang->hasVariants() ) {
411 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
415 $out = $this->getOutput();
417 # Send out an email authentication message if needed
418 if ( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
419 $status = $u->sendConfirmationMail();
420 if ( $status->isGood() ) {
421 $out->addWikiMsg( 'confirmemail_oncreate' );
423 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
427 # Save settings (including confirmation token)
430 # If not logged in, assume the new account as the current one and set
431 # session cookies then show a "welcome" message or a "need cookies"
433 if ( $this->getUser()->isAnon() ) {
436 // This should set it for OutputPage and the Skin
437 // which is needed or the personal links will be
439 $this->getContext()->setUser( $u );
440 Hooks
::run( 'AddNewAccount', array( $u, false ) );
441 $u->addNewUserLogEntry( 'create' );
442 if ( $this->hasSessionCookie() ) {
443 $this->successfulCreation();
445 $this->cookieRedirectCheck( 'new' );
448 # Confirm that the account was created
449 $out->setPageTitle( $this->msg( 'accountcreated' ) );
450 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
451 $out->addReturnTo( $this->getPageTitle() );
452 Hooks
::run( 'AddNewAccount', array( $u, false ) );
453 $u->addNewUserLogEntry( 'create2', $this->mReason
);
460 * Make a new user account using the loaded data.
462 * @throws PermissionsError|ReadOnlyError
465 public function addNewAccountInternal() {
466 global $wgAuth, $wgMemc, $wgAccountCreationThrottle, $wgEmailConfirmToEdit;
468 // If the user passes an invalid domain, something is fishy
469 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
470 return Status
::newFatal( 'wrongpassword' );
473 // If we are not allowing users to login locally, we should be checking
474 // to see if the user is actually able to authenticate to the authenti-
475 // cation server before they create an account (otherwise, they can
476 // create a local account and login as any domain user). We only need
477 // to check this for domains that aren't local.
478 if ( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
480 !$wgAuth->canCreateAccounts() &&
482 !$wgAuth->userExists( $this->mUsername
) ||
483 !$wgAuth->authenticate( $this->mUsername
, $this->mPassword
)
486 return Status
::newFatal( 'wrongpassword' );
490 if ( wfReadOnly() ) {
491 throw new ReadOnlyError
;
494 # Request forgery checks.
495 if ( !self
::getCreateaccountToken() ) {
496 self
::setCreateaccountToken();
498 return Status
::newFatal( 'nocookiesfornew' );
501 # The user didn't pass a createaccount token
502 if ( !$this->mToken
) {
503 return Status
::newFatal( 'sessionfailure' );
506 # Validate the createaccount token
507 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
508 return Status
::newFatal( 'sessionfailure' );
512 $currentUser = $this->getUser();
513 $creationBlock = $currentUser->isBlockedFromCreateAccount();
514 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
515 throw new PermissionsError( 'createaccount' );
516 } elseif ( $creationBlock instanceof Block
) {
517 // Throws an ErrorPageError.
518 $this->userBlockedMessage( $creationBlock );
520 // This should never be reached.
524 # Include checks that will include GlobalBlocking (Bug 38333)
525 $permErrors = $this->getPageTitle()->getUserPermissionsErrors(
531 if ( count( $permErrors ) ) {
532 throw new PermissionsError( 'createaccount', $permErrors );
535 $ip = $this->getRequest()->getIP();
536 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
537 return Status
::newFatal( 'sorbs_create_account_reason' );
540 # Now create a dummy user ($u) and check if it is valid
541 $u = User
::newFromName( $this->mUsername
, 'creatable' );
543 return Status
::newFatal( 'noname' );
544 } elseif ( 0 != $u->idForName( User
::READ_LOCKING
) ) {
545 return Status
::newFatal( 'userexists' );
548 if ( $this->mCreateaccountMail
) {
549 # do not force a password for account creation by email
550 # set invalid password, it will be replaced later by a random generated password
551 $this->mPassword
= null;
553 if ( $this->mPassword
!== $this->mRetype
) {
554 return Status
::newFatal( 'badretype' );
557 # check for password validity, return a fatal Status if invalid
558 $validity = $u->checkPasswordValidity( $this->mPassword
, 'create' );
559 if ( !$validity->isGood() ) {
560 $validity->ok
= false; // make sure this Status is fatal
565 # if you need a confirmed email address to edit, then obviously you
566 # need an email address.
567 if ( $wgEmailConfirmToEdit && strval( $this->mEmail
) === '' ) {
568 return Status
::newFatal( 'noemailtitle' );
571 if ( strval( $this->mEmail
) !== '' && !Sanitizer
::validateEmail( $this->mEmail
) ) {
572 return Status
::newFatal( 'invalidemailaddress' );
575 # Set some additional data so the AbortNewAccount hook can be used for
576 # more than just username validation
577 $u->setEmail( $this->mEmail
);
578 $u->setRealName( $this->mRealName
);
582 if ( !Hooks
::run( 'AbortNewAccount', array( $u, &$abortError, &$abortStatus ) ) ) {
583 // Hook point to add extra creation throttles and blocks
584 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
585 if ( $abortStatus === null ) {
586 // Report back the old string as a raw message status.
587 // This will report the error back as 'createaccount-hook-aborted'
588 // with the given string as the message.
589 // To return a different error code, return a Status object.
590 $abortError = new Message( 'createaccount-hook-aborted', array( $abortError ) );
593 return Status
::newFatal( $abortError );
595 // For MediaWiki 1.23+ and updated hooks, return the Status object
596 // returned from the hook.
601 // Hook point to check for exempt from account creation throttle
602 if ( !Hooks
::run( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
603 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook " .
604 "allowed account creation w/o throttle\n" );
606 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
607 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
608 $value = $wgMemc->get( $key );
610 $wgMemc->set( $key, 0, 86400 );
612 if ( $value >= $wgAccountCreationThrottle ) {
613 return Status
::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
615 $wgMemc->incr( $key );
619 if ( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
620 return Status
::newFatal( 'externaldberror' );
623 self
::clearCreateaccountToken();
625 return $this->initUser( $u, false );
629 * Actually add a user to the database.
630 * Give it a User object that has been initialised with a name.
633 * @param bool $autocreate True if this is an autocreation via auth plugin
634 * @return Status Status object, with the User object in the value member on success
637 function initUser( $u, $autocreate ) {
640 $status = $u->addToDatabase();
641 if ( !$status->isOK() ) {
645 if ( $wgAuth->allowPasswordChange() ) {
646 $u->setPassword( $this->mPassword
);
649 $u->setEmail( $this->mEmail
);
650 $u->setRealName( $this->mRealName
);
653 $wgAuth->initUser( $u, $autocreate );
658 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
660 // Watch user's userpage and talk page
661 $u->addWatch( $u->getUserPage(), WatchedItem
::IGNORE_USER_RIGHTS
);
663 return Status
::newGood( $u );
667 * Internally authenticate the login request.
669 * This may create a local account as a side effect if the
670 * authentication plugin allows transparent local account
674 public function authenticateUserData() {
675 global $wgUser, $wgAuth;
679 if ( $this->mUsername
== '' ) {
680 return self
::NO_NAME
;
683 // We require a login token to prevent login CSRF
684 // Handle part of this before incrementing the throttle so
685 // token-less login attempts don't count towards the throttle
686 // but wrong-token attempts do.
688 // If the user doesn't have a login token yet, set one.
689 if ( !self
::getLoginToken() ) {
690 self
::setLoginToken();
692 return self
::NEED_TOKEN
;
694 // If the user didn't pass a login token, tell them we need one
695 if ( !$this->mToken
) {
696 return self
::NEED_TOKEN
;
699 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
700 if ( $throttleCount === true ) {
701 return self
::THROTTLED
;
704 // Validate the login token
705 if ( $this->mToken
!== self
::getLoginToken() ) {
706 return self
::WRONG_TOKEN
;
709 // Load the current user now, and check to see if we're logging in as
710 // the same name. This is necessary because loading the current user
711 // (say by calling getName()) calls the UserLoadFromSession hook, which
712 // potentially creates the user in the database. Until we load $wgUser,
713 // checking for user existence using User::newFromName($name)->getId() below
714 // will effectively be using stale data.
715 if ( $this->getUser()->getName() === $this->mUsername
) {
716 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
718 return self
::SUCCESS
;
721 $u = User
::newFromName( $this->mUsername
);
722 if ( $u === false ) {
723 return self
::ILLEGAL
;
727 // Give extensions a way to indicate the username has been updated,
728 // rather than telling the user the account doesn't exist.
729 if ( !Hooks
::run( 'LoginUserMigrated', array( $u, &$msg ) ) ) {
730 $this->mAbortLoginErrorMsg
= $msg;
731 return self
::USER_MIGRATED
;
734 if ( !User
::isUsableName( $u->getName() ) ) {
735 return self
::ILLEGAL
;
738 $isAutoCreated = false;
739 if ( $u->getID() == 0 ) {
740 $status = $this->attemptAutoCreate( $u );
741 if ( $status !== self
::SUCCESS
) {
744 $isAutoCreated = true;
750 // Give general extensions, such as a captcha, a chance to abort logins
751 $abort = self
::ABORTED
;
752 if ( !Hooks
::run( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$msg ) ) ) {
753 $this->mAbortLoginErrorMsg
= $msg;
758 global $wgBlockDisablesLogin;
759 if ( !$u->checkPassword( $this->mPassword
) ) {
760 if ( $u->checkTemporaryPassword( $this->mPassword
) ) {
761 // The e-mailed temporary password should not be used for actu-
762 // al logins; that's a very sloppy habit, and insecure if an
763 // attacker has a few seconds to click "search" on someone's o-
766 // Allow it to be used only to reset the password a single time
767 // to a new value, which won't be in the user's e-mail ar-
770 // For backwards compatibility, we'll still recognize it at the
771 // login form to minimize surprises for people who have been
772 // logging in with a temporary password for some time.
774 // As a side-effect, we can authenticate the user's e-mail ad-
775 // dress if it's not already done, since the temporary password
776 // was sent via e-mail.
777 if ( !$u->isEmailConfirmed() && !wfReadOnly() ) {
782 // At this point we just return an appropriate code/ indicating
783 // that the UI should show a password reset form; bot inter-
784 // faces etc will probably just fail cleanly here.
785 $this->mAbortLoginErrorMsg
= 'resetpass-temp-emailed';
786 $this->mTempPasswordUsed
= true;
787 $retval = self
::RESET_PASS
;
789 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
791 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
792 // If we've enabled it, make it so that a blocked user cannot login
793 $retval = self
::USER_BLOCKED
;
794 } elseif ( $u->getPasswordExpired() == 'hard' ) {
795 // Force reset now, without logging in
796 $retval = self
::RESET_PASS
;
797 $this->mAbortLoginErrorMsg
= 'resetpass-expired';
799 $wgAuth->updateUser( $u );
801 // This should set it for OutputPage and the Skin
802 // which is needed or the personal links will be
804 $this->getContext()->setUser( $u );
806 // Please reset throttle for successful logins, thanks!
807 if ( $throttleCount ) {
808 self
::clearLoginThrottle( $this->mUsername
);
811 if ( $isAutoCreated ) {
812 // Must be run after $wgUser is set, for correct new user log
813 Hooks
::run( 'AuthPluginAutoCreate', array( $u ) );
816 $retval = self
::SUCCESS
;
818 Hooks
::run( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
824 * Increment the login attempt throttle hit count for the (username,current IP)
825 * tuple unless the throttle was already reached.
826 * @param string $username The user name
827 * @return bool|int The integer hit count or True if it is already at the limit
829 public static function incLoginThrottle( $username ) {
830 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
831 $username = trim( $username ); // sanity
834 if ( is_array( $wgPasswordAttemptThrottle ) ) {
835 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
836 $count = $wgPasswordAttemptThrottle['count'];
837 $period = $wgPasswordAttemptThrottle['seconds'];
839 $throttleCount = $wgMemc->get( $throttleKey );
840 if ( !$throttleCount ) {
841 $wgMemc->add( $throttleKey, 1, $period ); // start counter
842 } elseif ( $throttleCount < $count ) {
843 $wgMemc->incr( $throttleKey );
844 } elseif ( $throttleCount >= $count ) {
849 return $throttleCount;
853 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
854 * @param string $username The user name
857 public static function clearLoginThrottle( $username ) {
858 global $wgMemc, $wgRequest;
859 $username = trim( $username ); // sanity
861 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
862 $wgMemc->delete( $throttleKey );
866 * Attempt to automatically create a user on login. Only succeeds if there
867 * is an external authentication method which allows it.
871 * @return int Status code
873 function attemptAutoCreate( $user ) {
876 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
877 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
879 return self
::CREATE_BLOCKED
;
882 if ( !$wgAuth->autoCreate() ) {
883 return self
::NOT_EXISTS
;
886 if ( !$wgAuth->userExists( $user->getName() ) ) {
887 wfDebug( __METHOD__
. ": user does not exist\n" );
889 return self
::NOT_EXISTS
;
892 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
893 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
895 return self
::WRONG_PLUGIN_PASS
;
899 if ( !Hooks
::run( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
900 // Hook point to add extra creation throttles and blocks
901 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
902 $this->mAbortLoginErrorMsg
= $abortError;
904 return self
::ABORTED
;
907 wfDebug( __METHOD__
. ": creating account\n" );
908 $status = $this->initUser( $user, true );
910 if ( !$status->isOK() ) {
911 $errors = $status->getErrorsByType( 'error' );
912 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
914 return self
::ABORTED
;
917 return self
::SUCCESS
;
920 function processLogin() {
921 global $wgMemc, $wgLang, $wgSecureLogin, $wgPasswordAttemptThrottle,
922 $wgInvalidPasswordReset;
924 $status = $this->authenticateUserData();
927 # We've verified now, update the real record
928 $user = $this->getUser();
931 if ( $user->requiresHTTPS() ) {
932 $this->mStickHTTPS
= true;
935 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
936 $user->setCookies( $this->mRequest
, false, $this->mRemember
);
938 $user->setCookies( $this->mRequest
, null, $this->mRemember
);
940 self
::clearLoginToken();
942 // Reset the throttle
943 $request = $this->getRequest();
944 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
945 $wgMemc->delete( $key );
947 if ( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
948 /* Replace the language object to provide user interface in
949 * correct language immediately on this first page load.
951 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
952 $userLang = Language
::factory( $code );
954 $this->getContext()->setLanguage( $userLang );
955 // Reset SessionID on Successful login (bug 40995)
956 $this->renewSessionId();
957 if ( $this->getUser()->getPasswordExpired() == 'soft' ) {
958 $this->resetLoginForm( $this->msg( 'resetpass-expired-soft' ) );
959 } elseif ( $wgInvalidPasswordReset
960 && !$user->isValidPassword( $this->mPassword
)
962 $status = $user->checkPasswordValidity(
966 $this->resetLoginForm(
967 $status->getMessage( 'resetpass-validity-soft' )
970 $this->successfulLogin();
973 $this->cookieRedirectCheck( 'login' );
977 case self
::NEED_TOKEN
:
978 $error = $this->mAbortLoginErrorMsg ?
: 'nocookiesforlogin';
979 $this->mainLoginForm( $this->msg( $error )->parse() );
981 case self
::WRONG_TOKEN
:
982 $error = $this->mAbortLoginErrorMsg ?
: 'sessionfailure';
983 $this->mainLoginForm( $this->msg( $error )->text() );
987 $error = $this->mAbortLoginErrorMsg ?
: 'noname';
988 $this->mainLoginForm( $this->msg( $error )->text() );
990 case self
::WRONG_PLUGIN_PASS
:
991 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
992 $this->mainLoginForm( $this->msg( $error )->text() );
994 case self
::NOT_EXISTS
:
995 if ( $this->getUser()->isAllowed( 'createaccount' ) ) {
996 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchuser';
997 $this->mainLoginForm( $this->msg( $error,
998 wfEscapeWikiText( $this->mUsername
) )->parse() );
1000 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchusershort';
1001 $this->mainLoginForm( $this->msg( $error,
1002 wfEscapeWikiText( $this->mUsername
) )->text() );
1005 case self
::WRONG_PASS
:
1006 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
1007 $this->mainLoginForm( $this->msg( $error )->text() );
1009 case self
::EMPTY_PASS
:
1010 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpasswordempty';
1011 $this->mainLoginForm( $this->msg( $error )->text() );
1013 case self
::RESET_PASS
:
1014 $error = $this->mAbortLoginErrorMsg ?
: 'resetpass_announce';
1015 $this->resetLoginForm( $this->msg( $error ) );
1017 case self
::CREATE_BLOCKED
:
1018 $this->userBlockedMessage( $this->getUser()->isBlockedFromCreateAccount() );
1020 case self
::THROTTLED
:
1021 $error = $this->mAbortLoginErrorMsg ?
: 'login-throttled';
1022 $this->mainLoginForm( $this->msg( $error )
1023 ->params( $this->getLanguage()->formatDuration( $wgPasswordAttemptThrottle['seconds'] ) )
1027 case self
::USER_BLOCKED
:
1028 $error = $this->mAbortLoginErrorMsg ?
: 'login-userblocked';
1029 $this->mainLoginForm( $this->msg( $error, $this->mUsername
)->escaped() );
1032 $error = $this->mAbortLoginErrorMsg ?
: 'login-abort-generic';
1033 $this->mainLoginForm( $this->msg( $error,
1034 wfEscapeWikiText( $this->mUsername
) )->text() );
1036 case self
::USER_MIGRATED
:
1037 $error = $this->mAbortLoginErrorMsg ?
: 'login-migrated-generic';
1039 if ( is_array( $error ) ) {
1040 $error = array_shift( $this->mAbortLoginErrorMsg
);
1041 $params = $this->mAbortLoginErrorMsg
;
1043 $this->mainLoginForm( $this->msg( $error, $params )->text() );
1046 throw new MWException( 'Unhandled case value' );
1049 LoggerFactory
::getInstance( 'authmanager' )->info( 'Login attempt', array(
1051 'successful' => $status === self
::SUCCESS
,
1052 'status' => $status,
1057 * Show the Special:ChangePassword form, with custom message
1058 * @param Message $msg
1060 protected function resetLoginForm( Message
$msg ) {
1061 // Allow hooks to explain this password reset in more detail
1062 Hooks
::run( 'LoginPasswordResetMessage', array( &$msg, $this->mUsername
) );
1063 $reset = new SpecialChangePassword();
1064 $derivative = new DerivativeContext( $this->getContext() );
1065 $derivative->setTitle( $reset->getPageTitle() );
1066 $reset->setContext( $derivative );
1067 if ( !$this->mTempPasswordUsed
) {
1068 $reset->setOldPasswordMessage( 'oldpassword' );
1070 $reset->setChangeMessage( $msg );
1071 $reset->execute( null );
1076 * @param bool $throttle
1077 * @param string $emailTitle Message name of email title
1078 * @param string $emailText Message name of email text
1081 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle',
1082 $emailText = 'passwordremindertext'
1084 global $wgNewPasswordExpiry;
1086 if ( $u->getEmail() == '' ) {
1087 return Status
::newFatal( 'noemail', $u->getName() );
1089 $ip = $this->getRequest()->getIP();
1091 return Status
::newFatal( 'badipaddress' );
1094 $currentUser = $this->getUser();
1095 Hooks
::run( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
1097 $np = $u->randomPassword();
1098 $u->setNewpassword( $np, $throttle );
1100 $userLanguage = $u->getOption( 'language' );
1102 $mainPage = Title
::newMainPage();
1103 $mainPageUrl = $mainPage->getCanonicalURL();
1105 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $mainPageUrl . '>',
1106 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
1107 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
1113 * Run any hooks registered for logins, then HTTP redirect to
1114 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
1115 * nice message here, but that's really not as useful as just being sent to
1116 * wherever you logged in from. It should be clear that the action was
1117 * successful, given the lack of error messages plus the appearance of your
1118 * name in the upper right.
1122 function successfulLogin() {
1123 # Run any hooks; display injected HTML if any, else redirect
1124 $currentUser = $this->getUser();
1125 $injected_html = '';
1126 Hooks
::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1128 if ( $injected_html !== '' ) {
1129 $this->displaySuccessfulAction( 'success', $this->msg( 'loginsuccesstitle' ),
1130 'loginsuccess', $injected_html );
1132 $this->executeReturnTo( 'successredirect' );
1137 * Run any hooks registered for logins, then display a message welcoming
1142 function successfulCreation() {
1143 # Run any hooks; display injected HTML
1144 $currentUser = $this->getUser();
1145 $injected_html = '';
1146 $welcome_creation_msg = 'welcomecreation-msg';
1148 Hooks
::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1151 * Let any extensions change what message is shown.
1152 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
1155 Hooks
::run( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
1157 $this->displaySuccessfulAction(
1159 $this->msg( 'welcomeuser', $this->getUser()->getName() ),
1160 $welcome_creation_msg, $injected_html
1165 * Display a "successful action" page.
1167 * @param string $type Condition of return to; see `executeReturnTo`
1168 * @param string|Message $title Page's title
1169 * @param string $msgname
1170 * @param string $injected_html
1172 private function displaySuccessfulAction( $type, $title, $msgname, $injected_html ) {
1173 $out = $this->getOutput();
1174 $out->setPageTitle( $title );
1176 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
1179 $out->addHTML( $injected_html );
1181 $this->executeReturnTo( $type );
1185 * Output a message that informs the user that they cannot create an account because
1186 * there is a block on them or their IP which prevents account creation. Note that
1187 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
1188 * setting on blocks (bug 13611).
1189 * @param Block $block The block causing this error
1190 * @throws ErrorPageError
1192 function userBlockedMessage( Block
$block ) {
1193 # Let's be nice about this, it's likely that this feature will be used
1194 # for blocking large numbers of innocent people, e.g. range blocks on
1195 # schools. Don't blame it on the user. There's a small chance that it
1196 # really is the user's fault, i.e. the username is blocked and they
1197 # haven't bothered to log out before trying to create an account to
1198 # evade it, but we'll leave that to their guilty conscience to figure
1200 $errorParams = array(
1201 $block->getTarget(),
1202 $block->mReason ?
$block->mReason
: $this->msg( 'blockednoreason' )->text(),
1206 if ( $block->getType() === Block
::TYPE_RANGE
) {
1207 $errorMessage = 'cantcreateaccount-range-text';
1208 $errorParams[] = $this->getRequest()->getIP();
1210 $errorMessage = 'cantcreateaccount-text';
1213 throw new ErrorPageError(
1214 'cantcreateaccounttitle',
1221 * Add a "return to" link or redirect to it.
1222 * Extensions can use this to reuse the "return to" logic after
1223 * inject steps (such as redirection) into the login process.
1225 * @param string $type One of the following:
1226 * - error: display a return to link ignoring $wgRedirectOnLogin
1227 * - signup: display a return to link using $wgRedirectOnLogin if needed
1228 * - success: display a return to link using $wgRedirectOnLogin if needed
1229 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1230 * @param string $returnTo
1231 * @param array|string $returnToQuery
1232 * @param bool $stickHTTPs Keep redirect link on HTTPs
1235 public function showReturnToPage(
1236 $type, $returnTo = '', $returnToQuery = '', $stickHTTPs = false
1238 $this->mReturnTo
= $returnTo;
1239 $this->mReturnToQuery
= $returnToQuery;
1240 $this->mStickHTTPS
= $stickHTTPs;
1241 $this->executeReturnTo( $type );
1245 * Add a "return to" link or redirect to it.
1247 * @param string $type One of the following:
1248 * - error: display a return to link ignoring $wgRedirectOnLogin
1249 * - signup: display a return to link using $wgRedirectOnLogin if needed
1250 * - success: display a return to link using $wgRedirectOnLogin if needed
1251 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1253 private function executeReturnTo( $type ) {
1254 global $wgRedirectOnLogin, $wgSecureLogin;
1256 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
1257 $returnTo = $wgRedirectOnLogin;
1258 $returnToQuery = array();
1260 $returnTo = $this->mReturnTo
;
1261 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
1264 // Allow modification of redirect behavior
1265 Hooks
::run( 'PostLoginRedirect', array( &$returnTo, &$returnToQuery, &$type ) );
1267 $returnToTitle = Title
::newFromText( $returnTo );
1268 if ( !$returnToTitle ) {
1269 $returnToTitle = Title
::newMainPage();
1272 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1273 $options = array( 'http' );
1274 $proto = PROTO_HTTP
;
1275 } elseif ( $wgSecureLogin ) {
1276 $options = array( 'https' );
1277 $proto = PROTO_HTTPS
;
1280 $proto = PROTO_RELATIVE
;
1283 if ( $type == 'successredirect' ) {
1284 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1285 $this->getOutput()->redirect( $redirectUrl );
1287 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1292 * @param string $msg
1293 * @param string $msgtype
1294 * @throws ErrorPageError
1296 * @throws FatalError
1297 * @throws MWException
1298 * @throws PermissionsError
1299 * @throws ReadOnlyError
1302 function mainLoginForm( $msg, $msgtype = 'error' ) {
1303 global $wgEnableEmail, $wgEnableUserEmail;
1304 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1305 global $wgAuth, $wgEmailConfirmToEdit;
1306 global $wgSecureLogin, $wgPasswordResetRoutes;
1307 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
1309 $titleObj = $this->getPageTitle();
1310 $user = $this->getUser();
1311 $out = $this->getOutput();
1313 if ( $this->mType
== 'signup' ) {
1314 // Block signup here if in readonly. Keeps user from
1315 // going through the process (filling out data, etc)
1316 // and being informed later.
1317 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1318 if ( count( $permErrors ) ) {
1319 throw new PermissionsError( 'createaccount', $permErrors );
1320 } elseif ( $user->isBlockedFromCreateAccount() ) {
1321 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1324 } elseif ( wfReadOnly() ) {
1325 throw new ReadOnlyError
;
1329 // Pre-fill username (if not creating an account, bug 44775).
1330 if ( $this->mUsername
== '' && $this->mType
!= 'signup' ) {
1331 if ( $user->isLoggedIn() ) {
1332 $this->mUsername
= $user->getName();
1334 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1338 // Generic styles and scripts for both login and signup form
1339 $out->addModuleStyles( array(
1341 'mediawiki.ui.button',
1342 'mediawiki.ui.checkbox',
1343 'mediawiki.ui.input',
1344 'mediawiki.special.userlogin.common.styles'
1346 $out->addModules( array(
1347 'mediawiki.special.userlogin.common.js'
1350 if ( $this->mType
== 'signup' ) {
1351 // XXX hack pending RL or JS parse() support for complex content messages
1352 // https://bugzilla.wikimedia.org/show_bug.cgi?id=25349
1353 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
1354 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
1356 // Additional styles and scripts for signup form
1357 $out->addModules( array(
1358 'mediawiki.special.userlogin.signup.js'
1360 $out->addModuleStyles( array(
1361 'mediawiki.special.userlogin.signup.styles'
1364 $template = new UsercreateTemplate( $this->getConfig() );
1366 // Must match number of benefits defined in messages
1367 $template->set( 'benefitCount', 3 );
1369 $q = 'action=submitlogin&type=signup';
1370 $linkq = 'type=login';
1372 // Additional styles for login form
1373 $out->addModuleStyles( array(
1374 'mediawiki.special.userlogin.login.styles'
1377 $template = new UserloginTemplate( $this->getConfig() );
1379 $q = 'action=submitlogin&type=login';
1380 $linkq = 'type=signup';
1383 if ( $this->mReturnTo
!== '' ) {
1384 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1385 if ( $this->mReturnToQuery
!== '' ) {
1386 $returnto .= '&returntoquery=' .
1387 wfUrlencode( $this->mReturnToQuery
);
1390 $linkq .= $returnto;
1393 # Don't show a "create account" link if the user can't.
1394 if ( $this->showCreateOrLoginLink( $user ) ) {
1395 # Pass any language selection on to the mode switch link
1396 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
1397 $linkq .= '&uselang=' . $this->mLanguage
;
1399 // Supply URL, login template creates the button.
1400 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1402 $template->set( 'link', '' );
1405 $resetLink = $this->mType
== 'signup'
1407 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1409 $template->set( 'header', '' );
1410 $template->set( 'formheader', '' );
1411 $template->set( 'skin', $this->getSkin() );
1412 $template->set( 'name', $this->mUsername
);
1413 $template->set( 'password', $this->mPassword
);
1414 $template->set( 'retype', $this->mRetype
);
1415 $template->set( 'createemailset', $this->mCreateaccountMail
);
1416 $template->set( 'email', $this->mEmail
);
1417 $template->set( 'realname', $this->mRealName
);
1418 $template->set( 'domain', $this->mDomain
);
1419 $template->set( 'reason', $this->mReason
);
1421 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1422 $template->set( 'message', $msg );
1423 $template->set( 'messagetype', $msgtype );
1424 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1425 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1426 $template->set( 'useemail', $wgEnableEmail );
1427 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1428 $template->set( 'emailothers', $wgEnableUserEmail );
1429 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1430 $template->set( 'resetlink', $resetLink );
1431 $template->set( 'canremember', $wgExtendedLoginCookieExpiration === null ?
( $wgCookieExpiration > 0 ) : ( $wgExtendedLoginCookieExpiration > 0 ) );
1432 $template->set( 'usereason', $user->isLoggedIn() );
1433 $template->set( 'remember', $this->mRemember
);
1434 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1435 $template->set( 'stickhttps', (int)$this->mStickHTTPS
);
1436 $template->set( 'loggedin', $user->isLoggedIn() );
1437 $template->set( 'loggedinuser', $user->getName() );
1439 if ( $this->mType
== 'signup' ) {
1440 if ( !self
::getCreateaccountToken() ) {
1441 self
::setCreateaccountToken();
1443 $template->set( 'token', self
::getCreateaccountToken() );
1445 if ( !self
::getLoginToken() ) {
1446 self
::setLoginToken();
1448 $template->set( 'token', self
::getLoginToken() );
1451 # Prepare language selection links as needed
1452 if ( $wgLoginLanguageSelector ) {
1453 $template->set( 'languages', $this->makeLanguageSelector() );
1454 if ( $this->mLanguage
) {
1455 $template->set( 'uselang', $this->mLanguage
);
1459 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl
);
1460 // Use signupend-https for HTTPS requests if it's not blank, signupend otherwise
1461 $usingHTTPS = $this->mRequest
->getProtocol() == 'https';
1462 $signupendHTTPS = $this->msg( 'signupend-https' );
1463 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1464 $template->set( 'signupend', $signupendHTTPS->parse() );
1466 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1469 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
1470 if ( $usingHTTPS ) {
1471 $template->set( 'fromhttp', $this->mFromHTTP
);
1474 // Give authentication and captcha plugins a chance to modify the form
1475 $wgAuth->modifyUITemplate( $template, $this->mType
);
1476 if ( $this->mType
== 'signup' ) {
1477 Hooks
::run( 'UserCreateForm', array( &$template ) );
1479 Hooks
::run( 'UserLoginForm', array( &$template ) );
1482 $out->disallowUserJs(); // just in case...
1483 $out->addTemplate( $template );
1487 * Whether the login/create account form should display a link to the
1488 * other form (in addition to whatever the skin provides).
1493 private function showCreateOrLoginLink( &$user ) {
1494 if ( $this->mType
== 'signup' ) {
1496 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1504 * Check if a session cookie is present.
1506 * This will not pick up a cookie set during _this_ request, but is meant
1507 * to ensure that the client is returning the cookie which was set on a
1508 * previous pass through the system.
1513 function hasSessionCookie() {
1514 global $wgDisableCookieCheck;
1516 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1520 * Get the login token from the current session
1523 public static function getLoginToken() {
1526 return $wgRequest->getSessionData( 'wsLoginToken' );
1530 * Randomly generate a new login token and attach it to the current session
1532 public static function setLoginToken() {
1534 // Generate a token directly instead of using $user->getEditToken()
1535 // because the latter reuses $_SESSION['wsEditToken']
1536 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1540 * Remove any login token attached to the current session
1542 public static function clearLoginToken() {
1544 $wgRequest->setSessionData( 'wsLoginToken', null );
1548 * Get the createaccount token from the current session
1551 public static function getCreateaccountToken() {
1553 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1557 * Randomly generate a new createaccount token and attach it to the current session
1559 public static function setCreateaccountToken() {
1561 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1565 * Remove any createaccount token attached to the current session
1567 public static function clearCreateaccountToken() {
1569 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1573 * Renew the user's session id, using strong entropy
1575 private function renewSessionId() {
1576 global $wgSecureLogin, $wgCookieSecure;
1577 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1578 $wgCookieSecure = false;
1585 * @param string $type
1588 function cookieRedirectCheck( $type ) {
1589 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1590 $query = array( 'wpCookieCheck' => $type );
1591 if ( $this->mReturnTo
!== '' ) {
1592 $query['returnto'] = $this->mReturnTo
;
1593 $query['returntoquery'] = $this->mReturnToQuery
;
1595 $check = $titleObj->getFullURL( $query );
1597 $this->getOutput()->redirect( $check );
1601 * @param string $type
1604 function onCookieRedirectCheck( $type ) {
1605 if ( !$this->hasSessionCookie() ) {
1606 if ( $type == 'new' ) {
1607 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1608 } elseif ( $type == 'login' ) {
1609 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1612 $this->mainLoginForm( $this->msg( 'error' )->text() );
1615 $this->successfulLogin();
1620 * Produce a bar of links which allow the user to select another language
1621 * during login/registration but retain "returnto"
1625 function makeLanguageSelector() {
1626 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1627 if ( $msg->isBlank() ) {
1630 $langs = explode( "\n", $msg->text() );
1632 foreach ( $langs as $lang ) {
1633 $lang = trim( $lang, '* ' );
1634 $parts = explode( '|', $lang );
1635 if ( count( $parts ) >= 2 ) {
1636 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1640 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1641 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1645 * Create a language selector link for a particular language
1646 * Links back to this page preserving type and returnto
1648 * @param string $text Link text
1649 * @param string $lang Language code
1652 function makeLanguageSelectorLink( $text, $lang ) {
1653 if ( $this->getLanguage()->getCode() == $lang ) {
1654 // no link for currently used language
1655 return htmlspecialchars( $text );
1657 $query = array( 'uselang' => $lang );
1658 if ( $this->mType
== 'signup' ) {
1659 $query['type'] = 'signup';
1661 if ( $this->mReturnTo
!== '' ) {
1662 $query['returnto'] = $this->mReturnTo
;
1663 $query['returntoquery'] = $this->mReturnToQuery
;
1667 $targetLanguage = Language
::factory( $lang );
1668 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1670 return Linker
::linkKnown(
1671 $this->getPageTitle(),
1672 htmlspecialchars( $text ),
1678 protected function getGroupName() {