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
;
25 use MediaWiki\Session\SessionManager
;
28 * Implements Special:UserLogin
30 * @ingroup SpecialPage
32 class LoginFormPreAuthManager
extends SpecialPage
{
36 const WRONG_PLUGIN_PASS
= 3;
42 const CREATE_BLOCKED
= 9;
44 const USER_BLOCKED
= 11;
45 const NEED_TOKEN
= 12;
46 const WRONG_TOKEN
= 13;
47 const USER_MIGRATED
= 14;
49 public static $statusCodes = [
50 self
::SUCCESS
=> 'success',
51 self
::NO_NAME
=> 'no_name',
52 self
::ILLEGAL
=> 'illegal',
53 self
::WRONG_PLUGIN_PASS
=> 'wrong_plugin_pass',
54 self
::NOT_EXISTS
=> 'not_exists',
55 self
::WRONG_PASS
=> 'wrong_pass',
56 self
::EMPTY_PASS
=> 'empty_pass',
57 self
::RESET_PASS
=> 'reset_pass',
58 self
::ABORTED
=> 'aborted',
59 self
::CREATE_BLOCKED
=> 'create_blocked',
60 self
::THROTTLED
=> 'throttled',
61 self
::USER_BLOCKED
=> 'user_blocked',
62 self
::NEED_TOKEN
=> 'need_token',
63 self
::WRONG_TOKEN
=> 'wrong_token',
64 self
::USER_MIGRATED
=> 'user_migrated',
68 * Valid error and warning messages
70 * Special:Userlogin can show an error or warning message on the form when
71 * coming from another page. This is done via the ?error= or ?warning= GET
74 * This array is the list of valid message keys. All other values will be
80 public static $validErrorMessages = [
81 'exception-nologin-text',
83 'changeemail-no-info',
85 'confirmemail_needlogin',
89 public $mAbortLoginErrorMsg = null;
91 * @var int How many seconds user is throttled for
94 public $mThrottleWait = '?';
100 protected $mCookieCheck;
103 protected $mCreateaccount;
104 protected $mCreateaccountMail;
105 protected $mLoginattempt;
106 protected $mRemember;
109 protected $mLanguage;
110 protected $mSkipCookieCheck;
111 protected $mReturnToQuery;
113 protected $mStickHTTPS;
116 protected $mRealName;
117 protected $mEntryError = '';
118 protected $mEntryErrorType = 'error';
120 private $mTempPasswordUsed;
121 private $mLoaded = false;
122 private $mSecureLoginUrl;
124 /** @var WebRequest */
125 private $mOverrideRequest = null;
127 /** @var WebRequest Effective request; set at the beginning of load */
128 private $mRequest = null;
131 * @param WebRequest $request
133 public function __construct( $request = null ) {
134 global $wgUseMediaWikiUIEverywhere;
135 parent
::__construct( 'Userlogin' );
137 $this->mOverrideRequest
= $request;
138 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
139 $wgUseMediaWikiUIEverywhere = true;
142 public function doesWrites() {
147 * Returns an array of all valid error messages.
151 public static function getValidErrorMessages() {
152 static $messages = null;
154 $messages = self
::$validErrorMessages;
155 Hooks
::run( 'LoginFormValidErrorMessages', [ &$messages ] );
165 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
167 if ( $this->mLoaded
) {
170 $this->mLoaded
= true;
172 if ( $this->mOverrideRequest
=== null ) {
173 $request = $this->getRequest();
175 $request = $this->mOverrideRequest
;
177 $this->mRequest
= $request;
179 $this->mType
= $request->getText( 'type' );
180 $this->mUsername
= $request->getText( 'wpName' );
181 $this->mPassword
= $request->getText( 'wpPassword' );
182 $this->mRetype
= $request->getText( 'wpRetype' );
183 $this->mDomain
= $request->getText( 'wpDomain' );
184 $this->mReason
= $request->getText( 'wpReason' );
185 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
186 $this->mPosted
= $request->wasPosted();
187 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
189 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' ) && !$this->mCreateaccountMail
;
190 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
191 $this->mAction
= $request->getVal( 'action' );
192 $this->mRemember
= $request->getCheck( 'wpRemember' );
193 $this->mFromHTTP
= $request->getBool( 'fromhttp', false )
194 ||
$request->getBool( 'wpFromhttp', false );
195 $this->mStickHTTPS
= ( !$this->mFromHTTP
&& $request->getProtocol() === 'https' )
196 ||
$request->getBool( 'wpForceHttps', false );
197 $this->mLanguage
= $request->getText( 'uselang' );
198 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
199 $this->mToken
= $this->mType
== 'signup'
200 ?
$request->getVal( 'wpCreateaccountToken' )
201 : $request->getVal( 'wpLoginToken' );
202 $this->mReturnTo
= $request->getVal( 'returnto', '' );
203 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
205 // Show an error or warning passed on from a previous page
206 $entryError = $this->msg( $request->getVal( 'error', '' ) );
207 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
208 // bc: provide login link as a parameter for messages where the translation
210 $loginreqlink = Linker
::linkKnown(
211 $this->getPageTitle(),
212 $this->msg( 'loginreqlink' )->escaped(),
215 'returnto' => $this->mReturnTo
,
216 'returntoquery' => $this->mReturnToQuery
,
217 'uselang' => $this->mLanguage
,
218 'fromhttp' => $this->mFromHTTP ?
'1' : '0',
222 // Only show valid error or warning messages.
223 if ( $entryError->exists()
224 && in_array( $entryError->getKey(), self
::getValidErrorMessages() )
226 $this->mEntryErrorType
= 'error';
227 $this->mEntryError
= $entryError->rawParams( $loginreqlink )->parse();
229 } elseif ( $entryWarning->exists()
230 && in_array( $entryWarning->getKey(), self
::getValidErrorMessages() )
232 $this->mEntryErrorType
= 'warning';
233 $this->mEntryError
= $entryWarning->rawParams( $loginreqlink )->parse();
236 if ( $wgEnableEmail ) {
237 $this->mEmail
= $request->getText( 'wpEmail' );
241 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
242 $this->mRealName
= $request->getText( 'wpRealName' );
244 $this->mRealName
= '';
247 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
248 $this->mDomain
= $wgAuth->getDomain();
250 $wgAuth->setDomain( $this->mDomain
);
252 # 1. When switching accounts, it sucks to get automatically logged out
253 # 2. Do not return to PasswordReset after a successful password change
254 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
255 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
256 if ( is_object( $returnToTitle )
257 && ( $returnToTitle->isSpecial( 'Userlogout' )
258 ||
$returnToTitle->isSpecial( 'PasswordReset' ) )
260 $this->mReturnTo
= '';
261 $this->mReturnToQuery
= '';
265 function getDescription() {
266 if ( $this->mType
=== 'signup' ) {
267 return $this->msg( 'createaccount' )->text();
269 return $this->msg( 'login' )->text();
274 * @param string|null $subPage
276 public function execute( $subPage ) {
277 // Make sure session is persisted
278 $session = SessionManager
::getGlobalSession();
283 // Check for [[Special:Userlogin/signup]]. This affects form display and
285 if ( $subPage == 'signup' ) {
286 $this->mType
= 'signup';
290 // Make sure it's possible to log in
291 if ( $this->mType
!== 'signup' && !$session->canSetUser() ) {
292 throw new ErrorPageError(
293 'cannotloginnow-title',
294 'cannotloginnow-text',
296 $session->getProvider()->describe( RequestContext
::getMain()->getLanguage() )
302 * In the case where the user is already logged in, and was redirected to
303 * the login form from a page that requires login, do not show the login
304 * page. The use case scenario for this is when a user opens a large number
305 * of tabs, is redirected to the login page on all of them, and then logs
306 * in on one, expecting all the others to work properly.
308 * However, do show the form if it was visited intentionally (no 'returnto'
309 * is present). People who often switch between several accounts have grown
310 * accustomed to this behavior.
313 $this->mType
!== 'signup' &&
315 $this->getUser()->isLoggedIn() &&
316 ( $this->mReturnTo
!== '' ||
$this->mReturnToQuery
!== '' )
318 $this->successfulLogin();
321 // If logging in and not on HTTPS, either redirect to it or offer a link.
322 global $wgSecureLogin;
323 if ( $this->mRequest
->getProtocol() !== 'https' ) {
324 $title = $this->getFullTitle();
326 'returnto' => $this->mReturnTo
!== '' ?
$this->mReturnTo
: null,
327 'returntoquery' => $this->mReturnToQuery
!== '' ?
328 $this->mReturnToQuery
: null,
330 ( $this->mEntryErrorType
=== 'error' ?
'error' : 'warning' ) => $this->mEntryError
,
331 ] +
$this->mRequest
->getQueryValues();
332 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
334 && wfCanIPUseHTTPS( $this->getRequest()->getIP() )
335 && !$this->mFromHTTP
) // Avoid infinite redirect
337 $url = wfAppendQuery( $url, 'fromhttp=1' );
338 $this->getOutput()->redirect( $url );
339 // Since we only do this redir to change proto, always vary
340 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
344 // A wiki without HTTPS login support should set $wgServer to
345 // http://somehost, in which case the secure URL generated
346 // above won't actually start with https://
347 if ( substr( $url, 0, 8 ) === 'https://' ) {
348 $this->mSecureLoginUrl
= $url;
353 if ( !is_null( $this->mCookieCheck
) ) {
354 $this->onCookieRedirectCheck( $this->mCookieCheck
);
357 } elseif ( $this->mPosted
) {
358 if ( $this->mCreateaccount
) {
359 $this->addNewAccount();
362 } elseif ( $this->mCreateaccountMail
) {
363 $this->addNewAccountMailPassword();
366 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
367 $this->processLogin();
372 $this->mainLoginForm( $this->mEntryError
, $this->mEntryErrorType
);
378 function addNewAccountMailPassword() {
379 if ( $this->mEmail
== '' ) {
380 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
385 $status = $this->addNewAccountInternal();
386 LoggerFactory
::getInstance( 'authmanager' )->info(
387 'Account creation attempt with mailed password',
388 [ 'event' => 'accountcreation', 'status' => $status ]
390 if ( !$status->isGood() ) {
391 $error = $status->getMessage();
392 $this->mainLoginForm( $error->toString() );
398 $u = $status->getValue();
400 // Wipe the initial password and mail a temporary one
401 $u->setPassword( null );
403 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
405 Hooks
::run( 'AddNewAccount', [ $u, true ] );
406 $u->addNewUserLogEntry( 'byemail', $this->mReason
);
408 $out = $this->getOutput();
409 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
411 if ( !$result->isGood() ) {
412 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
414 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
415 $this->executeReturnTo( 'success' );
423 function addNewAccount() {
424 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
426 # Create the account and abort if there's a problem doing so
427 $status = $this->addNewAccountInternal();
428 LoggerFactory
::getInstance( 'authmanager' )->info( 'Account creation attempt', [
429 'event' => 'accountcreation',
433 if ( !$status->isGood() ) {
434 $error = $status->getMessage();
435 $this->mainLoginForm( $error->toString() );
440 $u = $status->getValue();
442 # Only save preferences if the user is not creating an account for someone else.
443 if ( $this->getUser()->isAnon() ) {
444 # If we showed up language selection links, and one was in use, be
445 # smart (and sensible) and save that language as the user's preference
446 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
447 $u->setOption( 'language', $this->mLanguage
);
450 # Otherwise the user's language preference defaults to $wgContLang,
451 # but it may be better to set it to their preferred $wgContLang variant,
452 # based on browser preferences or URL parameters.
453 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
455 if ( $wgContLang->hasVariants() ) {
456 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
460 $out = $this->getOutput();
462 # Send out an email authentication message if needed
463 if ( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
464 $status = $u->sendConfirmationMail();
465 if ( $status->isGood() ) {
466 $out->addWikiMsg( 'confirmemail_oncreate' );
468 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
472 # Save settings (including confirmation token)
475 # If not logged in, assume the new account as the current one and set
476 # session cookies then show a "welcome" message or a "need cookies"
478 if ( $this->getUser()->isAnon() ) {
481 // This should set it for OutputPage and the Skin
482 // which is needed or the personal links will be
484 $this->getContext()->setUser( $u );
485 Hooks
::run( 'AddNewAccount', [ $u, false ] );
486 $u->addNewUserLogEntry( 'create' );
487 if ( $this->hasSessionCookie() ) {
488 $this->successfulCreation();
490 $this->cookieRedirectCheck( 'new' );
493 # Confirm that the account was created
494 $out->setPageTitle( $this->msg( 'accountcreated' ) );
495 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
496 $out->addReturnTo( $this->getPageTitle() );
497 Hooks
::run( 'AddNewAccount', [ $u, false ] );
498 $u->addNewUserLogEntry( 'create2', $this->mReason
);
505 * Make a new user account using the loaded data.
507 * @throws PermissionsError|ReadOnlyError
510 public function addNewAccountInternal() {
511 global $wgAuth, $wgAccountCreationThrottle, $wgEmailConfirmToEdit;
513 // If the user passes an invalid domain, something is fishy
514 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
515 return Status
::newFatal( 'wrongpassword' );
518 // If we are not allowing users to login locally, we should be checking
519 // to see if the user is actually able to authenticate to the authenti-
520 // cation server before they create an account (otherwise, they can
521 // create a local account and login as any domain user). We only need
522 // to check this for domains that aren't local.
523 if ( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
525 !$wgAuth->canCreateAccounts() &&
527 !$wgAuth->userExists( $this->mUsername
) ||
528 !$wgAuth->authenticate( $this->mUsername
, $this->mPassword
)
531 return Status
::newFatal( 'wrongpassword' );
535 if ( wfReadOnly() ) {
536 throw new ReadOnlyError
;
539 # Request forgery checks.
540 $token = self
::getCreateaccountToken();
541 if ( $token->wasNew() ) {
542 return Status
::newFatal( 'nocookiesfornew' );
545 # The user didn't pass a createaccount token
546 if ( !$this->mToken
) {
547 return Status
::newFatal( 'sessionfailure' );
550 # Validate the createaccount token
551 if ( !$token->match( $this->mToken
) ) {
552 return Status
::newFatal( 'sessionfailure' );
556 $currentUser = $this->getUser();
557 $creationBlock = $currentUser->isBlockedFromCreateAccount();
558 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
559 throw new PermissionsError( 'createaccount' );
560 } elseif ( $creationBlock instanceof Block
) {
561 // Throws an ErrorPageError.
562 $this->userBlockedMessage( $creationBlock );
564 // This should never be reached.
568 # Include checks that will include GlobalBlocking (Bug 38333)
569 $permErrors = $this->getPageTitle()->getUserPermissionsErrors(
575 if ( count( $permErrors ) ) {
576 throw new PermissionsError( 'createaccount', $permErrors );
579 $ip = $this->getRequest()->getIP();
580 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
581 return Status
::newFatal( 'sorbs_create_account_reason' );
584 # Now create a dummy user ($u) and check if it is valid
585 $u = User
::newFromName( $this->mUsername
, 'creatable' );
587 return Status
::newFatal( 'noname' );
590 $cache = ObjectCache
::getLocalClusterInstance();
591 # Make sure the user does not exist already
592 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $this->mUsername
) ) );
594 return Status
::newFatal( 'usernameinprogress' );
595 } elseif ( $u->idForName( User
::READ_LOCKING
) ) {
596 return Status
::newFatal( 'userexists' );
599 if ( $this->mCreateaccountMail
) {
600 # do not force a password for account creation by email
601 # set invalid password, it will be replaced later by a random generated password
602 $this->mPassword
= null;
604 if ( $this->mPassword
!== $this->mRetype
) {
605 return Status
::newFatal( 'badretype' );
608 # check for password validity, return a fatal Status if invalid
609 $validity = $u->checkPasswordValidity( $this->mPassword
, 'create' );
610 if ( !$validity->isGood() ) {
611 $validity->ok
= false; // make sure this Status is fatal
616 # if you need a confirmed email address to edit, then obviously you
617 # need an email address.
618 if ( $wgEmailConfirmToEdit && strval( $this->mEmail
) === '' ) {
619 return Status
::newFatal( 'noemailtitle' );
622 if ( strval( $this->mEmail
) !== '' && !Sanitizer
::validateEmail( $this->mEmail
) ) {
623 return Status
::newFatal( 'invalidemailaddress' );
626 # Set some additional data so the AbortNewAccount hook can be used for
627 # more than just username validation
628 $u->setEmail( $this->mEmail
);
629 $u->setRealName( $this->mRealName
);
633 if ( !Hooks
::run( 'AbortNewAccount', [ $u, &$abortError, &$abortStatus ] ) ) {
634 // Hook point to add extra creation throttles and blocks
635 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
636 if ( $abortStatus === null ) {
637 // Report back the old string as a raw message status.
638 // This will report the error back as 'createaccount-hook-aborted'
639 // with the given string as the message.
640 // To return a different error code, return a Status object.
641 $abortError = new Message( 'createaccount-hook-aborted', [ $abortError ] );
644 return Status
::newFatal( $abortError );
646 // For MediaWiki 1.23+ and updated hooks, return the Status object
647 // returned from the hook.
652 // Hook point to check for exempt from account creation throttle
653 if ( !Hooks
::run( 'ExemptFromAccountCreationThrottle', [ $ip ] ) ) {
654 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook " .
655 "allowed account creation w/o throttle\n" );
657 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
658 $key = wfGlobalCacheKey( 'acctcreate', 'ip', $ip );
659 $value = $cache->get( $key );
661 $cache->set( $key, 0, $cache::TTL_DAY
);
663 if ( $value >= $wgAccountCreationThrottle ) {
664 return Status
::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
666 $cache->incr( $key );
670 if ( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
671 return Status
::newFatal( 'externaldberror' );
674 self
::clearCreateaccountToken();
676 return $this->initUser( $u, false );
680 * Actually add a user to the database.
681 * Give it a User object that has been initialised with a name.
684 * @param bool $autocreate True if this is an autocreation via auth plugin
685 * @return Status Status object, with the User object in the value member on success
688 function initUser( $u, $autocreate ) {
691 $status = $u->addToDatabase();
692 if ( !$status->isOK() ) {
696 if ( $wgAuth->allowPasswordChange() ) {
697 $u->setPassword( $this->mPassword
);
700 $u->setEmail( $this->mEmail
);
701 $u->setRealName( $this->mRealName
);
704 Hooks
::run( 'LocalUserCreated', [ $u, $autocreate ] );
706 $wgAuth->initUser( $u, $autocreate );
707 if ( $oldUser !== $u ) {
708 wfWarn( get_class( $wgAuth ) . '::initUser() replaced the user object' );
714 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
716 // Watch user's userpage and talk page
717 $u->addWatch( $u->getUserPage(), User
::IGNORE_USER_RIGHTS
);
719 return Status
::newGood( $u );
723 * Internally authenticate the login request.
725 * This may create a local account as a side effect if the
726 * authentication plugin allows transparent local account
730 public function authenticateUserData() {
731 global $wgUser, $wgAuth;
735 if ( $this->mUsername
== '' ) {
736 return self
::NO_NAME
;
739 // We require a login token to prevent login CSRF
740 // Handle part of this before incrementing the throttle so
741 // token-less login attempts don't count towards the throttle
742 // but wrong-token attempts do.
744 // If the user doesn't have a login token yet, set one.
745 $token = self
::getLoginToken();
746 if ( $token->wasNew() ) {
747 return self
::NEED_TOKEN
;
749 // If the user didn't pass a login token, tell them we need one
750 if ( !$this->mToken
) {
751 return self
::NEED_TOKEN
;
754 $throttleCount = self
::incrementLoginThrottle( $this->mUsername
);
755 if ( $throttleCount ) {
756 $this->mThrottleWait
= $throttleCount['wait'];
757 return self
::THROTTLED
;
760 // Validate the login token
761 if ( !$token->match( $this->mToken
) ) {
762 return self
::WRONG_TOKEN
;
765 // Load the current user now, and check to see if we're logging in as
766 // the same name. This is necessary because loading the current user
767 // (say by calling getName()) calls the UserLoadFromSession hook, which
768 // potentially creates the user in the database. Until we load $wgUser,
769 // checking for user existence using User::newFromName($name)->getId() below
770 // will effectively be using stale data.
771 if ( $this->getUser()->getName() === $this->mUsername
) {
772 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
774 return self
::SUCCESS
;
777 $u = User
::newFromName( $this->mUsername
);
778 if ( $u === false ) {
779 return self
::ILLEGAL
;
783 // Give extensions a way to indicate the username has been updated,
784 // rather than telling the user the account doesn't exist.
785 if ( !Hooks
::run( 'LoginUserMigrated', [ $u, &$msg ] ) ) {
786 $this->mAbortLoginErrorMsg
= $msg;
787 return self
::USER_MIGRATED
;
790 if ( !User
::isUsableName( $u->getName() ) ) {
791 return self
::ILLEGAL
;
794 $isAutoCreated = false;
795 if ( $u->getId() == 0 ) {
796 $status = $this->attemptAutoCreate( $u );
797 if ( $status !== self
::SUCCESS
) {
800 $isAutoCreated = true;
806 // Give general extensions, such as a captcha, a chance to abort logins
807 $abort = self
::ABORTED
;
808 if ( !Hooks
::run( 'AbortLogin', [ $u, $this->mPassword
, &$abort, &$msg ] ) ) {
809 if ( !in_array( $abort, array_keys( self
::$statusCodes ), true ) ) {
810 throw new Exception( 'Invalid status code returned from AbortLogin hook: ' . $abort );
812 $this->mAbortLoginErrorMsg
= $msg;
816 global $wgBlockDisablesLogin;
817 if ( !$u->checkPassword( $this->mPassword
) ) {
818 if ( $u->checkTemporaryPassword( $this->mPassword
) ) {
820 * The e-mailed temporary password should not be used for actu-
821 * al logins; that's a very sloppy habit, and insecure if an
822 * attacker has a few seconds to click "search" on someone's
825 * Allow it to be used only to reset the password a single time
826 * to a new value, which won't be in the user's e-mail ar-
829 * For backwards compatibility, we'll still recognize it at the
830 * login form to minimize surprises for people who have been
831 * logging in with a temporary password for some time.
833 * As a side-effect, we can authenticate the user's e-mail ad-
834 * dress if it's not already done, since the temporary password
835 * was sent via e-mail.
837 if ( !$u->isEmailConfirmed() && !wfReadOnly() ) {
842 // At this point we just return an appropriate code/ indicating
843 // that the UI should show a password reset form; bot inter-
844 // faces etc will probably just fail cleanly here.
845 $this->mAbortLoginErrorMsg
= 'resetpass-temp-emailed';
846 $this->mTempPasswordUsed
= true;
847 $retval = self
::RESET_PASS
;
849 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
851 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
852 // If we've enabled it, make it so that a blocked user cannot login
853 $retval = self
::USER_BLOCKED
;
854 } elseif ( $this->checkUserPasswordExpired( $u ) == 'hard' ) {
855 // Force reset now, without logging in
856 $retval = self
::RESET_PASS
;
857 $this->mAbortLoginErrorMsg
= 'resetpass-expired';
859 Hooks
::run( 'UserLoggedIn', [ $u ] );
861 $wgAuth->updateUser( $u );
862 if ( $oldUser !== $u ) {
863 wfWarn( get_class( $wgAuth ) . '::updateUser() replaced the user object' );
866 // This should set it for OutputPage and the Skin
867 // which is needed or the personal links will be
869 $this->getContext()->setUser( $u );
871 // Please reset throttle for successful logins, thanks!
872 self
::clearLoginThrottle( $this->mUsername
);
874 if ( $isAutoCreated ) {
875 // Must be run after $wgUser is set, for correct new user log
876 Hooks
::run( 'AuthPluginAutoCreate', [ $u ] );
879 $retval = self
::SUCCESS
;
881 Hooks
::run( 'LoginAuthenticateAudit', [ $u, $this->mPassword
, $retval ] );
887 * Increment the login attempt throttle hit count for the (username,current IP)
888 * tuple unless the throttle was already reached.
890 * @since 1.27 Return value changed.
891 * @param string $username The user name
892 * @return bool|array false if below limit or an array if above limit
893 * Array contains keys wait, count, and throttleIndex
895 public static function incrementLoginThrottle( $username ) {
896 global $wgPasswordAttemptThrottle, $wgRequest;
897 $canUsername = User
::getCanonicalName( $username, 'usable' );
898 $username = $canUsername !== false ?
$canUsername : $username;
901 if ( is_array( $wgPasswordAttemptThrottle ) ) {
902 $throttleConfig = $wgPasswordAttemptThrottle;
903 if ( isset( $wgPasswordAttemptThrottle['count'] ) ) {
904 // old style. Convert for backwards compat.
905 $throttleConfig = [ $wgPasswordAttemptThrottle ];
907 foreach ( $throttleConfig as $index => $specificThrottle ) {
908 if ( isset( $specificThrottle['allIPs'] ) ) {
911 $ip = $wgRequest->getIP();
913 $throttleKey = wfGlobalCacheKey( 'password-throttle',
914 $index, $ip, md5( $username )
916 $count = $specificThrottle['count'];
917 $period = $specificThrottle['seconds'];
919 $cache = ObjectCache
::getLocalClusterInstance();
920 $throttleCount = $cache->get( $throttleKey );
921 if ( !$throttleCount ) {
922 $cache->add( $throttleKey, 1, $period ); // start counter
923 } elseif ( $throttleCount < $count ) {
924 $cache->incr( $throttleKey );
925 } elseif ( $throttleCount >= $count ) {
926 $logMsg = 'Login attempt rejected because logins to '
927 . '{acct} from IP {ip} have been throttled for '
928 . '{period} seconds due to {count} failed attempts';
929 // If we are hitting a throttle for >= 50 attempts,
930 // it is much more likely to be an attack than someone
931 // simply forgetting their password, so log it at a
933 $level = $count >= 50 ? LogLevel
::WARNING
: LogLevel
::INFO
;
934 // It should be noted that once the throttle is hit,
935 // every attempt to login will generate the log message
936 // until the throttle expires, not just the attempt that
937 // puts the throttle over the top.
938 LoggerFactory
::getInstance( 'password-throttle' )->log(
946 'throttleIdentifier' => $index,
947 'method' => __METHOD__
952 'throttleIndex' => $index,
963 * Increment the login attempt throttle hit count for the (username,current IP)
964 * tuple unless the throttle was already reached.
966 * @deprecated Use LoginForm::incrementLoginThrottle instead
967 * @param string $username The user name
968 * @return bool|int true if above throttle, or 0 (prior to 1.27, returned current count)
970 public static function incLoginThrottle( $username ) {
971 wfDeprecated( __METHOD__
, "1.27" );
972 $res = self
::incrementLoginThrottle( $username );
973 return is_array( $res ) ?
true : 0;
977 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
978 * @param string $username The user name
981 public static function clearLoginThrottle( $username ) {
982 global $wgRequest, $wgPasswordAttemptThrottle;
983 $canUsername = User
::getCanonicalName( $username, 'usable' );
984 $username = $canUsername !== false ?
$canUsername : $username;
986 if ( is_array( $wgPasswordAttemptThrottle ) ) {
987 $throttleConfig = $wgPasswordAttemptThrottle;
988 if ( isset( $wgPasswordAttemptThrottle['count'] ) ) {
989 // old style. Convert for backwards compat.
990 $throttleConfig = [ $wgPasswordAttemptThrottle ];
992 foreach ( $throttleConfig as $index => $specificThrottle ) {
993 if ( isset( $specificThrottle['allIPs'] ) ) {
996 $ip = $wgRequest->getIP();
998 $throttleKey = wfGlobalCacheKey( 'password-throttle', $index,
999 $ip, md5( $username )
1001 ObjectCache
::getLocalClusterInstance()->delete( $throttleKey );
1007 * Attempt to automatically create a user on login. Only succeeds if there
1008 * is an external authentication method which allows it.
1012 * @return int Status code
1014 function attemptAutoCreate( $user ) {
1017 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
1018 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
1020 return self
::CREATE_BLOCKED
;
1023 if ( !$wgAuth->autoCreate() ) {
1024 return self
::NOT_EXISTS
;
1027 if ( !$wgAuth->userExists( $user->getName() ) ) {
1028 wfDebug( __METHOD__
. ": user does not exist\n" );
1030 return self
::NOT_EXISTS
;
1033 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
1034 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
1036 return self
::WRONG_PLUGIN_PASS
;
1040 if ( !Hooks
::run( 'AbortAutoAccount', [ $user, &$abortError ] ) ) {
1041 // Hook point to add extra creation throttles and blocks
1042 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
1043 $this->mAbortLoginErrorMsg
= $abortError;
1045 return self
::ABORTED
;
1048 wfDebug( __METHOD__
. ": creating account\n" );
1049 $status = $this->initUser( $user, true );
1051 if ( !$status->isOK() ) {
1052 $errors = $status->getErrorsByType( 'error' );
1053 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
1055 return self
::ABORTED
;
1058 return self
::SUCCESS
;
1061 function processLogin() {
1062 global $wgLang, $wgSecureLogin, $wgInvalidPasswordReset;
1064 $authRes = $this->authenticateUserData();
1065 switch ( $authRes ) {
1067 # We've verified now, update the real record
1068 $user = $this->getUser();
1071 if ( $user->requiresHTTPS() ) {
1072 $this->mStickHTTPS
= true;
1075 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1076 $user->setCookies( $this->mRequest
, false, $this->mRemember
);
1078 $user->setCookies( $this->mRequest
, null, $this->mRemember
);
1080 self
::clearLoginToken();
1082 // Reset the throttle
1083 self
::clearLoginThrottle( $this->mUsername
);
1085 $request = $this->getRequest();
1086 if ( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
1087 /* Replace the language object to provide user interface in
1088 * correct language immediately on this first page load.
1090 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
1091 $userLang = Language
::factory( $code );
1092 $wgLang = $userLang;
1093 RequestContext
::getMain()->setLanguage( $userLang );
1094 $this->getContext()->setLanguage( $userLang );
1095 // Reset SessionID on Successful login (bug 40995)
1096 $this->renewSessionId();
1097 if ( $this->checkUserPasswordExpired( $this->getUser() ) == 'soft' ) {
1098 $this->resetLoginForm( $this->msg( 'resetpass-expired-soft' ) );
1099 } elseif ( $wgInvalidPasswordReset
1100 && !$user->isValidPassword( $this->mPassword
)
1102 $status = $user->checkPasswordValidity(
1106 $this->resetLoginForm(
1107 $status->getMessage( 'resetpass-validity-soft' )
1110 $this->successfulLogin();
1113 $this->cookieRedirectCheck( 'login' );
1117 case self
::NEED_TOKEN
:
1118 $error = $this->mAbortLoginErrorMsg ?
: 'nocookiesforlogin';
1119 $this->mainLoginForm( $this->msg( $error )->parse() );
1121 case self
::WRONG_TOKEN
:
1122 $error = $this->mAbortLoginErrorMsg ?
: 'sessionfailure';
1123 $this->mainLoginForm( $this->msg( $error )->text() );
1127 $error = $this->mAbortLoginErrorMsg ?
: 'noname';
1128 $this->mainLoginForm( $this->msg( $error )->text() );
1130 case self
::WRONG_PLUGIN_PASS
:
1131 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
1132 $this->mainLoginForm( $this->msg( $error )->text() );
1134 case self
::NOT_EXISTS
:
1135 if ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1136 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchuser';
1137 $this->mainLoginForm( $this->msg( $error,
1138 wfEscapeWikiText( $this->mUsername
) )->parse() );
1140 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchusershort';
1141 $this->mainLoginForm( $this->msg( $error,
1142 wfEscapeWikiText( $this->mUsername
) )->text() );
1145 case self
::WRONG_PASS
:
1146 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
1147 $this->mainLoginForm( $this->msg( $error )->text() );
1149 case self
::EMPTY_PASS
:
1150 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpasswordempty';
1151 $this->mainLoginForm( $this->msg( $error )->text() );
1153 case self
::RESET_PASS
:
1154 $error = $this->mAbortLoginErrorMsg ?
: 'resetpass_announce';
1155 $this->resetLoginForm( $this->msg( $error ) );
1157 case self
::CREATE_BLOCKED
:
1158 $this->userBlockedMessage( $this->getUser()->isBlockedFromCreateAccount() );
1160 case self
::THROTTLED
:
1161 $error = $this->mAbortLoginErrorMsg ?
: 'login-throttled';
1162 $this->mainLoginForm( $this->msg( $error )
1163 ->durationParams( $this->mThrottleWait
)->text()
1166 case self
::USER_BLOCKED
:
1167 $error = $this->mAbortLoginErrorMsg ?
: 'login-userblocked';
1168 $this->mainLoginForm( $this->msg( $error, $this->mUsername
)->escaped() );
1171 $error = $this->mAbortLoginErrorMsg ?
: 'login-abort-generic';
1172 $this->mainLoginForm( $this->msg( $error,
1173 wfEscapeWikiText( $this->mUsername
) )->text() );
1175 case self
::USER_MIGRATED
:
1176 $error = $this->mAbortLoginErrorMsg ?
: 'login-migrated-generic';
1178 if ( is_array( $error ) ) {
1179 $error = array_shift( $this->mAbortLoginErrorMsg
);
1180 $params = $this->mAbortLoginErrorMsg
;
1182 $this->mainLoginForm( $this->msg( $error, $params )->text() );
1185 throw new MWException( 'Unhandled case value' );
1188 LoggerFactory
::getInstance( 'authmanager' )->info( 'Login attempt', [
1190 'successful' => $authRes === self
::SUCCESS
,
1191 'status' => LoginForm
::$statusCodes[$authRes],
1196 * Show the Special:ChangePassword form, with custom message
1197 * @param Message $msg
1199 protected function resetLoginForm( Message
$msg ) {
1200 // Allow hooks to explain this password reset in more detail
1201 Hooks
::run( 'LoginPasswordResetMessage', [ &$msg, $this->mUsername
] );
1202 $reset = new SpecialChangePasswordPreAuthManager();
1203 $derivative = new DerivativeContext( $this->getContext() );
1204 $derivative->setTitle( $reset->getPageTitle() );
1205 $reset->setContext( $derivative );
1206 if ( !$this->mTempPasswordUsed
) {
1207 $reset->setOldPasswordMessage( 'oldpassword' );
1209 $reset->setChangeMessage( $msg );
1210 $reset->execute( null );
1215 * @param bool $throttle
1216 * @param string $emailTitle Message name of email title
1217 * @param string $emailText Message name of email text
1220 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle',
1221 $emailText = 'passwordremindertext'
1223 global $wgNewPasswordExpiry, $wgMinimalPasswordLength;
1225 if ( $u->getEmail() == '' ) {
1226 return Status
::newFatal( 'noemail', $u->getName() );
1228 $ip = $this->getRequest()->getIP();
1230 return Status
::newFatal( 'badipaddress' );
1233 $currentUser = $this->getUser();
1234 Hooks
::run( 'User::mailPasswordInternal', [ &$currentUser, &$ip, &$u ] );
1236 $np = PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1237 $u->setNewpassword( $np, $throttle );
1239 $userLanguage = $u->getOption( 'language' );
1241 $mainPage = Title
::newMainPage();
1242 $mainPageUrl = $mainPage->getCanonicalURL();
1244 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $mainPageUrl . '>',
1245 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
1246 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
1252 * Run any hooks registered for logins, then HTTP redirect to
1253 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
1254 * nice message here, but that's really not as useful as just being sent to
1255 * wherever you logged in from. It should be clear that the action was
1256 * successful, given the lack of error messages plus the appearance of your
1257 * name in the upper right.
1261 function successfulLogin() {
1262 # Run any hooks; display injected HTML if any, else redirect
1263 $currentUser = $this->getUser();
1264 $injected_html = '';
1265 Hooks
::run( 'UserLoginComplete', [ &$currentUser, &$injected_html ] );
1267 if ( $injected_html !== '' ) {
1268 $this->displaySuccessfulAction( 'success', $this->msg( 'loginsuccesstitle' ),
1269 'loginsuccess', $injected_html );
1271 $this->executeReturnTo( 'successredirect' );
1276 * Run any hooks registered for logins, then display a message welcoming
1281 function successfulCreation() {
1282 # Run any hooks; display injected HTML
1283 $currentUser = $this->getUser();
1284 $injected_html = '';
1285 $welcome_creation_msg = 'welcomecreation-msg';
1287 Hooks
::run( 'UserLoginComplete', [ &$currentUser, &$injected_html ] );
1290 * Let any extensions change what message is shown.
1291 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
1294 Hooks
::run( 'BeforeWelcomeCreation', [ &$welcome_creation_msg, &$injected_html ] );
1296 $this->displaySuccessfulAction(
1298 $this->msg( 'welcomeuser', $this->getUser()->getName() ),
1299 $welcome_creation_msg, $injected_html
1304 * Display a "successful action" page.
1306 * @param string $type Condition of return to; see `executeReturnTo`
1307 * @param string|Message $title Page's title
1308 * @param string $msgname
1309 * @param string $injected_html
1311 private function displaySuccessfulAction( $type, $title, $msgname, $injected_html ) {
1312 $out = $this->getOutput();
1313 $out->setPageTitle( $title );
1315 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
1318 $out->addHTML( $injected_html );
1320 $this->executeReturnTo( $type );
1324 * Output a message that informs the user that they cannot create an account because
1325 * there is a block on them or their IP which prevents account creation. Note that
1326 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
1327 * setting on blocks (bug 13611).
1328 * @param Block $block The block causing this error
1329 * @throws ErrorPageError
1331 function userBlockedMessage( Block
$block ) {
1332 # Let's be nice about this, it's likely that this feature will be used
1333 # for blocking large numbers of innocent people, e.g. range blocks on
1334 # schools. Don't blame it on the user. There's a small chance that it
1335 # really is the user's fault, i.e. the username is blocked and they
1336 # haven't bothered to log out before trying to create an account to
1337 # evade it, but we'll leave that to their guilty conscience to figure
1340 $block->getTarget(),
1341 $block->mReason ?
$block->mReason
: $this->msg( 'blockednoreason' )->text(),
1345 if ( $block->getType() === Block
::TYPE_RANGE
) {
1346 $errorMessage = 'cantcreateaccount-range-text';
1347 $errorParams[] = $this->getRequest()->getIP();
1349 $errorMessage = 'cantcreateaccount-text';
1352 throw new ErrorPageError(
1353 'cantcreateaccounttitle',
1360 * Add a "return to" link or redirect to it.
1361 * Extensions can use this to reuse the "return to" logic after
1362 * inject steps (such as redirection) into the login process.
1364 * @param string $type One of the following:
1365 * - error: display a return to link ignoring $wgRedirectOnLogin
1366 * - signup: display a return to link using $wgRedirectOnLogin if needed
1367 * - success: display a return to link using $wgRedirectOnLogin if needed
1368 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1369 * @param string $returnTo
1370 * @param array|string $returnToQuery
1371 * @param bool $stickHTTPs Keep redirect link on HTTPs
1374 public function showReturnToPage(
1375 $type, $returnTo = '', $returnToQuery = '', $stickHTTPs = false
1377 $this->mReturnTo
= $returnTo;
1378 $this->mReturnToQuery
= $returnToQuery;
1379 $this->mStickHTTPS
= $stickHTTPs;
1380 $this->executeReturnTo( $type );
1384 * Add a "return to" link or redirect to it.
1386 * @param string $type One of the following:
1387 * - error: display a return to link ignoring $wgRedirectOnLogin
1388 * - signup: display a return to link using $wgRedirectOnLogin if needed
1389 * - success: display a return to link using $wgRedirectOnLogin if needed
1390 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1392 private function executeReturnTo( $type ) {
1393 global $wgRedirectOnLogin, $wgSecureLogin;
1395 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
1396 $returnTo = $wgRedirectOnLogin;
1397 $returnToQuery = [];
1399 $returnTo = $this->mReturnTo
;
1400 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
1403 // Allow modification of redirect behavior
1404 Hooks
::run( 'PostLoginRedirect', [ &$returnTo, &$returnToQuery, &$type ] );
1406 $returnToTitle = Title
::newFromText( $returnTo );
1407 if ( !$returnToTitle ) {
1408 $returnToTitle = Title
::newMainPage();
1411 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1412 $options = [ 'http' ];
1413 $proto = PROTO_HTTP
;
1414 } elseif ( $wgSecureLogin ) {
1415 $options = [ 'https' ];
1416 $proto = PROTO_HTTPS
;
1419 $proto = PROTO_RELATIVE
;
1422 if ( $type == 'successredirect' ) {
1423 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1424 $this->getOutput()->redirect( $redirectUrl );
1426 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1431 * @param string $msg
1432 * @param string $msgtype
1433 * @throws ErrorPageError
1435 * @throws FatalError
1436 * @throws MWException
1437 * @throws PermissionsError
1438 * @throws ReadOnlyError
1441 function mainLoginForm( $msg, $msgtype = 'error' ) {
1442 global $wgEnableEmail, $wgEnableUserEmail;
1443 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1444 global $wgAuth, $wgEmailConfirmToEdit;
1445 global $wgSecureLogin, $wgPasswordResetRoutes;
1446 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
1448 $titleObj = $this->getPageTitle();
1449 $user = $this->getUser();
1450 $out = $this->getOutput();
1452 if ( $this->mType
== 'signup' ) {
1453 // Block signup here if in readonly. Keeps user from
1454 // going through the process (filling out data, etc)
1455 // and being informed later.
1456 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1457 if ( count( $permErrors ) ) {
1458 throw new PermissionsError( 'createaccount', $permErrors );
1459 } elseif ( $user->isBlockedFromCreateAccount() ) {
1460 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1463 } elseif ( wfReadOnly() ) {
1464 throw new ReadOnlyError
;
1468 // Pre-fill username (if not creating an account, bug 44775).
1469 if ( $this->mUsername
== '' && $this->mType
!= 'signup' ) {
1470 if ( $user->isLoggedIn() ) {
1471 $this->mUsername
= $user->getName();
1473 $this->mUsername
= $this->getRequest()->getSession()->suggestLoginUsername();
1477 // Generic styles and scripts for both login and signup form
1478 $out->addModuleStyles( [
1480 'mediawiki.ui.button',
1481 'mediawiki.ui.checkbox',
1482 'mediawiki.ui.input',
1483 'mediawiki.special.userlogin.common.styles'
1486 if ( $this->mType
== 'signup' ) {
1487 // Additional styles and scripts for signup form
1489 'mediawiki.special.userlogin.signup.js'
1491 $out->addModuleStyles( [
1492 'mediawiki.special.userlogin.signup.styles'
1495 $template = new UsercreateTemplate( $this->getConfig() );
1497 // Must match number of benefits defined in messages
1498 $template->set( 'benefitCount', 3 );
1500 $q = 'action=submitlogin&type=signup';
1501 $linkq = 'type=login';
1503 // Additional styles for login form
1504 $out->addModuleStyles( [
1505 'mediawiki.special.userlogin.login.styles'
1508 $template = new UserloginTemplate( $this->getConfig() );
1510 $q = 'action=submitlogin&type=login';
1511 $linkq = 'type=signup';
1514 if ( $this->mReturnTo
!== '' ) {
1515 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1516 if ( $this->mReturnToQuery
!== '' ) {
1517 $returnto .= '&returntoquery=' .
1518 wfUrlencode( $this->mReturnToQuery
);
1521 $linkq .= $returnto;
1524 # Don't show a "create account" link if the user can't.
1525 if ( $this->showCreateOrLoginLink( $user ) ) {
1526 # Pass any language selection on to the mode switch link
1527 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
1528 $linkq .= '&uselang=' . $this->mLanguage
;
1530 // Supply URL, login template creates the button.
1531 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1533 $template->set( 'link', '' );
1536 $resetLink = $this->mType
== 'signup'
1538 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1540 $template->set( 'header', '' );
1541 $template->set( 'formheader', '' );
1542 $template->set( 'skin', $this->getSkin() );
1543 $template->set( 'name', $this->mUsername
);
1544 $template->set( 'password', $this->mPassword
);
1545 $template->set( 'retype', $this->mRetype
);
1546 $template->set( 'createemailset', $this->mCreateaccountMail
);
1547 $template->set( 'email', $this->mEmail
);
1548 $template->set( 'realname', $this->mRealName
);
1549 $template->set( 'domain', $this->mDomain
);
1550 $template->set( 'reason', $this->mReason
);
1552 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1553 $template->set( 'message', $msg );
1554 $template->set( 'messagetype', $msgtype );
1555 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1556 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1557 $template->set( 'useemail', $wgEnableEmail );
1558 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1559 $template->set( 'emailothers', $wgEnableUserEmail );
1560 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1561 $template->set( 'resetlink', $resetLink );
1562 $template->set( 'canremember', $wgExtendedLoginCookieExpiration === null ?
1563 ( $wgCookieExpiration > 0 ) :
1564 ( $wgExtendedLoginCookieExpiration > 0 ) );
1565 $template->set( 'usereason', $user->isLoggedIn() );
1566 $template->set( 'remember', $this->mRemember
);
1567 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1568 $template->set( 'stickhttps', (int)$this->mStickHTTPS
);
1569 $template->set( 'loggedin', $user->isLoggedIn() );
1570 $template->set( 'loggedinuser', $user->getName() );
1572 if ( $this->mType
== 'signup' ) {
1573 $template->set( 'token', self
::getCreateaccountToken()->toString() );
1575 $template->set( 'token', self
::getLoginToken()->toString() );
1578 # Prepare language selection links as needed
1579 if ( $wgLoginLanguageSelector ) {
1580 $template->set( 'languages', $this->makeLanguageSelector() );
1581 if ( $this->mLanguage
) {
1582 $template->set( 'uselang', $this->mLanguage
);
1586 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl
);
1587 // Use signupend-https for HTTPS requests if it's not blank, signupend otherwise
1588 $usingHTTPS = $this->mRequest
->getProtocol() == 'https';
1589 $signupendHTTPS = $this->msg( 'signupend-https' );
1590 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1591 $template->set( 'signupend', $signupendHTTPS->parse() );
1593 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1596 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
1597 if ( $usingHTTPS ) {
1598 $template->set( 'fromhttp', $this->mFromHTTP
);
1601 // Give authentication and captcha plugins a chance to modify the form
1602 $wgAuth->modifyUITemplate( $template, $this->mType
);
1603 if ( $this->mType
== 'signup' ) {
1604 Hooks
::run( 'UserCreateForm', [ &$template ] );
1606 Hooks
::run( 'UserLoginForm', [ &$template ] );
1609 $out->disallowUserJs(); // just in case...
1610 $out->addTemplate( $template );
1614 * Whether the login/create account form should display a link to the
1615 * other form (in addition to whatever the skin provides).
1620 private function showCreateOrLoginLink( &$user ) {
1621 if ( $this->mType
== 'signup' ) {
1623 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1631 * Check if a session cookie is present.
1633 * This will not pick up a cookie set during _this_ request, but is meant
1634 * to ensure that the client is returning the cookie which was set on a
1635 * previous pass through the system.
1640 function hasSessionCookie() {
1641 global $wgDisableCookieCheck, $wgInitialSessionId;
1643 return $wgDisableCookieCheck ||
(
1644 $wgInitialSessionId &&
1645 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1650 * Get the login token from the current session
1651 * @since 1.27 returns a MediaWiki\Session\Token instead of a string
1652 * @return MediaWiki\Session\Token
1654 public static function getLoginToken() {
1656 return $wgRequest->getSession()->getToken( '', 'login' );
1660 * Formerly randomly generated a login token that would be returned by
1661 * $this->getLoginToken().
1663 * Since 1.27, this is a no-op. The token is generated as necessary by
1664 * $this->getLoginToken().
1666 * @deprecated since 1.27
1668 public static function setLoginToken() {
1669 wfDeprecated( __METHOD__
, '1.27' );
1673 * Remove any login token attached to the current session
1675 public static function clearLoginToken() {
1677 $wgRequest->getSession()->resetToken( 'login' );
1681 * Get the createaccount token from the current session
1682 * @since 1.27 returns a MediaWiki\Session\Token instead of a string
1683 * @return MediaWiki\Session\Token
1685 public static function getCreateaccountToken() {
1687 return $wgRequest->getSession()->getToken( '', 'createaccount' );
1691 * Formerly randomly generated a createaccount token that would be returned
1692 * by $this->getCreateaccountToken().
1694 * Since 1.27, this is a no-op. The token is generated as necessary by
1695 * $this->getCreateaccountToken().
1697 * @deprecated since 1.27
1699 public static function setCreateaccountToken() {
1700 wfDeprecated( __METHOD__
, '1.27' );
1704 * Remove any createaccount token attached to the current session
1706 public static function clearCreateaccountToken() {
1708 $wgRequest->getSession()->resetToken( 'createaccount' );
1712 * Renew the user's session id, using strong entropy
1714 private function renewSessionId() {
1715 global $wgSecureLogin, $wgCookieSecure;
1716 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1717 $wgCookieSecure = false;
1720 SessionManager
::getGlobalSession()->resetId();
1721 SessionManager
::getGlobalSession()->resetAllTokens();
1725 * @param string $type
1728 function cookieRedirectCheck( $type ) {
1729 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1730 $query = [ 'wpCookieCheck' => $type ];
1731 if ( $this->mReturnTo
!== '' ) {
1732 $query['returnto'] = $this->mReturnTo
;
1733 $query['returntoquery'] = $this->mReturnToQuery
;
1735 $check = $titleObj->getFullURL( $query );
1737 $this->getOutput()->redirect( $check );
1741 * @param string $type
1744 function onCookieRedirectCheck( $type ) {
1745 if ( !$this->hasSessionCookie() ) {
1746 if ( $type == 'new' ) {
1747 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1748 } elseif ( $type == 'login' ) {
1749 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1752 $this->mainLoginForm( $this->msg( 'error' )->text() );
1755 $this->successfulLogin();
1760 * Produce a bar of links which allow the user to select another language
1761 * during login/registration but retain "returnto"
1765 function makeLanguageSelector() {
1766 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1767 if ( $msg->isBlank() ) {
1770 $langs = explode( "\n", $msg->text() );
1772 foreach ( $langs as $lang ) {
1773 $lang = trim( $lang, '* ' );
1774 $parts = explode( '|', $lang );
1775 if ( count( $parts ) >= 2 ) {
1776 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1780 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1781 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1785 * Create a language selector link for a particular language
1786 * Links back to this page preserving type and returnto
1788 * @param string $text Link text
1789 * @param string $lang Language code
1792 function makeLanguageSelectorLink( $text, $lang ) {
1793 if ( $this->getLanguage()->getCode() == $lang ) {
1794 // no link for currently used language
1795 return htmlspecialchars( $text );
1797 $query = [ 'uselang' => $lang ];
1798 if ( $this->mType
== 'signup' ) {
1799 $query['type'] = 'signup';
1801 if ( $this->mReturnTo
!== '' ) {
1802 $query['returnto'] = $this->mReturnTo
;
1803 $query['returntoquery'] = $this->mReturnToQuery
;
1807 $targetLanguage = Language
::factory( $lang );
1808 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1810 return Linker
::linkKnown(
1811 $this->getPageTitle(),
1812 htmlspecialchars( $text ),
1818 protected function getGroupName() {
1823 * Private function to check password expiration, until AuthManager comes
1824 * along to handle that.
1826 * @return string|bool
1828 private function checkUserPasswordExpired( User
$user ) {
1829 global $wgPasswordExpireGrace;
1830 $dbr = wfGetDB( DB_SLAVE
);
1831 $ts = $dbr->selectField( 'user', 'user_password_expires', [ 'user_id' => $user->getId() ] );
1834 $now = wfTimestamp();
1835 $expUnix = wfTimestamp( TS_UNIX
, $ts );
1836 if ( $ts !== null && $expUnix < $now ) {
1837 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
1842 protected function getSubpagesForPrefixSearch() {
1843 return [ 'signup' ];