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;
47 public static $statusCodes = array(
48 self
::SUCCESS
=> 'success',
49 self
::NO_NAME
=> 'no_name',
50 self
::ILLEGAL
=> 'illegal',
51 self
::WRONG_PLUGIN_PASS
=> 'wrong_plugin_pass',
52 self
::NOT_EXISTS
=> 'not_exists',
53 self
::WRONG_PASS
=> 'wrong_pass',
54 self
::EMPTY_PASS
=> 'empty_pass',
55 self
::RESET_PASS
=> 'reset_pass',
56 self
::ABORTED
=> 'aborted',
57 self
::CREATE_BLOCKED
=> 'create_blocked',
58 self
::THROTTLED
=> 'throttled',
59 self
::USER_BLOCKED
=> 'user_blocked',
60 self
::NEED_TOKEN
=> 'need_token',
61 self
::WRONG_TOKEN
=> 'wrong_token',
62 self
::USER_MIGRATED
=> 'user_migrated',
66 * Valid error and warning messages
68 * Special:Userlogin can show an error or warning message on the form when
69 * coming from another page. This is done via the ?error= or ?warning= GET
72 * This array is the list of valid message keys. All other values will be
78 public static $validErrorMessages = array(
79 'exception-nologin-text',
81 'changeemail-no-info',
83 'confirmemail_needlogin',
87 public $mAbortLoginErrorMsg = null;
93 protected $mCookieCheck;
96 protected $mCreateaccount;
97 protected $mCreateaccountMail;
98 protected $mLoginattempt;
102 protected $mLanguage;
103 protected $mSkipCookieCheck;
104 protected $mReturnToQuery;
106 protected $mStickHTTPS;
109 protected $mRealName;
110 protected $mEntryError = '';
111 protected $mEntryErrorType = 'error';
113 private $mTempPasswordUsed;
114 private $mLoaded = false;
115 private $mSecureLoginUrl;
117 /** @var WebRequest */
118 private $mOverrideRequest = null;
120 /** @var WebRequest Effective request; set at the beginning of load */
121 private $mRequest = null;
124 * @param WebRequest $request
126 public function __construct( $request = null ) {
127 global $wgUseMediaWikiUIEverywhere;
128 parent
::__construct( 'Userlogin' );
130 $this->mOverrideRequest
= $request;
131 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
132 $wgUseMediaWikiUIEverywhere = true;
136 * Returns an array of all valid error messages.
140 public static function getValidErrorMessages() {
141 static $messages = null;
143 $messages = self
::$validErrorMessages;
144 Hooks
::run( 'LoginFormValidErrorMessages', array( &$messages ) );
154 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
156 if ( $this->mLoaded
) {
159 $this->mLoaded
= true;
161 if ( $this->mOverrideRequest
=== null ) {
162 $request = $this->getRequest();
164 $request = $this->mOverrideRequest
;
166 $this->mRequest
= $request;
168 $this->mType
= $request->getText( 'type' );
169 $this->mUsername
= $request->getText( 'wpName' );
170 $this->mPassword
= $request->getText( 'wpPassword' );
171 $this->mRetype
= $request->getText( 'wpRetype' );
172 $this->mDomain
= $request->getText( 'wpDomain' );
173 $this->mReason
= $request->getText( 'wpReason' );
174 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
175 $this->mPosted
= $request->wasPosted();
176 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
178 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' ) && !$this->mCreateaccountMail
;
179 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
180 $this->mAction
= $request->getVal( 'action' );
181 $this->mRemember
= $request->getCheck( 'wpRemember' );
182 $this->mFromHTTP
= $request->getBool( 'fromhttp', false )
183 ||
$request->getBool( 'wpFromhttp', false );
184 $this->mStickHTTPS
= ( !$this->mFromHTTP
&& $request->getProtocol() === 'https' )
185 ||
$request->getBool( 'wpForceHttps', false );
186 $this->mLanguage
= $request->getText( 'uselang' );
187 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
188 $this->mToken
= $this->mType
== 'signup'
189 ?
$request->getVal( 'wpCreateaccountToken' )
190 : $request->getVal( 'wpLoginToken' );
191 $this->mReturnTo
= $request->getVal( 'returnto', '' );
192 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
194 // Show an error or warning passed on from a previous page
195 $entryError = $this->msg( $request->getVal( 'error', '' ) );
196 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
197 // bc: provide login link as a parameter for messages where the translation
199 $loginreqlink = Linker
::linkKnown(
200 $this->getPageTitle(),
201 $this->msg( 'loginreqlink' )->escaped(),
204 'returnto' => $this->mReturnTo
,
205 'returntoquery' => $this->mReturnToQuery
,
206 'uselang' => $this->mLanguage
,
207 'fromhttp' => $this->mFromHTTP ?
'1' : '0',
211 // Only show valid error or warning messages.
212 if ( $entryError->exists()
213 && in_array( $entryError->getKey(), self
::getValidErrorMessages() )
215 $this->mEntryErrorType
= 'error';
216 $this->mEntryError
= $entryError->rawParams( $loginreqlink )->parse();
218 } elseif ( $entryWarning->exists()
219 && in_array( $entryWarning->getKey(), self
::getValidErrorMessages() )
221 $this->mEntryErrorType
= 'warning';
222 $this->mEntryError
= $entryWarning->rawParams( $loginreqlink )->parse();
225 if ( $wgEnableEmail ) {
226 $this->mEmail
= $request->getText( 'wpEmail' );
230 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
231 $this->mRealName
= $request->getText( 'wpRealName' );
233 $this->mRealName
= '';
236 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
237 $this->mDomain
= $wgAuth->getDomain();
239 $wgAuth->setDomain( $this->mDomain
);
241 # 1. When switching accounts, it sucks to get automatically logged out
242 # 2. Do not return to PasswordReset after a successful password change
243 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
244 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
245 if ( is_object( $returnToTitle )
246 && ( $returnToTitle->isSpecial( 'Userlogout' )
247 ||
$returnToTitle->isSpecial( 'PasswordReset' ) )
249 $this->mReturnTo
= '';
250 $this->mReturnToQuery
= '';
254 function getDescription() {
255 if ( $this->mType
=== 'signup' ) {
256 return $this->msg( 'createaccount' )->text();
258 return $this->msg( 'login' )->text();
263 * @param string|null $subPage
265 public function execute( $subPage ) {
266 if ( session_id() == '' ) {
272 // Check for [[Special:Userlogin/signup]]. This affects form display and
274 if ( $subPage == 'signup' ) {
275 $this->mType
= 'signup';
279 // In the case where the user is already logged in, and was redirected to the login form from a
280 // page that requires login, do not show the login page. The use case scenario for this is when
281 // a user opens a large number of tabs, is redirected to the login page on all of them, and then
282 // logs in on one, expecting all the others to work properly.
284 // However, do show the form if it was visited intentionally (no 'returnto' is present). People
285 // who often switch between several accounts have grown accustomed to this behavior.
287 $this->mType
!== 'signup' &&
289 $this->getUser()->isLoggedIn() &&
290 ( $this->mReturnTo
!== '' ||
$this->mReturnToQuery
!== '' )
292 $this->successfulLogin();
295 // If logging in and not on HTTPS, either redirect to it or offer a link.
296 global $wgSecureLogin;
297 if ( $this->mRequest
->getProtocol() !== 'https' ) {
298 $title = $this->getFullTitle();
300 'returnto' => $this->mReturnTo
!== '' ?
$this->mReturnTo
: null,
301 'returntoquery' => $this->mReturnToQuery
!== '' ?
302 $this->mReturnToQuery
: null,
304 ( $this->mEntryErrorType
=== 'error' ?
'error' : 'warning' ) => $this->mEntryError
,
305 ) +
$this->mRequest
->getQueryValues();
306 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
308 && wfCanIPUseHTTPS( $this->getRequest()->getIP() )
309 && !$this->mFromHTTP
) // Avoid infinite redirect
311 $url = wfAppendQuery( $url, 'fromhttp=1' );
312 $this->getOutput()->redirect( $url );
313 // Since we only do this redir to change proto, always vary
314 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
318 // A wiki without HTTPS login support should set $wgServer to
319 // http://somehost, in which case the secure URL generated
320 // above won't actually start with https://
321 if ( substr( $url, 0, 8 ) === 'https://' ) {
322 $this->mSecureLoginUrl
= $url;
327 if ( !is_null( $this->mCookieCheck
) ) {
328 $this->onCookieRedirectCheck( $this->mCookieCheck
);
331 } elseif ( $this->mPosted
) {
332 if ( $this->mCreateaccount
) {
333 $this->addNewAccount();
336 } elseif ( $this->mCreateaccountMail
) {
337 $this->addNewAccountMailPassword();
340 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
341 $this->processLogin();
346 $this->mainLoginForm( $this->mEntryError
, $this->mEntryErrorType
);
352 function addNewAccountMailPassword() {
353 if ( $this->mEmail
== '' ) {
354 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
359 $status = $this->addNewAccountInternal();
360 LoggerFactory
::getInstance( 'authmanager' )->info( 'Account creation attempt with mailed password', array(
361 'event' => 'accountcreation',
364 if ( !$status->isGood() ) {
365 $error = $status->getMessage();
366 $this->mainLoginForm( $error->toString() );
371 $u = $status->getValue();
373 // Wipe the initial password and mail a temporary one
374 $u->setPassword( null );
376 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
378 Hooks
::run( 'AddNewAccount', array( $u, true ) );
379 $u->addNewUserLogEntry( 'byemail', $this->mReason
);
381 $out = $this->getOutput();
382 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
384 if ( !$result->isGood() ) {
385 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
387 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
388 $this->executeReturnTo( 'success' );
396 function addNewAccount() {
397 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
399 # Create the account and abort if there's a problem doing so
400 $status = $this->addNewAccountInternal();
401 LoggerFactory
::getInstance( 'authmanager' )->info( 'Account creation attempt', array(
402 'event' => 'accountcreation',
406 if ( !$status->isGood() ) {
407 $error = $status->getMessage();
408 $this->mainLoginForm( $error->toString() );
413 $u = $status->getValue();
415 # Only save preferences if the user is not creating an account for someone else.
416 if ( $this->getUser()->isAnon() ) {
417 # If we showed up language selection links, and one was in use, be
418 # smart (and sensible) and save that language as the user's preference
419 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
420 $u->setOption( 'language', $this->mLanguage
);
423 # Otherwise the user's language preference defaults to $wgContLang,
424 # but it may be better to set it to their preferred $wgContLang variant,
425 # based on browser preferences or URL parameters.
426 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
428 if ( $wgContLang->hasVariants() ) {
429 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
433 $out = $this->getOutput();
435 # Send out an email authentication message if needed
436 if ( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
437 $status = $u->sendConfirmationMail();
438 if ( $status->isGood() ) {
439 $out->addWikiMsg( 'confirmemail_oncreate' );
441 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
445 # Save settings (including confirmation token)
448 # If not logged in, assume the new account as the current one and set
449 # session cookies then show a "welcome" message or a "need cookies"
451 if ( $this->getUser()->isAnon() ) {
454 // This should set it for OutputPage and the Skin
455 // which is needed or the personal links will be
457 $this->getContext()->setUser( $u );
458 Hooks
::run( 'AddNewAccount', array( $u, false ) );
459 $u->addNewUserLogEntry( 'create' );
460 if ( $this->hasSessionCookie() ) {
461 $this->successfulCreation();
463 $this->cookieRedirectCheck( 'new' );
466 # Confirm that the account was created
467 $out->setPageTitle( $this->msg( 'accountcreated' ) );
468 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
469 $out->addReturnTo( $this->getPageTitle() );
470 Hooks
::run( 'AddNewAccount', array( $u, false ) );
471 $u->addNewUserLogEntry( 'create2', $this->mReason
);
478 * Make a new user account using the loaded data.
480 * @throws PermissionsError|ReadOnlyError
483 public function addNewAccountInternal() {
484 global $wgAuth, $wgMemc, $wgAccountCreationThrottle, $wgEmailConfirmToEdit;
486 // If the user passes an invalid domain, something is fishy
487 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
488 return Status
::newFatal( 'wrongpassword' );
491 // If we are not allowing users to login locally, we should be checking
492 // to see if the user is actually able to authenticate to the authenti-
493 // cation server before they create an account (otherwise, they can
494 // create a local account and login as any domain user). We only need
495 // to check this for domains that aren't local.
496 if ( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
498 !$wgAuth->canCreateAccounts() &&
500 !$wgAuth->userExists( $this->mUsername
) ||
501 !$wgAuth->authenticate( $this->mUsername
, $this->mPassword
)
504 return Status
::newFatal( 'wrongpassword' );
508 if ( wfReadOnly() ) {
509 throw new ReadOnlyError
;
512 # Request forgery checks.
513 if ( !self
::getCreateaccountToken() ) {
514 self
::setCreateaccountToken();
516 return Status
::newFatal( 'nocookiesfornew' );
519 # The user didn't pass a createaccount token
520 if ( !$this->mToken
) {
521 return Status
::newFatal( 'sessionfailure' );
524 # Validate the createaccount token
525 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
526 return Status
::newFatal( 'sessionfailure' );
530 $currentUser = $this->getUser();
531 $creationBlock = $currentUser->isBlockedFromCreateAccount();
532 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
533 throw new PermissionsError( 'createaccount' );
534 } elseif ( $creationBlock instanceof Block
) {
535 // Throws an ErrorPageError.
536 $this->userBlockedMessage( $creationBlock );
538 // This should never be reached.
542 # Include checks that will include GlobalBlocking (Bug 38333)
543 $permErrors = $this->getPageTitle()->getUserPermissionsErrors(
549 if ( count( $permErrors ) ) {
550 throw new PermissionsError( 'createaccount', $permErrors );
553 $ip = $this->getRequest()->getIP();
554 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
555 return Status
::newFatal( 'sorbs_create_account_reason' );
558 # Now create a dummy user ($u) and check if it is valid
559 $u = User
::newFromName( $this->mUsername
, 'creatable' );
561 return Status
::newFatal( 'noname' );
564 # Make sure the user does not exist already
565 $lock = $wgMemc->getScopedLock( wfGlobalCacheKey( 'account', md5( $this->mUsername
) ) );
567 return Status
::newFatal( 'usernameinprogress' );
568 } elseif ( $u->idForName( User
::READ_LOCKING
) ) {
569 return Status
::newFatal( 'userexists' );
572 if ( $this->mCreateaccountMail
) {
573 # do not force a password for account creation by email
574 # set invalid password, it will be replaced later by a random generated password
575 $this->mPassword
= null;
577 if ( $this->mPassword
!== $this->mRetype
) {
578 return Status
::newFatal( 'badretype' );
581 # check for password validity, return a fatal Status if invalid
582 $validity = $u->checkPasswordValidity( $this->mPassword
, 'create' );
583 if ( !$validity->isGood() ) {
584 $validity->ok
= false; // make sure this Status is fatal
589 # if you need a confirmed email address to edit, then obviously you
590 # need an email address.
591 if ( $wgEmailConfirmToEdit && strval( $this->mEmail
) === '' ) {
592 return Status
::newFatal( 'noemailtitle' );
595 if ( strval( $this->mEmail
) !== '' && !Sanitizer
::validateEmail( $this->mEmail
) ) {
596 return Status
::newFatal( 'invalidemailaddress' );
599 # Set some additional data so the AbortNewAccount hook can be used for
600 # more than just username validation
601 $u->setEmail( $this->mEmail
);
602 $u->setRealName( $this->mRealName
);
606 if ( !Hooks
::run( 'AbortNewAccount', array( $u, &$abortError, &$abortStatus ) ) ) {
607 // Hook point to add extra creation throttles and blocks
608 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
609 if ( $abortStatus === null ) {
610 // Report back the old string as a raw message status.
611 // This will report the error back as 'createaccount-hook-aborted'
612 // with the given string as the message.
613 // To return a different error code, return a Status object.
614 $abortError = new Message( 'createaccount-hook-aborted', array( $abortError ) );
617 return Status
::newFatal( $abortError );
619 // For MediaWiki 1.23+ and updated hooks, return the Status object
620 // returned from the hook.
625 // Hook point to check for exempt from account creation throttle
626 if ( !Hooks
::run( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
627 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook " .
628 "allowed account creation w/o throttle\n" );
630 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
631 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
632 $value = $wgMemc->get( $key );
634 $wgMemc->set( $key, 0, 86400 );
636 if ( $value >= $wgAccountCreationThrottle ) {
637 return Status
::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
639 $wgMemc->incr( $key );
643 if ( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
644 return Status
::newFatal( 'externaldberror' );
647 self
::clearCreateaccountToken();
649 return $this->initUser( $u, false );
653 * Actually add a user to the database.
654 * Give it a User object that has been initialised with a name.
657 * @param bool $autocreate True if this is an autocreation via auth plugin
658 * @return Status Status object, with the User object in the value member on success
661 function initUser( $u, $autocreate ) {
664 $status = $u->addToDatabase();
665 if ( !$status->isOK() ) {
669 if ( $wgAuth->allowPasswordChange() ) {
670 $u->setPassword( $this->mPassword
);
673 $u->setEmail( $this->mEmail
);
674 $u->setRealName( $this->mRealName
);
677 Hooks
::run( 'LocalUserCreated', array( $u, $autocreate ) );
679 $wgAuth->initUser( $u, $autocreate );
680 if ( $oldUser !== $u ) {
681 wfWarn( get_class( $wgAuth ) . '::initUser() replaced the user object' );
687 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
689 // Watch user's userpage and talk page
690 $u->addWatch( $u->getUserPage(), WatchedItem
::IGNORE_USER_RIGHTS
);
692 return Status
::newGood( $u );
696 * Internally authenticate the login request.
698 * This may create a local account as a side effect if the
699 * authentication plugin allows transparent local account
703 public function authenticateUserData() {
704 global $wgUser, $wgAuth;
708 if ( $this->mUsername
== '' ) {
709 return self
::NO_NAME
;
712 // We require a login token to prevent login CSRF
713 // Handle part of this before incrementing the throttle so
714 // token-less login attempts don't count towards the throttle
715 // but wrong-token attempts do.
717 // If the user doesn't have a login token yet, set one.
718 if ( !self
::getLoginToken() ) {
719 self
::setLoginToken();
721 return self
::NEED_TOKEN
;
723 // If the user didn't pass a login token, tell them we need one
724 if ( !$this->mToken
) {
725 return self
::NEED_TOKEN
;
728 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
729 if ( $throttleCount === true ) {
730 return self
::THROTTLED
;
733 // Validate the login token
734 if ( $this->mToken
!== self
::getLoginToken() ) {
735 return self
::WRONG_TOKEN
;
738 // Load the current user now, and check to see if we're logging in as
739 // the same name. This is necessary because loading the current user
740 // (say by calling getName()) calls the UserLoadFromSession hook, which
741 // potentially creates the user in the database. Until we load $wgUser,
742 // checking for user existence using User::newFromName($name)->getId() below
743 // will effectively be using stale data.
744 if ( $this->getUser()->getName() === $this->mUsername
) {
745 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
747 return self
::SUCCESS
;
750 $u = User
::newFromName( $this->mUsername
);
751 if ( $u === false ) {
752 return self
::ILLEGAL
;
756 // Give extensions a way to indicate the username has been updated,
757 // rather than telling the user the account doesn't exist.
758 if ( !Hooks
::run( 'LoginUserMigrated', array( $u, &$msg ) ) ) {
759 $this->mAbortLoginErrorMsg
= $msg;
760 return self
::USER_MIGRATED
;
763 if ( !User
::isUsableName( $u->getName() ) ) {
764 return self
::ILLEGAL
;
767 $isAutoCreated = false;
768 if ( $u->getID() == 0 ) {
769 $status = $this->attemptAutoCreate( $u );
770 if ( $status !== self
::SUCCESS
) {
773 $isAutoCreated = true;
779 // Give general extensions, such as a captcha, a chance to abort logins
780 $abort = self
::ABORTED
;
781 if ( !Hooks
::run( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$msg ) ) ) {
782 $this->mAbortLoginErrorMsg
= $msg;
787 global $wgBlockDisablesLogin;
788 if ( !$u->checkPassword( $this->mPassword
) ) {
789 if ( $u->checkTemporaryPassword( $this->mPassword
) ) {
790 // The e-mailed temporary password should not be used for actu-
791 // al logins; that's a very sloppy habit, and insecure if an
792 // attacker has a few seconds to click "search" on someone's o-
795 // Allow it to be used only to reset the password a single time
796 // to a new value, which won't be in the user's e-mail ar-
799 // For backwards compatibility, we'll still recognize it at the
800 // login form to minimize surprises for people who have been
801 // logging in with a temporary password for some time.
803 // As a side-effect, we can authenticate the user's e-mail ad-
804 // dress if it's not already done, since the temporary password
805 // was sent via e-mail.
806 if ( !$u->isEmailConfirmed() && !wfReadOnly() ) {
811 // At this point we just return an appropriate code/ indicating
812 // that the UI should show a password reset form; bot inter-
813 // faces etc will probably just fail cleanly here.
814 $this->mAbortLoginErrorMsg
= 'resetpass-temp-emailed';
815 $this->mTempPasswordUsed
= true;
816 $retval = self
::RESET_PASS
;
818 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
820 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
821 // If we've enabled it, make it so that a blocked user cannot login
822 $retval = self
::USER_BLOCKED
;
823 } elseif ( $u->getPasswordExpired() == 'hard' ) {
824 // Force reset now, without logging in
825 $retval = self
::RESET_PASS
;
826 $this->mAbortLoginErrorMsg
= 'resetpass-expired';
828 Hooks
::run( 'UserLoggedIn', array( $u ) );
830 $wgAuth->updateUser( $u );
831 if ( $oldUser !== $u ) {
832 wfWarn( get_class( $wgAuth ) . '::updateUser() replaced the user object' );
835 // This should set it for OutputPage and the Skin
836 // which is needed or the personal links will be
838 $this->getContext()->setUser( $u );
840 // Please reset throttle for successful logins, thanks!
841 if ( $throttleCount ) {
842 self
::clearLoginThrottle( $this->mUsername
);
845 if ( $isAutoCreated ) {
846 // Must be run after $wgUser is set, for correct new user log
847 Hooks
::run( 'AuthPluginAutoCreate', array( $u ) );
850 $retval = self
::SUCCESS
;
852 Hooks
::run( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
858 * Increment the login attempt throttle hit count for the (username,current IP)
859 * tuple unless the throttle was already reached.
860 * @param string $username The user name
861 * @return bool|int The integer hit count or True if it is already at the limit
863 public static function incLoginThrottle( $username ) {
864 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
865 $username = trim( $username ); // sanity
868 if ( is_array( $wgPasswordAttemptThrottle ) ) {
869 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
870 $count = $wgPasswordAttemptThrottle['count'];
871 $period = $wgPasswordAttemptThrottle['seconds'];
873 $throttleCount = $wgMemc->get( $throttleKey );
874 if ( !$throttleCount ) {
875 $wgMemc->add( $throttleKey, 1, $period ); // start counter
876 } elseif ( $throttleCount < $count ) {
877 $wgMemc->incr( $throttleKey );
878 } elseif ( $throttleCount >= $count ) {
883 return $throttleCount;
887 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
888 * @param string $username The user name
891 public static function clearLoginThrottle( $username ) {
892 global $wgMemc, $wgRequest;
893 $username = trim( $username ); // sanity
895 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
896 $wgMemc->delete( $throttleKey );
900 * Attempt to automatically create a user on login. Only succeeds if there
901 * is an external authentication method which allows it.
905 * @return int Status code
907 function attemptAutoCreate( $user ) {
910 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
911 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
913 return self
::CREATE_BLOCKED
;
916 if ( !$wgAuth->autoCreate() ) {
917 return self
::NOT_EXISTS
;
920 if ( !$wgAuth->userExists( $user->getName() ) ) {
921 wfDebug( __METHOD__
. ": user does not exist\n" );
923 return self
::NOT_EXISTS
;
926 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
927 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
929 return self
::WRONG_PLUGIN_PASS
;
933 if ( !Hooks
::run( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
934 // Hook point to add extra creation throttles and blocks
935 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
936 $this->mAbortLoginErrorMsg
= $abortError;
938 return self
::ABORTED
;
941 wfDebug( __METHOD__
. ": creating account\n" );
942 $status = $this->initUser( $user, true );
944 if ( !$status->isOK() ) {
945 $errors = $status->getErrorsByType( 'error' );
946 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
948 return self
::ABORTED
;
951 return self
::SUCCESS
;
954 function processLogin() {
955 global $wgMemc, $wgLang, $wgSecureLogin, $wgPasswordAttemptThrottle,
956 $wgInvalidPasswordReset;
958 $authRes = $this->authenticateUserData();
959 switch ( $authRes ) {
961 # We've verified now, update the real record
962 $user = $this->getUser();
965 if ( $user->requiresHTTPS() ) {
966 $this->mStickHTTPS
= true;
969 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
970 $user->setCookies( $this->mRequest
, false, $this->mRemember
);
972 $user->setCookies( $this->mRequest
, null, $this->mRemember
);
974 self
::clearLoginToken();
976 // Reset the throttle
977 $request = $this->getRequest();
978 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
979 $wgMemc->delete( $key );
981 if ( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
982 /* Replace the language object to provide user interface in
983 * correct language immediately on this first page load.
985 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
986 $userLang = Language
::factory( $code );
988 $this->getContext()->setLanguage( $userLang );
989 // Reset SessionID on Successful login (bug 40995)
990 $this->renewSessionId();
991 if ( $this->getUser()->getPasswordExpired() == 'soft' ) {
992 $this->resetLoginForm( $this->msg( 'resetpass-expired-soft' ) );
993 } elseif ( $wgInvalidPasswordReset
994 && !$user->isValidPassword( $this->mPassword
)
996 $status = $user->checkPasswordValidity(
1000 $this->resetLoginForm(
1001 $status->getMessage( 'resetpass-validity-soft' )
1004 $this->successfulLogin();
1007 $this->cookieRedirectCheck( 'login' );
1011 case self
::NEED_TOKEN
:
1012 $error = $this->mAbortLoginErrorMsg ?
: 'nocookiesforlogin';
1013 $this->mainLoginForm( $this->msg( $error )->parse() );
1015 case self
::WRONG_TOKEN
:
1016 $error = $this->mAbortLoginErrorMsg ?
: 'sessionfailure';
1017 $this->mainLoginForm( $this->msg( $error )->text() );
1021 $error = $this->mAbortLoginErrorMsg ?
: 'noname';
1022 $this->mainLoginForm( $this->msg( $error )->text() );
1024 case self
::WRONG_PLUGIN_PASS
:
1025 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
1026 $this->mainLoginForm( $this->msg( $error )->text() );
1028 case self
::NOT_EXISTS
:
1029 if ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1030 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchuser';
1031 $this->mainLoginForm( $this->msg( $error,
1032 wfEscapeWikiText( $this->mUsername
) )->parse() );
1034 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchusershort';
1035 $this->mainLoginForm( $this->msg( $error,
1036 wfEscapeWikiText( $this->mUsername
) )->text() );
1039 case self
::WRONG_PASS
:
1040 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
1041 $this->mainLoginForm( $this->msg( $error )->text() );
1043 case self
::EMPTY_PASS
:
1044 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpasswordempty';
1045 $this->mainLoginForm( $this->msg( $error )->text() );
1047 case self
::RESET_PASS
:
1048 $error = $this->mAbortLoginErrorMsg ?
: 'resetpass_announce';
1049 $this->resetLoginForm( $this->msg( $error ) );
1051 case self
::CREATE_BLOCKED
:
1052 $this->userBlockedMessage( $this->getUser()->isBlockedFromCreateAccount() );
1054 case self
::THROTTLED
:
1055 $error = $this->mAbortLoginErrorMsg ?
: 'login-throttled';
1056 $this->mainLoginForm( $this->msg( $error )
1057 ->params( $this->getLanguage()->formatDuration( $wgPasswordAttemptThrottle['seconds'] ) )
1061 case self
::USER_BLOCKED
:
1062 $error = $this->mAbortLoginErrorMsg ?
: 'login-userblocked';
1063 $this->mainLoginForm( $this->msg( $error, $this->mUsername
)->escaped() );
1066 $error = $this->mAbortLoginErrorMsg ?
: 'login-abort-generic';
1067 $this->mainLoginForm( $this->msg( $error,
1068 wfEscapeWikiText( $this->mUsername
) )->text() );
1070 case self
::USER_MIGRATED
:
1071 $error = $this->mAbortLoginErrorMsg ?
: 'login-migrated-generic';
1073 if ( is_array( $error ) ) {
1074 $error = array_shift( $this->mAbortLoginErrorMsg
);
1075 $params = $this->mAbortLoginErrorMsg
;
1077 $this->mainLoginForm( $this->msg( $error, $params )->text() );
1080 throw new MWException( 'Unhandled case value' );
1083 LoggerFactory
::getInstance( 'authmanager' )->info( 'Login attempt', array(
1085 'successful' => $authRes === self
::SUCCESS
,
1086 'status' => LoginForm
::$statusCodes[$authRes],
1091 * Show the Special:ChangePassword form, with custom message
1092 * @param Message $msg
1094 protected function resetLoginForm( Message
$msg ) {
1095 // Allow hooks to explain this password reset in more detail
1096 Hooks
::run( 'LoginPasswordResetMessage', array( &$msg, $this->mUsername
) );
1097 $reset = new SpecialChangePassword();
1098 $derivative = new DerivativeContext( $this->getContext() );
1099 $derivative->setTitle( $reset->getPageTitle() );
1100 $reset->setContext( $derivative );
1101 if ( !$this->mTempPasswordUsed
) {
1102 $reset->setOldPasswordMessage( 'oldpassword' );
1104 $reset->setChangeMessage( $msg );
1105 $reset->execute( null );
1110 * @param bool $throttle
1111 * @param string $emailTitle Message name of email title
1112 * @param string $emailText Message name of email text
1115 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle',
1116 $emailText = 'passwordremindertext'
1118 global $wgNewPasswordExpiry;
1120 if ( $u->getEmail() == '' ) {
1121 return Status
::newFatal( 'noemail', $u->getName() );
1123 $ip = $this->getRequest()->getIP();
1125 return Status
::newFatal( 'badipaddress' );
1128 $currentUser = $this->getUser();
1129 Hooks
::run( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
1131 $np = $u->randomPassword();
1132 $u->setNewpassword( $np, $throttle );
1134 $userLanguage = $u->getOption( 'language' );
1136 $mainPage = Title
::newMainPage();
1137 $mainPageUrl = $mainPage->getCanonicalURL();
1139 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $mainPageUrl . '>',
1140 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
1141 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
1147 * Run any hooks registered for logins, then HTTP redirect to
1148 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
1149 * nice message here, but that's really not as useful as just being sent to
1150 * wherever you logged in from. It should be clear that the action was
1151 * successful, given the lack of error messages plus the appearance of your
1152 * name in the upper right.
1156 function successfulLogin() {
1157 # Run any hooks; display injected HTML if any, else redirect
1158 $currentUser = $this->getUser();
1159 $injected_html = '';
1160 Hooks
::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1162 if ( $injected_html !== '' ) {
1163 $this->displaySuccessfulAction( 'success', $this->msg( 'loginsuccesstitle' ),
1164 'loginsuccess', $injected_html );
1166 $this->executeReturnTo( 'successredirect' );
1171 * Run any hooks registered for logins, then display a message welcoming
1176 function successfulCreation() {
1177 # Run any hooks; display injected HTML
1178 $currentUser = $this->getUser();
1179 $injected_html = '';
1180 $welcome_creation_msg = 'welcomecreation-msg';
1182 Hooks
::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1185 * Let any extensions change what message is shown.
1186 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
1189 Hooks
::run( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
1191 $this->displaySuccessfulAction(
1193 $this->msg( 'welcomeuser', $this->getUser()->getName() ),
1194 $welcome_creation_msg, $injected_html
1199 * Display a "successful action" page.
1201 * @param string $type Condition of return to; see `executeReturnTo`
1202 * @param string|Message $title Page's title
1203 * @param string $msgname
1204 * @param string $injected_html
1206 private function displaySuccessfulAction( $type, $title, $msgname, $injected_html ) {
1207 $out = $this->getOutput();
1208 $out->setPageTitle( $title );
1210 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
1213 $out->addHTML( $injected_html );
1215 $this->executeReturnTo( $type );
1219 * Output a message that informs the user that they cannot create an account because
1220 * there is a block on them or their IP which prevents account creation. Note that
1221 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
1222 * setting on blocks (bug 13611).
1223 * @param Block $block The block causing this error
1224 * @throws ErrorPageError
1226 function userBlockedMessage( Block
$block ) {
1227 # Let's be nice about this, it's likely that this feature will be used
1228 # for blocking large numbers of innocent people, e.g. range blocks on
1229 # schools. Don't blame it on the user. There's a small chance that it
1230 # really is the user's fault, i.e. the username is blocked and they
1231 # haven't bothered to log out before trying to create an account to
1232 # evade it, but we'll leave that to their guilty conscience to figure
1234 $errorParams = array(
1235 $block->getTarget(),
1236 $block->mReason ?
$block->mReason
: $this->msg( 'blockednoreason' )->text(),
1240 if ( $block->getType() === Block
::TYPE_RANGE
) {
1241 $errorMessage = 'cantcreateaccount-range-text';
1242 $errorParams[] = $this->getRequest()->getIP();
1244 $errorMessage = 'cantcreateaccount-text';
1247 throw new ErrorPageError(
1248 'cantcreateaccounttitle',
1255 * Add a "return to" link or redirect to it.
1256 * Extensions can use this to reuse the "return to" logic after
1257 * inject steps (such as redirection) into the login process.
1259 * @param string $type One of the following:
1260 * - error: display a return to link ignoring $wgRedirectOnLogin
1261 * - signup: display a return to link using $wgRedirectOnLogin if needed
1262 * - success: display a return to link using $wgRedirectOnLogin if needed
1263 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1264 * @param string $returnTo
1265 * @param array|string $returnToQuery
1266 * @param bool $stickHTTPs Keep redirect link on HTTPs
1269 public function showReturnToPage(
1270 $type, $returnTo = '', $returnToQuery = '', $stickHTTPs = false
1272 $this->mReturnTo
= $returnTo;
1273 $this->mReturnToQuery
= $returnToQuery;
1274 $this->mStickHTTPS
= $stickHTTPs;
1275 $this->executeReturnTo( $type );
1279 * Add a "return to" link or redirect to it.
1281 * @param string $type One of the following:
1282 * - error: display a return to link ignoring $wgRedirectOnLogin
1283 * - signup: display a return to link using $wgRedirectOnLogin if needed
1284 * - success: display a return to link using $wgRedirectOnLogin if needed
1285 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1287 private function executeReturnTo( $type ) {
1288 global $wgRedirectOnLogin, $wgSecureLogin;
1290 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
1291 $returnTo = $wgRedirectOnLogin;
1292 $returnToQuery = array();
1294 $returnTo = $this->mReturnTo
;
1295 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
1298 // Allow modification of redirect behavior
1299 Hooks
::run( 'PostLoginRedirect', array( &$returnTo, &$returnToQuery, &$type ) );
1301 $returnToTitle = Title
::newFromText( $returnTo );
1302 if ( !$returnToTitle ) {
1303 $returnToTitle = Title
::newMainPage();
1306 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1307 $options = array( 'http' );
1308 $proto = PROTO_HTTP
;
1309 } elseif ( $wgSecureLogin ) {
1310 $options = array( 'https' );
1311 $proto = PROTO_HTTPS
;
1314 $proto = PROTO_RELATIVE
;
1317 if ( $type == 'successredirect' ) {
1318 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1319 $this->getOutput()->redirect( $redirectUrl );
1321 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1326 * @param string $msg
1327 * @param string $msgtype
1328 * @throws ErrorPageError
1330 * @throws FatalError
1331 * @throws MWException
1332 * @throws PermissionsError
1333 * @throws ReadOnlyError
1336 function mainLoginForm( $msg, $msgtype = 'error' ) {
1337 global $wgEnableEmail, $wgEnableUserEmail;
1338 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1339 global $wgAuth, $wgEmailConfirmToEdit;
1340 global $wgSecureLogin, $wgPasswordResetRoutes;
1341 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
1343 $titleObj = $this->getPageTitle();
1344 $user = $this->getUser();
1345 $out = $this->getOutput();
1347 if ( $this->mType
== 'signup' ) {
1348 // Block signup here if in readonly. Keeps user from
1349 // going through the process (filling out data, etc)
1350 // and being informed later.
1351 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1352 if ( count( $permErrors ) ) {
1353 throw new PermissionsError( 'createaccount', $permErrors );
1354 } elseif ( $user->isBlockedFromCreateAccount() ) {
1355 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1358 } elseif ( wfReadOnly() ) {
1359 throw new ReadOnlyError
;
1363 // Pre-fill username (if not creating an account, bug 44775).
1364 if ( $this->mUsername
== '' && $this->mType
!= 'signup' ) {
1365 if ( $user->isLoggedIn() ) {
1366 $this->mUsername
= $user->getName();
1368 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1372 // Generic styles and scripts for both login and signup form
1373 $out->addModuleStyles( array(
1375 'mediawiki.ui.button',
1376 'mediawiki.ui.checkbox',
1377 'mediawiki.ui.input',
1378 'mediawiki.special.userlogin.common.styles'
1381 if ( $this->mType
== 'signup' ) {
1382 // XXX hack pending RL or JS parse() support for complex content messages
1383 // https://phabricator.wikimedia.org/T27349
1384 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
1385 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
1387 // Additional styles and scripts for signup form
1388 $out->addModules( array(
1389 'mediawiki.special.userlogin.signup.js'
1391 $out->addModuleStyles( array(
1392 'mediawiki.special.userlogin.signup.styles'
1395 $template = new UsercreateTemplate( $this->getConfig() );
1397 // Must match number of benefits defined in messages
1398 $template->set( 'benefitCount', 3 );
1400 $q = 'action=submitlogin&type=signup';
1401 $linkq = 'type=login';
1403 // Additional styles for login form
1404 $out->addModuleStyles( array(
1405 'mediawiki.special.userlogin.login.styles'
1408 $template = new UserloginTemplate( $this->getConfig() );
1410 $q = 'action=submitlogin&type=login';
1411 $linkq = 'type=signup';
1414 if ( $this->mReturnTo
!== '' ) {
1415 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1416 if ( $this->mReturnToQuery
!== '' ) {
1417 $returnto .= '&returntoquery=' .
1418 wfUrlencode( $this->mReturnToQuery
);
1421 $linkq .= $returnto;
1424 # Don't show a "create account" link if the user can't.
1425 if ( $this->showCreateOrLoginLink( $user ) ) {
1426 # Pass any language selection on to the mode switch link
1427 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
1428 $linkq .= '&uselang=' . $this->mLanguage
;
1430 // Supply URL, login template creates the button.
1431 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1433 $template->set( 'link', '' );
1436 $resetLink = $this->mType
== 'signup'
1438 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1440 $template->set( 'header', '' );
1441 $template->set( 'formheader', '' );
1442 $template->set( 'skin', $this->getSkin() );
1443 $template->set( 'name', $this->mUsername
);
1444 $template->set( 'password', $this->mPassword
);
1445 $template->set( 'retype', $this->mRetype
);
1446 $template->set( 'createemailset', $this->mCreateaccountMail
);
1447 $template->set( 'email', $this->mEmail
);
1448 $template->set( 'realname', $this->mRealName
);
1449 $template->set( 'domain', $this->mDomain
);
1450 $template->set( 'reason', $this->mReason
);
1452 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1453 $template->set( 'message', $msg );
1454 $template->set( 'messagetype', $msgtype );
1455 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1456 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1457 $template->set( 'useemail', $wgEnableEmail );
1458 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1459 $template->set( 'emailothers', $wgEnableUserEmail );
1460 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1461 $template->set( 'resetlink', $resetLink );
1462 $template->set( 'canremember', $wgExtendedLoginCookieExpiration === null ?
( $wgCookieExpiration > 0 ) : ( $wgExtendedLoginCookieExpiration > 0 ) );
1463 $template->set( 'usereason', $user->isLoggedIn() );
1464 $template->set( 'remember', $this->mRemember
);
1465 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1466 $template->set( 'stickhttps', (int)$this->mStickHTTPS
);
1467 $template->set( 'loggedin', $user->isLoggedIn() );
1468 $template->set( 'loggedinuser', $user->getName() );
1470 if ( $this->mType
== 'signup' ) {
1471 if ( !self
::getCreateaccountToken() ) {
1472 self
::setCreateaccountToken();
1474 $template->set( 'token', self
::getCreateaccountToken() );
1476 if ( !self
::getLoginToken() ) {
1477 self
::setLoginToken();
1479 $template->set( 'token', self
::getLoginToken() );
1482 # Prepare language selection links as needed
1483 if ( $wgLoginLanguageSelector ) {
1484 $template->set( 'languages', $this->makeLanguageSelector() );
1485 if ( $this->mLanguage
) {
1486 $template->set( 'uselang', $this->mLanguage
);
1490 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl
);
1491 // Use signupend-https for HTTPS requests if it's not blank, signupend otherwise
1492 $usingHTTPS = $this->mRequest
->getProtocol() == 'https';
1493 $signupendHTTPS = $this->msg( 'signupend-https' );
1494 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1495 $template->set( 'signupend', $signupendHTTPS->parse() );
1497 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1500 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
1501 if ( $usingHTTPS ) {
1502 $template->set( 'fromhttp', $this->mFromHTTP
);
1505 // Give authentication and captcha plugins a chance to modify the form
1506 $wgAuth->modifyUITemplate( $template, $this->mType
);
1507 if ( $this->mType
== 'signup' ) {
1508 Hooks
::run( 'UserCreateForm', array( &$template ) );
1510 Hooks
::run( 'UserLoginForm', array( &$template ) );
1513 $out->disallowUserJs(); // just in case...
1514 $out->addTemplate( $template );
1518 * Whether the login/create account form should display a link to the
1519 * other form (in addition to whatever the skin provides).
1524 private function showCreateOrLoginLink( &$user ) {
1525 if ( $this->mType
== 'signup' ) {
1527 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1535 * Check if a session cookie is present.
1537 * This will not pick up a cookie set during _this_ request, but is meant
1538 * to ensure that the client is returning the cookie which was set on a
1539 * previous pass through the system.
1544 function hasSessionCookie() {
1545 global $wgDisableCookieCheck;
1547 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1551 * Get the login token from the current session
1554 public static function getLoginToken() {
1557 return $wgRequest->getSessionData( 'wsLoginToken' );
1561 * Randomly generate a new login token and attach it to the current session
1563 public static function setLoginToken() {
1565 // Generate a token directly instead of using $user->getEditToken()
1566 // because the latter reuses $_SESSION['wsEditToken']
1567 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1571 * Remove any login token attached to the current session
1573 public static function clearLoginToken() {
1575 $wgRequest->setSessionData( 'wsLoginToken', null );
1579 * Get the createaccount token from the current session
1582 public static function getCreateaccountToken() {
1584 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1588 * Randomly generate a new createaccount token and attach it to the current session
1590 public static function setCreateaccountToken() {
1592 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1596 * Remove any createaccount token attached to the current session
1598 public static function clearCreateaccountToken() {
1600 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1604 * Renew the user's session id, using strong entropy
1606 private function renewSessionId() {
1607 global $wgSecureLogin, $wgCookieSecure;
1608 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1609 $wgCookieSecure = false;
1616 * @param string $type
1619 function cookieRedirectCheck( $type ) {
1620 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1621 $query = array( 'wpCookieCheck' => $type );
1622 if ( $this->mReturnTo
!== '' ) {
1623 $query['returnto'] = $this->mReturnTo
;
1624 $query['returntoquery'] = $this->mReturnToQuery
;
1626 $check = $titleObj->getFullURL( $query );
1628 $this->getOutput()->redirect( $check );
1632 * @param string $type
1635 function onCookieRedirectCheck( $type ) {
1636 if ( !$this->hasSessionCookie() ) {
1637 if ( $type == 'new' ) {
1638 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1639 } elseif ( $type == 'login' ) {
1640 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1643 $this->mainLoginForm( $this->msg( 'error' )->text() );
1646 $this->successfulLogin();
1651 * Produce a bar of links which allow the user to select another language
1652 * during login/registration but retain "returnto"
1656 function makeLanguageSelector() {
1657 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1658 if ( $msg->isBlank() ) {
1661 $langs = explode( "\n", $msg->text() );
1663 foreach ( $langs as $lang ) {
1664 $lang = trim( $lang, '* ' );
1665 $parts = explode( '|', $lang );
1666 if ( count( $parts ) >= 2 ) {
1667 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1671 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1672 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1676 * Create a language selector link for a particular language
1677 * Links back to this page preserving type and returnto
1679 * @param string $text Link text
1680 * @param string $lang Language code
1683 function makeLanguageSelectorLink( $text, $lang ) {
1684 if ( $this->getLanguage()->getCode() == $lang ) {
1685 // no link for currently used language
1686 return htmlspecialchars( $text );
1688 $query = array( 'uselang' => $lang );
1689 if ( $this->mType
== 'signup' ) {
1690 $query['type'] = 'signup';
1692 if ( $this->mReturnTo
!== '' ) {
1693 $query['returnto'] = $this->mReturnTo
;
1694 $query['returntoquery'] = $this->mReturnToQuery
;
1698 $targetLanguage = Language
::factory( $lang );
1699 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1701 return Linker
::linkKnown(
1702 $this->getPageTitle(),
1703 htmlspecialchars( $text ),
1709 protected function getGroupName() {