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 = null;
52 private $mLoaded = false;
53 private $mSecureLoginUrl;
58 private $mOverrideRequest = null;
61 * Effective request; set at the beginning of load
63 * @var WebRequest $mRequest
65 private $mRequest = null;
68 * @param WebRequest $request
70 public function __construct( $request = null ) {
71 parent
::__construct( 'Userlogin' );
73 $this->mOverrideRequest
= $request;
80 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
82 if ( $this->mLoaded
) {
85 $this->mLoaded
= true;
87 if ( $this->mOverrideRequest
=== null ) {
88 $request = $this->getRequest();
90 $request = $this->mOverrideRequest
;
92 $this->mRequest
= $request;
94 $this->mType
= $request->getText( 'type' );
95 $this->mUsername
= $request->getText( 'wpName' );
96 $this->mPassword
= $request->getText( 'wpPassword' );
97 $this->mRetype
= $request->getText( 'wpRetype' );
98 $this->mDomain
= $request->getText( 'wpDomain' );
99 $this->mReason
= $request->getText( 'wpReason' );
100 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
101 $this->mPosted
= $request->wasPosted();
102 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
104 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' ) && !$this->mCreateaccountMail
;
105 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
106 $this->mAction
= $request->getVal( 'action' );
107 $this->mRemember
= $request->getCheck( 'wpRemember' );
108 $this->mFromHTTP
= $request->getBool( 'fromhttp', false );
109 $this->mStickHTTPS
= ( !$this->mFromHTTP
&& $request->detectProtocol() === 'https' ) ||
$request->getBool( 'wpForceHttps', false );
110 $this->mLanguage
= $request->getText( 'uselang' );
111 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
112 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
113 $this->mReturnTo
= $request->getVal( 'returnto', '' );
114 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
116 if ( $wgEnableEmail ) {
117 $this->mEmail
= $request->getText( 'wpEmail' );
121 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
122 $this->mRealName
= $request->getText( 'wpRealName' );
124 $this->mRealName
= '';
127 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
128 $this->mDomain
= $wgAuth->getDomain();
130 $wgAuth->setDomain( $this->mDomain
);
132 # 1. When switching accounts, it sucks to get automatically logged out
133 # 2. Do not return to PasswordReset after a successful password change
134 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
135 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
136 if ( is_object( $returnToTitle ) && (
137 $returnToTitle->isSpecial( 'Userlogout' )
138 ||
$returnToTitle->isSpecial( 'PasswordReset' ) ) ) {
139 $this->mReturnTo
= '';
140 $this->mReturnToQuery
= '';
144 function getDescription() {
145 if ( $this->mType
=== 'signup' ) {
146 return $this->msg( 'createaccount' )->text();
148 return $this->msg( 'login' )->text();
153 * @param $subPage string|null
155 public function execute( $subPage ) {
156 if ( session_id() == '' ) {
162 // Check for [[Special:Userlogin/signup]]. This affects form display and
164 if ( $subPage == 'signup' ) {
165 $this->mType
= 'signup';
169 // If logging in and not on HTTPS, either redirect to it or offer a link.
170 global $wgSecureLogin;
171 if ( WebRequest
::detectProtocol() !== 'https' ) {
172 $title = $this->getFullTitle();
174 'returnto' => $this->mReturnTo
,
175 'returntoquery' => $this->mReturnToQuery
,
177 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
178 if ( $wgSecureLogin && wfCanIPUseHTTPS( $this->getRequest()->getIP() ) ) {
179 $url = wfAppendQuery( $url, 'fromhttp=1' );
180 $this->getOutput()->redirect( $url );
181 // Since we only do this redir to change proto, always vary
182 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
185 // A wiki without HTTPS login support should set $wgServer to
186 // http://somehost, in which case the secure URL generated
187 // above won't actually start with https://
188 if ( substr( $url, 0, 8 ) === 'https://' ) {
189 $this->mSecureLoginUrl
= $url;
194 if ( !is_null( $this->mCookieCheck
) ) {
195 $this->onCookieRedirectCheck( $this->mCookieCheck
);
197 } elseif ( $this->mPosted
) {
198 if ( $this->mCreateaccount
) {
199 $this->addNewAccount();
201 } elseif ( $this->mCreateaccountMail
) {
202 $this->addNewAccountMailPassword();
204 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
205 $this->processLogin();
209 $this->mainLoginForm( '' );
215 function addNewAccountMailPassword() {
216 if ( $this->mEmail
== '' ) {
217 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
221 $status = $this->addNewaccountInternal();
222 if ( !$status->isGood() ) {
223 $error = $this->getOutput()->parse( $status->getWikiText() );
224 $this->mainLoginForm( $error );
228 $u = $status->getValue();
230 // Wipe the initial password and mail a temporary one
231 $u->setPassword( null );
233 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
235 wfRunHooks( 'AddNewAccount', array( $u, true ) );
236 $u->addNewUserLogEntry( 'byemail', $this->mReason
);
238 $out = $this->getOutput();
239 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
241 if ( !$result->isGood() ) {
242 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
244 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
245 $this->executeReturnTo( 'success' );
253 function addNewAccount() {
254 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
256 # Create the account and abort if there's a problem doing so
257 $status = $this->addNewAccountInternal();
258 if ( !$status->isGood() ) {
259 $error = $this->getOutput()->parse( $status->getWikiText() );
260 $this->mainLoginForm( $error );
264 $u = $status->getValue();
266 # Only save preferences if the user is not creating an account for someone else.
267 if ( $this->getUser()->isAnon() ) {
268 # If we showed up language selection links, and one was in use, be
269 # smart (and sensible) and save that language as the user's preference
270 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
271 $u->setOption( 'language', $this->mLanguage
);
274 # Otherwise the user's language preference defaults to $wgContLang,
275 # but it may be better to set it to their preferred $wgContLang variant,
276 # based on browser preferences or URL parameters.
277 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
279 if ( $wgContLang->hasVariants() ) {
280 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
284 $out = $this->getOutput();
286 # Send out an email authentication message if needed
287 if ( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
288 $status = $u->sendConfirmationMail();
289 if ( $status->isGood() ) {
290 $out->addWikiMsg( 'confirmemail_oncreate' );
292 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
296 # Save settings (including confirmation token)
299 # If not logged in, assume the new account as the current one and set
300 # session cookies then show a "welcome" message or a "need cookies"
302 if ( $this->getUser()->isAnon() ) {
305 // This should set it for OutputPage and the Skin
306 // which is needed or the personal links will be
308 $this->getContext()->setUser( $u );
309 wfRunHooks( 'AddNewAccount', array( $u, false ) );
310 $u->addNewUserLogEntry( 'create' );
311 if ( $this->hasSessionCookie() ) {
312 $this->successfulCreation();
314 $this->cookieRedirectCheck( 'new' );
317 # Confirm that the account was created
318 $out->setPageTitle( $this->msg( 'accountcreated' ) );
319 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
320 $out->addReturnTo( $this->getTitle() );
321 wfRunHooks( 'AddNewAccount', array( $u, false ) );
322 $u->addNewUserLogEntry( 'create2', $this->mReason
);
328 * Make a new user account using the loaded data.
330 * @throws PermissionsError|ReadOnlyError
333 public function addNewAccountInternal() {
334 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
335 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
337 // If the user passes an invalid domain, something is fishy
338 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
339 return Status
::newFatal( 'wrongpassword' );
342 // If we are not allowing users to login locally, we should be checking
343 // to see if the user is actually able to authenticate to the authenti-
344 // cation server before they create an account (otherwise, they can
345 // create a local account and login as any domain user). We only need
346 // to check this for domains that aren't local.
347 if ( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
349 !$wgAuth->canCreateAccounts() &&
351 !$wgAuth->userExists( $this->mUsername
) ||
352 !$wgAuth->authenticate( $this->mUsername
, $this->mPassword
)
355 return Status
::newFatal( 'wrongpassword' );
359 if ( wfReadOnly() ) {
360 throw new ReadOnlyError
;
363 # Request forgery checks.
364 if ( !self
::getCreateaccountToken() ) {
365 self
::setCreateaccountToken();
366 return Status
::newFatal( 'nocookiesfornew' );
369 # The user didn't pass a createaccount token
370 if ( !$this->mToken
) {
371 return Status
::newFatal( 'sessionfailure' );
374 # Validate the createaccount token
375 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
376 return Status
::newFatal( 'sessionfailure' );
380 $currentUser = $this->getUser();
381 $creationBlock = $currentUser->isBlockedFromCreateAccount();
382 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
383 throw new PermissionsError( 'createaccount' );
384 } elseif ( $creationBlock instanceof Block
) {
385 // Throws an ErrorPageError.
386 $this->userBlockedMessage( $creationBlock );
387 // This should never be reached.
391 # Include checks that will include GlobalBlocking (Bug 38333)
392 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'createaccount', $currentUser, true );
393 if ( count( $permErrors ) ) {
394 throw new PermissionsError( 'createaccount', $permErrors );
397 $ip = $this->getRequest()->getIP();
398 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
399 return Status
::newFatal( 'sorbs_create_account_reason' );
402 # Now create a dummy user ($u) and check if it is valid
403 $name = trim( $this->mUsername
);
404 $u = User
::newFromName( $name, 'creatable' );
405 if ( !is_object( $u ) ) {
406 return Status
::newFatal( 'noname' );
407 } elseif ( 0 != $u->idForName() ) {
408 return Status
::newFatal( 'userexists' );
411 if ( $this->mCreateaccountMail
) {
412 # do not force a password for account creation by email
413 # set invalid password, it will be replaced later by a random generated password
414 $this->mPassword
= null;
416 if ( $this->mPassword
!== $this->mRetype
) {
417 return Status
::newFatal( 'badretype' );
420 # check for minimal password length
421 $valid = $u->getPasswordValidity( $this->mPassword
);
422 if ( $valid !== true ) {
423 if ( !is_array( $valid ) ) {
424 $valid = array( $valid, $wgMinimalPasswordLength );
426 return call_user_func_array( 'Status::newFatal', $valid );
430 # if you need a confirmed email address to edit, then obviously you
431 # need an email address.
432 if ( $wgEmailConfirmToEdit && strval( $this->mEmail
) === '' ) {
433 return Status
::newFatal( 'noemailtitle' );
436 if ( strval( $this->mEmail
) !== '' && !Sanitizer
::validateEmail( $this->mEmail
) ) {
437 return Status
::newFatal( 'invalidemailaddress' );
440 # Set some additional data so the AbortNewAccount hook can be used for
441 # more than just username validation
442 $u->setEmail( $this->mEmail
);
443 $u->setRealName( $this->mRealName
);
446 if ( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
447 // Hook point to add extra creation throttles and blocks
448 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
449 return Status
::newFatal( new RawMessage( $abortError ) );
452 // Hook point to check for exempt from account creation throttle
453 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
454 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
456 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
457 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
458 $value = $wgMemc->get( $key );
460 $wgMemc->set( $key, 0, 86400 );
462 if ( $value >= $wgAccountCreationThrottle ) {
463 return Status
::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
465 $wgMemc->incr( $key );
469 if ( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
470 return Status
::newFatal( 'externaldberror' );
473 self
::clearCreateaccountToken();
474 return $this->initUser( $u, false );
478 * Actually add a user to the database.
479 * Give it a User object that has been initialised with a name.
481 * @param $u User object.
482 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
483 * @return Status object, with the User object in the value member on success
486 function initUser( $u, $autocreate ) {
489 $status = $u->addToDatabase();
490 if ( !$status->isOK() ) {
494 if ( $wgAuth->allowPasswordChange() ) {
495 $u->setPassword( $this->mPassword
);
498 $u->setEmail( $this->mEmail
);
499 $u->setRealName( $this->mRealName
);
502 $wgAuth->initUser( $u, $autocreate );
504 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
508 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
510 return Status
::newGood( $u );
514 * Internally authenticate the login request.
516 * This may create a local account as a side effect if the
517 * authentication plugin allows transparent local account
521 public function authenticateUserData() {
522 global $wgUser, $wgAuth;
526 if ( $this->mUsername
== '' ) {
527 return self
::NO_NAME
;
530 // We require a login token to prevent login CSRF
531 // Handle part of this before incrementing the throttle so
532 // token-less login attempts don't count towards the throttle
533 // but wrong-token attempts do.
535 // If the user doesn't have a login token yet, set one.
536 if ( !self
::getLoginToken() ) {
537 self
::setLoginToken();
538 return self
::NEED_TOKEN
;
540 // If the user didn't pass a login token, tell them we need one
541 if ( !$this->mToken
) {
542 return self
::NEED_TOKEN
;
545 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
546 if ( $throttleCount === true ) {
547 return self
::THROTTLED
;
550 // Validate the login token
551 if ( $this->mToken
!== self
::getLoginToken() ) {
552 return self
::WRONG_TOKEN
;
555 // Load the current user now, and check to see if we're logging in as
556 // the same name. This is necessary because loading the current user
557 // (say by calling getName()) calls the UserLoadFromSession hook, which
558 // potentially creates the user in the database. Until we load $wgUser,
559 // checking for user existence using User::newFromName($name)->getId() below
560 // will effectively be using stale data.
561 if ( $this->getUser()->getName() === $this->mUsername
) {
562 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
563 return self
::SUCCESS
;
566 $u = User
::newFromName( $this->mUsername
);
567 if ( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
568 return self
::ILLEGAL
;
571 $isAutoCreated = false;
572 if ( $u->getID() == 0 ) {
573 $status = $this->attemptAutoCreate( $u );
574 if ( $status !== self
::SUCCESS
) {
577 $isAutoCreated = true;
583 // Give general extensions, such as a captcha, a chance to abort logins
584 $abort = self
::ABORTED
;
586 if ( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$msg ) ) ) {
587 $this->mAbortLoginErrorMsg
= $msg;
591 global $wgBlockDisablesLogin;
592 if ( !$u->checkPassword( $this->mPassword
) ) {
593 if ( $u->checkTemporaryPassword( $this->mPassword
) ) {
594 // The e-mailed temporary password should not be used for actu-
595 // al logins; that's a very sloppy habit, and insecure if an
596 // attacker has a few seconds to click "search" on someone's o-
599 // Allow it to be used only to reset the password a single time
600 // to a new value, which won't be in the user's e-mail ar-
603 // For backwards compatibility, we'll still recognize it at the
604 // login form to minimize surprises for people who have been
605 // logging in with a temporary password for some time.
607 // As a side-effect, we can authenticate the user's e-mail ad-
608 // dress if it's not already done, since the temporary password
609 // was sent via e-mail.
610 if ( !$u->isEmailConfirmed() ) {
615 // At this point we just return an appropriate code/ indicating
616 // that the UI should show a password reset form; bot inter-
617 // faces etc will probably just fail cleanly here.
618 $retval = self
::RESET_PASS
;
620 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
622 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
623 // If we've enabled it, make it so that a blocked user cannot login
624 $retval = self
::USER_BLOCKED
;
626 $wgAuth->updateUser( $u );
628 // This should set it for OutputPage and the Skin
629 // which is needed or the personal links will be
631 $this->getContext()->setUser( $u );
633 // Please reset throttle for successful logins, thanks!
634 if ( $throttleCount ) {
635 self
::clearLoginThrottle( $this->mUsername
);
638 if ( $isAutoCreated ) {
639 // Must be run after $wgUser is set, for correct new user log
640 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
643 $retval = self
::SUCCESS
;
645 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
650 * Increment the login attempt throttle hit count for the (username,current IP)
651 * tuple unless the throttle was already reached.
652 * @param string $username The user name
653 * @return Bool|Integer The integer hit count or True if it is already at the limit
655 public static function incLoginThrottle( $username ) {
656 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
657 $username = trim( $username ); // sanity
660 if ( is_array( $wgPasswordAttemptThrottle ) ) {
661 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
662 $count = $wgPasswordAttemptThrottle['count'];
663 $period = $wgPasswordAttemptThrottle['seconds'];
665 $throttleCount = $wgMemc->get( $throttleKey );
666 if ( !$throttleCount ) {
667 $wgMemc->add( $throttleKey, 1, $period ); // start counter
668 } elseif ( $throttleCount < $count ) {
669 $wgMemc->incr( $throttleKey );
670 } elseif ( $throttleCount >= $count ) {
675 return $throttleCount;
679 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
680 * @param string $username The user name
683 public static function clearLoginThrottle( $username ) {
684 global $wgMemc, $wgRequest;
685 $username = trim( $username ); // sanity
687 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
688 $wgMemc->delete( $throttleKey );
692 * Attempt to automatically create a user on login. Only succeeds if there
693 * is an external authentication method which allows it.
697 * @return integer Status code
699 function attemptAutoCreate( $user ) {
702 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
703 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
704 return self
::CREATE_BLOCKED
;
706 if ( !$wgAuth->autoCreate() ) {
707 return self
::NOT_EXISTS
;
709 if ( !$wgAuth->userExists( $user->getName() ) ) {
710 wfDebug( __METHOD__
. ": user does not exist\n" );
711 return self
::NOT_EXISTS
;
713 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
714 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
715 return self
::WRONG_PLUGIN_PASS
;
719 if ( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
720 // Hook point to add extra creation throttles and blocks
721 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
722 $this->mAbortLoginErrorMsg
= $abortError;
723 return self
::ABORTED
;
726 wfDebug( __METHOD__
. ": creating account\n" );
727 $status = $this->initUser( $user, true );
729 if ( !$status->isOK() ) {
730 $errors = $status->getErrorsByType( 'error' );
731 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
732 return self
::ABORTED
;
735 return self
::SUCCESS
;
738 function processLogin() {
739 global $wgMemc, $wgLang, $wgSecureLogin, $wgPasswordAttemptThrottle;
741 switch ( $this->authenticateUserData() ) {
743 # We've verified now, update the real record
744 $user = $this->getUser();
745 if ( (bool)$this->mRemember
!= $user->getBoolOption( 'rememberpassword' ) ) {
746 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
747 $user->saveSettings();
749 $user->invalidateCache();
752 if ( $user->requiresHTTPS() ) {
753 $this->mStickHTTPS
= true;
756 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
757 $user->setCookies( null, false );
761 self
::clearLoginToken();
763 // Reset the throttle
764 $request = $this->getRequest();
765 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
766 $wgMemc->delete( $key );
768 if ( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
769 /* Replace the language object to provide user interface in
770 * correct language immediately on this first page load.
772 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
773 $userLang = Language
::factory( $code );
775 $this->getContext()->setLanguage( $userLang );
776 // Reset SessionID on Successful login (bug 40995)
777 $this->renewSessionId();
778 $this->successfulLogin();
780 $this->cookieRedirectCheck( 'login' );
784 case self
::NEED_TOKEN
:
785 $error = $this->mAbortLoginErrorMsg ?
: 'nocookiesforlogin';
786 $this->mainLoginForm( $this->msg( $error )->parse() );
788 case self
::WRONG_TOKEN
:
789 $error = $this->mAbortLoginErrorMsg ?
: 'sessionfailure';
790 $this->mainLoginForm( $this->msg( $error )->text() );
794 $error = $this->mAbortLoginErrorMsg ?
: 'noname';
795 $this->mainLoginForm( $this->msg( $error )->text() );
797 case self
::WRONG_PLUGIN_PASS
:
798 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
799 $this->mainLoginForm( $this->msg( $error )->text() );
801 case self
::NOT_EXISTS
:
802 if ( $this->getUser()->isAllowed( 'createaccount' ) ) {
803 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchuser';
804 $this->mainLoginForm( $this->msg( $error,
805 wfEscapeWikiText( $this->mUsername
) )->parse() );
807 $error = $this->mAbortLoginErrorMsg ?
: 'nosuchusershort';
808 $this->mainLoginForm( $this->msg( $error,
809 wfEscapeWikiText( $this->mUsername
) )->text() );
812 case self
::WRONG_PASS
:
813 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpassword';
814 $this->mainLoginForm( $this->msg( $error )->text() );
816 case self
::EMPTY_PASS
:
817 $error = $this->mAbortLoginErrorMsg ?
: 'wrongpasswordempty';
818 $this->mainLoginForm( $this->msg( $error )->text() );
820 case self
::RESET_PASS
:
821 $error = $this->mAbortLoginErrorMsg ?
: 'resetpass_announce';
822 $this->resetLoginForm( $this->msg( $error )->text() );
824 case self
::CREATE_BLOCKED
:
825 $this->userBlockedMessage( $this->getUser()->isBlockedFromCreateAccount() );
827 case self
::THROTTLED
:
828 $error = $this->mAbortLoginErrorMsg ?
: 'login-throttled';
829 $this->mainLoginForm( $this->msg( $error )
830 ->params ( $this->getLanguage()->formatDuration( $wgPasswordAttemptThrottle['seconds'] ) )
834 case self
::USER_BLOCKED
:
835 $error = $this->mAbortLoginErrorMsg ?
: 'login-userblocked';
836 $this->mainLoginForm( $this->msg( $error, $this->mUsername
)->escaped() );
839 $error = $this->mAbortLoginErrorMsg ?
: 'login-abort-generic';
840 $this->mainLoginForm( $this->msg( $error )->text() );
843 throw new MWException( 'Unhandled case value' );
848 * @param $error string
850 function resetLoginForm( $error ) {
851 $this->getOutput()->addHTML( Xml
::element( 'p', array( 'class' => 'error' ), $error ) );
852 $reset = new SpecialChangePassword();
853 $reset->setContext( $this->getContext() );
854 $reset->execute( null );
858 * @param $u User object
859 * @param $throttle Boolean
860 * @param string $emailTitle message name of email title
861 * @param string $emailText message name of email text
862 * @return Status object
864 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
865 global $wgCanonicalServer, $wgScript, $wgNewPasswordExpiry;
867 if ( $u->getEmail() == '' ) {
868 return Status
::newFatal( 'noemail', $u->getName() );
870 $ip = $this->getRequest()->getIP();
872 return Status
::newFatal( 'badipaddress' );
875 $currentUser = $this->getUser();
876 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
878 $np = $u->randomPassword();
879 $u->setNewpassword( $np, $throttle );
881 $userLanguage = $u->getOption( 'language' );
882 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $wgCanonicalServer . $wgScript . '>',
883 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
884 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
890 * Run any hooks registered for logins, then HTTP redirect to
891 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
892 * nice message here, but that's really not as useful as just being sent to
893 * wherever you logged in from. It should be clear that the action was
894 * successful, given the lack of error messages plus the appearance of your
895 * name in the upper right.
899 function successfulLogin() {
900 # Run any hooks; display injected HTML if any, else redirect
901 $currentUser = $this->getUser();
903 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
905 if ( $injected_html !== '' ) {
906 $this->displaySuccessfulAction( $this->msg( 'loginsuccesstitle' ),
907 'loginsuccess', $injected_html );
909 $this->executeReturnTo( 'successredirect' );
914 * Run any hooks registered for logins, then display a message welcoming
919 function successfulCreation() {
920 # Run any hooks; display injected HTML
921 $currentUser = $this->getUser();
923 $welcome_creation_msg = 'welcomecreation-msg';
925 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
928 * Let any extensions change what message is shown.
929 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
932 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
934 $this->displaySuccessfulAction( $this->msg( 'welcomeuser', $this->getUser()->getName() ),
935 $welcome_creation_msg, $injected_html );
939 * Display an "successful action" page.
941 * @param string|Message $title page's title
942 * @param $msgname string
943 * @param $injected_html string
945 private function displaySuccessfulAction( $title, $msgname, $injected_html ) {
946 $out = $this->getOutput();
947 $out->setPageTitle( $title );
949 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
952 $out->addHTML( $injected_html );
954 $this->executeReturnTo( 'success' );
958 * Output a message that informs the user that they cannot create an account because
959 * there is a block on them or their IP which prevents account creation. Note that
960 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
961 * setting on blocks (bug 13611).
962 * @param $block Block the block causing this error
963 * @throws ErrorPageError
965 function userBlockedMessage( Block
$block ) {
966 # Let's be nice about this, it's likely that this feature will be used
967 # for blocking large numbers of innocent people, e.g. range blocks on
968 # schools. Don't blame it on the user. There's a small chance that it
969 # really is the user's fault, i.e. the username is blocked and they
970 # haven't bothered to log out before trying to create an account to
971 # evade it, but we'll leave that to their guilty conscience to figure
973 throw new ErrorPageError(
974 'cantcreateaccounttitle',
975 'cantcreateaccount-text',
978 $block->mReason ?
$block->mReason
: $this->msg( 'blockednoreason' )->text(),
985 * Add a "return to" link or redirect to it.
986 * Extensions can use this to reuse the "return to" logic after
987 * inject steps (such as redirection) into the login process.
989 * @param $type string, one of the following:
990 * - error: display a return to link ignoring $wgRedirectOnLogin
991 * - success: display a return to link using $wgRedirectOnLogin if needed
992 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
993 * @param string $returnTo
994 * @param array|string $returnToQuery
995 * @param bool $stickHTTPs Keep redirect link on HTTPs
998 public function showReturnToPage(
999 $type, $returnTo = '', $returnToQuery = '', $stickHTTPs = false
1001 $this->mReturnTo
= $returnTo;
1002 $this->mReturnToQuery
= $returnToQuery;
1003 $this->mStickHTTPS
= $stickHTTPs;
1004 $this->executeReturnTo( $type );
1008 * Add a "return to" link or redirect to it.
1010 * @param $type string, one of the following:
1011 * - error: display a return to link ignoring $wgRedirectOnLogin
1012 * - success: display a return to link using $wgRedirectOnLogin if needed
1013 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1015 private function executeReturnTo( $type ) {
1016 global $wgRedirectOnLogin, $wgSecureLogin;
1018 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
1019 $returnTo = $wgRedirectOnLogin;
1020 $returnToQuery = array();
1022 $returnTo = $this->mReturnTo
;
1023 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
1026 $returnToTitle = Title
::newFromText( $returnTo );
1027 if ( !$returnToTitle ) {
1028 $returnToTitle = Title
::newMainPage();
1031 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1032 $options = array( 'http' );
1033 $proto = PROTO_HTTP
;
1034 } elseif ( $wgSecureLogin ) {
1035 $options = array( 'https' );
1036 $proto = PROTO_HTTPS
;
1039 $proto = PROTO_RELATIVE
;
1042 if ( $type == 'successredirect' ) {
1043 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1044 $this->getOutput()->redirect( $redirectUrl );
1046 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1053 function mainLoginForm( $msg, $msgtype = 'error' ) {
1054 global $wgEnableEmail, $wgEnableUserEmail;
1055 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1056 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
1057 global $wgSecureLogin, $wgPasswordResetRoutes;
1059 $titleObj = $this->getTitle();
1060 $user = $this->getUser();
1061 $out = $this->getOutput();
1063 if ( $this->mType
== 'signup' ) {
1064 // Block signup here if in readonly. Keeps user from
1065 // going through the process (filling out data, etc)
1066 // and being informed later.
1067 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1068 if ( count( $permErrors ) ) {
1069 throw new PermissionsError( 'createaccount', $permErrors );
1070 } elseif ( $user->isBlockedFromCreateAccount() ) {
1071 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1073 } elseif ( wfReadOnly() ) {
1074 throw new ReadOnlyError
;
1078 // Pre-fill username (if not creating an account, bug 44775).
1079 if ( $this->mUsername
== '' && $this->mType
!= 'signup' ) {
1080 if ( $user->isLoggedIn() ) {
1081 $this->mUsername
= $user->getName();
1083 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1087 if ( $this->mType
== 'signup' ) {
1088 $template = new UsercreateTemplate();
1090 $out->addModuleStyles( array(
1092 'mediawiki.special.createaccount'
1094 // XXX hack pending RL or JS parse() support for complex content messages
1095 // https://bugzilla.wikimedia.org/show_bug.cgi?id=25349
1096 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
1097 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
1098 $out->addModules( array(
1099 'mediawiki.special.createaccount.js'
1101 // Must match number of benefits defined in messages
1102 $template->set( 'benefitCount', 3 );
1104 $q = 'action=submitlogin&type=signup';
1105 $linkq = 'type=login';
1107 $template = new UserloginTemplate();
1109 $out->addModuleStyles( array(
1111 'mediawiki.special.userlogin'
1114 $q = 'action=submitlogin&type=login';
1115 $linkq = 'type=signup';
1118 if ( $this->mReturnTo
!== '' ) {
1119 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1120 if ( $this->mReturnToQuery
!== '' ) {
1121 $returnto .= '&returntoquery=' .
1122 wfUrlencode( $this->mReturnToQuery
);
1125 $linkq .= $returnto;
1128 # Don't show a "create account" link if the user can't.
1129 if ( $this->showCreateOrLoginLink( $user ) ) {
1130 # Pass any language selection on to the mode switch link
1131 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
1132 $linkq .= '&uselang=' . $this->mLanguage
;
1134 // Supply URL, login template creates the button.
1135 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1137 $template->set( 'link', '' );
1140 $resetLink = $this->mType
== 'signup'
1142 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1144 $template->set( 'header', '' );
1145 $template->set( 'skin', $this->getSkin() );
1146 $template->set( 'name', $this->mUsername
);
1147 $template->set( 'password', $this->mPassword
);
1148 $template->set( 'retype', $this->mRetype
);
1149 $template->set( 'createemailset', $this->mCreateaccountMail
);
1150 $template->set( 'email', $this->mEmail
);
1151 $template->set( 'realname', $this->mRealName
);
1152 $template->set( 'domain', $this->mDomain
);
1153 $template->set( 'reason', $this->mReason
);
1155 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1156 $template->set( 'message', $msg );
1157 $template->set( 'messagetype', $msgtype );
1158 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1159 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1160 $template->set( 'useemail', $wgEnableEmail );
1161 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1162 $template->set( 'emailothers', $wgEnableUserEmail );
1163 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1164 $template->set( 'resetlink', $resetLink );
1165 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1166 $template->set( 'usereason', $user->isLoggedIn() );
1167 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1168 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1169 $template->set( 'stickhttps', (int)$this->mStickHTTPS
);
1171 if ( $this->mType
=== 'signup' && $user->isLoggedIn() ) {
1172 $template->set( 'createAnother', true );
1174 $template->set( 'createAnother', false );
1177 if ( $this->mType
== 'signup' ) {
1178 if ( !self
::getCreateaccountToken() ) {
1179 self
::setCreateaccountToken();
1181 $template->set( 'token', self
::getCreateaccountToken() );
1183 if ( !self
::getLoginToken() ) {
1184 self
::setLoginToken();
1186 $template->set( 'token', self
::getLoginToken() );
1189 # Prepare language selection links as needed
1190 if ( $wgLoginLanguageSelector ) {
1191 $template->set( 'languages', $this->makeLanguageSelector() );
1192 if ( $this->mLanguage
) {
1193 $template->set( 'uselang', $this->mLanguage
);
1197 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl
);
1198 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1199 // Ditto for signupend. New forms use neither.
1200 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1201 $loginendHTTPS = $this->msg( 'loginend-https' );
1202 $signupendHTTPS = $this->msg( 'signupend-https' );
1203 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1204 $template->set( 'loginend', $loginendHTTPS->parse() );
1206 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1208 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1209 $template->set( 'signupend', $signupendHTTPS->parse() );
1211 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1214 // Give authentication and captcha plugins a chance to modify the form
1215 $wgAuth->modifyUITemplate( $template, $this->mType
);
1216 if ( $this->mType
== 'signup' ) {
1217 wfRunHooks( 'UserCreateForm', array( &$template ) );
1219 wfRunHooks( 'UserLoginForm', array( &$template ) );
1222 $out->disallowUserJs(); // just in case...
1223 $out->addTemplate( $template );
1227 * Whether the login/create account form should display a link to the
1228 * other form (in addition to whatever the skin provides).
1233 private function showCreateOrLoginLink( &$user ) {
1234 if ( $user->isLoggedIn() ) {
1236 } elseif ( $this->mType
== 'signup' ) {
1238 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1246 * Check if a session cookie is present.
1248 * This will not pick up a cookie set during _this_ request, but is meant
1249 * to ensure that the client is returning the cookie which was set on a
1250 * previous pass through the system.
1255 function hasSessionCookie() {
1256 global $wgDisableCookieCheck;
1257 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1261 * Get the login token from the current session
1264 public static function getLoginToken() {
1266 return $wgRequest->getSessionData( 'wsLoginToken' );
1270 * Randomly generate a new login token and attach it to the current session
1272 public static function setLoginToken() {
1274 // Generate a token directly instead of using $user->editToken()
1275 // because the latter reuses $_SESSION['wsEditToken']
1276 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1280 * Remove any login token attached to the current session
1282 public static function clearLoginToken() {
1284 $wgRequest->setSessionData( 'wsLoginToken', null );
1288 * Get the createaccount token from the current session
1291 public static function getCreateaccountToken() {
1293 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1297 * Randomly generate a new createaccount token and attach it to the current session
1299 public static function setCreateaccountToken() {
1301 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1305 * Remove any createaccount token attached to the current session
1307 public static function clearCreateaccountToken() {
1309 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1313 * Renew the user's session id, using strong entropy
1315 private function renewSessionId() {
1316 global $wgSecureLogin, $wgCookieSecure;
1317 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1318 $wgCookieSecure = false;
1327 function cookieRedirectCheck( $type ) {
1328 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1329 $query = array( 'wpCookieCheck' => $type );
1330 if ( $this->mReturnTo
!== '' ) {
1331 $query['returnto'] = $this->mReturnTo
;
1332 $query['returntoquery'] = $this->mReturnToQuery
;
1334 $check = $titleObj->getFullURL( $query );
1336 $this->getOutput()->redirect( $check );
1342 function onCookieRedirectCheck( $type ) {
1343 if ( !$this->hasSessionCookie() ) {
1344 if ( $type == 'new' ) {
1345 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1346 } elseif ( $type == 'login' ) {
1347 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1350 $this->mainLoginForm( $this->msg( 'error' )->text() );
1353 $this->successfulLogin();
1358 * Produce a bar of links which allow the user to select another language
1359 * during login/registration but retain "returnto"
1363 function makeLanguageSelector() {
1364 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1365 if ( !$msg->isBlank() ) {
1366 $langs = explode( "\n", $msg->text() );
1368 foreach ( $langs as $lang ) {
1369 $lang = trim( $lang, '* ' );
1370 $parts = explode( '|', $lang );
1371 if ( count( $parts ) >= 2 ) {
1372 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1375 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1376 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1383 * Create a language selector link for a particular language
1384 * Links back to this page preserving type and returnto
1386 * @param string $text Link text
1387 * @param string $lang Language code
1390 function makeLanguageSelectorLink( $text, $lang ) {
1391 if ( $this->getLanguage()->getCode() == $lang ) {
1392 // no link for currently used language
1393 return htmlspecialchars( $text );
1395 $query = array( 'uselang' => $lang );
1396 if ( $this->mType
== 'signup' ) {
1397 $query['type'] = 'signup';
1399 if ( $this->mReturnTo
!== '' ) {
1400 $query['returnto'] = $this->mReturnTo
;
1401 $query['returntoquery'] = $this->mReturnToQuery
;
1405 $targetLanguage = Language
::factory( $lang );
1406 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1408 return Linker
::linkKnown(
1410 htmlspecialchars( $text ),
1416 protected function getGroupName() {