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;
137 * Returns an array of all valid error messages.
141 public static function getValidErrorMessages() {
142 static $messages = null;
144 $messages = self
::$validErrorMessages;
145 Hooks
::run( 'LoginFormValidErrorMessages', array( &$messages ) );
155 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
157 if ( $this->mLoaded
) {
160 $this->mLoaded
= true;
162 if ( $this->mOverrideRequest
=== null ) {
163 $request = $this->getRequest();
165 $request = $this->mOverrideRequest
;
167 $this->mRequest
= $request;
169 $this->mType
= $request->getText( 'type' );
170 $this->mUsername
= $request->getText( 'wpName' );
171 $this->mPassword
= $request->getText( 'wpPassword' );
172 $this->mRetype
= $request->getText( 'wpRetype' );
173 $this->mDomain
= $request->getText( 'wpDomain' );
174 $this->mReason
= $request->getText( 'wpReason' );
175 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
176 $this->mPosted
= $request->wasPosted();
177 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
179 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' ) && !$this->mCreateaccountMail
;
180 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
181 $this->mAction
= $request->getVal( 'action' );
182 $this->mRemember
= $request->getCheck( 'wpRemember' );
183 $this->mFromHTTP
= $request->getBool( 'fromhttp', false )
184 ||
$request->getBool( 'wpFromhttp', false );
185 $this->mStickHTTPS
= ( !$this->mFromHTTP
&& $request->getProtocol() === 'https' )
186 ||
$request->getBool( 'wpForceHttps', false );
187 $this->mLanguage
= $request->getText( 'uselang' );
188 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
189 $this->mToken
= $this->mType
== 'signup'
190 ?
$request->getVal( 'wpCreateaccountToken' )
191 : $request->getVal( 'wpLoginToken' );
192 $this->mReturnTo
= $request->getVal( 'returnto', '' );
193 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
195 // Show an error or warning passed on from a previous page
196 $entryError = $this->msg( $request->getVal( 'error', '' ) );
197 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
198 // bc: provide login link as a parameter for messages where the translation
200 $loginreqlink = Linker
::linkKnown(
201 $this->getPageTitle(),
202 $this->msg( 'loginreqlink' )->escaped(),
205 'returnto' => $this->mReturnTo
,
206 'returntoquery' => $this->mReturnToQuery
,
207 'uselang' => $this->mLanguage
,
208 'fromhttp' => $this->mFromHTTP ?
'1' : '0',
212 // Only show valid error or warning messages.
213 if ( $entryError->exists()
214 && in_array( $entryError->getKey(), self
::getValidErrorMessages() )
216 $this->mEntryErrorType
= 'error';
217 $this->mEntryError
= $entryError->rawParams( $loginreqlink )->parse();
219 } elseif ( $entryWarning->exists()
220 && in_array( $entryWarning->getKey(), self
::getValidErrorMessages() )
222 $this->mEntryErrorType
= 'warning';
223 $this->mEntryError
= $entryWarning->rawParams( $loginreqlink )->parse();
226 if ( $wgEnableEmail ) {
227 $this->mEmail
= $request->getText( 'wpEmail' );
231 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
232 $this->mRealName
= $request->getText( 'wpRealName' );
234 $this->mRealName
= '';
237 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
238 $this->mDomain
= $wgAuth->getDomain();
240 $wgAuth->setDomain( $this->mDomain
);
242 # 1. When switching accounts, it sucks to get automatically logged out
243 # 2. Do not return to PasswordReset after a successful password change
244 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
245 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
246 if ( is_object( $returnToTitle )
247 && ( $returnToTitle->isSpecial( 'Userlogout' )
248 ||
$returnToTitle->isSpecial( 'PasswordReset' ) )
250 $this->mReturnTo
= '';
251 $this->mReturnToQuery
= '';
255 function getDescription() {
256 if ( $this->mType
=== 'signup' ) {
257 return $this->msg( 'createaccount' )->text();
259 return $this->msg( 'login' )->text();
264 * @param string|null $subPage
266 public function execute( $subPage ) {
267 // Make sure session is persisted
268 $session = MediaWiki\Session\SessionManager
::getGlobalSession();
273 // Check for [[Special:Userlogin/signup]]. This affects form display and
275 if ( $subPage == 'signup' ) {
276 $this->mType
= 'signup';
280 // Make sure it's possible to log in
281 if ( $this->mType
!== 'signup' && !$session->canSetUser() ) {
282 throw new ErrorPageError(
283 'cannotloginnow-title',
284 'cannotloginnow-text',
286 $session->getProvider()->describe( RequestContext
::getMain()->getLanguage() )
292 * In the case where the user is already logged in, and was redirected to
293 * the login form from a page that requires login, do not show the login
294 * page. The use case scenario for this is when a user opens a large number
295 * of tabs, is redirected to the login page on all of them, and then logs
296 * in on one, expecting all the others to work properly.
298 * However, do show the form if it was visited intentionally (no 'returnto'
299 * is present). People who often switch between several accounts have grown
300 * accustomed to this behavior.
303 $this->mType
!== 'signup' &&
305 $this->getUser()->isLoggedIn() &&
306 ( $this->mReturnTo
!== '' ||
$this->mReturnToQuery
!== '' )
308 $this->successfulLogin();
311 // If logging in and not on HTTPS, either redirect to it or offer a link.
312 global $wgSecureLogin;
313 if ( $this->mRequest
->getProtocol() !== 'https' ) {
314 $title = $this->getFullTitle();
316 'returnto' => $this->mReturnTo
!== '' ?
$this->mReturnTo
: null,
317 'returntoquery' => $this->mReturnToQuery
!== '' ?
318 $this->mReturnToQuery
: null,
320 ( $this->mEntryErrorType
=== 'error' ?
'error' : 'warning' ) => $this->mEntryError
,
321 ) +
$this->mRequest
->getQueryValues();
322 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
324 && wfCanIPUseHTTPS( $this->getRequest()->getIP() )
325 && !$this->mFromHTTP
) // Avoid infinite redirect
327 $url = wfAppendQuery( $url, 'fromhttp=1' );
328 $this->getOutput()->redirect( $url );
329 // Since we only do this redir to change proto, always vary
330 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
334 // A wiki without HTTPS login support should set $wgServer to
335 // http://somehost, in which case the secure URL generated
336 // above won't actually start with https://
337 if ( substr( $url, 0, 8 ) === 'https://' ) {
338 $this->mSecureLoginUrl
= $url;
343 if ( !is_null( $this->mCookieCheck
) ) {
344 $this->onCookieRedirectCheck( $this->mCookieCheck
);
347 } elseif ( $this->mPosted
) {
348 if ( $this->mCreateaccount
) {
349 $this->addNewAccount();
352 } elseif ( $this->mCreateaccountMail
) {
353 $this->addNewAccountMailPassword();
356 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
357 $this->processLogin();
362 $this->mainLoginForm( $this->mEntryError
, $this->mEntryErrorType
);
368 function addNewAccountMailPassword() {
369 if ( $this->mEmail
== '' ) {
370 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
375 $status = $this->addNewAccountInternal();
376 LoggerFactory
::getInstance( 'authmanager' )->info(
377 'Account creation attempt with mailed password',
378 array( 'event' => 'accountcreation', 'status' => $status )
380 if ( !$status->isGood() ) {
381 $error = $status->getMessage();
382 $this->mainLoginForm( $error->toString() );
388 $u = $status->getValue();
390 // Wipe the initial password and mail a temporary one
391 $u->setPassword( null );
393 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
395 Hooks
::run( 'AddNewAccount', array( $u, true ) );
396 $u->addNewUserLogEntry( 'byemail', $this->mReason
);
398 $out = $this->getOutput();
399 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
401 if ( !$result->isGood() ) {
402 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
404 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
405 $this->executeReturnTo( 'success' );
413 function addNewAccount() {
414 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
416 # Create the account and abort if there's a problem doing so
417 $status = $this->addNewAccountInternal();
418 LoggerFactory
::getInstance( 'authmanager' )->info( 'Account creation attempt', array(
419 'event' => 'accountcreation',
423 if ( !$status->isGood() ) {
424 $error = $status->getMessage();
425 $this->mainLoginForm( $error->toString() );
430 $u = $status->getValue();
432 # Only save preferences if the user is not creating an account for someone else.
433 if ( $this->getUser()->isAnon() ) {
434 # If we showed up language selection links, and one was in use, be
435 # smart (and sensible) and save that language as the user's preference
436 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
437 $u->setOption( 'language', $this->mLanguage
);
440 # Otherwise the user's language preference defaults to $wgContLang,
441 # but it may be better to set it to their preferred $wgContLang variant,
442 # based on browser preferences or URL parameters.
443 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
445 if ( $wgContLang->hasVariants() ) {
446 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
450 $out = $this->getOutput();
452 # Send out an email authentication message if needed
453 if ( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
454 $status = $u->sendConfirmationMail();
455 if ( $status->isGood() ) {
456 $out->addWikiMsg( 'confirmemail_oncreate' );
458 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
462 # Save settings (including confirmation token)
465 # If not logged in, assume the new account as the current one and set
466 # session cookies then show a "welcome" message or a "need cookies"
468 if ( $this->getUser()->isAnon() ) {
471 // This should set it for OutputPage and the Skin
472 // which is needed or the personal links will be
474 $this->getContext()->setUser( $u );
475 Hooks
::run( 'AddNewAccount', array( $u, false ) );
476 $u->addNewUserLogEntry( 'create' );
477 if ( $this->hasSessionCookie() ) {
478 $this->successfulCreation();
480 $this->cookieRedirectCheck( 'new' );
483 # Confirm that the account was created
484 $out->setPageTitle( $this->msg( 'accountcreated' ) );
485 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
486 $out->addReturnTo( $this->getPageTitle() );
487 Hooks
::run( 'AddNewAccount', array( $u, false ) );
488 $u->addNewUserLogEntry( 'create2', $this->mReason
);
495 * Make a new user account using the loaded data.
497 * @throws PermissionsError|ReadOnlyError
500 public function addNewAccountInternal() {
501 global $wgAuth, $wgAccountCreationThrottle, $wgEmailConfirmToEdit;
503 // If the user passes an invalid domain, something is fishy
504 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
505 return Status
::newFatal( 'wrongpassword' );
508 // If we are not allowing users to login locally, we should be checking
509 // to see if the user is actually able to authenticate to the authenti-
510 // cation server before they create an account (otherwise, they can
511 // create a local account and login as any domain user). We only need
512 // to check this for domains that aren't local.
513 if ( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
515 !$wgAuth->canCreateAccounts() &&
517 !$wgAuth->userExists( $this->mUsername
) ||
518 !$wgAuth->authenticate( $this->mUsername
, $this->mPassword
)
521 return Status
::newFatal( 'wrongpassword' );
525 if ( wfReadOnly() ) {
526 throw new ReadOnlyError
;
529 # Request forgery checks.
530 if ( !self
::getCreateaccountToken() ) {
531 self
::setCreateaccountToken();
533 return Status
::newFatal( 'nocookiesfornew' );
536 # The user didn't pass a createaccount token
537 if ( !$this->mToken
) {
538 return Status
::newFatal( 'sessionfailure' );
541 # Validate the createaccount token
542 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
543 return Status
::newFatal( 'sessionfailure' );
547 $currentUser = $this->getUser();
548 $creationBlock = $currentUser->isBlockedFromCreateAccount();
549 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
550 throw new PermissionsError( 'createaccount' );
551 } elseif ( $creationBlock instanceof Block
) {
552 // Throws an ErrorPageError.
553 $this->userBlockedMessage( $creationBlock );
555 // This should never be reached.
559 # Include checks that will include GlobalBlocking (Bug 38333)
560 $permErrors = $this->getPageTitle()->getUserPermissionsErrors(
566 if ( count( $permErrors ) ) {
567 throw new PermissionsError( 'createaccount', $permErrors );
570 $ip = $this->getRequest()->getIP();
571 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
572 return Status
::newFatal( 'sorbs_create_account_reason' );
575 # Now create a dummy user ($u) and check if it is valid
576 $u = User
::newFromName( $this->mUsername
, 'creatable' );
578 return Status
::newFatal( 'noname' );
581 $cache = ObjectCache
::getLocalClusterInstance();
582 # Make sure the user does not exist already
583 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $this->mUsername
) ) );
585 return Status
::newFatal( 'usernameinprogress' );
586 } elseif ( $u->idForName( User
::READ_LOCKING
) ) {
587 return Status
::newFatal( 'userexists' );
590 if ( $this->mCreateaccountMail
) {
591 # do not force a password for account creation by email
592 # set invalid password, it will be replaced later by a random generated password
593 $this->mPassword
= null;
595 if ( $this->mPassword
!== $this->mRetype
) {
596 return Status
::newFatal( 'badretype' );
599 # check for password validity, return a fatal Status if invalid
600 $validity = $u->checkPasswordValidity( $this->mPassword
, 'create' );
601 if ( !$validity->isGood() ) {
602 $validity->ok
= false; // make sure this Status is fatal
607 # if you need a confirmed email address to edit, then obviously you
608 # need an email address.
609 if ( $wgEmailConfirmToEdit && strval( $this->mEmail
) === '' ) {
610 return Status
::newFatal( 'noemailtitle' );
613 if ( strval( $this->mEmail
) !== '' && !Sanitizer
::validateEmail( $this->mEmail
) ) {
614 return Status
::newFatal( 'invalidemailaddress' );
617 # Set some additional data so the AbortNewAccount hook can be used for
618 # more than just username validation
619 $u->setEmail( $this->mEmail
);
620 $u->setRealName( $this->mRealName
);
624 if ( !Hooks
::run( 'AbortNewAccount', array( $u, &$abortError, &$abortStatus ) ) ) {
625 // Hook point to add extra creation throttles and blocks
626 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
627 if ( $abortStatus === null ) {
628 // Report back the old string as a raw message status.
629 // This will report the error back as 'createaccount-hook-aborted'
630 // with the given string as the message.
631 // To return a different error code, return a Status object.
632 $abortError = new Message( 'createaccount-hook-aborted', array( $abortError ) );
635 return Status
::newFatal( $abortError );
637 // For MediaWiki 1.23+ and updated hooks, return the Status object
638 // returned from the hook.
643 // Hook point to check for exempt from account creation throttle
644 if ( !Hooks
::run( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
645 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook " .
646 "allowed account creation w/o throttle\n" );
648 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
649 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
650 $value = $cache->get( $key );
652 $cache->set( $key, 0, $cache::TTL_DAY
);
654 if ( $value >= $wgAccountCreationThrottle ) {
655 return Status
::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
657 $cache->incr( $key );
661 if ( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
662 return Status
::newFatal( 'externaldberror' );
665 self
::clearCreateaccountToken();
667 return $this->initUser( $u, false );
671 * Actually add a user to the database.
672 * Give it a User object that has been initialised with a name.
675 * @param bool $autocreate True if this is an autocreation via auth plugin
676 * @return Status Status object, with the User object in the value member on success
679 function initUser( $u, $autocreate ) {
682 $status = $u->addToDatabase();
683 if ( !$status->isOK() ) {
687 if ( $wgAuth->allowPasswordChange() ) {
688 $u->setPassword( $this->mPassword
);
691 $u->setEmail( $this->mEmail
);
692 $u->setRealName( $this->mRealName
);
695 Hooks
::run( 'LocalUserCreated', array( $u, $autocreate ) );
697 $wgAuth->initUser( $u, $autocreate );
698 if ( $oldUser !== $u ) {
699 wfWarn( get_class( $wgAuth ) . '::initUser() replaced the user object' );
705 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
707 // Watch user's userpage and talk page
708 $u->addWatch( $u->getUserPage(), WatchedItem
::IGNORE_USER_RIGHTS
);
710 return Status
::newGood( $u );
714 * Internally authenticate the login request.
716 * This may create a local account as a side effect if the
717 * authentication plugin allows transparent local account
721 public function authenticateUserData() {
722 global $wgUser, $wgAuth;
726 if ( $this->mUsername
== '' ) {
727 return self
::NO_NAME
;
730 // We require a login token to prevent login CSRF
731 // Handle part of this before incrementing the throttle so
732 // token-less login attempts don't count towards the throttle
733 // but wrong-token attempts do.
735 // If the user doesn't have a login token yet, set one.
736 if ( !self
::getLoginToken() ) {
737 self
::setLoginToken();
739 return self
::NEED_TOKEN
;
741 // If the user didn't pass a login token, tell them we need one
742 if ( !$this->mToken
) {
743 return self
::NEED_TOKEN
;
746 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
747 if ( $throttleCount === true ) {
748 return self
::THROTTLED
;
751 // Validate the login token
752 if ( $this->mToken
!== self
::getLoginToken() ) {
753 return self
::WRONG_TOKEN
;
756 // Load the current user now, and check to see if we're logging in as
757 // the same name. This is necessary because loading the current user
758 // (say by calling getName()) calls the UserLoadFromSession hook, which
759 // potentially creates the user in the database. Until we load $wgUser,
760 // checking for user existence using User::newFromName($name)->getId() below
761 // will effectively be using stale data.
762 if ( $this->getUser()->getName() === $this->mUsername
) {
763 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
765 return self
::SUCCESS
;
768 $u = User
::newFromName( $this->mUsername
);
769 if ( $u === false ) {
770 return self
::ILLEGAL
;
774 // Give extensions a way to indicate the username has been updated,
775 // rather than telling the user the account doesn't exist.
776 if ( !Hooks
::run( 'LoginUserMigrated', array( $u, &$msg ) ) ) {
777 $this->mAbortLoginErrorMsg
= $msg;
778 return self
::USER_MIGRATED
;
781 if ( !User
::isUsableName( $u->getName() ) ) {
782 return self
::ILLEGAL
;
785 $isAutoCreated = false;
786 if ( $u->getID() == 0 ) {
787 $status = $this->attemptAutoCreate( $u );
788 if ( $status !== self
::SUCCESS
) {
791 $isAutoCreated = true;
797 // Give general extensions, such as a captcha, a chance to abort logins
798 $abort = self
::ABORTED
;
799 if ( !Hooks
::run( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$msg ) ) ) {
800 if ( !in_array( $abort, array_keys( self
::$statusCodes ), true ) ) {
801 throw new Exception( 'Invalid status code returned from AbortLogin hook: ' . $abort );
803 $this->mAbortLoginErrorMsg
= $msg;
807 global $wgBlockDisablesLogin;
808 if ( !$u->checkPassword( $this->mPassword
) ) {
809 if ( $u->checkTemporaryPassword( $this->mPassword
) ) {
811 * The e-mailed temporary password should not be used for actu-
812 * al logins; that's a very sloppy habit, and insecure if an
813 * attacker has a few seconds to click "search" on someone's
816 * Allow it to be used only to reset the password a single time
817 * to a new value, which won't be in the user's e-mail ar-
820 * For backwards compatibility, we'll still recognize it at the
821 * login form to minimize surprises for people who have been
822 * logging in with a temporary password for some time.
824 * As a side-effect, we can authenticate the user's e-mail ad-
825 * dress if it's not already done, since the temporary password
826 * was sent via e-mail.
828 if ( !$u->isEmailConfirmed() && !wfReadOnly() ) {
833 // At this point we just return an appropriate code/ indicating
834 // that the UI should show a password reset form; bot inter-
835 // faces etc will probably just fail cleanly here.
836 $this->mAbortLoginErrorMsg
= 'resetpass-temp-emailed';
837 $this->mTempPasswordUsed
= true;
838 $retval = self
::RESET_PASS
;
840 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
842 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
843 // If we've enabled it, make it so that a blocked user cannot login
844 $retval = self
::USER_BLOCKED
;
845 } elseif ( $this->checkUserPasswordExpired( $u ) == 'hard' ) {
846 // Force reset now, without logging in
847 $retval = self
::RESET_PASS
;
848 $this->mAbortLoginErrorMsg
= 'resetpass-expired';
850 Hooks
::run( 'UserLoggedIn', array( $u ) );
852 $wgAuth->updateUser( $u );
853 if ( $oldUser !== $u ) {
854 wfWarn( get_class( $wgAuth ) . '::updateUser() replaced the user object' );
857 // This should set it for OutputPage and the Skin
858 // which is needed or the personal links will be
860 $this->getContext()->setUser( $u );
862 // Please reset throttle for successful logins, thanks!
863 if ( $throttleCount ) {
864 self
::clearLoginThrottle( $this->mUsername
);
867 if ( $isAutoCreated ) {
868 // Must be run after $wgUser is set, for correct new user log
869 Hooks
::run( 'AuthPluginAutoCreate', array( $u ) );
872 $retval = self
::SUCCESS
;
874 Hooks
::run( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
880 * Increment the login attempt throttle hit count for the (username,current IP)
881 * tuple unless the throttle was already reached.
882 * @param string $username The user name
883 * @return bool|int The integer hit count or True if it is already at the limit
885 public static function incLoginThrottle( $username ) {
886 global $wgPasswordAttemptThrottle, $wgRequest;
887 $username = trim( $username ); // sanity
890 if ( is_array( $wgPasswordAttemptThrottle ) ) {
891 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
892 $count = $wgPasswordAttemptThrottle['count'];
893 $period = $wgPasswordAttemptThrottle['seconds'];
895 $cache = ObjectCache
::getLocalClusterInstance();
896 $throttleCount = $cache->get( $throttleKey );
897 if ( !$throttleCount ) {
898 $cache->add( $throttleKey, 1, $period ); // start counter
899 } elseif ( $throttleCount < $count ) {
900 $cache->incr( $throttleKey );
901 } elseif ( $throttleCount >= $count ) {
906 return $throttleCount;
910 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
911 * @param string $username The user name
914 public static function clearLoginThrottle( $username ) {
916 $username = trim( $username ); // sanity
918 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
919 ObjectCache
::getLocalClusterInstance()->delete( $throttleKey );
923 * Attempt to automatically create a user on login. Only succeeds if there
924 * is an external authentication method which allows it.
928 * @return int Status code
930 function attemptAutoCreate( $user ) {
933 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
934 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
936 return self
::CREATE_BLOCKED
;
939 if ( !$wgAuth->autoCreate() ) {
940 return self
::NOT_EXISTS
;
943 if ( !$wgAuth->userExists( $user->getName() ) ) {
944 wfDebug( __METHOD__
. ": user does not exist\n" );
946 return self
::NOT_EXISTS
;
949 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
950 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
952 return self
::WRONG_PLUGIN_PASS
;
956 if ( !Hooks
::run( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
957 // Hook point to add extra creation throttles and blocks
958 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
959 $this->mAbortLoginErrorMsg
= $abortError;
961 return self
::ABORTED
;
964 wfDebug( __METHOD__
. ": creating account\n" );
965 $status = $this->initUser( $user, true );
967 if ( !$status->isOK() ) {
968 $errors = $status->getErrorsByType( 'error' );
969 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
971 return self
::ABORTED
;
974 return self
::SUCCESS
;
977 function processLogin() {
978 global $wgLang, $wgSecureLogin, $wgPasswordAttemptThrottle, $wgInvalidPasswordReset;
980 $cache = ObjectCache
::getLocalClusterInstance();
981 $authRes = $this->authenticateUserData();
982 switch ( $authRes ) {
984 # We've verified now, update the real record
985 $user = $this->getUser();
988 if ( $user->requiresHTTPS() ) {
989 $this->mStickHTTPS
= true;
992 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
993 $user->setCookies( $this->mRequest
, false, $this->mRemember
);
995 $user->setCookies( $this->mRequest
, null, $this->mRemember
);
997 self
::clearLoginToken();
999 // Reset the throttle
1000 $request = $this->getRequest();
1001 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
1002 $cache->delete( $key );
1004 if ( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
1005 /* Replace the language object to provide user interface in
1006 * correct language immediately on this first page load.
1008 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
1009 $userLang = Language
::factory( $code );
1010 $wgLang = $userLang;
1011 $this->getContext()->setLanguage( $userLang );
1012 // Reset SessionID on Successful login (bug 40995)
1013 $this->renewSessionId();
1014 if ( $this->checkUserPasswordExpired( $this->getUser() ) == 'soft' ) {
1015 $this->resetLoginForm( $this->msg( 'resetpass-expired-soft' ) );
1016 } elseif ( $wgInvalidPasswordReset
1017 && !$user->isValidPassword( $this->mPassword
)
1019 $status = $user->checkPasswordValidity(
1023 $this->resetLoginForm(
1024 $status->getMessage( 'resetpass-validity-soft' )
1027 $this->successfulLogin();
1030 $this->cookieRedirectCheck( 'login' );
1034 case self
::NEED_TOKEN
:
1035 $error = $this->mAbortLoginErrorMsg ?
: 'nocookiesforlogin';
1036 $this->mainLoginForm( $this->msg( $error )->parse() );
1038 case self
::WRONG_TOKEN
:
1039 $error = $this->mAbortLoginErrorMsg ?
: 'sessionfailure';
1040 $this->mainLoginForm( $this->msg( $error )->text() );
1044 $error = $this->mAbortLoginErrorMsg ?
: 'noname';
1045 $this->mainLoginForm( $this->msg( $error )->text() );
1047 case self
::WRONG_PLUGIN_PASS
:
1048 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
1049 $this->mainLoginForm( $this->msg( $error )->text() );
1051 case self
::NOT_EXISTS
:
1052 if ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1053 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchuser';
1054 $this->mainLoginForm( $this->msg( $error,
1055 wfEscapeWikiText( $this->mUsername
) )->parse() );
1057 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchusershort';
1058 $this->mainLoginForm( $this->msg( $error,
1059 wfEscapeWikiText( $this->mUsername
) )->text() );
1062 case self
::WRONG_PASS
:
1063 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
1064 $this->mainLoginForm( $this->msg( $error )->text() );
1066 case self
::EMPTY_PASS
:
1067 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpasswordempty';
1068 $this->mainLoginForm( $this->msg( $error )->text() );
1070 case self
::RESET_PASS
:
1071 $error = $this->mAbortLoginErrorMsg ?
: 'resetpass_announce';
1072 $this->resetLoginForm( $this->msg( $error ) );
1074 case self
::CREATE_BLOCKED
:
1075 $this->userBlockedMessage( $this->getUser()->isBlockedFromCreateAccount() );
1077 case self
::THROTTLED
:
1078 $error = $this->mAbortLoginErrorMsg ?
: 'login-throttled';
1079 $this->mainLoginForm( $this->msg( $error )
1080 ->params( $this->getLanguage()->formatDuration( $wgPasswordAttemptThrottle['seconds'] ) )
1084 case self
::USER_BLOCKED
:
1085 $error = $this->mAbortLoginErrorMsg ?
: 'login-userblocked';
1086 $this->mainLoginForm( $this->msg( $error, $this->mUsername
)->escaped() );
1089 $error = $this->mAbortLoginErrorMsg ?
: 'login-abort-generic';
1090 $this->mainLoginForm( $this->msg( $error,
1091 wfEscapeWikiText( $this->mUsername
) )->text() );
1093 case self
::USER_MIGRATED
:
1094 $error = $this->mAbortLoginErrorMsg ?
: 'login-migrated-generic';
1096 if ( is_array( $error ) ) {
1097 $error = array_shift( $this->mAbortLoginErrorMsg
);
1098 $params = $this->mAbortLoginErrorMsg
;
1100 $this->mainLoginForm( $this->msg( $error, $params )->text() );
1103 throw new MWException( 'Unhandled case value' );
1106 LoggerFactory
::getInstance( 'authmanager' )->info( 'Login attempt', array(
1108 'successful' => $authRes === self
::SUCCESS
,
1109 'status' => LoginForm
::$statusCodes[$authRes],
1114 * Show the Special:ChangePassword form, with custom message
1115 * @param Message $msg
1117 protected function resetLoginForm( Message
$msg ) {
1118 // Allow hooks to explain this password reset in more detail
1119 Hooks
::run( 'LoginPasswordResetMessage', array( &$msg, $this->mUsername
) );
1120 $reset = new SpecialChangePassword();
1121 $derivative = new DerivativeContext( $this->getContext() );
1122 $derivative->setTitle( $reset->getPageTitle() );
1123 $reset->setContext( $derivative );
1124 if ( !$this->mTempPasswordUsed
) {
1125 $reset->setOldPasswordMessage( 'oldpassword' );
1127 $reset->setChangeMessage( $msg );
1128 $reset->execute( null );
1133 * @param bool $throttle
1134 * @param string $emailTitle Message name of email title
1135 * @param string $emailText Message name of email text
1138 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle',
1139 $emailText = 'passwordremindertext'
1141 global $wgNewPasswordExpiry, $wgMinimalPasswordLength;
1143 if ( $u->getEmail() == '' ) {
1144 return Status
::newFatal( 'noemail', $u->getName() );
1146 $ip = $this->getRequest()->getIP();
1148 return Status
::newFatal( 'badipaddress' );
1151 $currentUser = $this->getUser();
1152 Hooks
::run( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
1154 $np = PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1155 $u->setNewpassword( $np, $throttle );
1157 $userLanguage = $u->getOption( 'language' );
1159 $mainPage = Title
::newMainPage();
1160 $mainPageUrl = $mainPage->getCanonicalURL();
1162 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $mainPageUrl . '>',
1163 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
1164 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
1170 * Run any hooks registered for logins, then HTTP redirect to
1171 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
1172 * nice message here, but that's really not as useful as just being sent to
1173 * wherever you logged in from. It should be clear that the action was
1174 * successful, given the lack of error messages plus the appearance of your
1175 * name in the upper right.
1179 function successfulLogin() {
1180 # Run any hooks; display injected HTML if any, else redirect
1181 $currentUser = $this->getUser();
1182 $injected_html = '';
1183 Hooks
::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1185 if ( $injected_html !== '' ) {
1186 $this->displaySuccessfulAction( 'success', $this->msg( 'loginsuccesstitle' ),
1187 'loginsuccess', $injected_html );
1189 $this->executeReturnTo( 'successredirect' );
1194 * Run any hooks registered for logins, then display a message welcoming
1199 function successfulCreation() {
1200 # Run any hooks; display injected HTML
1201 $currentUser = $this->getUser();
1202 $injected_html = '';
1203 $welcome_creation_msg = 'welcomecreation-msg';
1205 Hooks
::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1208 * Let any extensions change what message is shown.
1209 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
1212 Hooks
::run( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
1214 $this->displaySuccessfulAction(
1216 $this->msg( 'welcomeuser', $this->getUser()->getName() ),
1217 $welcome_creation_msg, $injected_html
1222 * Display a "successful action" page.
1224 * @param string $type Condition of return to; see `executeReturnTo`
1225 * @param string|Message $title Page's title
1226 * @param string $msgname
1227 * @param string $injected_html
1229 private function displaySuccessfulAction( $type, $title, $msgname, $injected_html ) {
1230 $out = $this->getOutput();
1231 $out->setPageTitle( $title );
1233 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
1236 $out->addHTML( $injected_html );
1238 $this->executeReturnTo( $type );
1242 * Output a message that informs the user that they cannot create an account because
1243 * there is a block on them or their IP which prevents account creation. Note that
1244 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
1245 * setting on blocks (bug 13611).
1246 * @param Block $block The block causing this error
1247 * @throws ErrorPageError
1249 function userBlockedMessage( Block
$block ) {
1250 # Let's be nice about this, it's likely that this feature will be used
1251 # for blocking large numbers of innocent people, e.g. range blocks on
1252 # schools. Don't blame it on the user. There's a small chance that it
1253 # really is the user's fault, i.e. the username is blocked and they
1254 # haven't bothered to log out before trying to create an account to
1255 # evade it, but we'll leave that to their guilty conscience to figure
1257 $errorParams = array(
1258 $block->getTarget(),
1259 $block->mReason ?
$block->mReason
: $this->msg( 'blockednoreason' )->text(),
1263 if ( $block->getType() === Block
::TYPE_RANGE
) {
1264 $errorMessage = 'cantcreateaccount-range-text';
1265 $errorParams[] = $this->getRequest()->getIP();
1267 $errorMessage = 'cantcreateaccount-text';
1270 throw new ErrorPageError(
1271 'cantcreateaccounttitle',
1278 * Add a "return to" link or redirect to it.
1279 * Extensions can use this to reuse the "return to" logic after
1280 * inject steps (such as redirection) into the login process.
1282 * @param string $type One of the following:
1283 * - error: display a return to link ignoring $wgRedirectOnLogin
1284 * - signup: display a return to link using $wgRedirectOnLogin if needed
1285 * - success: display a return to link using $wgRedirectOnLogin if needed
1286 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1287 * @param string $returnTo
1288 * @param array|string $returnToQuery
1289 * @param bool $stickHTTPs Keep redirect link on HTTPs
1292 public function showReturnToPage(
1293 $type, $returnTo = '', $returnToQuery = '', $stickHTTPs = false
1295 $this->mReturnTo
= $returnTo;
1296 $this->mReturnToQuery
= $returnToQuery;
1297 $this->mStickHTTPS
= $stickHTTPs;
1298 $this->executeReturnTo( $type );
1302 * Add a "return to" link or redirect to it.
1304 * @param string $type One of the following:
1305 * - error: display a return to link ignoring $wgRedirectOnLogin
1306 * - signup: display a return to link using $wgRedirectOnLogin if needed
1307 * - success: display a return to link using $wgRedirectOnLogin if needed
1308 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1310 private function executeReturnTo( $type ) {
1311 global $wgRedirectOnLogin, $wgSecureLogin;
1313 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
1314 $returnTo = $wgRedirectOnLogin;
1315 $returnToQuery = array();
1317 $returnTo = $this->mReturnTo
;
1318 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
1321 // Allow modification of redirect behavior
1322 Hooks
::run( 'PostLoginRedirect', array( &$returnTo, &$returnToQuery, &$type ) );
1324 $returnToTitle = Title
::newFromText( $returnTo );
1325 if ( !$returnToTitle ) {
1326 $returnToTitle = Title
::newMainPage();
1329 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1330 $options = array( 'http' );
1331 $proto = PROTO_HTTP
;
1332 } elseif ( $wgSecureLogin ) {
1333 $options = array( 'https' );
1334 $proto = PROTO_HTTPS
;
1337 $proto = PROTO_RELATIVE
;
1340 if ( $type == 'successredirect' ) {
1341 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1342 $this->getOutput()->redirect( $redirectUrl );
1344 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1349 * @param string $msg
1350 * @param string $msgtype
1351 * @throws ErrorPageError
1353 * @throws FatalError
1354 * @throws MWException
1355 * @throws PermissionsError
1356 * @throws ReadOnlyError
1359 function mainLoginForm( $msg, $msgtype = 'error' ) {
1360 global $wgEnableEmail, $wgEnableUserEmail;
1361 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1362 global $wgAuth, $wgEmailConfirmToEdit;
1363 global $wgSecureLogin, $wgPasswordResetRoutes;
1364 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
1366 $titleObj = $this->getPageTitle();
1367 $user = $this->getUser();
1368 $out = $this->getOutput();
1370 if ( $this->mType
== 'signup' ) {
1371 // Block signup here if in readonly. Keeps user from
1372 // going through the process (filling out data, etc)
1373 // and being informed later.
1374 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1375 if ( count( $permErrors ) ) {
1376 throw new PermissionsError( 'createaccount', $permErrors );
1377 } elseif ( $user->isBlockedFromCreateAccount() ) {
1378 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1381 } elseif ( wfReadOnly() ) {
1382 throw new ReadOnlyError
;
1386 // Pre-fill username (if not creating an account, bug 44775).
1387 if ( $this->mUsername
== '' && $this->mType
!= 'signup' ) {
1388 if ( $user->isLoggedIn() ) {
1389 $this->mUsername
= $user->getName();
1391 $this->mUsername
= $this->getRequest()->getSession()->suggestLoginUsername();
1395 // Generic styles and scripts for both login and signup form
1396 $out->addModuleStyles( array(
1398 'mediawiki.ui.button',
1399 'mediawiki.ui.checkbox',
1400 'mediawiki.ui.input',
1401 'mediawiki.special.userlogin.common.styles'
1404 if ( $this->mType
== 'signup' ) {
1405 // Additional styles and scripts for signup form
1406 $out->addModules( array(
1407 'mediawiki.special.userlogin.signup.js'
1409 $out->addModuleStyles( array(
1410 'mediawiki.special.userlogin.signup.styles'
1413 $template = new UsercreateTemplate( $this->getConfig() );
1415 // Must match number of benefits defined in messages
1416 $template->set( 'benefitCount', 3 );
1418 $q = 'action=submitlogin&type=signup';
1419 $linkq = 'type=login';
1421 // Additional styles for login form
1422 $out->addModuleStyles( array(
1423 'mediawiki.special.userlogin.login.styles'
1426 $template = new UserloginTemplate( $this->getConfig() );
1428 $q = 'action=submitlogin&type=login';
1429 $linkq = 'type=signup';
1432 if ( $this->mReturnTo
!== '' ) {
1433 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1434 if ( $this->mReturnToQuery
!== '' ) {
1435 $returnto .= '&returntoquery=' .
1436 wfUrlencode( $this->mReturnToQuery
);
1439 $linkq .= $returnto;
1442 # Don't show a "create account" link if the user can't.
1443 if ( $this->showCreateOrLoginLink( $user ) ) {
1444 # Pass any language selection on to the mode switch link
1445 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
1446 $linkq .= '&uselang=' . $this->mLanguage
;
1448 // Supply URL, login template creates the button.
1449 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1451 $template->set( 'link', '' );
1454 $resetLink = $this->mType
== 'signup'
1456 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1458 $template->set( 'header', '' );
1459 $template->set( 'formheader', '' );
1460 $template->set( 'skin', $this->getSkin() );
1461 $template->set( 'name', $this->mUsername
);
1462 $template->set( 'password', $this->mPassword
);
1463 $template->set( 'retype', $this->mRetype
);
1464 $template->set( 'createemailset', $this->mCreateaccountMail
);
1465 $template->set( 'email', $this->mEmail
);
1466 $template->set( 'realname', $this->mRealName
);
1467 $template->set( 'domain', $this->mDomain
);
1468 $template->set( 'reason', $this->mReason
);
1470 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1471 $template->set( 'message', $msg );
1472 $template->set( 'messagetype', $msgtype );
1473 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1474 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1475 $template->set( 'useemail', $wgEnableEmail );
1476 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1477 $template->set( 'emailothers', $wgEnableUserEmail );
1478 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1479 $template->set( 'resetlink', $resetLink );
1480 $template->set( 'canremember', $wgExtendedLoginCookieExpiration === null ?
1481 ( $wgCookieExpiration > 0 ) :
1482 ( $wgExtendedLoginCookieExpiration > 0 ) );
1483 $template->set( 'usereason', $user->isLoggedIn() );
1484 $template->set( 'remember', $this->mRemember
);
1485 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1486 $template->set( 'stickhttps', (int)$this->mStickHTTPS
);
1487 $template->set( 'loggedin', $user->isLoggedIn() );
1488 $template->set( 'loggedinuser', $user->getName() );
1490 if ( $this->mType
== 'signup' ) {
1491 if ( !self
::getCreateaccountToken() ) {
1492 self
::setCreateaccountToken();
1494 $template->set( 'token', self
::getCreateaccountToken() );
1496 if ( !self
::getLoginToken() ) {
1497 self
::setLoginToken();
1499 $template->set( 'token', self
::getLoginToken() );
1502 # Prepare language selection links as needed
1503 if ( $wgLoginLanguageSelector ) {
1504 $template->set( 'languages', $this->makeLanguageSelector() );
1505 if ( $this->mLanguage
) {
1506 $template->set( 'uselang', $this->mLanguage
);
1510 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl
);
1511 // Use signupend-https for HTTPS requests if it's not blank, signupend otherwise
1512 $usingHTTPS = $this->mRequest
->getProtocol() == 'https';
1513 $signupendHTTPS = $this->msg( 'signupend-https' );
1514 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1515 $template->set( 'signupend', $signupendHTTPS->parse() );
1517 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1520 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
1521 if ( $usingHTTPS ) {
1522 $template->set( 'fromhttp', $this->mFromHTTP
);
1525 // Give authentication and captcha plugins a chance to modify the form
1526 $wgAuth->modifyUITemplate( $template, $this->mType
);
1527 if ( $this->mType
== 'signup' ) {
1528 Hooks
::run( 'UserCreateForm', array( &$template ) );
1530 Hooks
::run( 'UserLoginForm', array( &$template ) );
1533 $out->disallowUserJs(); // just in case...
1534 $out->addTemplate( $template );
1538 * Whether the login/create account form should display a link to the
1539 * other form (in addition to whatever the skin provides).
1544 private function showCreateOrLoginLink( &$user ) {
1545 if ( $this->mType
== 'signup' ) {
1547 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1555 * Check if a session cookie is present.
1557 * This will not pick up a cookie set during _this_ request, but is meant
1558 * to ensure that the client is returning the cookie which was set on a
1559 * previous pass through the system.
1564 function hasSessionCookie() {
1565 global $wgDisableCookieCheck;
1567 return $wgDisableCookieCheck ||
1568 SessionManager
::singleton()->getPersistedSessionId( $this->getRequest() ) !== null;
1572 * Get the login token from the current session
1575 public static function getLoginToken() {
1578 return $wgRequest->getSessionData( 'wsLoginToken' );
1582 * Randomly generate a new login token and attach it to the current session
1584 public static function setLoginToken() {
1586 // Generate a token directly instead of using $user->getEditToken()
1587 // because the latter reuses wsEditToken in the session
1588 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1592 * Remove any login token attached to the current session
1594 public static function clearLoginToken() {
1596 $wgRequest->setSessionData( 'wsLoginToken', null );
1600 * Get the createaccount token from the current session
1603 public static function getCreateaccountToken() {
1605 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1609 * Randomly generate a new createaccount token and attach it to the current session
1611 public static function setCreateaccountToken() {
1613 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1617 * Remove any createaccount token attached to the current session
1619 public static function clearCreateaccountToken() {
1621 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1625 * Renew the user's session id, using strong entropy
1627 private function renewSessionId() {
1628 global $wgSecureLogin, $wgCookieSecure;
1629 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1630 $wgCookieSecure = false;
1633 MediaWiki\Session\SessionManager
::getGlobalSession()->resetId();
1637 * @param string $type
1640 function cookieRedirectCheck( $type ) {
1641 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1642 $query = array( 'wpCookieCheck' => $type );
1643 if ( $this->mReturnTo
!== '' ) {
1644 $query['returnto'] = $this->mReturnTo
;
1645 $query['returntoquery'] = $this->mReturnToQuery
;
1647 $check = $titleObj->getFullURL( $query );
1649 $this->getOutput()->redirect( $check );
1653 * @param string $type
1656 function onCookieRedirectCheck( $type ) {
1657 if ( !$this->hasSessionCookie() ) {
1658 if ( $type == 'new' ) {
1659 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1660 } elseif ( $type == 'login' ) {
1661 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1664 $this->mainLoginForm( $this->msg( 'error' )->text() );
1667 $this->successfulLogin();
1672 * Produce a bar of links which allow the user to select another language
1673 * during login/registration but retain "returnto"
1677 function makeLanguageSelector() {
1678 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1679 if ( $msg->isBlank() ) {
1682 $langs = explode( "\n", $msg->text() );
1684 foreach ( $langs as $lang ) {
1685 $lang = trim( $lang, '* ' );
1686 $parts = explode( '|', $lang );
1687 if ( count( $parts ) >= 2 ) {
1688 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1692 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1693 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1697 * Create a language selector link for a particular language
1698 * Links back to this page preserving type and returnto
1700 * @param string $text Link text
1701 * @param string $lang Language code
1704 function makeLanguageSelectorLink( $text, $lang ) {
1705 if ( $this->getLanguage()->getCode() == $lang ) {
1706 // no link for currently used language
1707 return htmlspecialchars( $text );
1709 $query = array( 'uselang' => $lang );
1710 if ( $this->mType
== 'signup' ) {
1711 $query['type'] = 'signup';
1713 if ( $this->mReturnTo
!== '' ) {
1714 $query['returnto'] = $this->mReturnTo
;
1715 $query['returntoquery'] = $this->mReturnToQuery
;
1719 $targetLanguage = Language
::factory( $lang );
1720 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1722 return Linker
::linkKnown(
1723 $this->getPageTitle(),
1724 htmlspecialchars( $text ),
1730 protected function getGroupName() {
1735 * Private function to check password expiration, until AuthManager comes
1736 * along to handle that.
1738 * @return string|bool
1740 private function checkUserPasswordExpired( User
$user ) {
1741 global $wgPasswordExpireGrace;
1742 $dbr = wfGetDB( DB_SLAVE
);
1743 $ts = $dbr->selectField( 'user', 'user_password_expires', array( 'user_id' => $user->getId() ) );
1746 $now = wfTimestamp();
1747 $expUnix = wfTimestamp( TS_UNIX
, $ts );
1748 if ( $ts !== null && $expUnix < $now ) {
1749 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';