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
;
24 use MediaWiki\Session\SessionManager
;
27 * Implements Special:UserLogin
29 * @ingroup SpecialPage
31 class LoginForm
extends SpecialPage
{
35 const WRONG_PLUGIN_PASS
= 3;
41 const CREATE_BLOCKED
= 9;
43 const USER_BLOCKED
= 11;
44 const NEED_TOKEN
= 12;
45 const WRONG_TOKEN
= 13;
46 const USER_MIGRATED
= 14;
48 public static $statusCodes = array(
49 self
::SUCCESS
=> 'success',
50 self
::NO_NAME
=> 'no_name',
51 self
::ILLEGAL
=> 'illegal',
52 self
::WRONG_PLUGIN_PASS
=> 'wrong_plugin_pass',
53 self
::NOT_EXISTS
=> 'not_exists',
54 self
::WRONG_PASS
=> 'wrong_pass',
55 self
::EMPTY_PASS
=> 'empty_pass',
56 self
::RESET_PASS
=> 'reset_pass',
57 self
::ABORTED
=> 'aborted',
58 self
::CREATE_BLOCKED
=> 'create_blocked',
59 self
::THROTTLED
=> 'throttled',
60 self
::USER_BLOCKED
=> 'user_blocked',
61 self
::NEED_TOKEN
=> 'need_token',
62 self
::WRONG_TOKEN
=> 'wrong_token',
63 self
::USER_MIGRATED
=> 'user_migrated',
67 * Valid error and warning messages
69 * Special:Userlogin can show an error or warning message on the form when
70 * coming from another page. This is done via the ?error= or ?warning= GET
73 * This array is the list of valid message keys. All other values will be
79 public static $validErrorMessages = array(
80 'exception-nologin-text',
82 'changeemail-no-info',
84 'confirmemail_needlogin',
88 public $mAbortLoginErrorMsg = null;
94 protected $mCookieCheck;
97 protected $mCreateaccount;
98 protected $mCreateaccountMail;
99 protected $mLoginattempt;
100 protected $mRemember;
103 protected $mLanguage;
104 protected $mSkipCookieCheck;
105 protected $mReturnToQuery;
107 protected $mStickHTTPS;
110 protected $mRealName;
111 protected $mEntryError = '';
112 protected $mEntryErrorType = 'error';
114 private $mTempPasswordUsed;
115 private $mLoaded = false;
116 private $mSecureLoginUrl;
118 /** @var WebRequest */
119 private $mOverrideRequest = null;
121 /** @var WebRequest Effective request; set at the beginning of load */
122 private $mRequest = null;
125 * @param WebRequest $request
127 public function __construct( $request = null ) {
128 global $wgUseMediaWikiUIEverywhere;
129 parent
::__construct( 'Userlogin' );
131 $this->mOverrideRequest
= $request;
132 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
133 $wgUseMediaWikiUIEverywhere = true;
136 public function doesWrites() {
141 * Returns an array of all valid error messages.
145 public static function getValidErrorMessages() {
146 static $messages = null;
148 $messages = self
::$validErrorMessages;
149 Hooks
::run( 'LoginFormValidErrorMessages', array( &$messages ) );
159 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
161 if ( $this->mLoaded
) {
164 $this->mLoaded
= true;
166 if ( $this->mOverrideRequest
=== null ) {
167 $request = $this->getRequest();
169 $request = $this->mOverrideRequest
;
171 $this->mRequest
= $request;
173 $this->mType
= $request->getText( 'type' );
174 $this->mUsername
= $request->getText( 'wpName' );
175 $this->mPassword
= $request->getText( 'wpPassword' );
176 $this->mRetype
= $request->getText( 'wpRetype' );
177 $this->mDomain
= $request->getText( 'wpDomain' );
178 $this->mReason
= $request->getText( 'wpReason' );
179 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
180 $this->mPosted
= $request->wasPosted();
181 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
183 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' ) && !$this->mCreateaccountMail
;
184 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
185 $this->mAction
= $request->getVal( 'action' );
186 $this->mRemember
= $request->getCheck( 'wpRemember' );
187 $this->mFromHTTP
= $request->getBool( 'fromhttp', false )
188 ||
$request->getBool( 'wpFromhttp', false );
189 $this->mStickHTTPS
= ( !$this->mFromHTTP
&& $request->getProtocol() === 'https' )
190 ||
$request->getBool( 'wpForceHttps', false );
191 $this->mLanguage
= $request->getText( 'uselang' );
192 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
193 $this->mToken
= $this->mType
== 'signup'
194 ?
$request->getVal( 'wpCreateaccountToken' )
195 : $request->getVal( 'wpLoginToken' );
196 $this->mReturnTo
= $request->getVal( 'returnto', '' );
197 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
199 // Show an error or warning passed on from a previous page
200 $entryError = $this->msg( $request->getVal( 'error', '' ) );
201 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
202 // bc: provide login link as a parameter for messages where the translation
204 $loginreqlink = Linker
::linkKnown(
205 $this->getPageTitle(),
206 $this->msg( 'loginreqlink' )->escaped(),
209 'returnto' => $this->mReturnTo
,
210 'returntoquery' => $this->mReturnToQuery
,
211 'uselang' => $this->mLanguage
,
212 'fromhttp' => $this->mFromHTTP ?
'1' : '0',
216 // Only show valid error or warning messages.
217 if ( $entryError->exists()
218 && in_array( $entryError->getKey(), self
::getValidErrorMessages() )
220 $this->mEntryErrorType
= 'error';
221 $this->mEntryError
= $entryError->rawParams( $loginreqlink )->parse();
223 } elseif ( $entryWarning->exists()
224 && in_array( $entryWarning->getKey(), self
::getValidErrorMessages() )
226 $this->mEntryErrorType
= 'warning';
227 $this->mEntryError
= $entryWarning->rawParams( $loginreqlink )->parse();
230 if ( $wgEnableEmail ) {
231 $this->mEmail
= $request->getText( 'wpEmail' );
235 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
236 $this->mRealName
= $request->getText( 'wpRealName' );
238 $this->mRealName
= '';
241 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
242 $this->mDomain
= $wgAuth->getDomain();
244 $wgAuth->setDomain( $this->mDomain
);
246 # 1. When switching accounts, it sucks to get automatically logged out
247 # 2. Do not return to PasswordReset after a successful password change
248 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
249 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
250 if ( is_object( $returnToTitle )
251 && ( $returnToTitle->isSpecial( 'Userlogout' )
252 ||
$returnToTitle->isSpecial( 'PasswordReset' ) )
254 $this->mReturnTo
= '';
255 $this->mReturnToQuery
= '';
259 function getDescription() {
260 if ( $this->mType
=== 'signup' ) {
261 return $this->msg( 'createaccount' )->text();
263 return $this->msg( 'login' )->text();
268 * @param string|null $subPage
270 public function execute( $subPage ) {
271 // Make sure session is persisted
272 $session = MediaWiki\Session\SessionManager
::getGlobalSession();
277 // Check for [[Special:Userlogin/signup]]. This affects form display and
279 if ( $subPage == 'signup' ) {
280 $this->mType
= 'signup';
284 // Make sure it's possible to log in
285 if ( $this->mType
!== 'signup' && !$session->canSetUser() ) {
286 throw new ErrorPageError(
287 'cannotloginnow-title',
288 'cannotloginnow-text',
290 $session->getProvider()->describe( RequestContext
::getMain()->getLanguage() )
296 * In the case where the user is already logged in, and was redirected to
297 * the login form from a page that requires login, do not show the login
298 * page. The use case scenario for this is when a user opens a large number
299 * of tabs, is redirected to the login page on all of them, and then logs
300 * in on one, expecting all the others to work properly.
302 * However, do show the form if it was visited intentionally (no 'returnto'
303 * is present). People who often switch between several accounts have grown
304 * accustomed to this behavior.
307 $this->mType
!== 'signup' &&
309 $this->getUser()->isLoggedIn() &&
310 ( $this->mReturnTo
!== '' ||
$this->mReturnToQuery
!== '' )
312 $this->successfulLogin();
315 // If logging in and not on HTTPS, either redirect to it or offer a link.
316 global $wgSecureLogin;
317 if ( $this->mRequest
->getProtocol() !== 'https' ) {
318 $title = $this->getFullTitle();
320 'returnto' => $this->mReturnTo
!== '' ?
$this->mReturnTo
: null,
321 'returntoquery' => $this->mReturnToQuery
!== '' ?
322 $this->mReturnToQuery
: null,
324 ( $this->mEntryErrorType
=== 'error' ?
'error' : 'warning' ) => $this->mEntryError
,
325 ) +
$this->mRequest
->getQueryValues();
326 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
328 && wfCanIPUseHTTPS( $this->getRequest()->getIP() )
329 && !$this->mFromHTTP
) // Avoid infinite redirect
331 $url = wfAppendQuery( $url, 'fromhttp=1' );
332 $this->getOutput()->redirect( $url );
333 // Since we only do this redir to change proto, always vary
334 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
338 // A wiki without HTTPS login support should set $wgServer to
339 // http://somehost, in which case the secure URL generated
340 // above won't actually start with https://
341 if ( substr( $url, 0, 8 ) === 'https://' ) {
342 $this->mSecureLoginUrl
= $url;
347 if ( !is_null( $this->mCookieCheck
) ) {
348 $this->onCookieRedirectCheck( $this->mCookieCheck
);
351 } elseif ( $this->mPosted
) {
352 if ( $this->mCreateaccount
) {
353 $this->addNewAccount();
356 } elseif ( $this->mCreateaccountMail
) {
357 $this->addNewAccountMailPassword();
360 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
361 $this->processLogin();
366 $this->mainLoginForm( $this->mEntryError
, $this->mEntryErrorType
);
372 function addNewAccountMailPassword() {
373 if ( $this->mEmail
== '' ) {
374 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
379 $status = $this->addNewAccountInternal();
380 LoggerFactory
::getInstance( 'authmanager' )->info(
381 'Account creation attempt with mailed password',
382 array( 'event' => 'accountcreation', 'status' => $status )
384 if ( !$status->isGood() ) {
385 $error = $status->getMessage();
386 $this->mainLoginForm( $error->toString() );
392 $u = $status->getValue();
394 // Wipe the initial password and mail a temporary one
395 $u->setPassword( null );
397 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
399 Hooks
::run( 'AddNewAccount', array( $u, true ) );
400 $u->addNewUserLogEntry( 'byemail', $this->mReason
);
402 $out = $this->getOutput();
403 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
405 if ( !$result->isGood() ) {
406 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
408 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
409 $this->executeReturnTo( 'success' );
417 function addNewAccount() {
418 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
420 # Create the account and abort if there's a problem doing so
421 $status = $this->addNewAccountInternal();
422 LoggerFactory
::getInstance( 'authmanager' )->info( 'Account creation attempt', array(
423 'event' => 'accountcreation',
427 if ( !$status->isGood() ) {
428 $error = $status->getMessage();
429 $this->mainLoginForm( $error->toString() );
434 $u = $status->getValue();
436 # Only save preferences if the user is not creating an account for someone else.
437 if ( $this->getUser()->isAnon() ) {
438 # If we showed up language selection links, and one was in use, be
439 # smart (and sensible) and save that language as the user's preference
440 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
441 $u->setOption( 'language', $this->mLanguage
);
444 # Otherwise the user's language preference defaults to $wgContLang,
445 # but it may be better to set it to their preferred $wgContLang variant,
446 # based on browser preferences or URL parameters.
447 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
449 if ( $wgContLang->hasVariants() ) {
450 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
454 $out = $this->getOutput();
456 # Send out an email authentication message if needed
457 if ( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
458 $status = $u->sendConfirmationMail();
459 if ( $status->isGood() ) {
460 $out->addWikiMsg( 'confirmemail_oncreate' );
462 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
466 # Save settings (including confirmation token)
469 # If not logged in, assume the new account as the current one and set
470 # session cookies then show a "welcome" message or a "need cookies"
472 if ( $this->getUser()->isAnon() ) {
475 // This should set it for OutputPage and the Skin
476 // which is needed or the personal links will be
478 $this->getContext()->setUser( $u );
479 Hooks
::run( 'AddNewAccount', array( $u, false ) );
480 $u->addNewUserLogEntry( 'create' );
481 if ( $this->hasSessionCookie() ) {
482 $this->successfulCreation();
484 $this->cookieRedirectCheck( 'new' );
487 # Confirm that the account was created
488 $out->setPageTitle( $this->msg( 'accountcreated' ) );
489 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
490 $out->addReturnTo( $this->getPageTitle() );
491 Hooks
::run( 'AddNewAccount', array( $u, false ) );
492 $u->addNewUserLogEntry( 'create2', $this->mReason
);
499 * Make a new user account using the loaded data.
501 * @throws PermissionsError|ReadOnlyError
504 public function addNewAccountInternal() {
505 global $wgAuth, $wgAccountCreationThrottle, $wgEmailConfirmToEdit;
507 // If the user passes an invalid domain, something is fishy
508 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
509 return Status
::newFatal( 'wrongpassword' );
512 // If we are not allowing users to login locally, we should be checking
513 // to see if the user is actually able to authenticate to the authenti-
514 // cation server before they create an account (otherwise, they can
515 // create a local account and login as any domain user). We only need
516 // to check this for domains that aren't local.
517 if ( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
519 !$wgAuth->canCreateAccounts() &&
521 !$wgAuth->userExists( $this->mUsername
) ||
522 !$wgAuth->authenticate( $this->mUsername
, $this->mPassword
)
525 return Status
::newFatal( 'wrongpassword' );
529 if ( wfReadOnly() ) {
530 throw new ReadOnlyError
;
533 # Request forgery checks.
534 if ( !self
::getCreateaccountToken() ) {
535 self
::setCreateaccountToken();
537 return Status
::newFatal( 'nocookiesfornew' );
540 # The user didn't pass a createaccount token
541 if ( !$this->mToken
) {
542 return Status
::newFatal( 'sessionfailure' );
545 # Validate the createaccount token
546 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
547 return Status
::newFatal( 'sessionfailure' );
551 $currentUser = $this->getUser();
552 $creationBlock = $currentUser->isBlockedFromCreateAccount();
553 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
554 throw new PermissionsError( 'createaccount' );
555 } elseif ( $creationBlock instanceof Block
) {
556 // Throws an ErrorPageError.
557 $this->userBlockedMessage( $creationBlock );
559 // This should never be reached.
563 # Include checks that will include GlobalBlocking (Bug 38333)
564 $permErrors = $this->getPageTitle()->getUserPermissionsErrors(
570 if ( count( $permErrors ) ) {
571 throw new PermissionsError( 'createaccount', $permErrors );
574 $ip = $this->getRequest()->getIP();
575 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
576 return Status
::newFatal( 'sorbs_create_account_reason' );
579 # Now create a dummy user ($u) and check if it is valid
580 $u = User
::newFromName( $this->mUsername
, 'creatable' );
582 return Status
::newFatal( 'noname' );
585 $cache = ObjectCache
::getLocalClusterInstance();
586 # Make sure the user does not exist already
587 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $this->mUsername
) ) );
589 return Status
::newFatal( 'usernameinprogress' );
590 } elseif ( $u->idForName( User
::READ_LOCKING
) ) {
591 return Status
::newFatal( 'userexists' );
594 if ( $this->mCreateaccountMail
) {
595 # do not force a password for account creation by email
596 # set invalid password, it will be replaced later by a random generated password
597 $this->mPassword
= null;
599 if ( $this->mPassword
!== $this->mRetype
) {
600 return Status
::newFatal( 'badretype' );
603 # check for password validity, return a fatal Status if invalid
604 $validity = $u->checkPasswordValidity( $this->mPassword
, 'create' );
605 if ( !$validity->isGood() ) {
606 $validity->ok
= false; // make sure this Status is fatal
611 # if you need a confirmed email address to edit, then obviously you
612 # need an email address.
613 if ( $wgEmailConfirmToEdit && strval( $this->mEmail
) === '' ) {
614 return Status
::newFatal( 'noemailtitle' );
617 if ( strval( $this->mEmail
) !== '' && !Sanitizer
::validateEmail( $this->mEmail
) ) {
618 return Status
::newFatal( 'invalidemailaddress' );
621 # Set some additional data so the AbortNewAccount hook can be used for
622 # more than just username validation
623 $u->setEmail( $this->mEmail
);
624 $u->setRealName( $this->mRealName
);
628 if ( !Hooks
::run( 'AbortNewAccount', array( $u, &$abortError, &$abortStatus ) ) ) {
629 // Hook point to add extra creation throttles and blocks
630 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
631 if ( $abortStatus === null ) {
632 // Report back the old string as a raw message status.
633 // This will report the error back as 'createaccount-hook-aborted'
634 // with the given string as the message.
635 // To return a different error code, return a Status object.
636 $abortError = new Message( 'createaccount-hook-aborted', array( $abortError ) );
639 return Status
::newFatal( $abortError );
641 // For MediaWiki 1.23+ and updated hooks, return the Status object
642 // returned from the hook.
647 // Hook point to check for exempt from account creation throttle
648 if ( !Hooks
::run( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
649 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook " .
650 "allowed account creation w/o throttle\n" );
652 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
653 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
654 $value = $cache->get( $key );
656 $cache->set( $key, 0, $cache::TTL_DAY
);
658 if ( $value >= $wgAccountCreationThrottle ) {
659 return Status
::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
661 $cache->incr( $key );
665 if ( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
666 return Status
::newFatal( 'externaldberror' );
669 self
::clearCreateaccountToken();
671 return $this->initUser( $u, false );
675 * Actually add a user to the database.
676 * Give it a User object that has been initialised with a name.
679 * @param bool $autocreate True if this is an autocreation via auth plugin
680 * @return Status Status object, with the User object in the value member on success
683 function initUser( $u, $autocreate ) {
686 $status = $u->addToDatabase();
687 if ( !$status->isOK() ) {
691 if ( $wgAuth->allowPasswordChange() ) {
692 $u->setPassword( $this->mPassword
);
695 $u->setEmail( $this->mEmail
);
696 $u->setRealName( $this->mRealName
);
699 Hooks
::run( 'LocalUserCreated', array( $u, $autocreate ) );
701 $wgAuth->initUser( $u, $autocreate );
702 if ( $oldUser !== $u ) {
703 wfWarn( get_class( $wgAuth ) . '::initUser() replaced the user object' );
709 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
711 // Watch user's userpage and talk page
712 $u->addWatch( $u->getUserPage(), WatchedItem
::IGNORE_USER_RIGHTS
);
714 return Status
::newGood( $u );
718 * Internally authenticate the login request.
720 * This may create a local account as a side effect if the
721 * authentication plugin allows transparent local account
725 public function authenticateUserData() {
726 global $wgUser, $wgAuth;
730 if ( $this->mUsername
== '' ) {
731 return self
::NO_NAME
;
734 // We require a login token to prevent login CSRF
735 // Handle part of this before incrementing the throttle so
736 // token-less login attempts don't count towards the throttle
737 // but wrong-token attempts do.
739 // If the user doesn't have a login token yet, set one.
740 if ( !self
::getLoginToken() ) {
741 self
::setLoginToken();
743 return self
::NEED_TOKEN
;
745 // If the user didn't pass a login token, tell them we need one
746 if ( !$this->mToken
) {
747 return self
::NEED_TOKEN
;
750 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
751 if ( $throttleCount === true ) {
752 return self
::THROTTLED
;
755 // Validate the login token
756 if ( $this->mToken
!== self
::getLoginToken() ) {
757 return self
::WRONG_TOKEN
;
760 // Load the current user now, and check to see if we're logging in as
761 // the same name. This is necessary because loading the current user
762 // (say by calling getName()) calls the UserLoadFromSession hook, which
763 // potentially creates the user in the database. Until we load $wgUser,
764 // checking for user existence using User::newFromName($name)->getId() below
765 // will effectively be using stale data.
766 if ( $this->getUser()->getName() === $this->mUsername
) {
767 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
769 return self
::SUCCESS
;
772 $u = User
::newFromName( $this->mUsername
);
773 if ( $u === false ) {
774 return self
::ILLEGAL
;
778 // Give extensions a way to indicate the username has been updated,
779 // rather than telling the user the account doesn't exist.
780 if ( !Hooks
::run( 'LoginUserMigrated', array( $u, &$msg ) ) ) {
781 $this->mAbortLoginErrorMsg
= $msg;
782 return self
::USER_MIGRATED
;
785 if ( !User
::isUsableName( $u->getName() ) ) {
786 return self
::ILLEGAL
;
789 $isAutoCreated = false;
790 if ( $u->getID() == 0 ) {
791 $status = $this->attemptAutoCreate( $u );
792 if ( $status !== self
::SUCCESS
) {
795 $isAutoCreated = true;
801 // Give general extensions, such as a captcha, a chance to abort logins
802 $abort = self
::ABORTED
;
803 if ( !Hooks
::run( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$msg ) ) ) {
804 if ( !in_array( $abort, array_keys( self
::$statusCodes ), true ) ) {
805 throw new Exception( 'Invalid status code returned from AbortLogin hook: ' . $abort );
807 $this->mAbortLoginErrorMsg
= $msg;
811 global $wgBlockDisablesLogin;
812 if ( !$u->checkPassword( $this->mPassword
) ) {
813 if ( $u->checkTemporaryPassword( $this->mPassword
) ) {
815 * The e-mailed temporary password should not be used for actu-
816 * al logins; that's a very sloppy habit, and insecure if an
817 * attacker has a few seconds to click "search" on someone's
820 * Allow it to be used only to reset the password a single time
821 * to a new value, which won't be in the user's e-mail ar-
824 * For backwards compatibility, we'll still recognize it at the
825 * login form to minimize surprises for people who have been
826 * logging in with a temporary password for some time.
828 * As a side-effect, we can authenticate the user's e-mail ad-
829 * dress if it's not already done, since the temporary password
830 * was sent via e-mail.
832 if ( !$u->isEmailConfirmed() && !wfReadOnly() ) {
837 // At this point we just return an appropriate code/ indicating
838 // that the UI should show a password reset form; bot inter-
839 // faces etc will probably just fail cleanly here.
840 $this->mAbortLoginErrorMsg
= 'resetpass-temp-emailed';
841 $this->mTempPasswordUsed
= true;
842 $retval = self
::RESET_PASS
;
844 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
846 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
847 // If we've enabled it, make it so that a blocked user cannot login
848 $retval = self
::USER_BLOCKED
;
849 } elseif ( $this->checkUserPasswordExpired( $u ) == 'hard' ) {
850 // Force reset now, without logging in
851 $retval = self
::RESET_PASS
;
852 $this->mAbortLoginErrorMsg
= 'resetpass-expired';
854 Hooks
::run( 'UserLoggedIn', array( $u ) );
856 $wgAuth->updateUser( $u );
857 if ( $oldUser !== $u ) {
858 wfWarn( get_class( $wgAuth ) . '::updateUser() replaced the user object' );
861 // This should set it for OutputPage and the Skin
862 // which is needed or the personal links will be
864 $this->getContext()->setUser( $u );
866 // Please reset throttle for successful logins, thanks!
867 if ( $throttleCount ) {
868 self
::clearLoginThrottle( $this->mUsername
);
871 if ( $isAutoCreated ) {
872 // Must be run after $wgUser is set, for correct new user log
873 Hooks
::run( 'AuthPluginAutoCreate', array( $u ) );
876 $retval = self
::SUCCESS
;
878 Hooks
::run( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
884 * Increment the login attempt throttle hit count for the (username,current IP)
885 * tuple unless the throttle was already reached.
886 * @param string $username The user name
887 * @return bool|int The integer hit count or True if it is already at the limit
889 public static function incLoginThrottle( $username ) {
890 global $wgPasswordAttemptThrottle, $wgRequest;
891 $username = trim( $username ); // sanity
894 if ( is_array( $wgPasswordAttemptThrottle ) ) {
895 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
896 $count = $wgPasswordAttemptThrottle['count'];
897 $period = $wgPasswordAttemptThrottle['seconds'];
899 $cache = ObjectCache
::getLocalClusterInstance();
900 $throttleCount = $cache->get( $throttleKey );
901 if ( !$throttleCount ) {
902 $cache->add( $throttleKey, 1, $period ); // start counter
903 } elseif ( $throttleCount < $count ) {
904 $cache->incr( $throttleKey );
905 } elseif ( $throttleCount >= $count ) {
910 return $throttleCount;
914 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
915 * @param string $username The user name
918 public static function clearLoginThrottle( $username ) {
920 $username = trim( $username ); // sanity
922 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
923 ObjectCache
::getLocalClusterInstance()->delete( $throttleKey );
927 * Attempt to automatically create a user on login. Only succeeds if there
928 * is an external authentication method which allows it.
932 * @return int Status code
934 function attemptAutoCreate( $user ) {
937 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
938 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
940 return self
::CREATE_BLOCKED
;
943 if ( !$wgAuth->autoCreate() ) {
944 return self
::NOT_EXISTS
;
947 if ( !$wgAuth->userExists( $user->getName() ) ) {
948 wfDebug( __METHOD__
. ": user does not exist\n" );
950 return self
::NOT_EXISTS
;
953 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
954 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
956 return self
::WRONG_PLUGIN_PASS
;
960 if ( !Hooks
::run( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
961 // Hook point to add extra creation throttles and blocks
962 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
963 $this->mAbortLoginErrorMsg
= $abortError;
965 return self
::ABORTED
;
968 wfDebug( __METHOD__
. ": creating account\n" );
969 $status = $this->initUser( $user, true );
971 if ( !$status->isOK() ) {
972 $errors = $status->getErrorsByType( 'error' );
973 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
975 return self
::ABORTED
;
978 return self
::SUCCESS
;
981 function processLogin() {
982 global $wgLang, $wgSecureLogin, $wgPasswordAttemptThrottle, $wgInvalidPasswordReset;
984 $cache = ObjectCache
::getLocalClusterInstance();
985 $authRes = $this->authenticateUserData();
986 switch ( $authRes ) {
988 # We've verified now, update the real record
989 $user = $this->getUser();
992 if ( $user->requiresHTTPS() ) {
993 $this->mStickHTTPS
= true;
996 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
997 $user->setCookies( $this->mRequest
, false, $this->mRemember
);
999 $user->setCookies( $this->mRequest
, null, $this->mRemember
);
1001 self
::clearLoginToken();
1003 // Reset the throttle
1004 $request = $this->getRequest();
1005 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
1006 $cache->delete( $key );
1008 if ( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
1009 /* Replace the language object to provide user interface in
1010 * correct language immediately on this first page load.
1012 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
1013 $userLang = Language
::factory( $code );
1014 $wgLang = $userLang;
1015 $this->getContext()->setLanguage( $userLang );
1016 // Reset SessionID on Successful login (bug 40995)
1017 $this->renewSessionId();
1018 if ( $this->checkUserPasswordExpired( $this->getUser() ) == 'soft' ) {
1019 $this->resetLoginForm( $this->msg( 'resetpass-expired-soft' ) );
1020 } elseif ( $wgInvalidPasswordReset
1021 && !$user->isValidPassword( $this->mPassword
)
1023 $status = $user->checkPasswordValidity(
1027 $this->resetLoginForm(
1028 $status->getMessage( 'resetpass-validity-soft' )
1031 $this->successfulLogin();
1034 $this->cookieRedirectCheck( 'login' );
1038 case self
::NEED_TOKEN
:
1039 $error = $this->mAbortLoginErrorMsg ?
: 'nocookiesforlogin';
1040 $this->mainLoginForm( $this->msg( $error )->parse() );
1042 case self
::WRONG_TOKEN
:
1043 $error = $this->mAbortLoginErrorMsg ?
: 'sessionfailure';
1044 $this->mainLoginForm( $this->msg( $error )->text() );
1048 $error = $this->mAbortLoginErrorMsg ?
: 'noname';
1049 $this->mainLoginForm( $this->msg( $error )->text() );
1051 case self
::WRONG_PLUGIN_PASS
:
1052 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
1053 $this->mainLoginForm( $this->msg( $error )->text() );
1055 case self
::NOT_EXISTS
:
1056 if ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1057 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchuser';
1058 $this->mainLoginForm( $this->msg( $error,
1059 wfEscapeWikiText( $this->mUsername
) )->parse() );
1061 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchusershort';
1062 $this->mainLoginForm( $this->msg( $error,
1063 wfEscapeWikiText( $this->mUsername
) )->text() );
1066 case self
::WRONG_PASS
:
1067 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
1068 $this->mainLoginForm( $this->msg( $error )->text() );
1070 case self
::EMPTY_PASS
:
1071 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpasswordempty';
1072 $this->mainLoginForm( $this->msg( $error )->text() );
1074 case self
::RESET_PASS
:
1075 $error = $this->mAbortLoginErrorMsg ?
: 'resetpass_announce';
1076 $this->resetLoginForm( $this->msg( $error ) );
1078 case self
::CREATE_BLOCKED
:
1079 $this->userBlockedMessage( $this->getUser()->isBlockedFromCreateAccount() );
1081 case self
::THROTTLED
:
1082 $error = $this->mAbortLoginErrorMsg ?
: 'login-throttled';
1083 $this->mainLoginForm( $this->msg( $error )
1084 ->params( $this->getLanguage()->formatDuration( $wgPasswordAttemptThrottle['seconds'] ) )
1088 case self
::USER_BLOCKED
:
1089 $error = $this->mAbortLoginErrorMsg ?
: 'login-userblocked';
1090 $this->mainLoginForm( $this->msg( $error, $this->mUsername
)->escaped() );
1093 $error = $this->mAbortLoginErrorMsg ?
: 'login-abort-generic';
1094 $this->mainLoginForm( $this->msg( $error,
1095 wfEscapeWikiText( $this->mUsername
) )->text() );
1097 case self
::USER_MIGRATED
:
1098 $error = $this->mAbortLoginErrorMsg ?
: 'login-migrated-generic';
1100 if ( is_array( $error ) ) {
1101 $error = array_shift( $this->mAbortLoginErrorMsg
);
1102 $params = $this->mAbortLoginErrorMsg
;
1104 $this->mainLoginForm( $this->msg( $error, $params )->text() );
1107 throw new MWException( 'Unhandled case value' );
1110 LoggerFactory
::getInstance( 'authmanager' )->info( 'Login attempt', array(
1112 'successful' => $authRes === self
::SUCCESS
,
1113 'status' => LoginForm
::$statusCodes[$authRes],
1118 * Show the Special:ChangePassword form, with custom message
1119 * @param Message $msg
1121 protected function resetLoginForm( Message
$msg ) {
1122 // Allow hooks to explain this password reset in more detail
1123 Hooks
::run( 'LoginPasswordResetMessage', array( &$msg, $this->mUsername
) );
1124 $reset = new SpecialChangePassword();
1125 $derivative = new DerivativeContext( $this->getContext() );
1126 $derivative->setTitle( $reset->getPageTitle() );
1127 $reset->setContext( $derivative );
1128 if ( !$this->mTempPasswordUsed
) {
1129 $reset->setOldPasswordMessage( 'oldpassword' );
1131 $reset->setChangeMessage( $msg );
1132 $reset->execute( null );
1137 * @param bool $throttle
1138 * @param string $emailTitle Message name of email title
1139 * @param string $emailText Message name of email text
1142 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle',
1143 $emailText = 'passwordremindertext'
1145 global $wgNewPasswordExpiry, $wgMinimalPasswordLength;
1147 if ( $u->getEmail() == '' ) {
1148 return Status
::newFatal( 'noemail', $u->getName() );
1150 $ip = $this->getRequest()->getIP();
1152 return Status
::newFatal( 'badipaddress' );
1155 $currentUser = $this->getUser();
1156 Hooks
::run( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
1158 $np = PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1159 $u->setNewpassword( $np, $throttle );
1161 $userLanguage = $u->getOption( 'language' );
1163 $mainPage = Title
::newMainPage();
1164 $mainPageUrl = $mainPage->getCanonicalURL();
1166 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $mainPageUrl . '>',
1167 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
1168 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
1174 * Run any hooks registered for logins, then HTTP redirect to
1175 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
1176 * nice message here, but that's really not as useful as just being sent to
1177 * wherever you logged in from. It should be clear that the action was
1178 * successful, given the lack of error messages plus the appearance of your
1179 * name in the upper right.
1183 function successfulLogin() {
1184 # Run any hooks; display injected HTML if any, else redirect
1185 $currentUser = $this->getUser();
1186 $injected_html = '';
1187 Hooks
::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1189 if ( $injected_html !== '' ) {
1190 $this->displaySuccessfulAction( 'success', $this->msg( 'loginsuccesstitle' ),
1191 'loginsuccess', $injected_html );
1193 $this->executeReturnTo( 'successredirect' );
1198 * Run any hooks registered for logins, then display a message welcoming
1203 function successfulCreation() {
1204 # Run any hooks; display injected HTML
1205 $currentUser = $this->getUser();
1206 $injected_html = '';
1207 $welcome_creation_msg = 'welcomecreation-msg';
1209 Hooks
::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1212 * Let any extensions change what message is shown.
1213 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
1216 Hooks
::run( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
1218 $this->displaySuccessfulAction(
1220 $this->msg( 'welcomeuser', $this->getUser()->getName() ),
1221 $welcome_creation_msg, $injected_html
1226 * Display a "successful action" page.
1228 * @param string $type Condition of return to; see `executeReturnTo`
1229 * @param string|Message $title Page's title
1230 * @param string $msgname
1231 * @param string $injected_html
1233 private function displaySuccessfulAction( $type, $title, $msgname, $injected_html ) {
1234 $out = $this->getOutput();
1235 $out->setPageTitle( $title );
1237 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
1240 $out->addHTML( $injected_html );
1242 $this->executeReturnTo( $type );
1246 * Output a message that informs the user that they cannot create an account because
1247 * there is a block on them or their IP which prevents account creation. Note that
1248 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
1249 * setting on blocks (bug 13611).
1250 * @param Block $block The block causing this error
1251 * @throws ErrorPageError
1253 function userBlockedMessage( Block
$block ) {
1254 # Let's be nice about this, it's likely that this feature will be used
1255 # for blocking large numbers of innocent people, e.g. range blocks on
1256 # schools. Don't blame it on the user. There's a small chance that it
1257 # really is the user's fault, i.e. the username is blocked and they
1258 # haven't bothered to log out before trying to create an account to
1259 # evade it, but we'll leave that to their guilty conscience to figure
1261 $errorParams = array(
1262 $block->getTarget(),
1263 $block->mReason ?
$block->mReason
: $this->msg( 'blockednoreason' )->text(),
1267 if ( $block->getType() === Block
::TYPE_RANGE
) {
1268 $errorMessage = 'cantcreateaccount-range-text';
1269 $errorParams[] = $this->getRequest()->getIP();
1271 $errorMessage = 'cantcreateaccount-text';
1274 throw new ErrorPageError(
1275 'cantcreateaccounttitle',
1282 * Add a "return to" link or redirect to it.
1283 * Extensions can use this to reuse the "return to" logic after
1284 * inject steps (such as redirection) into the login process.
1286 * @param string $type One of the following:
1287 * - error: display a return to link ignoring $wgRedirectOnLogin
1288 * - signup: display a return to link using $wgRedirectOnLogin if needed
1289 * - success: display a return to link using $wgRedirectOnLogin if needed
1290 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1291 * @param string $returnTo
1292 * @param array|string $returnToQuery
1293 * @param bool $stickHTTPs Keep redirect link on HTTPs
1296 public function showReturnToPage(
1297 $type, $returnTo = '', $returnToQuery = '', $stickHTTPs = false
1299 $this->mReturnTo
= $returnTo;
1300 $this->mReturnToQuery
= $returnToQuery;
1301 $this->mStickHTTPS
= $stickHTTPs;
1302 $this->executeReturnTo( $type );
1306 * Add a "return to" link or redirect to it.
1308 * @param string $type One of the following:
1309 * - error: display a return to link ignoring $wgRedirectOnLogin
1310 * - signup: display a return to link using $wgRedirectOnLogin if needed
1311 * - success: display a return to link using $wgRedirectOnLogin if needed
1312 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1314 private function executeReturnTo( $type ) {
1315 global $wgRedirectOnLogin, $wgSecureLogin;
1317 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
1318 $returnTo = $wgRedirectOnLogin;
1319 $returnToQuery = array();
1321 $returnTo = $this->mReturnTo
;
1322 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
1325 // Allow modification of redirect behavior
1326 Hooks
::run( 'PostLoginRedirect', array( &$returnTo, &$returnToQuery, &$type ) );
1328 $returnToTitle = Title
::newFromText( $returnTo );
1329 if ( !$returnToTitle ) {
1330 $returnToTitle = Title
::newMainPage();
1333 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1334 $options = array( 'http' );
1335 $proto = PROTO_HTTP
;
1336 } elseif ( $wgSecureLogin ) {
1337 $options = array( 'https' );
1338 $proto = PROTO_HTTPS
;
1341 $proto = PROTO_RELATIVE
;
1344 if ( $type == 'successredirect' ) {
1345 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1346 $this->getOutput()->redirect( $redirectUrl );
1348 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1353 * @param string $msg
1354 * @param string $msgtype
1355 * @throws ErrorPageError
1357 * @throws FatalError
1358 * @throws MWException
1359 * @throws PermissionsError
1360 * @throws ReadOnlyError
1363 function mainLoginForm( $msg, $msgtype = 'error' ) {
1364 global $wgEnableEmail, $wgEnableUserEmail;
1365 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1366 global $wgAuth, $wgEmailConfirmToEdit;
1367 global $wgSecureLogin, $wgPasswordResetRoutes;
1368 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
1370 $titleObj = $this->getPageTitle();
1371 $user = $this->getUser();
1372 $out = $this->getOutput();
1374 if ( $this->mType
== 'signup' ) {
1375 // Block signup here if in readonly. Keeps user from
1376 // going through the process (filling out data, etc)
1377 // and being informed later.
1378 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1379 if ( count( $permErrors ) ) {
1380 throw new PermissionsError( 'createaccount', $permErrors );
1381 } elseif ( $user->isBlockedFromCreateAccount() ) {
1382 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1385 } elseif ( wfReadOnly() ) {
1386 throw new ReadOnlyError
;
1390 // Pre-fill username (if not creating an account, bug 44775).
1391 if ( $this->mUsername
== '' && $this->mType
!= 'signup' ) {
1392 if ( $user->isLoggedIn() ) {
1393 $this->mUsername
= $user->getName();
1395 $this->mUsername
= $this->getRequest()->getSession()->suggestLoginUsername();
1399 // Generic styles and scripts for both login and signup form
1400 $out->addModuleStyles( array(
1402 'mediawiki.ui.button',
1403 'mediawiki.ui.checkbox',
1404 'mediawiki.ui.input',
1405 'mediawiki.special.userlogin.common.styles'
1408 if ( $this->mType
== 'signup' ) {
1409 // Additional styles and scripts for signup form
1410 $out->addModules( array(
1411 'mediawiki.special.userlogin.signup.js'
1413 $out->addModuleStyles( array(
1414 'mediawiki.special.userlogin.signup.styles'
1417 $template = new UsercreateTemplate( $this->getConfig() );
1419 // Must match number of benefits defined in messages
1420 $template->set( 'benefitCount', 3 );
1422 $q = 'action=submitlogin&type=signup';
1423 $linkq = 'type=login';
1425 // Additional styles for login form
1426 $out->addModuleStyles( array(
1427 'mediawiki.special.userlogin.login.styles'
1430 $template = new UserloginTemplate( $this->getConfig() );
1432 $q = 'action=submitlogin&type=login';
1433 $linkq = 'type=signup';
1436 if ( $this->mReturnTo
!== '' ) {
1437 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1438 if ( $this->mReturnToQuery
!== '' ) {
1439 $returnto .= '&returntoquery=' .
1440 wfUrlencode( $this->mReturnToQuery
);
1443 $linkq .= $returnto;
1446 # Don't show a "create account" link if the user can't.
1447 if ( $this->showCreateOrLoginLink( $user ) ) {
1448 # Pass any language selection on to the mode switch link
1449 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
1450 $linkq .= '&uselang=' . $this->mLanguage
;
1452 // Supply URL, login template creates the button.
1453 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1455 $template->set( 'link', '' );
1458 $resetLink = $this->mType
== 'signup'
1460 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1462 $template->set( 'header', '' );
1463 $template->set( 'formheader', '' );
1464 $template->set( 'skin', $this->getSkin() );
1465 $template->set( 'name', $this->mUsername
);
1466 $template->set( 'password', $this->mPassword
);
1467 $template->set( 'retype', $this->mRetype
);
1468 $template->set( 'createemailset', $this->mCreateaccountMail
);
1469 $template->set( 'email', $this->mEmail
);
1470 $template->set( 'realname', $this->mRealName
);
1471 $template->set( 'domain', $this->mDomain
);
1472 $template->set( 'reason', $this->mReason
);
1474 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1475 $template->set( 'message', $msg );
1476 $template->set( 'messagetype', $msgtype );
1477 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1478 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1479 $template->set( 'useemail', $wgEnableEmail );
1480 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1481 $template->set( 'emailothers', $wgEnableUserEmail );
1482 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1483 $template->set( 'resetlink', $resetLink );
1484 $template->set( 'canremember', $wgExtendedLoginCookieExpiration === null ?
1485 ( $wgCookieExpiration > 0 ) :
1486 ( $wgExtendedLoginCookieExpiration > 0 ) );
1487 $template->set( 'usereason', $user->isLoggedIn() );
1488 $template->set( 'remember', $this->mRemember
);
1489 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1490 $template->set( 'stickhttps', (int)$this->mStickHTTPS
);
1491 $template->set( 'loggedin', $user->isLoggedIn() );
1492 $template->set( 'loggedinuser', $user->getName() );
1494 if ( $this->mType
== 'signup' ) {
1495 if ( !self
::getCreateaccountToken() ) {
1496 self
::setCreateaccountToken();
1498 $template->set( 'token', self
::getCreateaccountToken() );
1500 if ( !self
::getLoginToken() ) {
1501 self
::setLoginToken();
1503 $template->set( 'token', self
::getLoginToken() );
1506 # Prepare language selection links as needed
1507 if ( $wgLoginLanguageSelector ) {
1508 $template->set( 'languages', $this->makeLanguageSelector() );
1509 if ( $this->mLanguage
) {
1510 $template->set( 'uselang', $this->mLanguage
);
1514 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl
);
1515 // Use signupend-https for HTTPS requests if it's not blank, signupend otherwise
1516 $usingHTTPS = $this->mRequest
->getProtocol() == 'https';
1517 $signupendHTTPS = $this->msg( 'signupend-https' );
1518 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1519 $template->set( 'signupend', $signupendHTTPS->parse() );
1521 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1524 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
1525 if ( $usingHTTPS ) {
1526 $template->set( 'fromhttp', $this->mFromHTTP
);
1529 // Give authentication and captcha plugins a chance to modify the form
1530 $wgAuth->modifyUITemplate( $template, $this->mType
);
1531 if ( $this->mType
== 'signup' ) {
1532 Hooks
::run( 'UserCreateForm', array( &$template ) );
1534 Hooks
::run( 'UserLoginForm', array( &$template ) );
1537 $out->disallowUserJs(); // just in case...
1538 $out->addTemplate( $template );
1542 * Whether the login/create account form should display a link to the
1543 * other form (in addition to whatever the skin provides).
1548 private function showCreateOrLoginLink( &$user ) {
1549 if ( $this->mType
== 'signup' ) {
1551 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1559 * Check if a session cookie is present.
1561 * This will not pick up a cookie set during _this_ request, but is meant
1562 * to ensure that the client is returning the cookie which was set on a
1563 * previous pass through the system.
1568 function hasSessionCookie() {
1569 global $wgDisableCookieCheck, $wgInitialSessionId;
1571 return $wgDisableCookieCheck ||
(
1572 $wgInitialSessionId &&
1573 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1578 * Get the login token from the current session
1581 public static function getLoginToken() {
1584 return $wgRequest->getSessionData( 'wsLoginToken' );
1588 * Randomly generate a new login token and attach it to the current session
1590 public static function setLoginToken() {
1592 // Generate a token directly instead of using $user->getEditToken()
1593 // because the latter reuses wsEditToken in the session
1594 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1598 * Remove any login token attached to the current session
1600 public static function clearLoginToken() {
1602 $wgRequest->setSessionData( 'wsLoginToken', null );
1606 * Get the createaccount token from the current session
1609 public static function getCreateaccountToken() {
1611 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1615 * Randomly generate a new createaccount token and attach it to the current session
1617 public static function setCreateaccountToken() {
1619 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1623 * Remove any createaccount token attached to the current session
1625 public static function clearCreateaccountToken() {
1627 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1631 * Renew the user's session id, using strong entropy
1633 private function renewSessionId() {
1634 global $wgSecureLogin, $wgCookieSecure;
1635 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1636 $wgCookieSecure = false;
1639 MediaWiki\Session\SessionManager
::getGlobalSession()->resetId();
1643 * @param string $type
1646 function cookieRedirectCheck( $type ) {
1647 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1648 $query = array( 'wpCookieCheck' => $type );
1649 if ( $this->mReturnTo
!== '' ) {
1650 $query['returnto'] = $this->mReturnTo
;
1651 $query['returntoquery'] = $this->mReturnToQuery
;
1653 $check = $titleObj->getFullURL( $query );
1655 $this->getOutput()->redirect( $check );
1659 * @param string $type
1662 function onCookieRedirectCheck( $type ) {
1663 if ( !$this->hasSessionCookie() ) {
1664 if ( $type == 'new' ) {
1665 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1666 } elseif ( $type == 'login' ) {
1667 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1670 $this->mainLoginForm( $this->msg( 'error' )->text() );
1673 $this->successfulLogin();
1678 * Produce a bar of links which allow the user to select another language
1679 * during login/registration but retain "returnto"
1683 function makeLanguageSelector() {
1684 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1685 if ( $msg->isBlank() ) {
1688 $langs = explode( "\n", $msg->text() );
1690 foreach ( $langs as $lang ) {
1691 $lang = trim( $lang, '* ' );
1692 $parts = explode( '|', $lang );
1693 if ( count( $parts ) >= 2 ) {
1694 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1698 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1699 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1703 * Create a language selector link for a particular language
1704 * Links back to this page preserving type and returnto
1706 * @param string $text Link text
1707 * @param string $lang Language code
1710 function makeLanguageSelectorLink( $text, $lang ) {
1711 if ( $this->getLanguage()->getCode() == $lang ) {
1712 // no link for currently used language
1713 return htmlspecialchars( $text );
1715 $query = array( 'uselang' => $lang );
1716 if ( $this->mType
== 'signup' ) {
1717 $query['type'] = 'signup';
1719 if ( $this->mReturnTo
!== '' ) {
1720 $query['returnto'] = $this->mReturnTo
;
1721 $query['returntoquery'] = $this->mReturnToQuery
;
1725 $targetLanguage = Language
::factory( $lang );
1726 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1728 return Linker
::linkKnown(
1729 $this->getPageTitle(),
1730 htmlspecialchars( $text ),
1736 protected function getGroupName() {
1741 * Private function to check password expiration, until AuthManager comes
1742 * along to handle that.
1744 * @return string|bool
1746 private function checkUserPasswordExpired( User
$user ) {
1747 global $wgPasswordExpireGrace;
1748 $dbr = wfGetDB( DB_SLAVE
);
1749 $ts = $dbr->selectField( 'user', 'user_password_expires', array( 'user_id' => $user->getId() ) );
1752 $now = wfTimestamp();
1753 $expUnix = wfTimestamp( TS_UNIX
, $ts );
1754 if ( $ts !== null && $expUnix < $now ) {
1755 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';