a86c3567f2b6dd8061536aa8db387e08e1bd4ab2
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
= '';
145 $this->mShowVForm
= $this->shouldShowVForm();
148 function getDescription() {
149 if ( !$this->getUser()->isAllowed( 'createaccount' ) ) {
150 return $this->msg( 'userloginnocreate' )->text();
152 if ( $this->mShowVForm
) {
153 if ( $this->mType
=== 'signup' ) {
154 return $this->msg( 'createaccount' )->text();
156 return $this->msg( 'login' )->text();
159 return $this->msg( 'userlogin' )->text();
163 public function execute( $par ) {
164 if ( session_id() == '' ) {
171 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
172 $this->mType
= 'signup';
175 // If logging in and not on HTTPS, either redirect to it or offer a link.
176 global $wgSecureLogin;
178 $this->mType
!== 'signup' &&
179 WebRequest
::detectProtocol() !== 'https'
181 $title = $this->getFullTitle();
183 'returnto' => $this->mReturnTo
,
184 'returntoquery' => $this->mReturnToQuery
,
185 'wpStickHTTPS' => $this->mStickHTTPS
187 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
188 if ( $wgSecureLogin ) {
189 $this->getOutput()->redirect( $url );
192 // A wiki without HTTPS login support should set $wgServer to
193 // http://somehost, in which case the secure URL generated
194 // above won't actually start with https://
195 if ( substr( $url, 0, 8 ) === 'https://' ) {
196 $this->mSecureLoginUrl
= $url;
201 if ( !is_null( $this->mCookieCheck
) ) {
202 $this->onCookieRedirectCheck( $this->mCookieCheck
);
204 } elseif( $this->mPosted
) {
205 if( $this->mCreateaccount
) {
206 $this->addNewAccount();
208 } elseif ( $this->mCreateaccountMail
) {
209 $this->addNewAccountMailPassword();
211 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
212 $this->processLogin();
216 $this->mainLoginForm( '' );
222 function addNewAccountMailPassword() {
223 if ( $this->mEmail
== '' ) {
224 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
228 $status = $this->addNewaccountInternal();
229 if( !$status->isGood() ) {
230 $error = $this->getOutput()->parse( $status->getWikiText() );
231 $this->mainLoginForm( $error );
235 $u = $status->getValue();
237 // Wipe the initial password and mail a temporary one
238 $u->setPassword( null );
240 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
242 wfRunHooks( 'AddNewAccount', array( $u, true ) );
243 $u->addNewUserLogEntry( 'byemail', $this->mReason
);
245 $out = $this->getOutput();
246 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
248 if( !$result->isGood() ) {
249 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
251 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
252 $this->executeReturnTo( 'success' );
260 function addNewAccount() {
261 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
263 # Create the account and abort if there's a problem doing so
264 $status = $this->addNewAccountInternal();
265 if( !$status->isGood() ) {
266 $error = $this->getOutput()->parse( $status->getWikiText() );
267 $this->mainLoginForm( $error );
271 $u = $status->getValue();
273 # Only save preferences if the user is not creating an account for someone else.
274 if ( $this->getUser()->isAnon() ) {
275 # If we showed up language selection links, and one was in use, be
276 # smart (and sensible) and save that language as the user's preference
277 if( $wgLoginLanguageSelector && $this->mLanguage
) {
278 $u->setOption( 'language', $this->mLanguage
);
281 # Otherwise the user's language preference defaults to $wgContLang,
282 # but it may be better to set it to their preferred $wgContLang variant,
283 # based on browser preferences or URL parameters.
284 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
286 if ( $wgContLang->hasVariants() ) {
287 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
291 $out = $this->getOutput();
293 # Send out an email authentication message if needed
294 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
295 $status = $u->sendConfirmationMail();
296 if( $status->isGood() ) {
297 $out->addWikiMsg( 'confirmemail_oncreate' );
299 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
303 # Save settings (including confirmation token)
306 # If not logged in, assume the new account as the current one and set
307 # session cookies then show a "welcome" message or a "need cookies"
309 if( $this->getUser()->isAnon() ) {
312 // This should set it for OutputPage and the Skin
313 // which is needed or the personal links will be
315 $this->getContext()->setUser( $u );
316 wfRunHooks( 'AddNewAccount', array( $u, false ) );
317 $u->addNewUserLogEntry( 'create' );
318 if( $this->hasSessionCookie() ) {
319 $this->successfulCreation();
321 $this->cookieRedirectCheck( 'new' );
324 # Confirm that the account was created
325 $out->setPageTitle( $this->msg( 'accountcreated' ) );
326 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
327 $out->addReturnTo( $this->getTitle() );
328 wfRunHooks( 'AddNewAccount', array( $u, false ) );
329 $u->addNewUserLogEntry( 'create2', $this->mReason
);
335 * Make a new user account using the loaded data.
337 * @throws PermissionsError|ReadOnlyError
340 public function addNewAccountInternal() {
341 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
342 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
344 // If the user passes an invalid domain, something is fishy
345 if( !$wgAuth->validDomain( $this->mDomain
) ) {
346 return Status
::newFatal( 'wrongpassword' );
349 // If we are not allowing users to login locally, we should be checking
350 // to see if the user is actually able to authenticate to the authenti-
351 // cation server before they create an account (otherwise, they can
352 // create a local account and login as any domain user). We only need
353 // to check this for domains that aren't local.
354 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
356 !$wgAuth->canCreateAccounts() &&
358 !$wgAuth->userExists( $this->mUsername
) ||
359 !$wgAuth->authenticate( $this->mUsername
, $this->mPassword
)
362 return Status
::newFatal( 'wrongpassword' );
366 if ( wfReadOnly() ) {
367 throw new ReadOnlyError
;
370 # Request forgery checks.
371 if ( !self
::getCreateaccountToken() ) {
372 self
::setCreateaccountToken();
373 return Status
::newFatal( 'nocookiesfornew' );
376 # The user didn't pass a createaccount token
377 if ( !$this->mToken
) {
378 return Status
::newFatal( 'sessionfailure' );
381 # Validate the createaccount token
382 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
383 return Status
::newFatal( 'sessionfailure' );
387 $currentUser = $this->getUser();
388 $creationBlock = $currentUser->isBlockedFromCreateAccount();
389 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
390 throw new PermissionsError( 'createaccount' );
391 } elseif ( $creationBlock instanceof Block
) {
392 // Throws an ErrorPageError.
393 $this->userBlockedMessage( $creationBlock );
394 // This should never be reached.
398 # Include checks that will include GlobalBlocking (Bug 38333)
399 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'createaccount', $currentUser, true );
400 if ( count( $permErrors ) ) {
401 throw new PermissionsError( 'createaccount', $permErrors );
404 $ip = $this->getRequest()->getIP();
405 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
406 return Status
::newFatal( 'sorbs_create_account_reason' );
409 # Now create a dummy user ($u) and check if it is valid
410 $name = trim( $this->mUsername
);
411 $u = User
::newFromName( $name, 'creatable' );
412 if ( !is_object( $u ) ) {
413 return Status
::newFatal( 'noname' );
414 } elseif ( 0 != $u->idForName() ) {
415 return Status
::newFatal( 'userexists' );
418 if ( $this->mCreateaccountMail
) {
419 # do not force a password for account creation by email
420 # set invalid password, it will be replaced later by a random generated password
421 $this->mPassword
= null;
423 if ( $this->mPassword
!== $this->mRetype
) {
424 return Status
::newFatal( 'badretype' );
427 # check for minimal password length
428 $valid = $u->getPasswordValidity( $this->mPassword
);
429 if ( $valid !== true ) {
430 if ( !is_array( $valid ) ) {
431 $valid = array( $valid, $wgMinimalPasswordLength );
433 return call_user_func_array( 'Status::newFatal', $valid );
437 # if you need a confirmed email address to edit, then obviously you
438 # need an email address.
439 if ( $wgEmailConfirmToEdit && strval( $this->mEmail
) === '' ) {
440 return Status
::newFatal( 'noemailtitle' );
443 if ( strval( $this->mEmail
) !== '' && !Sanitizer
::validateEmail( $this->mEmail
) ) {
444 return Status
::newFatal( 'invalidemailaddress' );
447 # Set some additional data so the AbortNewAccount hook can be used for
448 # more than just username validation
449 $u->setEmail( $this->mEmail
);
450 $u->setRealName( $this->mRealName
);
453 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
454 // Hook point to add extra creation throttles and blocks
455 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
456 return Status
::newFatal( new RawMessage( $abortError ) );
459 // Hook point to check for exempt from account creation throttle
460 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
461 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
463 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
464 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
465 $value = $wgMemc->get( $key );
467 $wgMemc->set( $key, 0, 86400 );
469 if ( $value >= $wgAccountCreationThrottle ) {
470 return Status
::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
472 $wgMemc->incr( $key );
476 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
477 return Status
::newFatal( 'externaldberror' );
480 self
::clearCreateaccountToken();
481 return $this->initUser( $u, false );
485 * Actually add a user to the database.
486 * Give it a User object that has been initialised with a name.
488 * @param $u User object.
489 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
490 * @return Status object, with the User object in the value member on success
493 function initUser( $u, $autocreate ) {
496 $status = $u->addToDatabase();
497 if ( !$status->isOK() ) {
501 if ( $wgAuth->allowPasswordChange() ) {
502 $u->setPassword( $this->mPassword
);
505 $u->setEmail( $this->mEmail
);
506 $u->setRealName( $this->mRealName
);
509 $wgAuth->initUser( $u, $autocreate );
511 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
515 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
517 return Status
::newGood( $u );
521 * Internally authenticate the login request.
523 * This may create a local account as a side effect if the
524 * authentication plugin allows transparent local account
528 public function authenticateUserData() {
529 global $wgUser, $wgAuth;
533 if ( $this->mUsername
== '' ) {
534 return self
::NO_NAME
;
537 // We require a login token to prevent login CSRF
538 // Handle part of this before incrementing the throttle so
539 // token-less login attempts don't count towards the throttle
540 // but wrong-token attempts do.
542 // If the user doesn't have a login token yet, set one.
543 if ( !self
::getLoginToken() ) {
544 self
::setLoginToken();
545 return self
::NEED_TOKEN
;
547 // If the user didn't pass a login token, tell them we need one
548 if ( !$this->mToken
) {
549 return self
::NEED_TOKEN
;
552 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
553 if ( $throttleCount === true ) {
554 return self
::THROTTLED
;
557 // Validate the login token
558 if ( $this->mToken
!== self
::getLoginToken() ) {
559 return self
::WRONG_TOKEN
;
562 // Load the current user now, and check to see if we're logging in as
563 // the same name. This is necessary because loading the current user
564 // (say by calling getName()) calls the UserLoadFromSession hook, which
565 // potentially creates the user in the database. Until we load $wgUser,
566 // checking for user existence using User::newFromName($name)->getId() below
567 // will effectively be using stale data.
568 if ( $this->getUser()->getName() === $this->mUsername
) {
569 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
570 return self
::SUCCESS
;
573 $u = User
::newFromName( $this->mUsername
);
574 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
575 return self
::ILLEGAL
;
578 $isAutoCreated = false;
579 if ( $u->getID() == 0 ) {
580 $status = $this->attemptAutoCreate( $u );
581 if ( $status !== self
::SUCCESS
) {
584 $isAutoCreated = true;
590 // Give general extensions, such as a captcha, a chance to abort logins
591 $abort = self
::ABORTED
;
592 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
596 global $wgBlockDisablesLogin;
597 if ( !$u->checkPassword( $this->mPassword
) ) {
598 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
599 // The e-mailed temporary password should not be used for actu-
600 // al logins; that's a very sloppy habit, and insecure if an
601 // attacker has a few seconds to click "search" on someone's o-
604 // Allow it to be used only to reset the password a single time
605 // to a new value, which won't be in the user's e-mail ar-
608 // For backwards compatibility, we'll still recognize it at the
609 // login form to minimize surprises for people who have been
610 // logging in with a temporary password for some time.
612 // As a side-effect, we can authenticate the user's e-mail ad-
613 // dress if it's not already done, since the temporary password
614 // was sent via e-mail.
615 if( !$u->isEmailConfirmed() ) {
620 // At this point we just return an appropriate code/ indicating
621 // that the UI should show a password reset form; bot inter-
622 // faces etc will probably just fail cleanly here.
623 $retval = self
::RESET_PASS
;
625 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
627 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
628 // If we've enabled it, make it so that a blocked user cannot login
629 $retval = self
::USER_BLOCKED
;
631 $wgAuth->updateUser( $u );
633 // This should set it for OutputPage and the Skin
634 // which is needed or the personal links will be
636 $this->getContext()->setUser( $u );
638 // Please reset throttle for successful logins, thanks!
639 if ( $throttleCount ) {
640 self
::clearLoginThrottle( $this->mUsername
);
643 if ( $isAutoCreated ) {
644 // Must be run after $wgUser is set, for correct new user log
645 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
648 $retval = self
::SUCCESS
;
650 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
655 * Increment the login attempt throttle hit count for the (username,current IP)
656 * tuple unless the throttle was already reached.
657 * @param string $username The user name
658 * @return Bool|Integer The integer hit count or True if it is already at the limit
660 public static function incLoginThrottle( $username ) {
661 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
662 $username = trim( $username ); // sanity
665 if ( is_array( $wgPasswordAttemptThrottle ) ) {
666 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
667 $count = $wgPasswordAttemptThrottle['count'];
668 $period = $wgPasswordAttemptThrottle['seconds'];
670 $throttleCount = $wgMemc->get( $throttleKey );
671 if ( !$throttleCount ) {
672 $wgMemc->add( $throttleKey, 1, $period ); // start counter
673 } elseif ( $throttleCount < $count ) {
674 $wgMemc->incr( $throttleKey );
675 } elseif ( $throttleCount >= $count ) {
680 return $throttleCount;
684 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
685 * @param string $username The user name
688 public static function clearLoginThrottle( $username ) {
689 global $wgMemc, $wgRequest;
690 $username = trim( $username ); // sanity
692 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
693 $wgMemc->delete( $throttleKey );
697 * Attempt to automatically create a user on login. Only succeeds if there
698 * is an external authentication method which allows it.
702 * @return integer Status code
704 function attemptAutoCreate( $user ) {
707 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
708 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
709 return self
::CREATE_BLOCKED
;
711 if ( !$wgAuth->autoCreate() ) {
712 return self
::NOT_EXISTS
;
714 if ( !$wgAuth->userExists( $user->getName() ) ) {
715 wfDebug( __METHOD__
. ": user does not exist\n" );
716 return self
::NOT_EXISTS
;
718 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
719 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
720 return self
::WRONG_PLUGIN_PASS
;
724 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
725 // Hook point to add extra creation throttles and blocks
726 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
727 $this->mAbortLoginErrorMsg
= $abortError;
728 return self
::ABORTED
;
731 wfDebug( __METHOD__
. ": creating account\n" );
732 $status = $this->initUser( $user, true );
734 if ( !$status->isOK() ) {
735 $errors = $status->getErrorsByType( 'error' );
736 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
737 return self
::ABORTED
;
740 return self
::SUCCESS
;
743 function processLogin() {
744 global $wgMemc, $wgLang, $wgSecureLogin;
746 switch ( $this->authenticateUserData() ) {
748 # We've verified now, update the real record
749 $user = $this->getUser();
750 if( (bool)$this->mRemember
!= $user->getBoolOption( 'rememberpassword' ) ) {
751 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
752 $user->saveSettings();
754 $user->invalidateCache();
757 if( $wgSecureLogin && !$this->mStickHTTPS
) {
758 $user->setCookies( null, false );
762 self
::clearLoginToken();
764 // Reset the throttle
765 $request = $this->getRequest();
766 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
767 $wgMemc->delete( $key );
769 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
770 /* Replace the language object to provide user interface in
771 * correct language immediately on this first page load.
773 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
774 $userLang = Language
::factory( $code );
776 $this->getContext()->setLanguage( $userLang );
777 // Reset SessionID on Successful login (bug 40995)
778 $this->renewSessionId();
779 $this->successfulLogin();
781 $this->cookieRedirectCheck( 'login' );
785 case self
::NEED_TOKEN
:
786 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
788 case self
::WRONG_TOKEN
:
789 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
793 $this->mainLoginForm( $this->msg( 'noname' )->text() );
795 case self
::WRONG_PLUGIN_PASS
:
796 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
798 case self
::NOT_EXISTS
:
799 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
800 $this->mainLoginForm( $this->msg( 'nosuchuser',
801 wfEscapeWikiText( $this->mUsername
) )->parse() );
803 $this->mainLoginForm( $this->msg( 'nosuchusershort',
804 wfEscapeWikiText( $this->mUsername
) )->text() );
807 case self
::WRONG_PASS
:
808 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
810 case self
::EMPTY_PASS
:
811 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
813 case self
::RESET_PASS
:
814 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
816 case self
::CREATE_BLOCKED
:
817 $this->userBlockedMessage( $this->getUser()->mBlock
);
819 case self
::THROTTLED
:
820 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
822 case self
::USER_BLOCKED
:
823 $this->mainLoginForm( $this->msg( 'login-userblocked',
824 $this->mUsername
)->escaped() );
827 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
830 throw new MWException( 'Unhandled case value' );
835 * @param $error string
837 function resetLoginForm( $error ) {
838 $this->getOutput()->addHTML( Xml
::element( 'p', array( 'class' => 'error' ), $error ) );
839 $reset = new SpecialChangePassword();
840 $reset->setContext( $this->getContext() );
841 $reset->execute( null );
845 * @param $u User object
846 * @param $throttle Boolean
847 * @param string $emailTitle message name of email title
848 * @param string $emailText message name of email text
849 * @return Status object
851 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
852 global $wgCanonicalServer, $wgScript, $wgNewPasswordExpiry;
854 if ( $u->getEmail() == '' ) {
855 return Status
::newFatal( 'noemail', $u->getName() );
857 $ip = $this->getRequest()->getIP();
859 return Status
::newFatal( 'badipaddress' );
862 $currentUser = $this->getUser();
863 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
865 $np = $u->randomPassword();
866 $u->setNewpassword( $np, $throttle );
868 $userLanguage = $u->getOption( 'language' );
869 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $wgCanonicalServer . $wgScript . '>',
870 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
871 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
877 * Run any hooks registered for logins, then HTTP redirect to
878 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
879 * nice message here, but that's really not as useful as just being sent to
880 * wherever you logged in from. It should be clear that the action was
881 * successful, given the lack of error messages plus the appearance of your
882 * name in the upper right.
886 function successfulLogin() {
887 # Run any hooks; display injected HTML if any, else redirect
888 $currentUser = $this->getUser();
890 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
892 if( $injected_html !== '' ) {
893 $this->displaySuccessfulAction( $this->msg( 'loginsuccesstitle' ),
894 'loginsuccess', $injected_html );
896 $this->executeReturnTo( 'successredirect' );
901 * Run any hooks registered for logins, then display a message welcoming
906 function successfulCreation() {
907 # Run any hooks; display injected HTML
908 $currentUser = $this->getUser();
910 $welcome_creation_msg = 'welcomecreation-msg';
912 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
915 * Let any extensions change what message is shown.
916 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
919 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
921 $this->displaySuccessfulAction( $this->msg( 'welcomeuser', $this->getUser()->getName() ),
922 $welcome_creation_msg, $injected_html );
926 * Display an "successful action" page.
928 * @param string|Message $title page's title
929 * @param $msgname string
930 * @param $injected_html string
932 private function displaySuccessfulAction( $title, $msgname, $injected_html ) {
933 $out = $this->getOutput();
934 $out->setPageTitle( $title );
936 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
939 $out->addHTML( $injected_html );
941 $this->executeReturnTo( 'success' );
945 * Output a message that informs the user that they cannot create an account because
946 * there is a block on them or their IP which prevents account creation. Note that
947 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
948 * setting on blocks (bug 13611).
949 * @param $block Block the block causing this error
950 * @throws ErrorPageError
952 function userBlockedMessage( Block
$block ) {
953 # Let's be nice about this, it's likely that this feature will be used
954 # for blocking large numbers of innocent people, e.g. range blocks on
955 # schools. Don't blame it on the user. There's a small chance that it
956 # really is the user's fault, i.e. the username is blocked and they
957 # haven't bothered to log out before trying to create an account to
958 # evade it, but we'll leave that to their guilty conscience to figure
960 throw new ErrorPageError(
961 'cantcreateaccounttitle',
962 'cantcreateaccount-text',
965 $block->mReason ?
$block->mReason
: $this->msg( 'blockednoreason' )->text(),
972 * Add a "return to" link or redirect to it.
974 * @param $type string, one of the following:
975 * - error: display a return to link ignoring $wgRedirectOnLogin
976 * - success: display a return to link using $wgRedirectOnLogin if needed
977 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
979 private function executeReturnTo( $type ) {
980 global $wgRedirectOnLogin, $wgSecureLogin;
982 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
983 $returnTo = $wgRedirectOnLogin;
984 $returnToQuery = array();
986 $returnTo = $this->mReturnTo
;
987 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
990 $returnToTitle = Title
::newFromText( $returnTo );
991 if ( !$returnToTitle ) {
992 $returnToTitle = Title
::newMainPage();
995 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
996 $options = array( 'http' );
998 } elseif( $wgSecureLogin ) {
999 $options = array( 'https' );
1000 $proto = PROTO_HTTPS
;
1003 $proto = PROTO_RELATIVE
;
1006 if ( $type == 'successredirect' ) {
1007 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1008 $this->getOutput()->redirect( $redirectUrl );
1010 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1015 * Whether to show new vertically laid out login form.
1016 * ?useNew=1 forces new style, ?useNew=0 forces old style,
1017 * otherwise consult $wgUseVFormUserLogin.
1020 private function shouldShowVForm() {
1021 global $wgUseVFormUserLogin;
1023 if ( $this->mType
== 'signup' ) {
1026 return $this->mRequest
->getBool( 'useNew', $wgUseVFormUserLogin );
1033 function mainLoginForm( $msg, $msgtype = 'error' ) {
1034 global $wgEnableEmail, $wgEnableUserEmail;
1035 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1036 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
1037 global $wgSecureLogin, $wgSecureLoginDefaultHTTPS, $wgPasswordResetRoutes;
1039 $titleObj = $this->getTitle();
1040 $user = $this->getUser();
1041 $out = $this->getOutput();
1043 if ( $this->mType
== 'signup' ) {
1044 // Block signup here if in readonly. Keeps user from
1045 // going through the process (filling out data, etc)
1046 // and being informed later.
1047 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1048 if ( count( $permErrors ) ) {
1049 throw new PermissionsError( 'createaccount', $permErrors );
1050 } elseif ( $user->isBlockedFromCreateAccount() ) {
1051 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1053 } elseif ( wfReadOnly() ) {
1054 throw new ReadOnlyError
;
1058 // Pre-fill username (if not creating an account, bug 44775).
1059 if ( $this->mUsername
== '' && $this->mType
!= 'signup' ) {
1060 if ( $user->isLoggedIn() ) {
1061 $this->mUsername
= $user->getName();
1063 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1067 if ( $this->mType
== 'signup' ) {
1068 $template = new UsercreateTemplate();
1069 $q = 'action=submitlogin&type=signup';
1070 $linkq = 'type=login';
1071 $linkmsg = 'gotaccount';
1072 $out->addModules( 'mediawiki.special.userlogin.signup' );
1074 if ( $this->mShowVForm
) {
1075 $template = new UserloginTemplateVForm();
1076 $out->addModuleStyles( array(
1078 'mediawiki.special.userlogin.vform'
1081 $template = new UserloginTemplate();
1083 $q = 'action=submitlogin&type=login';
1084 $linkq = 'type=signup';
1085 $linkmsg = 'nologin';
1088 if ( $this->mReturnTo
!== '' ) {
1089 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1090 if ( $this->mReturnToQuery
!== '' ) {
1091 $returnto .= '&returntoquery=' .
1092 wfUrlencode( $this->mReturnToQuery
);
1095 $linkq .= $returnto;
1098 # Don't show a "create account" link if the user can't.
1099 if( $this->showCreateOrLoginLink( $user ) ) {
1100 # Pass any language selection on to the mode switch link
1101 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1102 $linkq .= '&uselang=' . $this->mLanguage
;
1104 if ( !$this->mShowVForm
) {
1105 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1106 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1108 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1111 // Supply URL, login template creates the button.
1112 // (The template 'link' key, passed above, is obsolete in the VForm design.)
1113 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1116 $template->set( 'link', '' );
1119 // Decide if we default stickHTTPS on
1120 if ( $wgSecureLoginDefaultHTTPS && $this->mAction
!= 'submitlogin' && !$this->mLoginattempt
) {
1121 $this->mStickHTTPS
= true;
1124 $resetLink = $this->mType
== 'signup'
1126 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1128 $template->set( 'header', '' );
1129 $template->set( 'name', $this->mUsername
);
1130 $template->set( 'password', $this->mPassword
);
1131 $template->set( 'retype', $this->mRetype
);
1132 $template->set( 'createemailset', $this->mCreateaccountMail
);
1133 $template->set( 'email', $this->mEmail
);
1134 $template->set( 'realname', $this->mRealName
);
1135 $template->set( 'domain', $this->mDomain
);
1136 $template->set( 'reason', $this->mReason
);
1138 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1139 $template->set( 'message', $msg );
1140 $template->set( 'messagetype', $msgtype );
1141 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1142 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1143 $template->set( 'useemail', $wgEnableEmail );
1144 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1145 $template->set( 'emailothers', $wgEnableUserEmail );
1146 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1147 $template->set( 'resetlink', $resetLink );
1148 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1149 $template->set( 'usereason', $user->isLoggedIn() );
1150 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1151 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1152 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1154 if ( $this->mType
== 'signup' ) {
1155 if ( !self
::getCreateaccountToken() ) {
1156 self
::setCreateaccountToken();
1158 $template->set( 'token', self
::getCreateaccountToken() );
1160 if ( !self
::getLoginToken() ) {
1161 self
::setLoginToken();
1163 $template->set( 'token', self
::getLoginToken() );
1166 # Prepare language selection links as needed
1167 if( $wgLoginLanguageSelector ) {
1168 $template->set( 'languages', $this->makeLanguageSelector() );
1169 if( $this->mLanguage
) {
1170 $template->set( 'uselang', $this->mLanguage
);
1174 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl
);
1175 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1176 // Ditto for signupend. New forms use neither.
1177 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1178 $loginendHTTPS = $this->msg( 'loginend-https' );
1179 $signupendHTTPS = $this->msg( 'signupend-https' );
1180 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1181 $template->set( 'loginend', $loginendHTTPS->parse() );
1183 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1185 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1186 $template->set( 'signupend', $signupendHTTPS->parse() );
1188 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1191 // Give authentication and captcha plugins a chance to modify the form
1192 $wgAuth->modifyUITemplate( $template, $this->mType
);
1193 if ( $this->mType
== 'signup' ) {
1194 wfRunHooks( 'UserCreateForm', array( &$template ) );
1196 wfRunHooks( 'UserLoginForm', array( &$template ) );
1199 $out->disallowUserJs(); // just in case...
1200 $out->addTemplate( $template );
1210 function showCreateOrLoginLink( &$user ) {
1211 if( $this->mType
== 'signup' ) {
1213 } elseif( $user->isAllowed( 'createaccount' ) ) {
1221 * Check if a session cookie is present.
1223 * This will not pick up a cookie set during _this_ request, but is meant
1224 * to ensure that the client is returning the cookie which was set on a
1225 * previous pass through the system.
1230 function hasSessionCookie() {
1231 global $wgDisableCookieCheck;
1232 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1236 * Get the login token from the current session
1239 public static function getLoginToken() {
1241 return $wgRequest->getSessionData( 'wsLoginToken' );
1245 * Randomly generate a new login token and attach it to the current session
1247 public static function setLoginToken() {
1249 // Generate a token directly instead of using $user->editToken()
1250 // because the latter reuses $_SESSION['wsEditToken']
1251 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1255 * Remove any login token attached to the current session
1257 public static function clearLoginToken() {
1259 $wgRequest->setSessionData( 'wsLoginToken', null );
1263 * Get the createaccount token from the current session
1266 public static function getCreateaccountToken() {
1268 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1272 * Randomly generate a new createaccount token and attach it to the current session
1274 public static function setCreateaccountToken() {
1276 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1280 * Remove any createaccount token attached to the current session
1282 public static function clearCreateaccountToken() {
1284 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1288 * Renew the user's session id, using strong entropy
1290 private function renewSessionId() {
1291 global $wgSecureLogin, $wgCookieSecure;
1292 if( $wgSecureLogin && !$this->mStickHTTPS
) {
1293 $wgCookieSecure = false;
1296 // If either we don't trust PHP's entropy, or if we need
1297 // to change cookie settings when logging in because of
1298 // wpStickHTTPS, then change the session ID manually.
1299 $cookieParams = session_get_cookie_params();
1300 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
1301 session_regenerate_id( false );
1305 wfSetupSession( MWCryptRand
::generateHex( 32 ) );
1313 function cookieRedirectCheck( $type ) {
1314 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1315 $query = array( 'wpCookieCheck' => $type );
1316 if ( $this->mReturnTo
!== '' ) {
1317 $query['returnto'] = $this->mReturnTo
;
1318 $query['returntoquery'] = $this->mReturnToQuery
;
1320 $check = $titleObj->getFullURL( $query );
1322 $this->getOutput()->redirect( $check );
1328 function onCookieRedirectCheck( $type ) {
1329 if ( !$this->hasSessionCookie() ) {
1330 if ( $type == 'new' ) {
1331 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1332 } elseif ( $type == 'login' ) {
1333 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1336 $this->mainLoginForm( $this->msg( 'error' )->text() );
1339 $this->successfulLogin();
1344 * Produce a bar of links which allow the user to select another language
1345 * during login/registration but retain "returnto"
1349 function makeLanguageSelector() {
1350 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1351 if( !$msg->isBlank() ) {
1352 $langs = explode( "\n", $msg->text() );
1354 foreach( $langs as $lang ) {
1355 $lang = trim( $lang, '* ' );
1356 $parts = explode( '|', $lang );
1357 if ( count( $parts ) >= 2 ) {
1358 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1361 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1362 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1369 * Create a language selector link for a particular language
1370 * Links back to this page preserving type and returnto
1372 * @param string $text Link text
1373 * @param string $lang Language code
1376 function makeLanguageSelectorLink( $text, $lang ) {
1377 if( $this->getLanguage()->getCode() == $lang ) {
1378 // no link for currently used language
1379 return htmlspecialchars( $text );
1381 $query = array( 'uselang' => $lang );
1382 if( $this->mType
== 'signup' ) {
1383 $query['type'] = 'signup';
1385 if( $this->mReturnTo
!== '' ) {
1386 $query['returnto'] = $this->mReturnTo
;
1387 $query['returntoquery'] = $this->mReturnToQuery
;
1391 $targetLanguage = Language
::factory( $lang );
1392 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1394 return Linker
::linkKnown(
1396 htmlspecialchars( $text ),
1402 protected function getGroupName() {