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
25 * Implements Special:UserLogin
27 * @ingroup SpecialPage
29 class LoginForm
extends SpecialPage
{
33 const WRONG_PLUGIN_PASS
= 3;
39 const CREATE_BLOCKED
= 9;
41 const USER_BLOCKED
= 11;
42 const NEED_TOKEN
= 12;
43 const WRONG_TOKEN
= 13;
44 const USER_MIGRATED
= 14;
47 * Valid error and warning messages
49 * Special:Userlogin can show an error or warning message on the form when
50 * coming from another page. This is done via the ?error= or ?warning= GET
53 * This array is the list of valid message keys. All other values will be
59 public static $validErrorMessages = array(
60 'exception-nologin-text',
62 'changeemail-no-info',
64 'confirmemail_needlogin',
68 public $mAbortLoginErrorMsg = null;
74 protected $mCookieCheck;
77 protected $mCreateaccount;
78 protected $mCreateaccountMail;
79 protected $mLoginattempt;
84 protected $mSkipCookieCheck;
85 protected $mReturnToQuery;
87 protected $mStickHTTPS;
91 protected $mEntryError = '';
92 protected $mEntryErrorType = 'error';
94 private $mTempPasswordUsed;
95 private $mLoaded = false;
96 private $mSecureLoginUrl;
98 /** @var WebRequest */
99 private $mOverrideRequest = null;
101 /** @var WebRequest Effective request; set at the beginning of load */
102 private $mRequest = null;
105 * @param WebRequest $request
107 public function __construct( $request = null ) {
108 global $wgUseMediaWikiUIEverywhere;
109 parent
::__construct( 'Userlogin' );
111 $this->mOverrideRequest
= $request;
112 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
113 $wgUseMediaWikiUIEverywhere = true;
117 * Returns an array of all valid error messages.
121 public static function getValidErrorMessages() {
122 static $messages = null;
124 $messages = self
::$validErrorMessages;
125 wfRunHooks( 'LoginFormValidErrorMessages', array( &$messages ) );
135 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
137 if ( $this->mLoaded
) {
140 $this->mLoaded
= true;
142 if ( $this->mOverrideRequest
=== null ) {
143 $request = $this->getRequest();
145 $request = $this->mOverrideRequest
;
147 $this->mRequest
= $request;
149 $this->mType
= $request->getText( 'type' );
150 $this->mUsername
= $request->getText( 'wpName' );
151 $this->mPassword
= $request->getText( 'wpPassword' );
152 $this->mRetype
= $request->getText( 'wpRetype' );
153 $this->mDomain
= $request->getText( 'wpDomain' );
154 $this->mReason
= $request->getText( 'wpReason' );
155 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
156 $this->mPosted
= $request->wasPosted();
157 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
159 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' ) && !$this->mCreateaccountMail
;
160 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
161 $this->mAction
= $request->getVal( 'action' );
162 $this->mRemember
= $request->getCheck( 'wpRemember' );
163 $this->mFromHTTP
= $request->getBool( 'fromhttp', false );
164 $this->mStickHTTPS
= ( !$this->mFromHTTP
&& $request->getProtocol() === 'https' )
165 ||
$request->getBool( 'wpForceHttps', false );
166 $this->mLanguage
= $request->getText( 'uselang' );
167 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
168 $this->mToken
= $this->mType
== 'signup'
169 ?
$request->getVal( 'wpCreateaccountToken' )
170 : $request->getVal( 'wpLoginToken' );
171 $this->mReturnTo
= $request->getVal( 'returnto', '' );
172 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
174 // Show an error or warning passed on from a previous page
175 $entryError = $this->msg( $request->getVal( 'error', '' ) );
176 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
177 // bc: provide login link as a parameter for messages where the translation
179 $loginreqlink = Linker
::linkKnown(
180 $this->getPageTitle(),
181 $this->msg( 'loginreqlink' )->escaped(),
184 'returnto' => $this->mReturnTo
,
185 'returntoquery' => $this->mReturnToQuery
,
186 'uselang' => $this->mLanguage
,
187 'fromhttp' => $this->mFromHTTP ?
'1' : '0',
191 // Only show valid error or warning messages.
192 if ( $entryError->exists()
193 && in_array( $entryError->getKey(), self
::getValidErrorMessages() )
195 $this->mEntryErrorType
= 'error';
196 $this->mEntryError
= $entryError->rawParams( $loginreqlink )->escaped();
198 } elseif ( $entryWarning->exists()
199 && in_array( $entryWarning->getKey(), self
::getValidErrorMessages() )
201 $this->mEntryErrorType
= 'warning';
202 $this->mEntryError
= $entryWarning->rawParams( $loginreqlink )->escaped();
205 if ( $wgEnableEmail ) {
206 $this->mEmail
= $request->getText( 'wpEmail' );
210 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
211 $this->mRealName
= $request->getText( 'wpRealName' );
213 $this->mRealName
= '';
216 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
217 $this->mDomain
= $wgAuth->getDomain();
219 $wgAuth->setDomain( $this->mDomain
);
221 # 1. When switching accounts, it sucks to get automatically logged out
222 # 2. Do not return to PasswordReset after a successful password change
223 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
224 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
225 if ( is_object( $returnToTitle )
226 && ( $returnToTitle->isSpecial( 'Userlogout' )
227 ||
$returnToTitle->isSpecial( 'PasswordReset' ) )
229 $this->mReturnTo
= '';
230 $this->mReturnToQuery
= '';
234 function getDescription() {
235 if ( $this->mType
=== 'signup' ) {
236 return $this->msg( 'createaccount' )->text();
238 return $this->msg( 'login' )->text();
243 * @param string|null $subPage
245 public function execute( $subPage ) {
246 if ( session_id() == '' ) {
252 // Check for [[Special:Userlogin/signup]]. This affects form display and
254 if ( $subPage == 'signup' ) {
255 $this->mType
= 'signup';
259 // In the case where the user is already logged in, and was redirected to the login form from a
260 // page that requires login, do not show the login page. The use case scenario for this is when
261 // a user opens a large number of tabs, is redirected to the login page on all of them, and then
262 // logs in on one, expecting all the others to work properly.
264 // However, do show the form if it was visited intentionally (no 'returnto' is present). People
265 // who often switch between several accounts have grown accustomed to this behavior.
267 $this->mType
!== 'signup' &&
269 $this->getUser()->isLoggedIn() &&
270 ( $this->mReturnTo
!== '' ||
$this->mReturnToQuery
!== '' )
272 $this->successfulLogin();
275 // If logging in and not on HTTPS, either redirect to it or offer a link.
276 global $wgSecureLogin;
277 if ( $this->mRequest
->getProtocol() !== 'https' ) {
278 $title = $this->getFullTitle();
280 'returnto' => $this->mReturnTo
!== '' ?
$this->mReturnTo
: null,
281 'returntoquery' => $this->mReturnToQuery
!== '' ?
282 $this->mReturnToQuery
: null,
284 ( $this->mEntryErrorType
=== 'error' ?
'error' : 'warning' ) => $this->mEntryError
,
285 ) +
$this->mRequest
->getQueryValues();
286 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
288 && wfCanIPUseHTTPS( $this->getRequest()->getIP() )
289 && !$this->mFromHTTP
) // Avoid infinite redirect
291 $url = wfAppendQuery( $url, 'fromhttp=1' );
292 $this->getOutput()->redirect( $url );
293 // Since we only do this redir to change proto, always vary
294 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
298 // A wiki without HTTPS login support should set $wgServer to
299 // http://somehost, in which case the secure URL generated
300 // above won't actually start with https://
301 if ( substr( $url, 0, 8 ) === 'https://' ) {
302 $this->mSecureLoginUrl
= $url;
307 if ( !is_null( $this->mCookieCheck
) ) {
308 $this->onCookieRedirectCheck( $this->mCookieCheck
);
311 } elseif ( $this->mPosted
) {
312 if ( $this->mCreateaccount
) {
313 $this->addNewAccount();
316 } elseif ( $this->mCreateaccountMail
) {
317 $this->addNewAccountMailPassword();
320 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
321 $this->processLogin();
326 $this->mainLoginForm( $this->mEntryError
, $this->mEntryErrorType
);
332 function addNewAccountMailPassword() {
333 if ( $this->mEmail
== '' ) {
334 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
339 $status = $this->addNewAccountInternal();
340 if ( !$status->isGood() ) {
341 $error = $status->getMessage();
342 $this->mainLoginForm( $error->toString() );
347 $u = $status->getValue();
349 // Wipe the initial password and mail a temporary one
350 $u->setPassword( null );
352 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
354 wfRunHooks( 'AddNewAccount', array( $u, true ) );
355 $u->addNewUserLogEntry( 'byemail', $this->mReason
);
357 $out = $this->getOutput();
358 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
360 if ( !$result->isGood() ) {
361 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
363 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
364 $this->executeReturnTo( 'success' );
372 function addNewAccount() {
373 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
375 # Create the account and abort if there's a problem doing so
376 $status = $this->addNewAccountInternal();
377 if ( !$status->isGood() ) {
378 $error = $status->getMessage();
379 $this->mainLoginForm( $error->toString() );
384 $u = $status->getValue();
386 # Only save preferences if the user is not creating an account for someone else.
387 if ( $this->getUser()->isAnon() ) {
388 # If we showed up language selection links, and one was in use, be
389 # smart (and sensible) and save that language as the user's preference
390 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
391 $u->setOption( 'language', $this->mLanguage
);
394 # Otherwise the user's language preference defaults to $wgContLang,
395 # but it may be better to set it to their preferred $wgContLang variant,
396 # based on browser preferences or URL parameters.
397 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
399 if ( $wgContLang->hasVariants() ) {
400 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
404 $out = $this->getOutput();
406 # Send out an email authentication message if needed
407 if ( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
408 $status = $u->sendConfirmationMail();
409 if ( $status->isGood() ) {
410 $out->addWikiMsg( 'confirmemail_oncreate' );
412 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
416 # Save settings (including confirmation token)
419 # If not logged in, assume the new account as the current one and set
420 # session cookies then show a "welcome" message or a "need cookies"
422 if ( $this->getUser()->isAnon() ) {
425 // This should set it for OutputPage and the Skin
426 // which is needed or the personal links will be
428 $this->getContext()->setUser( $u );
429 wfRunHooks( 'AddNewAccount', array( $u, false ) );
430 $u->addNewUserLogEntry( 'create' );
431 if ( $this->hasSessionCookie() ) {
432 $this->successfulCreation();
434 $this->cookieRedirectCheck( 'new' );
437 # Confirm that the account was created
438 $out->setPageTitle( $this->msg( 'accountcreated' ) );
439 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
440 $out->addReturnTo( $this->getPageTitle() );
441 wfRunHooks( 'AddNewAccount', array( $u, false ) );
442 $u->addNewUserLogEntry( 'create2', $this->mReason
);
449 * Make a new user account using the loaded data.
451 * @throws PermissionsError|ReadOnlyError
454 public function addNewAccountInternal() {
455 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
456 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
458 // If the user passes an invalid domain, something is fishy
459 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
460 return Status
::newFatal( 'wrongpassword' );
463 // If we are not allowing users to login locally, we should be checking
464 // to see if the user is actually able to authenticate to the authenti-
465 // cation server before they create an account (otherwise, they can
466 // create a local account and login as any domain user). We only need
467 // to check this for domains that aren't local.
468 if ( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
470 !$wgAuth->canCreateAccounts() &&
472 !$wgAuth->userExists( $this->mUsername
) ||
473 !$wgAuth->authenticate( $this->mUsername
, $this->mPassword
)
476 return Status
::newFatal( 'wrongpassword' );
480 if ( wfReadOnly() ) {
481 throw new ReadOnlyError
;
484 # Request forgery checks.
485 if ( !self
::getCreateaccountToken() ) {
486 self
::setCreateaccountToken();
488 return Status
::newFatal( 'nocookiesfornew' );
491 # The user didn't pass a createaccount token
492 if ( !$this->mToken
) {
493 return Status
::newFatal( 'sessionfailure' );
496 # Validate the createaccount token
497 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
498 return Status
::newFatal( 'sessionfailure' );
502 $currentUser = $this->getUser();
503 $creationBlock = $currentUser->isBlockedFromCreateAccount();
504 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
505 throw new PermissionsError( 'createaccount' );
506 } elseif ( $creationBlock instanceof Block
) {
507 // Throws an ErrorPageError.
508 $this->userBlockedMessage( $creationBlock );
510 // This should never be reached.
514 # Include checks that will include GlobalBlocking (Bug 38333)
515 $permErrors = $this->getPageTitle()->getUserPermissionsErrors(
521 if ( count( $permErrors ) ) {
522 throw new PermissionsError( 'createaccount', $permErrors );
525 $ip = $this->getRequest()->getIP();
526 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
527 return Status
::newFatal( 'sorbs_create_account_reason' );
530 // Normalize the name so that silly things don't cause "invalid username"
531 // errors. User::newFromName does some rather strict checking, rejecting
532 // e.g. leading/trailing/multiple spaces. But first we need to reject
533 // usernames that would be treated as titles with a fragment part.
534 if ( strpos( $this->mUsername
, '#' ) !== false ) {
535 return Status
::newFatal( 'noname' );
537 $title = Title
::makeTitleSafe( NS_USER
, $this->mUsername
);
538 if ( !is_object( $title ) ) {
539 return Status
::newFatal( 'noname' );
542 # Now create a dummy user ($u) and check if it is valid
543 $u = User
::newFromName( $title->getText(), 'creatable' );
544 if ( !is_object( $u ) ) {
545 return Status
::newFatal( 'noname' );
546 } elseif ( 0 != $u->idForName() ) {
547 return Status
::newFatal( 'userexists' );
550 if ( $this->mCreateaccountMail
) {
551 # do not force a password for account creation by email
552 # set invalid password, it will be replaced later by a random generated password
553 $this->mPassword
= null;
555 if ( $this->mPassword
!== $this->mRetype
) {
556 return Status
::newFatal( 'badretype' );
559 # check for minimal password length
560 $valid = $u->getPasswordValidity( $this->mPassword
);
561 if ( $valid !== true ) {
562 if ( !is_array( $valid ) ) {
563 $valid = array( $valid, $wgMinimalPasswordLength );
566 return call_user_func_array( 'Status::newFatal', $valid );
570 # if you need a confirmed email address to edit, then obviously you
571 # need an email address.
572 if ( $wgEmailConfirmToEdit && strval( $this->mEmail
) === '' ) {
573 return Status
::newFatal( 'noemailtitle' );
576 if ( strval( $this->mEmail
) !== '' && !Sanitizer
::validateEmail( $this->mEmail
) ) {
577 return Status
::newFatal( 'invalidemailaddress' );
580 # Set some additional data so the AbortNewAccount hook can be used for
581 # more than just username validation
582 $u->setEmail( $this->mEmail
);
583 $u->setRealName( $this->mRealName
);
587 if ( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError, &$abortStatus ) ) ) {
588 // Hook point to add extra creation throttles and blocks
589 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
590 if ( $abortStatus === null ) {
591 // Report back the old string as a raw message status.
592 // This will report the error back as 'createaccount-hook-aborted'
593 // with the given string as the message.
594 // To return a different error code, return a Status object.
595 $abortError = new Message( 'createaccount-hook-aborted', array( $abortError ) );
598 return Status
::newFatal( $abortError );
600 // For MediaWiki 1.23+ and updated hooks, return the Status object
601 // returned from the hook.
606 // Hook point to check for exempt from account creation throttle
607 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
608 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook " .
609 "allowed account creation w/o throttle\n" );
611 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
612 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
613 $value = $wgMemc->get( $key );
615 $wgMemc->set( $key, 0, 86400 );
617 if ( $value >= $wgAccountCreationThrottle ) {
618 return Status
::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
620 $wgMemc->incr( $key );
624 if ( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
625 return Status
::newFatal( 'externaldberror' );
628 self
::clearCreateaccountToken();
630 return $this->initUser( $u, false );
634 * Actually add a user to the database.
635 * Give it a User object that has been initialised with a name.
638 * @param bool $autocreate True if this is an autocreation via auth plugin
639 * @return Status Status object, with the User object in the value member on success
642 function initUser( $u, $autocreate ) {
645 $status = $u->addToDatabase();
646 if ( !$status->isOK() ) {
650 if ( $wgAuth->allowPasswordChange() ) {
651 $u->setPassword( $this->mPassword
);
654 $u->setEmail( $this->mEmail
);
655 $u->setRealName( $this->mRealName
);
658 $wgAuth->initUser( $u, $autocreate );
663 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
665 // Watch user's userpage and talk page
666 $u->addWatch( $u->getUserPage(), WatchedItem
::IGNORE_USER_RIGHTS
);
668 return Status
::newGood( $u );
672 * Internally authenticate the login request.
674 * This may create a local account as a side effect if the
675 * authentication plugin allows transparent local account
679 public function authenticateUserData() {
680 global $wgUser, $wgAuth;
684 if ( $this->mUsername
== '' ) {
685 return self
::NO_NAME
;
688 // We require a login token to prevent login CSRF
689 // Handle part of this before incrementing the throttle so
690 // token-less login attempts don't count towards the throttle
691 // but wrong-token attempts do.
693 // If the user doesn't have a login token yet, set one.
694 if ( !self
::getLoginToken() ) {
695 self
::setLoginToken();
697 return self
::NEED_TOKEN
;
699 // If the user didn't pass a login token, tell them we need one
700 if ( !$this->mToken
) {
701 return self
::NEED_TOKEN
;
704 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
705 if ( $throttleCount === true ) {
706 return self
::THROTTLED
;
709 // Validate the login token
710 if ( $this->mToken
!== self
::getLoginToken() ) {
711 return self
::WRONG_TOKEN
;
714 // Load the current user now, and check to see if we're logging in as
715 // the same name. This is necessary because loading the current user
716 // (say by calling getName()) calls the UserLoadFromSession hook, which
717 // potentially creates the user in the database. Until we load $wgUser,
718 // checking for user existence using User::newFromName($name)->getId() below
719 // will effectively be using stale data.
720 if ( $this->getUser()->getName() === $this->mUsername
) {
721 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
723 return self
::SUCCESS
;
726 $u = User
::newFromName( $this->mUsername
);
728 // Give extensions a way to indicate the username has been updated,
729 // rather than telling the user the account doesn't exist.
730 if ( !wfRunHooks( 'LoginUserMigrated', array( $u, &$msg ) ) ) {
731 $this->mAbortLoginErrorMsg
= $msg;
732 return self
::USER_MIGRATED
;
735 if ( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
736 return self
::ILLEGAL
;
739 $isAutoCreated = false;
740 if ( $u->getID() == 0 ) {
741 $status = $this->attemptAutoCreate( $u );
742 if ( $status !== self
::SUCCESS
) {
745 $isAutoCreated = true;
751 // Give general extensions, such as a captcha, a chance to abort logins
752 $abort = self
::ABORTED
;
754 if ( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$msg ) ) ) {
755 $this->mAbortLoginErrorMsg
= $msg;
760 global $wgBlockDisablesLogin;
761 if ( !$u->checkPassword( $this->mPassword
) ) {
762 if ( $u->checkTemporaryPassword( $this->mPassword
) ) {
763 // The e-mailed temporary password should not be used for actu-
764 // al logins; that's a very sloppy habit, and insecure if an
765 // attacker has a few seconds to click "search" on someone's o-
768 // Allow it to be used only to reset the password a single time
769 // to a new value, which won't be in the user's e-mail ar-
772 // For backwards compatibility, we'll still recognize it at the
773 // login form to minimize surprises for people who have been
774 // logging in with a temporary password for some time.
776 // As a side-effect, we can authenticate the user's e-mail ad-
777 // dress if it's not already done, since the temporary password
778 // was sent via e-mail.
779 if ( !$u->isEmailConfirmed() ) {
784 // At this point we just return an appropriate code/ indicating
785 // that the UI should show a password reset form; bot inter-
786 // faces etc will probably just fail cleanly here.
787 $this->mAbortLoginErrorMsg
= 'resetpass-temp-emailed';
788 $this->mTempPasswordUsed
= true;
789 $retval = self
::RESET_PASS
;
791 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
793 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
794 // If we've enabled it, make it so that a blocked user cannot login
795 $retval = self
::USER_BLOCKED
;
796 } elseif ( $u->getPasswordExpired() == 'hard' ) {
797 // Force reset now, without logging in
798 $retval = self
::RESET_PASS
;
799 $this->mAbortLoginErrorMsg
= 'resetpass-expired';
801 $wgAuth->updateUser( $u );
803 // This should set it for OutputPage and the Skin
804 // which is needed or the personal links will be
806 $this->getContext()->setUser( $u );
808 // Please reset throttle for successful logins, thanks!
809 if ( $throttleCount ) {
810 self
::clearLoginThrottle( $this->mUsername
);
813 if ( $isAutoCreated ) {
814 // Must be run after $wgUser is set, for correct new user log
815 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
818 $retval = self
::SUCCESS
;
820 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
826 * Increment the login attempt throttle hit count for the (username,current IP)
827 * tuple unless the throttle was already reached.
828 * @param string $username The user name
829 * @return bool|int The integer hit count or True if it is already at the limit
831 public static function incLoginThrottle( $username ) {
832 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
833 $username = trim( $username ); // sanity
836 if ( is_array( $wgPasswordAttemptThrottle ) ) {
837 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
838 $count = $wgPasswordAttemptThrottle['count'];
839 $period = $wgPasswordAttemptThrottle['seconds'];
841 $throttleCount = $wgMemc->get( $throttleKey );
842 if ( !$throttleCount ) {
843 $wgMemc->add( $throttleKey, 1, $period ); // start counter
844 } elseif ( $throttleCount < $count ) {
845 $wgMemc->incr( $throttleKey );
846 } elseif ( $throttleCount >= $count ) {
851 return $throttleCount;
855 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
856 * @param string $username The user name
859 public static function clearLoginThrottle( $username ) {
860 global $wgMemc, $wgRequest;
861 $username = trim( $username ); // sanity
863 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
864 $wgMemc->delete( $throttleKey );
868 * Attempt to automatically create a user on login. Only succeeds if there
869 * is an external authentication method which allows it.
873 * @return int Status code
875 function attemptAutoCreate( $user ) {
878 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
879 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
881 return self
::CREATE_BLOCKED
;
884 if ( !$wgAuth->autoCreate() ) {
885 return self
::NOT_EXISTS
;
888 if ( !$wgAuth->userExists( $user->getName() ) ) {
889 wfDebug( __METHOD__
. ": user does not exist\n" );
891 return self
::NOT_EXISTS
;
894 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
895 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
897 return self
::WRONG_PLUGIN_PASS
;
901 if ( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
902 // Hook point to add extra creation throttles and blocks
903 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
904 $this->mAbortLoginErrorMsg
= $abortError;
906 return self
::ABORTED
;
909 wfDebug( __METHOD__
. ": creating account\n" );
910 $status = $this->initUser( $user, true );
912 if ( !$status->isOK() ) {
913 $errors = $status->getErrorsByType( 'error' );
914 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
916 return self
::ABORTED
;
919 return self
::SUCCESS
;
922 function processLogin() {
923 global $wgMemc, $wgLang, $wgSecureLogin, $wgPasswordAttemptThrottle,
924 $wgInvalidPasswordReset;
926 switch ( $this->authenticateUserData() ) {
928 # We've verified now, update the real record
929 $user = $this->getUser();
930 $user->invalidateCache();
932 if ( $user->requiresHTTPS() ) {
933 $this->mStickHTTPS
= true;
936 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
937 $user->setCookies( $this->mRequest
, false, $this->mRemember
);
939 $user->setCookies( $this->mRequest
, null, $this->mRemember
);
941 self
::clearLoginToken();
943 // Reset the throttle
944 $request = $this->getRequest();
945 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
946 $wgMemc->delete( $key );
948 if ( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
949 /* Replace the language object to provide user interface in
950 * correct language immediately on this first page load.
952 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
953 $userLang = Language
::factory( $code );
955 $this->getContext()->setLanguage( $userLang );
956 // Reset SessionID on Successful login (bug 40995)
957 $this->renewSessionId();
958 if ( $this->getUser()->getPasswordExpired() == 'soft' ) {
959 $this->resetLoginForm( $this->msg( 'resetpass-expired-soft' ) );
960 } elseif ( $wgInvalidPasswordReset
961 && !$user->isValidPassword( $this->mPassword
)
963 $status = $user->checkPasswordValidity( $this->mPassword
);
964 $this->resetLoginForm(
965 $status->getMessage( 'resetpass-validity-soft' )
968 $this->successfulLogin();
971 $this->cookieRedirectCheck( 'login' );
975 case self
::NEED_TOKEN
:
976 $error = $this->mAbortLoginErrorMsg ?
: 'nocookiesforlogin';
977 $this->mainLoginForm( $this->msg( $error )->parse() );
979 case self
::WRONG_TOKEN
:
980 $error = $this->mAbortLoginErrorMsg ?
: 'sessionfailure';
981 $this->mainLoginForm( $this->msg( $error )->text() );
985 $error = $this->mAbortLoginErrorMsg ?
: 'noname';
986 $this->mainLoginForm( $this->msg( $error )->text() );
988 case self
::WRONG_PLUGIN_PASS
:
989 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
990 $this->mainLoginForm( $this->msg( $error )->text() );
992 case self
::NOT_EXISTS
:
993 if ( $this->getUser()->isAllowed( 'createaccount' ) ) {
994 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchuser';
995 $this->mainLoginForm( $this->msg( $error,
996 wfEscapeWikiText( $this->mUsername
) )->parse() );
998 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchusershort';
999 $this->mainLoginForm( $this->msg( $error,
1000 wfEscapeWikiText( $this->mUsername
) )->text() );
1003 case self
::WRONG_PASS
:
1004 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
1005 $this->mainLoginForm( $this->msg( $error )->text() );
1007 case self
::EMPTY_PASS
:
1008 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpasswordempty';
1009 $this->mainLoginForm( $this->msg( $error )->text() );
1011 case self
::RESET_PASS
:
1012 $error = $this->mAbortLoginErrorMsg ?
: 'resetpass_announce';
1013 $this->resetLoginForm( $this->msg( $error ) );
1015 case self
::CREATE_BLOCKED
:
1016 $this->userBlockedMessage( $this->getUser()->isBlockedFromCreateAccount() );
1018 case self
::THROTTLED
:
1019 $error = $this->mAbortLoginErrorMsg ?
: 'login-throttled';
1020 $this->mainLoginForm( $this->msg( $error )
1021 ->params( $this->getLanguage()->formatDuration( $wgPasswordAttemptThrottle['seconds'] ) )
1025 case self
::USER_BLOCKED
:
1026 $error = $this->mAbortLoginErrorMsg ?
: 'login-userblocked';
1027 $this->mainLoginForm( $this->msg( $error, $this->mUsername
)->escaped() );
1030 $error = $this->mAbortLoginErrorMsg ?
: 'login-abort-generic';
1031 $this->mainLoginForm( $this->msg( $error,
1032 wfEscapeWikiText( $this->mUsername
) )->text() );
1034 case self
::USER_MIGRATED
:
1035 $error = $this->mAbortLoginErrorMsg ?
: 'login-migrated-generic';
1037 if ( is_array( $error ) ) {
1038 $error = array_shift( $this->mAbortLoginErrorMsg
);
1039 $params = $this->mAbortLoginErrorMsg
;
1041 $this->mainLoginForm( $this->msg( $error, $params )->text() );
1044 throw new MWException( 'Unhandled case value' );
1049 * Show the Special:ChangePassword form, with custom message
1050 * @param Message $msg
1052 protected function resetLoginForm( Message
$msg ) {
1053 // Allow hooks to explain this password reset in more detail
1054 wfRunHooks( 'LoginPasswordResetMessage', array( &$msg, $this->mUsername
) );
1055 $reset = new SpecialChangePassword();
1056 $derivative = new DerivativeContext( $this->getContext() );
1057 $derivative->setTitle( $reset->getPageTitle() );
1058 $reset->setContext( $derivative );
1059 if ( !$this->mTempPasswordUsed
) {
1060 $reset->setOldPasswordMessage( 'oldpassword' );
1062 $reset->setChangeMessage( $msg );
1063 $reset->execute( null );
1068 * @param bool $throttle
1069 * @param string $emailTitle Message name of email title
1070 * @param string $emailText Message name of email text
1073 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle',
1074 $emailText = 'passwordremindertext'
1076 global $wgNewPasswordExpiry;
1078 if ( $u->getEmail() == '' ) {
1079 return Status
::newFatal( 'noemail', $u->getName() );
1081 $ip = $this->getRequest()->getIP();
1083 return Status
::newFatal( 'badipaddress' );
1086 $currentUser = $this->getUser();
1087 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
1089 $np = $u->randomPassword();
1090 $u->setNewpassword( $np, $throttle );
1092 $userLanguage = $u->getOption( 'language' );
1094 $mainPage = Title
::newMainPage();
1095 $mainPageUrl = $mainPage->getCanonicalURL();
1097 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $mainPageUrl . '>',
1098 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
1099 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
1105 * Run any hooks registered for logins, then HTTP redirect to
1106 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
1107 * nice message here, but that's really not as useful as just being sent to
1108 * wherever you logged in from. It should be clear that the action was
1109 * successful, given the lack of error messages plus the appearance of your
1110 * name in the upper right.
1114 function successfulLogin() {
1115 # Run any hooks; display injected HTML if any, else redirect
1116 $currentUser = $this->getUser();
1117 $injected_html = '';
1118 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1120 if ( $injected_html !== '' ) {
1121 $this->displaySuccessfulAction( 'success', $this->msg( 'loginsuccesstitle' ),
1122 'loginsuccess', $injected_html );
1124 $this->executeReturnTo( 'successredirect' );
1129 * Run any hooks registered for logins, then display a message welcoming
1134 function successfulCreation() {
1135 # Run any hooks; display injected HTML
1136 $currentUser = $this->getUser();
1137 $injected_html = '';
1138 $welcome_creation_msg = 'welcomecreation-msg';
1140 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1143 * Let any extensions change what message is shown.
1144 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
1147 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
1149 $this->displaySuccessfulAction(
1151 $this->msg( 'welcomeuser', $this->getUser()->getName() ),
1152 $welcome_creation_msg, $injected_html
1157 * Display a "successful action" page.
1159 * @param string $type Condition of return to; see `executeReturnTo`
1160 * @param string|Message $title Page's title
1161 * @param string $msgname
1162 * @param string $injected_html
1164 private function displaySuccessfulAction( $type, $title, $msgname, $injected_html ) {
1165 $out = $this->getOutput();
1166 $out->setPageTitle( $title );
1168 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
1171 $out->addHTML( $injected_html );
1173 $this->executeReturnTo( $type );
1177 * Output a message that informs the user that they cannot create an account because
1178 * there is a block on them or their IP which prevents account creation. Note that
1179 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
1180 * setting on blocks (bug 13611).
1181 * @param Block $block The block causing this error
1182 * @throws ErrorPageError
1184 function userBlockedMessage( Block
$block ) {
1185 # Let's be nice about this, it's likely that this feature will be used
1186 # for blocking large numbers of innocent people, e.g. range blocks on
1187 # schools. Don't blame it on the user. There's a small chance that it
1188 # really is the user's fault, i.e. the username is blocked and they
1189 # haven't bothered to log out before trying to create an account to
1190 # evade it, but we'll leave that to their guilty conscience to figure
1192 $errorParams = array(
1193 $block->getTarget(),
1194 $block->mReason ?
$block->mReason
: $this->msg( 'blockednoreason' )->text(),
1198 if ( $block->getType() === Block
::TYPE_RANGE
) {
1199 $errorMessage = 'cantcreateaccount-range-text';
1200 $errorParams[] = $this->getRequest()->getIP();
1202 $errorMessage = 'cantcreateaccount-text';
1205 throw new ErrorPageError(
1206 'cantcreateaccounttitle',
1213 * Add a "return to" link or redirect to it.
1214 * Extensions can use this to reuse the "return to" logic after
1215 * inject steps (such as redirection) into the login process.
1217 * @param string $type One of the following:
1218 * - error: display a return to link ignoring $wgRedirectOnLogin
1219 * - signup: display a return to link using $wgRedirectOnLogin if needed
1220 * - success: display a return to link using $wgRedirectOnLogin if needed
1221 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1222 * @param string $returnTo
1223 * @param array|string $returnToQuery
1224 * @param bool $stickHTTPs Keep redirect link on HTTPs
1227 public function showReturnToPage(
1228 $type, $returnTo = '', $returnToQuery = '', $stickHTTPs = false
1230 $this->mReturnTo
= $returnTo;
1231 $this->mReturnToQuery
= $returnToQuery;
1232 $this->mStickHTTPS
= $stickHTTPs;
1233 $this->executeReturnTo( $type );
1237 * Add a "return to" link or redirect to it.
1239 * @param string $type One of the following:
1240 * - error: display a return to link ignoring $wgRedirectOnLogin
1241 * - signup: display a return to link using $wgRedirectOnLogin if needed
1242 * - success: display a return to link using $wgRedirectOnLogin if needed
1243 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1245 private function executeReturnTo( $type ) {
1246 global $wgRedirectOnLogin, $wgSecureLogin;
1248 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
1249 $returnTo = $wgRedirectOnLogin;
1250 $returnToQuery = array();
1252 $returnTo = $this->mReturnTo
;
1253 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
1256 // Allow modification of redirect behavior
1257 wfRunHooks( 'PostLoginRedirect', array( &$returnTo, &$returnToQuery, &$type ) );
1259 $returnToTitle = Title
::newFromText( $returnTo );
1260 if ( !$returnToTitle ) {
1261 $returnToTitle = Title
::newMainPage();
1264 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1265 $options = array( 'http' );
1266 $proto = PROTO_HTTP
;
1267 } elseif ( $wgSecureLogin ) {
1268 $options = array( 'https' );
1269 $proto = PROTO_HTTPS
;
1272 $proto = PROTO_RELATIVE
;
1275 if ( $type == 'successredirect' ) {
1276 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1277 $this->getOutput()->redirect( $redirectUrl );
1279 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1284 * @param string $msg
1285 * @param string $msgtype
1288 function mainLoginForm( $msg, $msgtype = 'error' ) {
1289 global $wgEnableEmail, $wgEnableUserEmail;
1290 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1291 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
1292 global $wgSecureLogin, $wgPasswordResetRoutes;
1294 $titleObj = $this->getPageTitle();
1295 $user = $this->getUser();
1296 $out = $this->getOutput();
1298 if ( $this->mType
== 'signup' ) {
1299 // Block signup here if in readonly. Keeps user from
1300 // going through the process (filling out data, etc)
1301 // and being informed later.
1302 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1303 if ( count( $permErrors ) ) {
1304 throw new PermissionsError( 'createaccount', $permErrors );
1305 } elseif ( $user->isBlockedFromCreateAccount() ) {
1306 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1309 } elseif ( wfReadOnly() ) {
1310 throw new ReadOnlyError
;
1314 // Pre-fill username (if not creating an account, bug 44775).
1315 if ( $this->mUsername
== '' && $this->mType
!= 'signup' ) {
1316 if ( $user->isLoggedIn() ) {
1317 $this->mUsername
= $user->getName();
1319 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1323 // Generic styles and scripts for both login and signup form
1324 $out->addModuleStyles( array(
1326 'mediawiki.ui.button',
1327 'mediawiki.ui.checkbox',
1328 'mediawiki.ui.input',
1329 'mediawiki.special.userlogin.common.styles'
1331 $out->addModules( array(
1332 'mediawiki.special.userlogin.common.js'
1335 if ( $this->mType
== 'signup' ) {
1336 // XXX hack pending RL or JS parse() support for complex content messages
1337 // https://bugzilla.wikimedia.org/show_bug.cgi?id=25349
1338 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
1339 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
1341 // Additional styles and scripts for signup form
1342 $out->addModules( array(
1343 'mediawiki.special.userlogin.signup.js'
1345 $out->addModuleStyles( array(
1346 'mediawiki.special.userlogin.signup.styles'
1349 $template = new UsercreateTemplate();
1351 // Must match number of benefits defined in messages
1352 $template->set( 'benefitCount', 3 );
1354 $q = 'action=submitlogin&type=signup';
1355 $linkq = 'type=login';
1357 // Additional styles for login form
1358 $out->addModuleStyles( array(
1359 'mediawiki.special.userlogin.login.styles'
1362 $template = new UserloginTemplate();
1364 $q = 'action=submitlogin&type=login';
1365 $linkq = 'type=signup';
1368 if ( $this->mReturnTo
!== '' ) {
1369 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1370 if ( $this->mReturnToQuery
!== '' ) {
1371 $returnto .= '&returntoquery=' .
1372 wfUrlencode( $this->mReturnToQuery
);
1375 $linkq .= $returnto;
1378 # Don't show a "create account" link if the user can't.
1379 if ( $this->showCreateOrLoginLink( $user ) ) {
1380 # Pass any language selection on to the mode switch link
1381 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
1382 $linkq .= '&uselang=' . $this->mLanguage
;
1384 // Supply URL, login template creates the button.
1385 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1387 $template->set( 'link', '' );
1390 $resetLink = $this->mType
== 'signup'
1392 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1394 $template->set( 'header', '' );
1395 $template->set( 'skin', $this->getSkin() );
1396 $template->set( 'name', $this->mUsername
);
1397 $template->set( 'password', $this->mPassword
);
1398 $template->set( 'retype', $this->mRetype
);
1399 $template->set( 'createemailset', $this->mCreateaccountMail
);
1400 $template->set( 'email', $this->mEmail
);
1401 $template->set( 'realname', $this->mRealName
);
1402 $template->set( 'domain', $this->mDomain
);
1403 $template->set( 'reason', $this->mReason
);
1405 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1406 $template->set( 'message', $msg );
1407 $template->set( 'messagetype', $msgtype );
1408 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1409 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1410 $template->set( 'useemail', $wgEnableEmail );
1411 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1412 $template->set( 'emailothers', $wgEnableUserEmail );
1413 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1414 $template->set( 'resetlink', $resetLink );
1415 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1416 $template->set( 'usereason', $user->isLoggedIn() );
1417 $template->set( 'remember', $this->mRemember
);
1418 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1419 $template->set( 'stickhttps', (int)$this->mStickHTTPS
);
1420 $template->set( 'loggedin', $user->isLoggedIn() );
1421 $template->set( 'loggedinuser', $user->getName() );
1423 if ( $this->mType
== 'signup' ) {
1424 if ( !self
::getCreateaccountToken() ) {
1425 self
::setCreateaccountToken();
1427 $template->set( 'token', self
::getCreateaccountToken() );
1429 if ( !self
::getLoginToken() ) {
1430 self
::setLoginToken();
1432 $template->set( 'token', self
::getLoginToken() );
1435 # Prepare language selection links as needed
1436 if ( $wgLoginLanguageSelector ) {
1437 $template->set( 'languages', $this->makeLanguageSelector() );
1438 if ( $this->mLanguage
) {
1439 $template->set( 'uselang', $this->mLanguage
);
1443 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl
);
1444 // Use signupend-https for HTTPS requests if it's not blank, signupend otherwise
1445 $usingHTTPS = $this->mRequest
->getProtocol() == 'https';
1446 $signupendHTTPS = $this->msg( 'signupend-https' );
1447 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1448 $template->set( 'signupend', $signupendHTTPS->parse() );
1450 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1453 // Give authentication and captcha plugins a chance to modify the form
1454 $wgAuth->modifyUITemplate( $template, $this->mType
);
1455 if ( $this->mType
== 'signup' ) {
1456 wfRunHooks( 'UserCreateForm', array( &$template ) );
1458 wfRunHooks( 'UserLoginForm', array( &$template ) );
1461 $out->disallowUserJs(); // just in case...
1462 $out->addTemplate( $template );
1466 * Whether the login/create account form should display a link to the
1467 * other form (in addition to whatever the skin provides).
1472 private function showCreateOrLoginLink( &$user ) {
1473 if ( $this->mType
== 'signup' ) {
1475 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1483 * Check if a session cookie is present.
1485 * This will not pick up a cookie set during _this_ request, but is meant
1486 * to ensure that the client is returning the cookie which was set on a
1487 * previous pass through the system.
1492 function hasSessionCookie() {
1493 global $wgDisableCookieCheck;
1495 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1499 * Get the login token from the current session
1502 public static function getLoginToken() {
1505 return $wgRequest->getSessionData( 'wsLoginToken' );
1509 * Randomly generate a new login token and attach it to the current session
1511 public static function setLoginToken() {
1513 // Generate a token directly instead of using $user->getEditToken()
1514 // because the latter reuses $_SESSION['wsEditToken']
1515 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1519 * Remove any login token attached to the current session
1521 public static function clearLoginToken() {
1523 $wgRequest->setSessionData( 'wsLoginToken', null );
1527 * Get the createaccount token from the current session
1530 public static function getCreateaccountToken() {
1533 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1537 * Randomly generate a new createaccount token and attach it to the current session
1539 public static function setCreateaccountToken() {
1541 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1545 * Remove any createaccount token attached to the current session
1547 public static function clearCreateaccountToken() {
1549 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1553 * Renew the user's session id, using strong entropy
1555 private function renewSessionId() {
1556 global $wgSecureLogin, $wgCookieSecure;
1557 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1558 $wgCookieSecure = false;
1565 * @param string $type
1568 function cookieRedirectCheck( $type ) {
1569 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1570 $query = array( 'wpCookieCheck' => $type );
1571 if ( $this->mReturnTo
!== '' ) {
1572 $query['returnto'] = $this->mReturnTo
;
1573 $query['returntoquery'] = $this->mReturnToQuery
;
1575 $check = $titleObj->getFullURL( $query );
1577 $this->getOutput()->redirect( $check );
1581 * @param string $type
1584 function onCookieRedirectCheck( $type ) {
1585 if ( !$this->hasSessionCookie() ) {
1586 if ( $type == 'new' ) {
1587 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1588 } elseif ( $type == 'login' ) {
1589 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1592 $this->mainLoginForm( $this->msg( 'error' )->text() );
1595 $this->successfulLogin();
1600 * Produce a bar of links which allow the user to select another language
1601 * during login/registration but retain "returnto"
1605 function makeLanguageSelector() {
1606 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1607 if ( !$msg->isBlank() ) {
1608 $langs = explode( "\n", $msg->text() );
1610 foreach ( $langs as $lang ) {
1611 $lang = trim( $lang, '* ' );
1612 $parts = explode( '|', $lang );
1613 if ( count( $parts ) >= 2 ) {
1614 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1618 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1619 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1626 * Create a language selector link for a particular language
1627 * Links back to this page preserving type and returnto
1629 * @param string $text Link text
1630 * @param string $lang Language code
1633 function makeLanguageSelectorLink( $text, $lang ) {
1634 if ( $this->getLanguage()->getCode() == $lang ) {
1635 // no link for currently used language
1636 return htmlspecialchars( $text );
1638 $query = array( 'uselang' => $lang );
1639 if ( $this->mType
== 'signup' ) {
1640 $query['type'] = 'signup';
1642 if ( $this->mReturnTo
!== '' ) {
1643 $query['returnto'] = $this->mReturnTo
;
1644 $query['returntoquery'] = $this->mReturnToQuery
;
1648 $targetLanguage = Language
::factory( $lang );
1649 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1651 return Linker
::linkKnown(
1652 $this->getPageTitle(),
1653 htmlspecialchars( $text ),
1659 protected function getGroupName() {