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
{
34 const WRONG_PLUGIN_PASS
= 3;
40 const CREATE_BLOCKED
= 9;
42 const USER_BLOCKED
= 11;
43 const NEED_TOKEN
= 12;
44 const WRONG_TOKEN
= 13;
46 var $mUsername, $mPassword, $mRetype, $mReturnTo, $mCookieCheck, $mPosted;
47 var $mAction, $mCreateaccount, $mCreateaccountMail;
48 var $mLoginattempt, $mRemember, $mEmail, $mDomain, $mLanguage;
49 var $mSkipCookieCheck, $mReturnToQuery, $mToken, $mStickHTTPS;
50 var $mType, $mReason, $mRealName;
51 var $mAbortLoginErrorMsg = 'login-abort-generic';
52 private $mLoaded = false;
53 private $mSecureLoginUrl;
54 // TODO Remove old forms and mShowVForm gating after all WMF wikis have
55 // adapted messages and help links to new versions.
61 private $mOverrideRequest = null;
64 * Effective request; set at the beginning of load
66 * @var WebRequest $mRequest
68 private $mRequest = null;
71 * @param WebRequest $request
73 public function __construct( $request = null ) {
74 parent
::__construct( 'Userlogin' );
76 $this->mOverrideRequest
= $request;
83 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
85 if ( $this->mLoaded
) {
88 $this->mLoaded
= true;
90 if ( $this->mOverrideRequest
=== null ) {
91 $request = $this->getRequest();
93 $request = $this->mOverrideRequest
;
95 $this->mRequest
= $request;
97 $this->mType
= $request->getText( 'type' );
98 $this->mUsername
= $request->getText( 'wpName' );
99 $this->mPassword
= $request->getText( 'wpPassword' );
100 $this->mRetype
= $request->getText( 'wpRetype' );
101 $this->mDomain
= $request->getText( 'wpDomain' );
102 $this->mReason
= $request->getText( 'wpReason' );
103 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
104 $this->mPosted
= $request->wasPosted();
105 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
107 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' ) && !$this->mCreateaccountMail
;
108 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
109 $this->mAction
= $request->getVal( 'action' );
110 $this->mRemember
= $request->getCheck( 'wpRemember' );
111 $this->mStickHTTPS
= $request->getCheck( 'wpStickHTTPS' );
112 $this->mLanguage
= $request->getText( 'uselang' );
113 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
114 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
115 $this->mReturnTo
= $request->getVal( 'returnto', '' );
116 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
118 if ( $wgEnableEmail ) {
119 $this->mEmail
= $request->getText( 'wpEmail' );
123 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
124 $this->mRealName
= $request->getText( 'wpRealName' );
126 $this->mRealName
= '';
129 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
130 $this->mDomain
= $wgAuth->getDomain();
132 $wgAuth->setDomain( $this->mDomain
);
134 # 1. When switching accounts, it sucks to get automatically logged out
135 # 2. Do not return to PasswordReset after a successful password change
136 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
137 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
138 if ( is_object( $returnToTitle ) && (
139 $returnToTitle->isSpecial( 'Userlogout' )
140 ||
$returnToTitle->isSpecial( 'PasswordReset' ) ) ) {
141 $this->mReturnTo
= '';
142 $this->mReturnToQuery
= '';
146 function getDescription() {
147 if ( !$this->getUser()->isAllowed( 'createaccount' ) ) {
148 return $this->msg( 'userloginnocreate' )->text();
150 if ( $this->mShowVForm
) {
151 if ( $this->mType
=== 'signup' ) {
152 return $this->msg( 'createaccount' )->text();
154 return $this->msg( 'login' )->text();
157 return $this->msg( 'userlogin' )->text();
162 * @param $subPage string|null
164 public function execute( $subPage ) {
165 if ( session_id() == '' ) {
171 // Check for [[Special:Userlogin/signup]. This affects form display and
173 if ( $subPage == 'signup' ) {
174 $this->mType
= 'signup';
176 $this->mShowVForm
= $this->shouldShowVForm();
180 // If logging in and not on HTTPS, either redirect to it or offer a link.
181 global $wgSecureLogin;
183 $this->mType
!== 'signup' &&
184 WebRequest
::detectProtocol() !== 'https'
186 $title = $this->getFullTitle();
188 'returnto' => $this->mReturnTo
,
189 'returntoquery' => $this->mReturnToQuery
,
190 'wpStickHTTPS' => $this->mStickHTTPS
192 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
193 if ( $wgSecureLogin ) {
194 $this->getOutput()->redirect( $url );
197 // A wiki without HTTPS login support should set $wgServer to
198 // http://somehost, in which case the secure URL generated
199 // above won't actually start with https://
200 if ( substr( $url, 0, 8 ) === 'https://' ) {
201 $this->mSecureLoginUrl
= $url;
206 if ( !is_null( $this->mCookieCheck
) ) {
207 $this->onCookieRedirectCheck( $this->mCookieCheck
);
209 } elseif ( $this->mPosted
) {
210 if ( $this->mCreateaccount
) {
211 $this->addNewAccount();
213 } elseif ( $this->mCreateaccountMail
) {
214 $this->addNewAccountMailPassword();
216 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
217 $this->processLogin();
221 $this->mainLoginForm( '' );
227 function addNewAccountMailPassword() {
228 if ( $this->mEmail
== '' ) {
229 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
233 $status = $this->addNewaccountInternal();
234 if ( !$status->isGood() ) {
235 $error = $this->getOutput()->parse( $status->getWikiText() );
236 $this->mainLoginForm( $error );
240 $u = $status->getValue();
242 // Wipe the initial password and mail a temporary one
243 $u->setPassword( null );
245 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
247 wfRunHooks( 'AddNewAccount', array( $u, true ) );
248 $u->addNewUserLogEntry( 'byemail', $this->mReason
);
250 $out = $this->getOutput();
251 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
253 if ( !$result->isGood() ) {
254 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
256 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
257 $this->executeReturnTo( 'success' );
265 function addNewAccount() {
266 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
268 # Create the account and abort if there's a problem doing so
269 $status = $this->addNewAccountInternal();
270 if ( !$status->isGood() ) {
271 $error = $this->getOutput()->parse( $status->getWikiText() );
272 $this->mainLoginForm( $error );
276 $u = $status->getValue();
278 # Only save preferences if the user is not creating an account for someone else.
279 if ( $this->getUser()->isAnon() ) {
280 # If we showed up language selection links, and one was in use, be
281 # smart (and sensible) and save that language as the user's preference
282 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
283 $u->setOption( 'language', $this->mLanguage
);
286 # Otherwise the user's language preference defaults to $wgContLang,
287 # but it may be better to set it to their preferred $wgContLang variant,
288 # based on browser preferences or URL parameters.
289 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
291 if ( $wgContLang->hasVariants() ) {
292 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
296 $out = $this->getOutput();
298 # Send out an email authentication message if needed
299 if ( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
300 $status = $u->sendConfirmationMail();
301 if ( $status->isGood() ) {
302 $out->addWikiMsg( 'confirmemail_oncreate' );
304 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
308 # Save settings (including confirmation token)
311 # If not logged in, assume the new account as the current one and set
312 # session cookies then show a "welcome" message or a "need cookies"
314 if ( $this->getUser()->isAnon() ) {
317 // This should set it for OutputPage and the Skin
318 // which is needed or the personal links will be
320 $this->getContext()->setUser( $u );
321 wfRunHooks( 'AddNewAccount', array( $u, false ) );
322 $u->addNewUserLogEntry( 'create' );
323 if ( $this->hasSessionCookie() ) {
324 $this->successfulCreation();
326 $this->cookieRedirectCheck( 'new' );
329 # Confirm that the account was created
330 $out->setPageTitle( $this->msg( 'accountcreated' ) );
331 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
332 $out->addReturnTo( $this->getTitle() );
333 wfRunHooks( 'AddNewAccount', array( $u, false ) );
334 $u->addNewUserLogEntry( 'create2', $this->mReason
);
340 * Make a new user account using the loaded data.
342 * @throws PermissionsError|ReadOnlyError
345 public function addNewAccountInternal() {
346 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
347 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
349 // If the user passes an invalid domain, something is fishy
350 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
351 return Status
::newFatal( 'wrongpassword' );
354 // If we are not allowing users to login locally, we should be checking
355 // to see if the user is actually able to authenticate to the authenti-
356 // cation server before they create an account (otherwise, they can
357 // create a local account and login as any domain user). We only need
358 // to check this for domains that aren't local.
359 if ( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
361 !$wgAuth->canCreateAccounts() &&
363 !$wgAuth->userExists( $this->mUsername
) ||
364 !$wgAuth->authenticate( $this->mUsername
, $this->mPassword
)
367 return Status
::newFatal( 'wrongpassword' );
371 if ( wfReadOnly() ) {
372 throw new ReadOnlyError
;
375 # Request forgery checks.
376 if ( !self
::getCreateaccountToken() ) {
377 self
::setCreateaccountToken();
378 return Status
::newFatal( 'nocookiesfornew' );
381 # The user didn't pass a createaccount token
382 if ( !$this->mToken
) {
383 return Status
::newFatal( 'sessionfailure' );
386 # Validate the createaccount token
387 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
388 return Status
::newFatal( 'sessionfailure' );
392 $currentUser = $this->getUser();
393 $creationBlock = $currentUser->isBlockedFromCreateAccount();
394 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
395 throw new PermissionsError( 'createaccount' );
396 } elseif ( $creationBlock instanceof Block
) {
397 // Throws an ErrorPageError.
398 $this->userBlockedMessage( $creationBlock );
399 // This should never be reached.
403 # Include checks that will include GlobalBlocking (Bug 38333)
404 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'createaccount', $currentUser, true );
405 if ( count( $permErrors ) ) {
406 throw new PermissionsError( 'createaccount', $permErrors );
409 $ip = $this->getRequest()->getIP();
410 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
411 return Status
::newFatal( 'sorbs_create_account_reason' );
414 # Now create a dummy user ($u) and check if it is valid
415 $name = trim( $this->mUsername
);
416 $u = User
::newFromName( $name, 'creatable' );
417 if ( !is_object( $u ) ) {
418 return Status
::newFatal( 'noname' );
419 } elseif ( 0 != $u->idForName() ) {
420 return Status
::newFatal( 'userexists' );
423 if ( $this->mCreateaccountMail
) {
424 # do not force a password for account creation by email
425 # set invalid password, it will be replaced later by a random generated password
426 $this->mPassword
= null;
428 if ( $this->mPassword
!== $this->mRetype
) {
429 return Status
::newFatal( 'badretype' );
432 # check for minimal password length
433 $valid = $u->getPasswordValidity( $this->mPassword
);
434 if ( $valid !== true ) {
435 if ( !is_array( $valid ) ) {
436 $valid = array( $valid, $wgMinimalPasswordLength );
438 return call_user_func_array( 'Status::newFatal', $valid );
442 # if you need a confirmed email address to edit, then obviously you
443 # need an email address.
444 if ( $wgEmailConfirmToEdit && strval( $this->mEmail
) === '' ) {
445 return Status
::newFatal( 'noemailtitle' );
448 if ( strval( $this->mEmail
) !== '' && !Sanitizer
::validateEmail( $this->mEmail
) ) {
449 return Status
::newFatal( 'invalidemailaddress' );
452 # Set some additional data so the AbortNewAccount hook can be used for
453 # more than just username validation
454 $u->setEmail( $this->mEmail
);
455 $u->setRealName( $this->mRealName
);
458 if ( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
459 // Hook point to add extra creation throttles and blocks
460 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
461 return Status
::newFatal( new RawMessage( $abortError ) );
464 // Hook point to check for exempt from account creation throttle
465 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
466 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
468 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
469 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
470 $value = $wgMemc->get( $key );
472 $wgMemc->set( $key, 0, 86400 );
474 if ( $value >= $wgAccountCreationThrottle ) {
475 return Status
::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
477 $wgMemc->incr( $key );
481 if ( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
482 return Status
::newFatal( 'externaldberror' );
485 self
::clearCreateaccountToken();
486 return $this->initUser( $u, false );
490 * Actually add a user to the database.
491 * Give it a User object that has been initialised with a name.
493 * @param $u User object.
494 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
495 * @return Status object, with the User object in the value member on success
498 function initUser( $u, $autocreate ) {
501 $status = $u->addToDatabase();
502 if ( !$status->isOK() ) {
506 if ( $wgAuth->allowPasswordChange() ) {
507 $u->setPassword( $this->mPassword
);
510 $u->setEmail( $this->mEmail
);
511 $u->setRealName( $this->mRealName
);
514 $wgAuth->initUser( $u, $autocreate );
516 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
520 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
522 return Status
::newGood( $u );
526 * Internally authenticate the login request.
528 * This may create a local account as a side effect if the
529 * authentication plugin allows transparent local account
533 public function authenticateUserData() {
534 global $wgUser, $wgAuth;
538 if ( $this->mUsername
== '' ) {
539 return self
::NO_NAME
;
542 // We require a login token to prevent login CSRF
543 // Handle part of this before incrementing the throttle so
544 // token-less login attempts don't count towards the throttle
545 // but wrong-token attempts do.
547 // If the user doesn't have a login token yet, set one.
548 if ( !self
::getLoginToken() ) {
549 self
::setLoginToken();
550 return self
::NEED_TOKEN
;
552 // If the user didn't pass a login token, tell them we need one
553 if ( !$this->mToken
) {
554 return self
::NEED_TOKEN
;
557 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
558 if ( $throttleCount === true ) {
559 return self
::THROTTLED
;
562 // Validate the login token
563 if ( $this->mToken
!== self
::getLoginToken() ) {
564 return self
::WRONG_TOKEN
;
567 // Load the current user now, and check to see if we're logging in as
568 // the same name. This is necessary because loading the current user
569 // (say by calling getName()) calls the UserLoadFromSession hook, which
570 // potentially creates the user in the database. Until we load $wgUser,
571 // checking for user existence using User::newFromName($name)->getId() below
572 // will effectively be using stale data.
573 if ( $this->getUser()->getName() === $this->mUsername
) {
574 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
575 return self
::SUCCESS
;
578 $u = User
::newFromName( $this->mUsername
);
579 if ( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
580 return self
::ILLEGAL
;
583 $isAutoCreated = false;
584 if ( $u->getID() == 0 ) {
585 $status = $this->attemptAutoCreate( $u );
586 if ( $status !== self
::SUCCESS
) {
589 $isAutoCreated = true;
595 // Give general extensions, such as a captcha, a chance to abort logins
596 $abort = self
::ABORTED
;
597 if ( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
601 global $wgBlockDisablesLogin;
602 if ( !$u->checkPassword( $this->mPassword
) ) {
603 if ( $u->checkTemporaryPassword( $this->mPassword
) ) {
604 // The e-mailed temporary password should not be used for actu-
605 // al logins; that's a very sloppy habit, and insecure if an
606 // attacker has a few seconds to click "search" on someone's o-
609 // Allow it to be used only to reset the password a single time
610 // to a new value, which won't be in the user's e-mail ar-
613 // For backwards compatibility, we'll still recognize it at the
614 // login form to minimize surprises for people who have been
615 // logging in with a temporary password for some time.
617 // As a side-effect, we can authenticate the user's e-mail ad-
618 // dress if it's not already done, since the temporary password
619 // was sent via e-mail.
620 if ( !$u->isEmailConfirmed() ) {
625 // At this point we just return an appropriate code/ indicating
626 // that the UI should show a password reset form; bot inter-
627 // faces etc will probably just fail cleanly here.
628 $retval = self
::RESET_PASS
;
630 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
632 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
633 // If we've enabled it, make it so that a blocked user cannot login
634 $retval = self
::USER_BLOCKED
;
636 $wgAuth->updateUser( $u );
638 // This should set it for OutputPage and the Skin
639 // which is needed or the personal links will be
641 $this->getContext()->setUser( $u );
643 // Please reset throttle for successful logins, thanks!
644 if ( $throttleCount ) {
645 self
::clearLoginThrottle( $this->mUsername
);
648 if ( $isAutoCreated ) {
649 // Must be run after $wgUser is set, for correct new user log
650 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
653 $retval = self
::SUCCESS
;
655 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
660 * Increment the login attempt throttle hit count for the (username,current IP)
661 * tuple unless the throttle was already reached.
662 * @param string $username The user name
663 * @return Bool|Integer The integer hit count or True if it is already at the limit
665 public static function incLoginThrottle( $username ) {
666 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
667 $username = trim( $username ); // sanity
670 if ( is_array( $wgPasswordAttemptThrottle ) ) {
671 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
672 $count = $wgPasswordAttemptThrottle['count'];
673 $period = $wgPasswordAttemptThrottle['seconds'];
675 $throttleCount = $wgMemc->get( $throttleKey );
676 if ( !$throttleCount ) {
677 $wgMemc->add( $throttleKey, 1, $period ); // start counter
678 } elseif ( $throttleCount < $count ) {
679 $wgMemc->incr( $throttleKey );
680 } elseif ( $throttleCount >= $count ) {
685 return $throttleCount;
689 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
690 * @param string $username The user name
693 public static function clearLoginThrottle( $username ) {
694 global $wgMemc, $wgRequest;
695 $username = trim( $username ); // sanity
697 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
698 $wgMemc->delete( $throttleKey );
702 * Attempt to automatically create a user on login. Only succeeds if there
703 * is an external authentication method which allows it.
707 * @return integer Status code
709 function attemptAutoCreate( $user ) {
712 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
713 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
714 return self
::CREATE_BLOCKED
;
716 if ( !$wgAuth->autoCreate() ) {
717 return self
::NOT_EXISTS
;
719 if ( !$wgAuth->userExists( $user->getName() ) ) {
720 wfDebug( __METHOD__
. ": user does not exist\n" );
721 return self
::NOT_EXISTS
;
723 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
724 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
725 return self
::WRONG_PLUGIN_PASS
;
729 if ( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
730 // Hook point to add extra creation throttles and blocks
731 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
732 $this->mAbortLoginErrorMsg
= $abortError;
733 return self
::ABORTED
;
736 wfDebug( __METHOD__
. ": creating account\n" );
737 $status = $this->initUser( $user, true );
739 if ( !$status->isOK() ) {
740 $errors = $status->getErrorsByType( 'error' );
741 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
742 return self
::ABORTED
;
745 return self
::SUCCESS
;
748 function processLogin() {
749 global $wgMemc, $wgLang, $wgSecureLogin;
751 switch ( $this->authenticateUserData() ) {
753 # We've verified now, update the real record
754 $user = $this->getUser();
755 if ( (bool)$this->mRemember
!= $user->getBoolOption( 'rememberpassword' ) ) {
756 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
757 $user->saveSettings();
759 $user->invalidateCache();
762 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
763 $user->setCookies( null, false );
767 self
::clearLoginToken();
769 // Reset the throttle
770 $request = $this->getRequest();
771 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
772 $wgMemc->delete( $key );
774 if ( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
775 /* Replace the language object to provide user interface in
776 * correct language immediately on this first page load.
778 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
779 $userLang = Language
::factory( $code );
781 $this->getContext()->setLanguage( $userLang );
782 // Reset SessionID on Successful login (bug 40995)
783 $this->renewSessionId();
784 $this->successfulLogin();
786 $this->cookieRedirectCheck( 'login' );
790 case self
::NEED_TOKEN
:
791 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
793 case self
::WRONG_TOKEN
:
794 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
798 $this->mainLoginForm( $this->msg( 'noname' )->text() );
800 case self
::WRONG_PLUGIN_PASS
:
801 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
803 case self
::NOT_EXISTS
:
804 if ( $this->getUser()->isAllowed( 'createaccount' ) ) {
805 $this->mainLoginForm( $this->msg( 'nosuchuser',
806 wfEscapeWikiText( $this->mUsername
) )->parse() );
808 $this->mainLoginForm( $this->msg( 'nosuchusershort',
809 wfEscapeWikiText( $this->mUsername
) )->text() );
812 case self
::WRONG_PASS
:
813 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
815 case self
::EMPTY_PASS
:
816 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
818 case self
::RESET_PASS
:
819 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
821 case self
::CREATE_BLOCKED
:
822 $this->userBlockedMessage( $this->getUser()->isBlockedFromCreateAccount() );
824 case self
::THROTTLED
:
825 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
827 case self
::USER_BLOCKED
:
828 $this->mainLoginForm( $this->msg( 'login-userblocked',
829 $this->mUsername
)->escaped() );
832 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
835 throw new MWException( 'Unhandled case value' );
840 * @param $error string
842 function resetLoginForm( $error ) {
843 $this->getOutput()->addHTML( Xml
::element( 'p', array( 'class' => 'error' ), $error ) );
844 $reset = new SpecialChangePassword();
845 $reset->setContext( $this->getContext() );
846 $reset->execute( null );
850 * @param $u User object
851 * @param $throttle Boolean
852 * @param string $emailTitle message name of email title
853 * @param string $emailText message name of email text
854 * @return Status object
856 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
857 global $wgCanonicalServer, $wgScript, $wgNewPasswordExpiry;
859 if ( $u->getEmail() == '' ) {
860 return Status
::newFatal( 'noemail', $u->getName() );
862 $ip = $this->getRequest()->getIP();
864 return Status
::newFatal( 'badipaddress' );
867 $currentUser = $this->getUser();
868 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
870 $np = $u->randomPassword();
871 $u->setNewpassword( $np, $throttle );
873 $userLanguage = $u->getOption( 'language' );
874 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $wgCanonicalServer . $wgScript . '>',
875 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
876 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
882 * Run any hooks registered for logins, then HTTP redirect to
883 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
884 * nice message here, but that's really not as useful as just being sent to
885 * wherever you logged in from. It should be clear that the action was
886 * successful, given the lack of error messages plus the appearance of your
887 * name in the upper right.
891 function successfulLogin() {
892 # Run any hooks; display injected HTML if any, else redirect
893 $currentUser = $this->getUser();
895 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
897 if ( $injected_html !== '' ) {
898 $this->displaySuccessfulAction( $this->msg( 'loginsuccesstitle' ),
899 'loginsuccess', $injected_html );
901 $this->executeReturnTo( 'successredirect' );
906 * Run any hooks registered for logins, then display a message welcoming
911 function successfulCreation() {
912 # Run any hooks; display injected HTML
913 $currentUser = $this->getUser();
915 $welcome_creation_msg = 'welcomecreation-msg';
917 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
920 * Let any extensions change what message is shown.
921 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
924 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
926 $this->displaySuccessfulAction( $this->msg( 'welcomeuser', $this->getUser()->getName() ),
927 $welcome_creation_msg, $injected_html );
931 * Display an "successful action" page.
933 * @param string|Message $title page's title
934 * @param $msgname string
935 * @param $injected_html string
937 private function displaySuccessfulAction( $title, $msgname, $injected_html ) {
938 $out = $this->getOutput();
939 $out->setPageTitle( $title );
941 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
944 $out->addHTML( $injected_html );
946 $this->executeReturnTo( 'success' );
950 * Output a message that informs the user that they cannot create an account because
951 * there is a block on them or their IP which prevents account creation. Note that
952 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
953 * setting on blocks (bug 13611).
954 * @param $block Block the block causing this error
955 * @throws ErrorPageError
957 function userBlockedMessage( Block
$block ) {
958 # Let's be nice about this, it's likely that this feature will be used
959 # for blocking large numbers of innocent people, e.g. range blocks on
960 # schools. Don't blame it on the user. There's a small chance that it
961 # really is the user's fault, i.e. the username is blocked and they
962 # haven't bothered to log out before trying to create an account to
963 # evade it, but we'll leave that to their guilty conscience to figure
965 throw new ErrorPageError(
966 'cantcreateaccounttitle',
967 'cantcreateaccount-text',
970 $block->mReason ?
$block->mReason
: $this->msg( 'blockednoreason' )->text(),
977 * Add a "return to" link or redirect to it.
979 * @param $type string, one of the following:
980 * - error: display a return to link ignoring $wgRedirectOnLogin
981 * - success: display a return to link using $wgRedirectOnLogin if needed
982 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
984 private function executeReturnTo( $type ) {
985 global $wgRedirectOnLogin, $wgSecureLogin;
987 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
988 $returnTo = $wgRedirectOnLogin;
989 $returnToQuery = array();
991 $returnTo = $this->mReturnTo
;
992 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
995 $returnToTitle = Title
::newFromText( $returnTo );
996 if ( !$returnToTitle ) {
997 $returnToTitle = Title
::newMainPage();
1000 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1001 $options = array( 'http' );
1002 $proto = PROTO_HTTP
;
1003 } elseif ( $wgSecureLogin ) {
1004 $options = array( 'https' );
1005 $proto = PROTO_HTTPS
;
1008 $proto = PROTO_RELATIVE
;
1011 if ( $type == 'successredirect' ) {
1012 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1013 $this->getOutput()->redirect( $redirectUrl );
1015 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1020 * Whether to show new vertically laid out login form.
1021 * ?useNew=1 forces new style, ?useNew=0 forces old style,
1022 * otherwise consult $wgUseVFormUserLogin.
1025 private function shouldShowVForm() {
1026 global $wgUseVFormUserLogin;
1028 if ( $this->mType
== 'signup' ) {
1031 return $this->mRequest
->getBool( 'useNew', $wgUseVFormUserLogin );
1038 function mainLoginForm( $msg, $msgtype = 'error' ) {
1039 global $wgEnableEmail, $wgEnableUserEmail;
1040 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1041 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
1042 global $wgSecureLogin, $wgSecureLoginDefaultHTTPS, $wgPasswordResetRoutes;
1044 $titleObj = $this->getTitle();
1045 $user = $this->getUser();
1046 $out = $this->getOutput();
1048 if ( $this->mType
== 'signup' ) {
1049 // Block signup here if in readonly. Keeps user from
1050 // going through the process (filling out data, etc)
1051 // and being informed later.
1052 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1053 if ( count( $permErrors ) ) {
1054 throw new PermissionsError( 'createaccount', $permErrors );
1055 } elseif ( $user->isBlockedFromCreateAccount() ) {
1056 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1058 } elseif ( wfReadOnly() ) {
1059 throw new ReadOnlyError
;
1063 // Pre-fill username (if not creating an account, bug 44775).
1064 if ( $this->mUsername
== '' && $this->mType
!= 'signup' ) {
1065 if ( $user->isLoggedIn() ) {
1066 $this->mUsername
= $user->getName();
1068 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1072 if ( $this->mType
== 'signup' ) {
1073 $template = new UsercreateTemplate();
1074 $q = 'action=submitlogin&type=signup';
1075 $linkq = 'type=login';
1076 $linkmsg = 'gotaccount';
1077 $out->addModules( 'mediawiki.special.userlogin.signup' );
1079 if ( $this->mShowVForm
) {
1080 $template = new UserloginTemplateVForm();
1081 $out->addModuleStyles( array(
1083 'mediawiki.special.userlogin.vform'
1086 $template = new UserloginTemplate();
1088 $q = 'action=submitlogin&type=login';
1089 $linkq = 'type=signup';
1090 $linkmsg = 'nologin';
1093 if ( $this->mReturnTo
!== '' ) {
1094 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1095 if ( $this->mReturnToQuery
!== '' ) {
1096 $returnto .= '&returntoquery=' .
1097 wfUrlencode( $this->mReturnToQuery
);
1100 $linkq .= $returnto;
1103 # Don't show a "create account" link if the user can't.
1104 if ( $this->showCreateOrLoginLink( $user ) ) {
1105 # Pass any language selection on to the mode switch link
1106 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
1107 $linkq .= '&uselang=' . $this->mLanguage
;
1109 if ( !$this->mShowVForm
) {
1110 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1111 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1113 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1116 // Supply URL, login template creates the button.
1117 // (The template 'link' key, passed above, is obsolete in the VForm design.)
1118 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1121 $template->set( 'link', '' );
1124 // Decide if we default stickHTTPS on
1125 if ( $wgSecureLoginDefaultHTTPS && $this->mAction
!= 'submitlogin' && !$this->mLoginattempt
) {
1126 $this->mStickHTTPS
= true;
1129 $resetLink = $this->mType
== 'signup'
1131 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1133 $template->set( 'header', '' );
1134 $template->set( 'skin', $this->getSkin() );
1135 $template->set( 'name', $this->mUsername
);
1136 $template->set( 'password', $this->mPassword
);
1137 $template->set( 'retype', $this->mRetype
);
1138 $template->set( 'createemailset', $this->mCreateaccountMail
);
1139 $template->set( 'email', $this->mEmail
);
1140 $template->set( 'realname', $this->mRealName
);
1141 $template->set( 'domain', $this->mDomain
);
1142 $template->set( 'reason', $this->mReason
);
1144 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1145 $template->set( 'message', $msg );
1146 $template->set( 'messagetype', $msgtype );
1147 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1148 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1149 $template->set( 'useemail', $wgEnableEmail );
1150 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1151 $template->set( 'emailothers', $wgEnableUserEmail );
1152 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1153 $template->set( 'resetlink', $resetLink );
1154 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1155 $template->set( 'usereason', $user->isLoggedIn() );
1156 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1157 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1158 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1160 if ( $this->mType
== 'signup' ) {
1161 if ( !self
::getCreateaccountToken() ) {
1162 self
::setCreateaccountToken();
1164 $template->set( 'token', self
::getCreateaccountToken() );
1166 if ( !self
::getLoginToken() ) {
1167 self
::setLoginToken();
1169 $template->set( 'token', self
::getLoginToken() );
1172 # Prepare language selection links as needed
1173 if ( $wgLoginLanguageSelector ) {
1174 $template->set( 'languages', $this->makeLanguageSelector() );
1175 if ( $this->mLanguage
) {
1176 $template->set( 'uselang', $this->mLanguage
);
1180 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl
);
1181 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1182 // Ditto for signupend. New forms use neither.
1183 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1184 $loginendHTTPS = $this->msg( 'loginend-https' );
1185 $signupendHTTPS = $this->msg( 'signupend-https' );
1186 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1187 $template->set( 'loginend', $loginendHTTPS->parse() );
1189 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1191 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1192 $template->set( 'signupend', $signupendHTTPS->parse() );
1194 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1197 // Give authentication and captcha plugins a chance to modify the form
1198 $wgAuth->modifyUITemplate( $template, $this->mType
);
1199 if ( $this->mType
== 'signup' ) {
1200 wfRunHooks( 'UserCreateForm', array( &$template ) );
1202 wfRunHooks( 'UserLoginForm', array( &$template ) );
1205 $out->disallowUserJs(); // just in case...
1206 $out->addTemplate( $template );
1216 function showCreateOrLoginLink( &$user ) {
1217 if ( $this->mType
== 'signup' ) {
1219 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1227 * Check if a session cookie is present.
1229 * This will not pick up a cookie set during _this_ request, but is meant
1230 * to ensure that the client is returning the cookie which was set on a
1231 * previous pass through the system.
1236 function hasSessionCookie() {
1237 global $wgDisableCookieCheck;
1238 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1242 * Get the login token from the current session
1245 public static function getLoginToken() {
1247 return $wgRequest->getSessionData( 'wsLoginToken' );
1251 * Randomly generate a new login token and attach it to the current session
1253 public static function setLoginToken() {
1255 // Generate a token directly instead of using $user->editToken()
1256 // because the latter reuses $_SESSION['wsEditToken']
1257 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1261 * Remove any login token attached to the current session
1263 public static function clearLoginToken() {
1265 $wgRequest->setSessionData( 'wsLoginToken', null );
1269 * Get the createaccount token from the current session
1272 public static function getCreateaccountToken() {
1274 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1278 * Randomly generate a new createaccount token and attach it to the current session
1280 public static function setCreateaccountToken() {
1282 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1286 * Remove any createaccount token attached to the current session
1288 public static function clearCreateaccountToken() {
1290 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1294 * Renew the user's session id, using strong entropy
1296 private function renewSessionId() {
1297 global $wgSecureLogin, $wgCookieSecure;
1298 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1299 $wgCookieSecure = false;
1302 // If either we don't trust PHP's entropy, or if we need
1303 // to change cookie settings when logging in because of
1304 // wpStickHTTPS, then change the session ID manually.
1305 $cookieParams = session_get_cookie_params();
1306 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
1307 session_regenerate_id( false );
1311 wfSetupSession( MWCryptRand
::generateHex( 32 ) );
1319 function cookieRedirectCheck( $type ) {
1320 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1321 $query = array( 'wpCookieCheck' => $type );
1322 if ( $this->mReturnTo
!== '' ) {
1323 $query['returnto'] = $this->mReturnTo
;
1324 $query['returntoquery'] = $this->mReturnToQuery
;
1326 $check = $titleObj->getFullURL( $query );
1328 $this->getOutput()->redirect( $check );
1334 function onCookieRedirectCheck( $type ) {
1335 if ( !$this->hasSessionCookie() ) {
1336 if ( $type == 'new' ) {
1337 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1338 } elseif ( $type == 'login' ) {
1339 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1342 $this->mainLoginForm( $this->msg( 'error' )->text() );
1345 $this->successfulLogin();
1350 * Produce a bar of links which allow the user to select another language
1351 * during login/registration but retain "returnto"
1355 function makeLanguageSelector() {
1356 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1357 if ( !$msg->isBlank() ) {
1358 $langs = explode( "\n", $msg->text() );
1360 foreach ( $langs as $lang ) {
1361 $lang = trim( $lang, '* ' );
1362 $parts = explode( '|', $lang );
1363 if ( count( $parts ) >= 2 ) {
1364 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1367 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1368 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1375 * Create a language selector link for a particular language
1376 * Links back to this page preserving type and returnto
1378 * @param string $text Link text
1379 * @param string $lang Language code
1382 function makeLanguageSelectorLink( $text, $lang ) {
1383 if ( $this->getLanguage()->getCode() == $lang ) {
1384 // no link for currently used language
1385 return htmlspecialchars( $text );
1387 $query = array( 'uselang' => $lang );
1388 if ( $this->mType
== 'signup' ) {
1389 $query['type'] = 'signup';
1391 if ( $this->mReturnTo
!== '' ) {
1392 $query['returnto'] = $this->mReturnTo
;
1393 $query['returntoquery'] = $this->mReturnToQuery
;
1397 $targetLanguage = Language
::factory( $lang );
1398 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1400 return Linker
::linkKnown(
1402 htmlspecialchars( $text ),
1408 protected function getGroupName() {