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;
135 public function doesWrites() {
140 * Returns an array of all valid error messages.
144 public static function getValidErrorMessages() {
145 static $messages = null;
147 $messages = self
::$validErrorMessages;
148 Hooks
::run( 'LoginFormValidErrorMessages', array( &$messages ) );
158 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
160 if ( $this->mLoaded
) {
163 $this->mLoaded
= true;
165 if ( $this->mOverrideRequest
=== null ) {
166 $request = $this->getRequest();
168 $request = $this->mOverrideRequest
;
170 $this->mRequest
= $request;
172 $this->mType
= $request->getText( 'type' );
173 $this->mUsername
= $request->getText( 'wpName' );
174 $this->mPassword
= $request->getText( 'wpPassword' );
175 $this->mRetype
= $request->getText( 'wpRetype' );
176 $this->mDomain
= $request->getText( 'wpDomain' );
177 $this->mReason
= $request->getText( 'wpReason' );
178 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
179 $this->mPosted
= $request->wasPosted();
180 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
182 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' ) && !$this->mCreateaccountMail
;
183 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
184 $this->mAction
= $request->getVal( 'action' );
185 $this->mRemember
= $request->getCheck( 'wpRemember' );
186 $this->mFromHTTP
= $request->getBool( 'fromhttp', false )
187 ||
$request->getBool( 'wpFromhttp', false );
188 $this->mStickHTTPS
= ( !$this->mFromHTTP
&& $request->getProtocol() === 'https' )
189 ||
$request->getBool( 'wpForceHttps', false );
190 $this->mLanguage
= $request->getText( 'uselang' );
191 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
192 $this->mToken
= $this->mType
== 'signup'
193 ?
$request->getVal( 'wpCreateaccountToken' )
194 : $request->getVal( 'wpLoginToken' );
195 $this->mReturnTo
= $request->getVal( 'returnto', '' );
196 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
198 // Show an error or warning passed on from a previous page
199 $entryError = $this->msg( $request->getVal( 'error', '' ) );
200 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
201 // bc: provide login link as a parameter for messages where the translation
203 $loginreqlink = Linker
::linkKnown(
204 $this->getPageTitle(),
205 $this->msg( 'loginreqlink' )->escaped(),
208 'returnto' => $this->mReturnTo
,
209 'returntoquery' => $this->mReturnToQuery
,
210 'uselang' => $this->mLanguage
,
211 'fromhttp' => $this->mFromHTTP ?
'1' : '0',
215 // Only show valid error or warning messages.
216 if ( $entryError->exists()
217 && in_array( $entryError->getKey(), self
::getValidErrorMessages() )
219 $this->mEntryErrorType
= 'error';
220 $this->mEntryError
= $entryError->rawParams( $loginreqlink )->parse();
222 } elseif ( $entryWarning->exists()
223 && in_array( $entryWarning->getKey(), self
::getValidErrorMessages() )
225 $this->mEntryErrorType
= 'warning';
226 $this->mEntryError
= $entryWarning->rawParams( $loginreqlink )->parse();
229 if ( $wgEnableEmail ) {
230 $this->mEmail
= $request->getText( 'wpEmail' );
234 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
235 $this->mRealName
= $request->getText( 'wpRealName' );
237 $this->mRealName
= '';
240 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
241 $this->mDomain
= $wgAuth->getDomain();
243 $wgAuth->setDomain( $this->mDomain
);
245 # 1. When switching accounts, it sucks to get automatically logged out
246 # 2. Do not return to PasswordReset after a successful password change
247 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
248 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
249 if ( is_object( $returnToTitle )
250 && ( $returnToTitle->isSpecial( 'Userlogout' )
251 ||
$returnToTitle->isSpecial( 'PasswordReset' ) )
253 $this->mReturnTo
= '';
254 $this->mReturnToQuery
= '';
258 function getDescription() {
259 if ( $this->mType
=== 'signup' ) {
260 return $this->msg( 'createaccount' )->text();
262 return $this->msg( 'login' )->text();
267 * @param string|null $subPage
269 public function execute( $subPage ) {
270 if ( session_id() == '' ) {
276 // Check for [[Special:Userlogin/signup]]. This affects form display and
278 if ( $subPage == 'signup' ) {
279 $this->mType
= 'signup';
284 * In the case where the user is already logged in, and was redirected to
285 * the login form from a page that requires login, do not show the login
286 * page. The use case scenario for this is when a user opens a large number
287 * of tabs, is redirected to the login page on all of them, and then logs
288 * in on one, expecting all the others to work properly.
290 * However, do show the form if it was visited intentionally (no 'returnto'
291 * is present). People who often switch between several accounts have grown
292 * accustomed to this behavior.
295 $this->mType
!== 'signup' &&
297 $this->getUser()->isLoggedIn() &&
298 ( $this->mReturnTo
!== '' ||
$this->mReturnToQuery
!== '' )
300 $this->successfulLogin();
303 // If logging in and not on HTTPS, either redirect to it or offer a link.
304 global $wgSecureLogin;
305 if ( $this->mRequest
->getProtocol() !== 'https' ) {
306 $title = $this->getFullTitle();
308 'returnto' => $this->mReturnTo
!== '' ?
$this->mReturnTo
: null,
309 'returntoquery' => $this->mReturnToQuery
!== '' ?
310 $this->mReturnToQuery
: null,
312 ( $this->mEntryErrorType
=== 'error' ?
'error' : 'warning' ) => $this->mEntryError
,
313 ) +
$this->mRequest
->getQueryValues();
314 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
316 && wfCanIPUseHTTPS( $this->getRequest()->getIP() )
317 && !$this->mFromHTTP
) // Avoid infinite redirect
319 $url = wfAppendQuery( $url, 'fromhttp=1' );
320 $this->getOutput()->redirect( $url );
321 // Since we only do this redir to change proto, always vary
322 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
326 // A wiki without HTTPS login support should set $wgServer to
327 // http://somehost, in which case the secure URL generated
328 // above won't actually start with https://
329 if ( substr( $url, 0, 8 ) === 'https://' ) {
330 $this->mSecureLoginUrl
= $url;
335 if ( !is_null( $this->mCookieCheck
) ) {
336 $this->onCookieRedirectCheck( $this->mCookieCheck
);
339 } elseif ( $this->mPosted
) {
340 if ( $this->mCreateaccount
) {
341 $this->addNewAccount();
344 } elseif ( $this->mCreateaccountMail
) {
345 $this->addNewAccountMailPassword();
348 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
349 $this->processLogin();
354 $this->mainLoginForm( $this->mEntryError
, $this->mEntryErrorType
);
360 function addNewAccountMailPassword() {
361 if ( $this->mEmail
== '' ) {
362 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
367 $status = $this->addNewAccountInternal();
368 LoggerFactory
::getInstance( 'authmanager' )->info(
369 'Account creation attempt with mailed password',
370 array( 'event' => 'accountcreation', 'status' => $status )
372 if ( !$status->isGood() ) {
373 $error = $status->getMessage();
374 $this->mainLoginForm( $error->toString() );
380 $u = $status->getValue();
382 // Wipe the initial password and mail a temporary one
383 $u->setPassword( null );
385 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
387 Hooks
::run( 'AddNewAccount', array( $u, true ) );
388 $u->addNewUserLogEntry( 'byemail', $this->mReason
);
390 $out = $this->getOutput();
391 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
393 if ( !$result->isGood() ) {
394 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
396 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
397 $this->executeReturnTo( 'success' );
405 function addNewAccount() {
406 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
408 # Create the account and abort if there's a problem doing so
409 $status = $this->addNewAccountInternal();
410 LoggerFactory
::getInstance( 'authmanager' )->info( 'Account creation attempt', array(
411 'event' => 'accountcreation',
415 if ( !$status->isGood() ) {
416 $error = $status->getMessage();
417 $this->mainLoginForm( $error->toString() );
422 $u = $status->getValue();
424 # Only save preferences if the user is not creating an account for someone else.
425 if ( $this->getUser()->isAnon() ) {
426 # If we showed up language selection links, and one was in use, be
427 # smart (and sensible) and save that language as the user's preference
428 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
429 $u->setOption( 'language', $this->mLanguage
);
432 # Otherwise the user's language preference defaults to $wgContLang,
433 # but it may be better to set it to their preferred $wgContLang variant,
434 # based on browser preferences or URL parameters.
435 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
437 if ( $wgContLang->hasVariants() ) {
438 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
442 $out = $this->getOutput();
444 # Send out an email authentication message if needed
445 if ( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
446 $status = $u->sendConfirmationMail();
447 if ( $status->isGood() ) {
448 $out->addWikiMsg( 'confirmemail_oncreate' );
450 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
454 # Save settings (including confirmation token)
457 # If not logged in, assume the new account as the current one and set
458 # session cookies then show a "welcome" message or a "need cookies"
460 if ( $this->getUser()->isAnon() ) {
463 // This should set it for OutputPage and the Skin
464 // which is needed or the personal links will be
466 $this->getContext()->setUser( $u );
467 Hooks
::run( 'AddNewAccount', array( $u, false ) );
468 $u->addNewUserLogEntry( 'create' );
469 if ( $this->hasSessionCookie() ) {
470 $this->successfulCreation();
472 $this->cookieRedirectCheck( 'new' );
475 # Confirm that the account was created
476 $out->setPageTitle( $this->msg( 'accountcreated' ) );
477 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
478 $out->addReturnTo( $this->getPageTitle() );
479 Hooks
::run( 'AddNewAccount', array( $u, false ) );
480 $u->addNewUserLogEntry( 'create2', $this->mReason
);
487 * Make a new user account using the loaded data.
489 * @throws PermissionsError|ReadOnlyError
492 public function addNewAccountInternal() {
493 global $wgAuth, $wgAccountCreationThrottle, $wgEmailConfirmToEdit;
495 // If the user passes an invalid domain, something is fishy
496 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
497 return Status
::newFatal( 'wrongpassword' );
500 // If we are not allowing users to login locally, we should be checking
501 // to see if the user is actually able to authenticate to the authenti-
502 // cation server before they create an account (otherwise, they can
503 // create a local account and login as any domain user). We only need
504 // to check this for domains that aren't local.
505 if ( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
507 !$wgAuth->canCreateAccounts() &&
509 !$wgAuth->userExists( $this->mUsername
) ||
510 !$wgAuth->authenticate( $this->mUsername
, $this->mPassword
)
513 return Status
::newFatal( 'wrongpassword' );
517 if ( wfReadOnly() ) {
518 throw new ReadOnlyError
;
521 # Request forgery checks.
522 if ( !self
::getCreateaccountToken() ) {
523 self
::setCreateaccountToken();
525 return Status
::newFatal( 'nocookiesfornew' );
528 # The user didn't pass a createaccount token
529 if ( !$this->mToken
) {
530 return Status
::newFatal( 'sessionfailure' );
533 # Validate the createaccount token
534 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
535 return Status
::newFatal( 'sessionfailure' );
539 $currentUser = $this->getUser();
540 $creationBlock = $currentUser->isBlockedFromCreateAccount();
541 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
542 throw new PermissionsError( 'createaccount' );
543 } elseif ( $creationBlock instanceof Block
) {
544 // Throws an ErrorPageError.
545 $this->userBlockedMessage( $creationBlock );
547 // This should never be reached.
551 # Include checks that will include GlobalBlocking (Bug 38333)
552 $permErrors = $this->getPageTitle()->getUserPermissionsErrors(
558 if ( count( $permErrors ) ) {
559 throw new PermissionsError( 'createaccount', $permErrors );
562 $ip = $this->getRequest()->getIP();
563 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
564 return Status
::newFatal( 'sorbs_create_account_reason' );
567 # Now create a dummy user ($u) and check if it is valid
568 $u = User
::newFromName( $this->mUsername
, 'creatable' );
570 return Status
::newFatal( 'noname' );
573 $cache = ObjectCache
::getLocalClusterInstance();
574 # Make sure the user does not exist already
575 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $this->mUsername
) ) );
577 return Status
::newFatal( 'usernameinprogress' );
578 } elseif ( $u->idForName( User
::READ_LOCKING
) ) {
579 return Status
::newFatal( 'userexists' );
582 if ( $this->mCreateaccountMail
) {
583 # do not force a password for account creation by email
584 # set invalid password, it will be replaced later by a random generated password
585 $this->mPassword
= null;
587 if ( $this->mPassword
!== $this->mRetype
) {
588 return Status
::newFatal( 'badretype' );
591 # check for password validity, return a fatal Status if invalid
592 $validity = $u->checkPasswordValidity( $this->mPassword
, 'create' );
593 if ( !$validity->isGood() ) {
594 $validity->ok
= false; // make sure this Status is fatal
599 # if you need a confirmed email address to edit, then obviously you
600 # need an email address.
601 if ( $wgEmailConfirmToEdit && strval( $this->mEmail
) === '' ) {
602 return Status
::newFatal( 'noemailtitle' );
605 if ( strval( $this->mEmail
) !== '' && !Sanitizer
::validateEmail( $this->mEmail
) ) {
606 return Status
::newFatal( 'invalidemailaddress' );
609 # Set some additional data so the AbortNewAccount hook can be used for
610 # more than just username validation
611 $u->setEmail( $this->mEmail
);
612 $u->setRealName( $this->mRealName
);
616 if ( !Hooks
::run( 'AbortNewAccount', array( $u, &$abortError, &$abortStatus ) ) ) {
617 // Hook point to add extra creation throttles and blocks
618 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
619 if ( $abortStatus === null ) {
620 // Report back the old string as a raw message status.
621 // This will report the error back as 'createaccount-hook-aborted'
622 // with the given string as the message.
623 // To return a different error code, return a Status object.
624 $abortError = new Message( 'createaccount-hook-aborted', array( $abortError ) );
627 return Status
::newFatal( $abortError );
629 // For MediaWiki 1.23+ and updated hooks, return the Status object
630 // returned from the hook.
635 // Hook point to check for exempt from account creation throttle
636 if ( !Hooks
::run( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
637 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook " .
638 "allowed account creation w/o throttle\n" );
640 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
641 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
642 $value = $cache->get( $key );
644 $cache->set( $key, 0, $cache::TTL_DAY
);
646 if ( $value >= $wgAccountCreationThrottle ) {
647 return Status
::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
649 $cache->incr( $key );
653 if ( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
654 return Status
::newFatal( 'externaldberror' );
657 self
::clearCreateaccountToken();
659 return $this->initUser( $u, false );
663 * Actually add a user to the database.
664 * Give it a User object that has been initialised with a name.
667 * @param bool $autocreate True if this is an autocreation via auth plugin
668 * @return Status Status object, with the User object in the value member on success
671 function initUser( $u, $autocreate ) {
674 $status = $u->addToDatabase();
675 if ( !$status->isOK() ) {
679 if ( $wgAuth->allowPasswordChange() ) {
680 $u->setPassword( $this->mPassword
);
683 $u->setEmail( $this->mEmail
);
684 $u->setRealName( $this->mRealName
);
687 Hooks
::run( 'LocalUserCreated', array( $u, $autocreate ) );
689 $wgAuth->initUser( $u, $autocreate );
690 if ( $oldUser !== $u ) {
691 wfWarn( get_class( $wgAuth ) . '::initUser() replaced the user object' );
697 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
699 // Watch user's userpage and talk page
700 $u->addWatch( $u->getUserPage(), WatchedItem
::IGNORE_USER_RIGHTS
);
702 return Status
::newGood( $u );
706 * Internally authenticate the login request.
708 * This may create a local account as a side effect if the
709 * authentication plugin allows transparent local account
713 public function authenticateUserData() {
714 global $wgUser, $wgAuth;
718 if ( $this->mUsername
== '' ) {
719 return self
::NO_NAME
;
722 // We require a login token to prevent login CSRF
723 // Handle part of this before incrementing the throttle so
724 // token-less login attempts don't count towards the throttle
725 // but wrong-token attempts do.
727 // If the user doesn't have a login token yet, set one.
728 if ( !self
::getLoginToken() ) {
729 self
::setLoginToken();
731 return self
::NEED_TOKEN
;
733 // If the user didn't pass a login token, tell them we need one
734 if ( !$this->mToken
) {
735 return self
::NEED_TOKEN
;
738 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
739 if ( $throttleCount === true ) {
740 return self
::THROTTLED
;
743 // Validate the login token
744 if ( $this->mToken
!== self
::getLoginToken() ) {
745 return self
::WRONG_TOKEN
;
748 // Load the current user now, and check to see if we're logging in as
749 // the same name. This is necessary because loading the current user
750 // (say by calling getName()) calls the UserLoadFromSession hook, which
751 // potentially creates the user in the database. Until we load $wgUser,
752 // checking for user existence using User::newFromName($name)->getId() below
753 // will effectively be using stale data.
754 if ( $this->getUser()->getName() === $this->mUsername
) {
755 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
757 return self
::SUCCESS
;
760 $u = User
::newFromName( $this->mUsername
);
761 if ( $u === false ) {
762 return self
::ILLEGAL
;
766 // Give extensions a way to indicate the username has been updated,
767 // rather than telling the user the account doesn't exist.
768 if ( !Hooks
::run( 'LoginUserMigrated', array( $u, &$msg ) ) ) {
769 $this->mAbortLoginErrorMsg
= $msg;
770 return self
::USER_MIGRATED
;
773 if ( !User
::isUsableName( $u->getName() ) ) {
774 return self
::ILLEGAL
;
777 $isAutoCreated = false;
778 if ( $u->getID() == 0 ) {
779 $status = $this->attemptAutoCreate( $u );
780 if ( $status !== self
::SUCCESS
) {
783 $isAutoCreated = true;
789 // Give general extensions, such as a captcha, a chance to abort logins
790 $abort = self
::ABORTED
;
791 if ( !Hooks
::run( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$msg ) ) ) {
792 if ( !in_array( $abort, array_keys( self
::$statusCodes ), true ) ) {
793 throw new Exception( 'Invalid status code returned from AbortLogin hook: ' . $abort );
795 $this->mAbortLoginErrorMsg
= $msg;
799 global $wgBlockDisablesLogin;
800 if ( !$u->checkPassword( $this->mPassword
) ) {
801 if ( $u->checkTemporaryPassword( $this->mPassword
) ) {
803 * The e-mailed temporary password should not be used for actu-
804 * al logins; that's a very sloppy habit, and insecure if an
805 * attacker has a few seconds to click "search" on someone's
808 * Allow it to be used only to reset the password a single time
809 * to a new value, which won't be in the user's e-mail ar-
812 * For backwards compatibility, we'll still recognize it at the
813 * login form to minimize surprises for people who have been
814 * logging in with a temporary password for some time.
816 * As a side-effect, we can authenticate the user's e-mail ad-
817 * dress if it's not already done, since the temporary password
818 * was sent via e-mail.
820 if ( !$u->isEmailConfirmed() && !wfReadOnly() ) {
825 // At this point we just return an appropriate code/ indicating
826 // that the UI should show a password reset form; bot inter-
827 // faces etc will probably just fail cleanly here.
828 $this->mAbortLoginErrorMsg
= 'resetpass-temp-emailed';
829 $this->mTempPasswordUsed
= true;
830 $retval = self
::RESET_PASS
;
832 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
834 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
835 // If we've enabled it, make it so that a blocked user cannot login
836 $retval = self
::USER_BLOCKED
;
837 } elseif ( $this->checkUserPasswordExpired( $u ) == 'hard' ) {
838 // Force reset now, without logging in
839 $retval = self
::RESET_PASS
;
840 $this->mAbortLoginErrorMsg
= 'resetpass-expired';
842 Hooks
::run( 'UserLoggedIn', array( $u ) );
844 $wgAuth->updateUser( $u );
845 if ( $oldUser !== $u ) {
846 wfWarn( get_class( $wgAuth ) . '::updateUser() replaced the user object' );
849 // This should set it for OutputPage and the Skin
850 // which is needed or the personal links will be
852 $this->getContext()->setUser( $u );
854 // Please reset throttle for successful logins, thanks!
855 if ( $throttleCount ) {
856 self
::clearLoginThrottle( $this->mUsername
);
859 if ( $isAutoCreated ) {
860 // Must be run after $wgUser is set, for correct new user log
861 Hooks
::run( 'AuthPluginAutoCreate', array( $u ) );
864 $retval = self
::SUCCESS
;
866 Hooks
::run( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
872 * Increment the login attempt throttle hit count for the (username,current IP)
873 * tuple unless the throttle was already reached.
874 * @param string $username The user name
875 * @return bool|int The integer hit count or True if it is already at the limit
877 public static function incLoginThrottle( $username ) {
878 global $wgPasswordAttemptThrottle, $wgRequest;
879 $username = trim( $username ); // sanity
882 if ( is_array( $wgPasswordAttemptThrottle ) ) {
883 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
884 $count = $wgPasswordAttemptThrottle['count'];
885 $period = $wgPasswordAttemptThrottle['seconds'];
887 $cache = ObjectCache
::getLocalClusterInstance();
888 $throttleCount = $cache->get( $throttleKey );
889 if ( !$throttleCount ) {
890 $cache->add( $throttleKey, 1, $period ); // start counter
891 } elseif ( $throttleCount < $count ) {
892 $cache->incr( $throttleKey );
893 } elseif ( $throttleCount >= $count ) {
898 return $throttleCount;
902 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
903 * @param string $username The user name
906 public static function clearLoginThrottle( $username ) {
908 $username = trim( $username ); // sanity
910 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
911 ObjectCache
::getLocalClusterInstance()->delete( $throttleKey );
915 * Attempt to automatically create a user on login. Only succeeds if there
916 * is an external authentication method which allows it.
920 * @return int Status code
922 function attemptAutoCreate( $user ) {
925 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
926 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
928 return self
::CREATE_BLOCKED
;
931 if ( !$wgAuth->autoCreate() ) {
932 return self
::NOT_EXISTS
;
935 if ( !$wgAuth->userExists( $user->getName() ) ) {
936 wfDebug( __METHOD__
. ": user does not exist\n" );
938 return self
::NOT_EXISTS
;
941 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
942 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
944 return self
::WRONG_PLUGIN_PASS
;
948 if ( !Hooks
::run( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
949 // Hook point to add extra creation throttles and blocks
950 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
951 $this->mAbortLoginErrorMsg
= $abortError;
953 return self
::ABORTED
;
956 wfDebug( __METHOD__
. ": creating account\n" );
957 $status = $this->initUser( $user, true );
959 if ( !$status->isOK() ) {
960 $errors = $status->getErrorsByType( 'error' );
961 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
963 return self
::ABORTED
;
966 return self
::SUCCESS
;
969 function processLogin() {
970 global $wgLang, $wgSecureLogin, $wgPasswordAttemptThrottle, $wgInvalidPasswordReset;
972 $cache = ObjectCache
::getLocalClusterInstance();
973 $authRes = $this->authenticateUserData();
974 switch ( $authRes ) {
976 # We've verified now, update the real record
977 $user = $this->getUser();
980 if ( $user->requiresHTTPS() ) {
981 $this->mStickHTTPS
= true;
984 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
985 $user->setCookies( $this->mRequest
, false, $this->mRemember
);
987 $user->setCookies( $this->mRequest
, null, $this->mRemember
);
989 self
::clearLoginToken();
991 // Reset the throttle
992 $request = $this->getRequest();
993 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
994 $cache->delete( $key );
996 if ( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
997 /* Replace the language object to provide user interface in
998 * correct language immediately on this first page load.
1000 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
1001 $userLang = Language
::factory( $code );
1002 $wgLang = $userLang;
1003 $this->getContext()->setLanguage( $userLang );
1004 // Reset SessionID on Successful login (bug 40995)
1005 $this->renewSessionId();
1006 if ( $this->checkUserPasswordExpired( $this->getUser() ) == 'soft' ) {
1007 $this->resetLoginForm( $this->msg( 'resetpass-expired-soft' ) );
1008 } elseif ( $wgInvalidPasswordReset
1009 && !$user->isValidPassword( $this->mPassword
)
1011 $status = $user->checkPasswordValidity(
1015 $this->resetLoginForm(
1016 $status->getMessage( 'resetpass-validity-soft' )
1019 $this->successfulLogin();
1022 $this->cookieRedirectCheck( 'login' );
1026 case self
::NEED_TOKEN
:
1027 $error = $this->mAbortLoginErrorMsg ?
: 'nocookiesforlogin';
1028 $this->mainLoginForm( $this->msg( $error )->parse() );
1030 case self
::WRONG_TOKEN
:
1031 $error = $this->mAbortLoginErrorMsg ?
: 'sessionfailure';
1032 $this->mainLoginForm( $this->msg( $error )->text() );
1036 $error = $this->mAbortLoginErrorMsg ?
: 'noname';
1037 $this->mainLoginForm( $this->msg( $error )->text() );
1039 case self
::WRONG_PLUGIN_PASS
:
1040 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
1041 $this->mainLoginForm( $this->msg( $error )->text() );
1043 case self
::NOT_EXISTS
:
1044 if ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1045 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchuser';
1046 $this->mainLoginForm( $this->msg( $error,
1047 wfEscapeWikiText( $this->mUsername
) )->parse() );
1049 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchusershort';
1050 $this->mainLoginForm( $this->msg( $error,
1051 wfEscapeWikiText( $this->mUsername
) )->text() );
1054 case self
::WRONG_PASS
:
1055 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
1056 $this->mainLoginForm( $this->msg( $error )->text() );
1058 case self
::EMPTY_PASS
:
1059 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpasswordempty';
1060 $this->mainLoginForm( $this->msg( $error )->text() );
1062 case self
::RESET_PASS
:
1063 $error = $this->mAbortLoginErrorMsg ?
: 'resetpass_announce';
1064 $this->resetLoginForm( $this->msg( $error ) );
1066 case self
::CREATE_BLOCKED
:
1067 $this->userBlockedMessage( $this->getUser()->isBlockedFromCreateAccount() );
1069 case self
::THROTTLED
:
1070 $error = $this->mAbortLoginErrorMsg ?
: 'login-throttled';
1071 $this->mainLoginForm( $this->msg( $error )
1072 ->params( $this->getLanguage()->formatDuration( $wgPasswordAttemptThrottle['seconds'] ) )
1076 case self
::USER_BLOCKED
:
1077 $error = $this->mAbortLoginErrorMsg ?
: 'login-userblocked';
1078 $this->mainLoginForm( $this->msg( $error, $this->mUsername
)->escaped() );
1081 $error = $this->mAbortLoginErrorMsg ?
: 'login-abort-generic';
1082 $this->mainLoginForm( $this->msg( $error,
1083 wfEscapeWikiText( $this->mUsername
) )->text() );
1085 case self
::USER_MIGRATED
:
1086 $error = $this->mAbortLoginErrorMsg ?
: 'login-migrated-generic';
1088 if ( is_array( $error ) ) {
1089 $error = array_shift( $this->mAbortLoginErrorMsg
);
1090 $params = $this->mAbortLoginErrorMsg
;
1092 $this->mainLoginForm( $this->msg( $error, $params )->text() );
1095 throw new MWException( 'Unhandled case value' );
1098 LoggerFactory
::getInstance( 'authmanager' )->info( 'Login attempt', array(
1100 'successful' => $authRes === self
::SUCCESS
,
1101 'status' => LoginForm
::$statusCodes[$authRes],
1106 * Show the Special:ChangePassword form, with custom message
1107 * @param Message $msg
1109 protected function resetLoginForm( Message
$msg ) {
1110 // Allow hooks to explain this password reset in more detail
1111 Hooks
::run( 'LoginPasswordResetMessage', array( &$msg, $this->mUsername
) );
1112 $reset = new SpecialChangePassword();
1113 $derivative = new DerivativeContext( $this->getContext() );
1114 $derivative->setTitle( $reset->getPageTitle() );
1115 $reset->setContext( $derivative );
1116 if ( !$this->mTempPasswordUsed
) {
1117 $reset->setOldPasswordMessage( 'oldpassword' );
1119 $reset->setChangeMessage( $msg );
1120 $reset->execute( null );
1125 * @param bool $throttle
1126 * @param string $emailTitle Message name of email title
1127 * @param string $emailText Message name of email text
1130 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle',
1131 $emailText = 'passwordremindertext'
1133 global $wgNewPasswordExpiry, $wgMinimalPasswordLength;
1135 if ( $u->getEmail() == '' ) {
1136 return Status
::newFatal( 'noemail', $u->getName() );
1138 $ip = $this->getRequest()->getIP();
1140 return Status
::newFatal( 'badipaddress' );
1143 $currentUser = $this->getUser();
1144 Hooks
::run( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
1146 $np = PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1147 $u->setNewpassword( $np, $throttle );
1149 $userLanguage = $u->getOption( 'language' );
1151 $mainPage = Title
::newMainPage();
1152 $mainPageUrl = $mainPage->getCanonicalURL();
1154 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $mainPageUrl . '>',
1155 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
1156 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
1162 * Run any hooks registered for logins, then HTTP redirect to
1163 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
1164 * nice message here, but that's really not as useful as just being sent to
1165 * wherever you logged in from. It should be clear that the action was
1166 * successful, given the lack of error messages plus the appearance of your
1167 * name in the upper right.
1171 function successfulLogin() {
1172 # Run any hooks; display injected HTML if any, else redirect
1173 $currentUser = $this->getUser();
1174 $injected_html = '';
1175 Hooks
::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1177 if ( $injected_html !== '' ) {
1178 $this->displaySuccessfulAction( 'success', $this->msg( 'loginsuccesstitle' ),
1179 'loginsuccess', $injected_html );
1181 $this->executeReturnTo( 'successredirect' );
1186 * Run any hooks registered for logins, then display a message welcoming
1191 function successfulCreation() {
1192 # Run any hooks; display injected HTML
1193 $currentUser = $this->getUser();
1194 $injected_html = '';
1195 $welcome_creation_msg = 'welcomecreation-msg';
1197 Hooks
::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1200 * Let any extensions change what message is shown.
1201 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
1204 Hooks
::run( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
1206 $this->displaySuccessfulAction(
1208 $this->msg( 'welcomeuser', $this->getUser()->getName() ),
1209 $welcome_creation_msg, $injected_html
1214 * Display a "successful action" page.
1216 * @param string $type Condition of return to; see `executeReturnTo`
1217 * @param string|Message $title Page's title
1218 * @param string $msgname
1219 * @param string $injected_html
1221 private function displaySuccessfulAction( $type, $title, $msgname, $injected_html ) {
1222 $out = $this->getOutput();
1223 $out->setPageTitle( $title );
1225 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
1228 $out->addHTML( $injected_html );
1230 $this->executeReturnTo( $type );
1234 * Output a message that informs the user that they cannot create an account because
1235 * there is a block on them or their IP which prevents account creation. Note that
1236 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
1237 * setting on blocks (bug 13611).
1238 * @param Block $block The block causing this error
1239 * @throws ErrorPageError
1241 function userBlockedMessage( Block
$block ) {
1242 # Let's be nice about this, it's likely that this feature will be used
1243 # for blocking large numbers of innocent people, e.g. range blocks on
1244 # schools. Don't blame it on the user. There's a small chance that it
1245 # really is the user's fault, i.e. the username is blocked and they
1246 # haven't bothered to log out before trying to create an account to
1247 # evade it, but we'll leave that to their guilty conscience to figure
1249 $errorParams = array(
1250 $block->getTarget(),
1251 $block->mReason ?
$block->mReason
: $this->msg( 'blockednoreason' )->text(),
1255 if ( $block->getType() === Block
::TYPE_RANGE
) {
1256 $errorMessage = 'cantcreateaccount-range-text';
1257 $errorParams[] = $this->getRequest()->getIP();
1259 $errorMessage = 'cantcreateaccount-text';
1262 throw new ErrorPageError(
1263 'cantcreateaccounttitle',
1270 * Add a "return to" link or redirect to it.
1271 * Extensions can use this to reuse the "return to" logic after
1272 * inject steps (such as redirection) into the login process.
1274 * @param string $type One of the following:
1275 * - error: display a return to link ignoring $wgRedirectOnLogin
1276 * - signup: display a return to link using $wgRedirectOnLogin if needed
1277 * - success: display a return to link using $wgRedirectOnLogin if needed
1278 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1279 * @param string $returnTo
1280 * @param array|string $returnToQuery
1281 * @param bool $stickHTTPs Keep redirect link on HTTPs
1284 public function showReturnToPage(
1285 $type, $returnTo = '', $returnToQuery = '', $stickHTTPs = false
1287 $this->mReturnTo
= $returnTo;
1288 $this->mReturnToQuery
= $returnToQuery;
1289 $this->mStickHTTPS
= $stickHTTPs;
1290 $this->executeReturnTo( $type );
1294 * Add a "return to" link or redirect to it.
1296 * @param string $type One of the following:
1297 * - error: display a return to link ignoring $wgRedirectOnLogin
1298 * - signup: display a return to link using $wgRedirectOnLogin if needed
1299 * - success: display a return to link using $wgRedirectOnLogin if needed
1300 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1302 private function executeReturnTo( $type ) {
1303 global $wgRedirectOnLogin, $wgSecureLogin;
1305 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
1306 $returnTo = $wgRedirectOnLogin;
1307 $returnToQuery = array();
1309 $returnTo = $this->mReturnTo
;
1310 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
1313 // Allow modification of redirect behavior
1314 Hooks
::run( 'PostLoginRedirect', array( &$returnTo, &$returnToQuery, &$type ) );
1316 $returnToTitle = Title
::newFromText( $returnTo );
1317 if ( !$returnToTitle ) {
1318 $returnToTitle = Title
::newMainPage();
1321 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1322 $options = array( 'http' );
1323 $proto = PROTO_HTTP
;
1324 } elseif ( $wgSecureLogin ) {
1325 $options = array( 'https' );
1326 $proto = PROTO_HTTPS
;
1329 $proto = PROTO_RELATIVE
;
1332 if ( $type == 'successredirect' ) {
1333 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1334 $this->getOutput()->redirect( $redirectUrl );
1336 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1341 * @param string $msg
1342 * @param string $msgtype
1343 * @throws ErrorPageError
1345 * @throws FatalError
1346 * @throws MWException
1347 * @throws PermissionsError
1348 * @throws ReadOnlyError
1351 function mainLoginForm( $msg, $msgtype = 'error' ) {
1352 global $wgEnableEmail, $wgEnableUserEmail;
1353 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1354 global $wgAuth, $wgEmailConfirmToEdit;
1355 global $wgSecureLogin, $wgPasswordResetRoutes;
1356 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
1358 $titleObj = $this->getPageTitle();
1359 $user = $this->getUser();
1360 $out = $this->getOutput();
1362 if ( $this->mType
== 'signup' ) {
1363 // Block signup here if in readonly. Keeps user from
1364 // going through the process (filling out data, etc)
1365 // and being informed later.
1366 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1367 if ( count( $permErrors ) ) {
1368 throw new PermissionsError( 'createaccount', $permErrors );
1369 } elseif ( $user->isBlockedFromCreateAccount() ) {
1370 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1373 } elseif ( wfReadOnly() ) {
1374 throw new ReadOnlyError
;
1378 // Pre-fill username (if not creating an account, bug 44775).
1379 if ( $this->mUsername
== '' && $this->mType
!= 'signup' ) {
1380 if ( $user->isLoggedIn() ) {
1381 $this->mUsername
= $user->getName();
1383 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1387 // Generic styles and scripts for both login and signup form
1388 $out->addModuleStyles( array(
1390 'mediawiki.ui.button',
1391 'mediawiki.ui.checkbox',
1392 'mediawiki.ui.input',
1393 'mediawiki.special.userlogin.common.styles'
1396 if ( $this->mType
== 'signup' ) {
1397 // Additional styles and scripts for signup form
1398 $out->addModules( array(
1399 'mediawiki.special.userlogin.signup.js'
1401 $out->addModuleStyles( array(
1402 'mediawiki.special.userlogin.signup.styles'
1405 $template = new UsercreateTemplate( $this->getConfig() );
1407 // Must match number of benefits defined in messages
1408 $template->set( 'benefitCount', 3 );
1410 $q = 'action=submitlogin&type=signup';
1411 $linkq = 'type=login';
1413 // Additional styles for login form
1414 $out->addModuleStyles( array(
1415 'mediawiki.special.userlogin.login.styles'
1418 $template = new UserloginTemplate( $this->getConfig() );
1420 $q = 'action=submitlogin&type=login';
1421 $linkq = 'type=signup';
1424 if ( $this->mReturnTo
!== '' ) {
1425 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1426 if ( $this->mReturnToQuery
!== '' ) {
1427 $returnto .= '&returntoquery=' .
1428 wfUrlencode( $this->mReturnToQuery
);
1431 $linkq .= $returnto;
1434 # Don't show a "create account" link if the user can't.
1435 if ( $this->showCreateOrLoginLink( $user ) ) {
1436 # Pass any language selection on to the mode switch link
1437 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
1438 $linkq .= '&uselang=' . $this->mLanguage
;
1440 // Supply URL, login template creates the button.
1441 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1443 $template->set( 'link', '' );
1446 $resetLink = $this->mType
== 'signup'
1448 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1450 $template->set( 'header', '' );
1451 $template->set( 'formheader', '' );
1452 $template->set( 'skin', $this->getSkin() );
1453 $template->set( 'name', $this->mUsername
);
1454 $template->set( 'password', $this->mPassword
);
1455 $template->set( 'retype', $this->mRetype
);
1456 $template->set( 'createemailset', $this->mCreateaccountMail
);
1457 $template->set( 'email', $this->mEmail
);
1458 $template->set( 'realname', $this->mRealName
);
1459 $template->set( 'domain', $this->mDomain
);
1460 $template->set( 'reason', $this->mReason
);
1462 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1463 $template->set( 'message', $msg );
1464 $template->set( 'messagetype', $msgtype );
1465 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1466 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1467 $template->set( 'useemail', $wgEnableEmail );
1468 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1469 $template->set( 'emailothers', $wgEnableUserEmail );
1470 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1471 $template->set( 'resetlink', $resetLink );
1472 $template->set( 'canremember', $wgExtendedLoginCookieExpiration === null ?
1473 ( $wgCookieExpiration > 0 ) :
1474 ( $wgExtendedLoginCookieExpiration > 0 ) );
1475 $template->set( 'usereason', $user->isLoggedIn() );
1476 $template->set( 'remember', $this->mRemember
);
1477 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1478 $template->set( 'stickhttps', (int)$this->mStickHTTPS
);
1479 $template->set( 'loggedin', $user->isLoggedIn() );
1480 $template->set( 'loggedinuser', $user->getName() );
1482 if ( $this->mType
== 'signup' ) {
1483 if ( !self
::getCreateaccountToken() ) {
1484 self
::setCreateaccountToken();
1486 $template->set( 'token', self
::getCreateaccountToken() );
1488 if ( !self
::getLoginToken() ) {
1489 self
::setLoginToken();
1491 $template->set( 'token', self
::getLoginToken() );
1494 # Prepare language selection links as needed
1495 if ( $wgLoginLanguageSelector ) {
1496 $template->set( 'languages', $this->makeLanguageSelector() );
1497 if ( $this->mLanguage
) {
1498 $template->set( 'uselang', $this->mLanguage
);
1502 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl
);
1503 // Use signupend-https for HTTPS requests if it's not blank, signupend otherwise
1504 $usingHTTPS = $this->mRequest
->getProtocol() == 'https';
1505 $signupendHTTPS = $this->msg( 'signupend-https' );
1506 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1507 $template->set( 'signupend', $signupendHTTPS->parse() );
1509 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1512 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
1513 if ( $usingHTTPS ) {
1514 $template->set( 'fromhttp', $this->mFromHTTP
);
1517 // Give authentication and captcha plugins a chance to modify the form
1518 $wgAuth->modifyUITemplate( $template, $this->mType
);
1519 if ( $this->mType
== 'signup' ) {
1520 Hooks
::run( 'UserCreateForm', array( &$template ) );
1522 Hooks
::run( 'UserLoginForm', array( &$template ) );
1525 $out->disallowUserJs(); // just in case...
1526 $out->addTemplate( $template );
1530 * Whether the login/create account form should display a link to the
1531 * other form (in addition to whatever the skin provides).
1536 private function showCreateOrLoginLink( &$user ) {
1537 if ( $this->mType
== 'signup' ) {
1539 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1547 * Check if a session cookie is present.
1549 * This will not pick up a cookie set during _this_ request, but is meant
1550 * to ensure that the client is returning the cookie which was set on a
1551 * previous pass through the system.
1556 function hasSessionCookie() {
1557 global $wgDisableCookieCheck;
1559 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1563 * Get the login token from the current session
1566 public static function getLoginToken() {
1569 return $wgRequest->getSessionData( 'wsLoginToken' );
1573 * Randomly generate a new login token and attach it to the current session
1575 public static function setLoginToken() {
1577 // Generate a token directly instead of using $user->getEditToken()
1578 // because the latter reuses $_SESSION['wsEditToken']
1579 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1583 * Remove any login token attached to the current session
1585 public static function clearLoginToken() {
1587 $wgRequest->setSessionData( 'wsLoginToken', null );
1591 * Get the createaccount token from the current session
1594 public static function getCreateaccountToken() {
1596 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1600 * Randomly generate a new createaccount token and attach it to the current session
1602 public static function setCreateaccountToken() {
1604 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1608 * Remove any createaccount token attached to the current session
1610 public static function clearCreateaccountToken() {
1612 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1616 * Renew the user's session id, using strong entropy
1618 private function renewSessionId() {
1619 global $wgSecureLogin, $wgCookieSecure;
1620 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1621 $wgCookieSecure = false;
1628 * @param string $type
1631 function cookieRedirectCheck( $type ) {
1632 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1633 $query = array( 'wpCookieCheck' => $type );
1634 if ( $this->mReturnTo
!== '' ) {
1635 $query['returnto'] = $this->mReturnTo
;
1636 $query['returntoquery'] = $this->mReturnToQuery
;
1638 $check = $titleObj->getFullURL( $query );
1640 $this->getOutput()->redirect( $check );
1644 * @param string $type
1647 function onCookieRedirectCheck( $type ) {
1648 if ( !$this->hasSessionCookie() ) {
1649 if ( $type == 'new' ) {
1650 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1651 } elseif ( $type == 'login' ) {
1652 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1655 $this->mainLoginForm( $this->msg( 'error' )->text() );
1658 $this->successfulLogin();
1663 * Produce a bar of links which allow the user to select another language
1664 * during login/registration but retain "returnto"
1668 function makeLanguageSelector() {
1669 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1670 if ( $msg->isBlank() ) {
1673 $langs = explode( "\n", $msg->text() );
1675 foreach ( $langs as $lang ) {
1676 $lang = trim( $lang, '* ' );
1677 $parts = explode( '|', $lang );
1678 if ( count( $parts ) >= 2 ) {
1679 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1683 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1684 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1688 * Create a language selector link for a particular language
1689 * Links back to this page preserving type and returnto
1691 * @param string $text Link text
1692 * @param string $lang Language code
1695 function makeLanguageSelectorLink( $text, $lang ) {
1696 if ( $this->getLanguage()->getCode() == $lang ) {
1697 // no link for currently used language
1698 return htmlspecialchars( $text );
1700 $query = array( 'uselang' => $lang );
1701 if ( $this->mType
== 'signup' ) {
1702 $query['type'] = 'signup';
1704 if ( $this->mReturnTo
!== '' ) {
1705 $query['returnto'] = $this->mReturnTo
;
1706 $query['returntoquery'] = $this->mReturnToQuery
;
1710 $targetLanguage = Language
::factory( $lang );
1711 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1713 return Linker
::linkKnown(
1714 $this->getPageTitle(),
1715 htmlspecialchars( $text ),
1721 protected function getGroupName() {
1726 * Private function to check password expiration, until AuthManager comes
1727 * along to handle that.
1729 * @return string|bool
1731 private function checkUserPasswordExpired( User
$user ) {
1732 global $wgPasswordExpireGrace;
1733 $dbr = wfGetDB( DB_SLAVE
);
1734 $ts = $dbr->selectField( 'user', 'user_password_expires', array( 'user_id' => $user->getId() ) );
1737 $now = wfTimestamp();
1738 $expUnix = wfTimestamp( TS_UNIX
, $ts );
1739 if ( $ts !== null && $expUnix < $now ) {
1740 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';