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.
978 * Extensions can use this to reuse the "return to" logic after
979 * inject steps (such as redirection) into the login process.
981 * @param $type string, one of the following:
982 * - error: display a return to link ignoring $wgRedirectOnLogin
983 * - success: display a return to link using $wgRedirectOnLogin if needed
984 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
985 * @param string $returnTo
986 * @param array|string $returnToQuery
987 * @param bool $stickHTTPs Keep redirect link on HTTPs
990 public function showReturnToPage(
991 $type, $returnTo = '', $returnToQuery = '', $stickHTTPs = false
993 $this->mReturnTo
= $returnTo;
994 $this->mReturnToQuery
= $returnToQuery;
995 $this->mStickHTTPS
= $stickHTTPs;
996 $this->executeReturnTo( $type );
1000 * Add a "return to" link or redirect to it.
1002 * @param $type string, one of the following:
1003 * - error: display a return to link ignoring $wgRedirectOnLogin
1004 * - success: display a return to link using $wgRedirectOnLogin if needed
1005 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1007 private function executeReturnTo( $type ) {
1008 global $wgRedirectOnLogin, $wgSecureLogin;
1010 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
1011 $returnTo = $wgRedirectOnLogin;
1012 $returnToQuery = array();
1014 $returnTo = $this->mReturnTo
;
1015 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
1018 $returnToTitle = Title
::newFromText( $returnTo );
1019 if ( !$returnToTitle ) {
1020 $returnToTitle = Title
::newMainPage();
1023 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1024 $options = array( 'http' );
1025 $proto = PROTO_HTTP
;
1026 } elseif ( $wgSecureLogin ) {
1027 $options = array( 'https' );
1028 $proto = PROTO_HTTPS
;
1031 $proto = PROTO_RELATIVE
;
1034 if ( $type == 'successredirect' ) {
1035 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1036 $this->getOutput()->redirect( $redirectUrl );
1038 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1043 * Whether to show new vertically laid out login form.
1044 * ?useNew=1 forces new style, ?useNew=0 forces old style,
1045 * otherwise consult $wgUseVFormUserLogin.
1048 private function shouldShowVForm() {
1049 global $wgUseVFormCreateAccount, $wgUseVFormUserLogin;
1051 if ( $this->mType
== 'signup' ) {
1052 return $this->mRequest
->getBool( 'useNew', $wgUseVFormCreateAccount );
1054 return $this->mRequest
->getBool( 'useNew', $wgUseVFormUserLogin );
1061 function mainLoginForm( $msg, $msgtype = 'error' ) {
1062 global $wgEnableEmail, $wgEnableUserEmail;
1063 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1064 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
1065 global $wgSecureLogin, $wgSecureLoginDefaultHTTPS, $wgPasswordResetRoutes;
1067 $titleObj = $this->getTitle();
1068 $user = $this->getUser();
1069 $out = $this->getOutput();
1071 if ( $this->mType
== 'signup' ) {
1072 // Block signup here if in readonly. Keeps user from
1073 // going through the process (filling out data, etc)
1074 // and being informed later.
1075 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1076 if ( count( $permErrors ) ) {
1077 throw new PermissionsError( 'createaccount', $permErrors );
1078 } elseif ( $user->isBlockedFromCreateAccount() ) {
1079 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1081 } elseif ( wfReadOnly() ) {
1082 throw new ReadOnlyError
;
1086 // Pre-fill username (if not creating an account, bug 44775).
1087 if ( $this->mUsername
== '' && $this->mType
!= 'signup' ) {
1088 if ( $user->isLoggedIn() ) {
1089 $this->mUsername
= $user->getName();
1091 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1095 if ( $this->mType
== 'signup' ) {
1096 $out->addModules( 'mediawiki.special.userlogin.signup' );
1097 if ( $this->mShowVForm
) {
1098 $template = new UsercreateTemplateVForm();
1099 $out->addModuleStyles( array(
1101 'mediawiki.special.createaccount.vform'
1103 // XXX hack pending RL or JS parse() support for complex content messages
1104 // https://bugzilla.wikimedia.org/show_bug.cgi?id=25349
1105 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
1106 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
1107 $out->addModules( 'mediawiki.special.createaccount.vform.js' );
1108 // Must match number of benefits defined in messages
1109 $template->set( 'benefitCount', 3 );
1111 $template = new UsercreateTemplate();
1113 $q = 'action=submitlogin&type=signup';
1114 $linkq = 'type=login';
1115 $linkmsg = 'gotaccount';
1117 if ( $this->mShowVForm
) {
1118 $template = new UserloginTemplateVForm();
1119 $out->addModuleStyles( array(
1121 'mediawiki.special.userlogin.vform'
1124 $template = new UserloginTemplate();
1126 $q = 'action=submitlogin&type=login';
1127 $linkq = 'type=signup';
1128 $linkmsg = 'nologin';
1131 if ( $this->mReturnTo
!== '' ) {
1132 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1133 if ( $this->mReturnToQuery
!== '' ) {
1134 $returnto .= '&returntoquery=' .
1135 wfUrlencode( $this->mReturnToQuery
);
1138 $linkq .= $returnto;
1141 # Don't show a "create account" link if the user can't.
1142 if ( $this->showCreateOrLoginLink( $user ) ) {
1143 # Pass any language selection on to the mode switch link
1144 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
1145 $linkq .= '&uselang=' . $this->mLanguage
;
1147 if ( !$this->mShowVForm
) {
1148 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1149 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1151 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1154 // Supply URL, login template creates the button.
1155 // (The template 'link' key, passed above, is obsolete in the VForm design.)
1156 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1159 $template->set( 'link', '' );
1162 // Decide if we default stickHTTPS on
1163 if ( $wgSecureLoginDefaultHTTPS && $this->mAction
!= 'submitlogin' && !$this->mLoginattempt
) {
1164 $this->mStickHTTPS
= true;
1167 $resetLink = $this->mType
== 'signup'
1169 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1171 $template->set( 'header', '' );
1172 $template->set( 'skin', $this->getSkin() );
1173 $template->set( 'name', $this->mUsername
);
1174 $template->set( 'password', $this->mPassword
);
1175 $template->set( 'retype', $this->mRetype
);
1176 $template->set( 'createemailset', $this->mCreateaccountMail
);
1177 $template->set( 'email', $this->mEmail
);
1178 $template->set( 'realname', $this->mRealName
);
1179 $template->set( 'domain', $this->mDomain
);
1180 $template->set( 'reason', $this->mReason
);
1182 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1183 $template->set( 'message', $msg );
1184 $template->set( 'messagetype', $msgtype );
1185 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1186 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1187 $template->set( 'useemail', $wgEnableEmail );
1188 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1189 $template->set( 'emailothers', $wgEnableUserEmail );
1190 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1191 $template->set( 'resetlink', $resetLink );
1192 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1193 $template->set( 'usereason', $user->isLoggedIn() );
1194 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1195 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1196 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1198 if ( $this->mType
== 'signup' ) {
1199 if ( !self
::getCreateaccountToken() ) {
1200 self
::setCreateaccountToken();
1202 $template->set( 'token', self
::getCreateaccountToken() );
1204 if ( !self
::getLoginToken() ) {
1205 self
::setLoginToken();
1207 $template->set( 'token', self
::getLoginToken() );
1210 # Prepare language selection links as needed
1211 if ( $wgLoginLanguageSelector ) {
1212 $template->set( 'languages', $this->makeLanguageSelector() );
1213 if ( $this->mLanguage
) {
1214 $template->set( 'uselang', $this->mLanguage
);
1218 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl
);
1219 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1220 // Ditto for signupend. New forms use neither.
1221 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1222 $loginendHTTPS = $this->msg( 'loginend-https' );
1223 $signupendHTTPS = $this->msg( 'signupend-https' );
1224 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1225 $template->set( 'loginend', $loginendHTTPS->parse() );
1227 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1229 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1230 $template->set( 'signupend', $signupendHTTPS->parse() );
1232 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1235 // Give authentication and captcha plugins a chance to modify the form
1236 $wgAuth->modifyUITemplate( $template, $this->mType
);
1237 if ( $this->mType
== 'signup' ) {
1238 wfRunHooks( 'UserCreateForm', array( &$template ) );
1240 wfRunHooks( 'UserLoginForm', array( &$template ) );
1243 $out->disallowUserJs(); // just in case...
1244 $out->addTemplate( $template );
1254 function showCreateOrLoginLink( &$user ) {
1255 if ( $this->mType
== 'signup' ) {
1257 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1265 * Check if a session cookie is present.
1267 * This will not pick up a cookie set during _this_ request, but is meant
1268 * to ensure that the client is returning the cookie which was set on a
1269 * previous pass through the system.
1274 function hasSessionCookie() {
1275 global $wgDisableCookieCheck;
1276 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1280 * Get the login token from the current session
1283 public static function getLoginToken() {
1285 return $wgRequest->getSessionData( 'wsLoginToken' );
1289 * Randomly generate a new login token and attach it to the current session
1291 public static function setLoginToken() {
1293 // Generate a token directly instead of using $user->editToken()
1294 // because the latter reuses $_SESSION['wsEditToken']
1295 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1299 * Remove any login token attached to the current session
1301 public static function clearLoginToken() {
1303 $wgRequest->setSessionData( 'wsLoginToken', null );
1307 * Get the createaccount token from the current session
1310 public static function getCreateaccountToken() {
1312 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1316 * Randomly generate a new createaccount token and attach it to the current session
1318 public static function setCreateaccountToken() {
1320 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1324 * Remove any createaccount token attached to the current session
1326 public static function clearCreateaccountToken() {
1328 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1332 * Renew the user's session id, using strong entropy
1334 private function renewSessionId() {
1335 global $wgSecureLogin, $wgCookieSecure;
1336 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1337 $wgCookieSecure = false;
1340 // If either we don't trust PHP's entropy, or if we need
1341 // to change cookie settings when logging in because of
1342 // wpStickHTTPS, then change the session ID manually.
1343 $cookieParams = session_get_cookie_params();
1344 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
1345 session_regenerate_id( false );
1349 wfSetupSession( MWCryptRand
::generateHex( 32 ) );
1357 function cookieRedirectCheck( $type ) {
1358 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1359 $query = array( 'wpCookieCheck' => $type );
1360 if ( $this->mReturnTo
!== '' ) {
1361 $query['returnto'] = $this->mReturnTo
;
1362 $query['returntoquery'] = $this->mReturnToQuery
;
1364 $check = $titleObj->getFullURL( $query );
1366 $this->getOutput()->redirect( $check );
1372 function onCookieRedirectCheck( $type ) {
1373 if ( !$this->hasSessionCookie() ) {
1374 if ( $type == 'new' ) {
1375 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1376 } elseif ( $type == 'login' ) {
1377 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1380 $this->mainLoginForm( $this->msg( 'error' )->text() );
1383 $this->successfulLogin();
1388 * Produce a bar of links which allow the user to select another language
1389 * during login/registration but retain "returnto"
1393 function makeLanguageSelector() {
1394 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1395 if ( !$msg->isBlank() ) {
1396 $langs = explode( "\n", $msg->text() );
1398 foreach ( $langs as $lang ) {
1399 $lang = trim( $lang, '* ' );
1400 $parts = explode( '|', $lang );
1401 if ( count( $parts ) >= 2 ) {
1402 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1405 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1406 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1413 * Create a language selector link for a particular language
1414 * Links back to this page preserving type and returnto
1416 * @param string $text Link text
1417 * @param string $lang Language code
1420 function makeLanguageSelectorLink( $text, $lang ) {
1421 if ( $this->getLanguage()->getCode() == $lang ) {
1422 // no link for currently used language
1423 return htmlspecialchars( $text );
1425 $query = array( 'uselang' => $lang );
1426 if ( $this->mType
== 'signup' ) {
1427 $query['type'] = 'signup';
1429 if ( $this->mReturnTo
!== '' ) {
1430 $query['returnto'] = $this->mReturnTo
;
1431 $query['returntoquery'] = $this->mReturnToQuery
;
1435 $targetLanguage = Language
::factory( $lang );
1436 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1438 return Linker
::linkKnown(
1440 htmlspecialchars( $text ),
1446 protected function getGroupName() {