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;
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 );
183 // A wiki without HTTPS login support should set $wgServer to
184 // http://somehost, in which case the secure URL generated
185 // above won't actually start with https://
186 if ( substr( $url, 0, 8 ) === 'https://' ) {
187 $this->mSecureLoginUrl
= $url;
192 if ( !is_null( $this->mCookieCheck
) ) {
193 $this->onCookieRedirectCheck( $this->mCookieCheck
);
195 } elseif ( $this->mPosted
) {
196 if ( $this->mCreateaccount
) {
197 $this->addNewAccount();
199 } elseif ( $this->mCreateaccountMail
) {
200 $this->addNewAccountMailPassword();
202 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
203 $this->processLogin();
207 $this->mainLoginForm( '' );
213 function addNewAccountMailPassword() {
214 if ( $this->mEmail
== '' ) {
215 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
219 $status = $this->addNewaccountInternal();
220 if ( !$status->isGood() ) {
221 $error = $this->getOutput()->parse( $status->getWikiText() );
222 $this->mainLoginForm( $error );
226 $u = $status->getValue();
228 // Wipe the initial password and mail a temporary one
229 $u->setPassword( null );
231 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
233 wfRunHooks( 'AddNewAccount', array( $u, true ) );
234 $u->addNewUserLogEntry( 'byemail', $this->mReason
);
236 $out = $this->getOutput();
237 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
239 if ( !$result->isGood() ) {
240 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
242 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
243 $this->executeReturnTo( 'success' );
251 function addNewAccount() {
252 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
254 # Create the account and abort if there's a problem doing so
255 $status = $this->addNewAccountInternal();
256 if ( !$status->isGood() ) {
257 $error = $this->getOutput()->parse( $status->getWikiText() );
258 $this->mainLoginForm( $error );
262 $u = $status->getValue();
264 # Only save preferences if the user is not creating an account for someone else.
265 if ( $this->getUser()->isAnon() ) {
266 # If we showed up language selection links, and one was in use, be
267 # smart (and sensible) and save that language as the user's preference
268 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
269 $u->setOption( 'language', $this->mLanguage
);
272 # Otherwise the user's language preference defaults to $wgContLang,
273 # but it may be better to set it to their preferred $wgContLang variant,
274 # based on browser preferences or URL parameters.
275 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
277 if ( $wgContLang->hasVariants() ) {
278 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
282 $out = $this->getOutput();
284 # Send out an email authentication message if needed
285 if ( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
286 $status = $u->sendConfirmationMail();
287 if ( $status->isGood() ) {
288 $out->addWikiMsg( 'confirmemail_oncreate' );
290 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
294 # Save settings (including confirmation token)
297 # If not logged in, assume the new account as the current one and set
298 # session cookies then show a "welcome" message or a "need cookies"
300 if ( $this->getUser()->isAnon() ) {
303 // This should set it for OutputPage and the Skin
304 // which is needed or the personal links will be
306 $this->getContext()->setUser( $u );
307 wfRunHooks( 'AddNewAccount', array( $u, false ) );
308 $u->addNewUserLogEntry( 'create' );
309 if ( $this->hasSessionCookie() ) {
310 $this->successfulCreation();
312 $this->cookieRedirectCheck( 'new' );
315 # Confirm that the account was created
316 $out->setPageTitle( $this->msg( 'accountcreated' ) );
317 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
318 $out->addReturnTo( $this->getTitle() );
319 wfRunHooks( 'AddNewAccount', array( $u, false ) );
320 $u->addNewUserLogEntry( 'create2', $this->mReason
);
326 * Make a new user account using the loaded data.
328 * @throws PermissionsError|ReadOnlyError
331 public function addNewAccountInternal() {
332 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
333 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
335 // If the user passes an invalid domain, something is fishy
336 if ( !$wgAuth->validDomain( $this->mDomain
) ) {
337 return Status
::newFatal( 'wrongpassword' );
340 // If we are not allowing users to login locally, we should be checking
341 // to see if the user is actually able to authenticate to the authenti-
342 // cation server before they create an account (otherwise, they can
343 // create a local account and login as any domain user). We only need
344 // to check this for domains that aren't local.
345 if ( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
347 !$wgAuth->canCreateAccounts() &&
349 !$wgAuth->userExists( $this->mUsername
) ||
350 !$wgAuth->authenticate( $this->mUsername
, $this->mPassword
)
353 return Status
::newFatal( 'wrongpassword' );
357 if ( wfReadOnly() ) {
358 throw new ReadOnlyError
;
361 # Request forgery checks.
362 if ( !self
::getCreateaccountToken() ) {
363 self
::setCreateaccountToken();
364 return Status
::newFatal( 'nocookiesfornew' );
367 # The user didn't pass a createaccount token
368 if ( !$this->mToken
) {
369 return Status
::newFatal( 'sessionfailure' );
372 # Validate the createaccount token
373 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
374 return Status
::newFatal( 'sessionfailure' );
378 $currentUser = $this->getUser();
379 $creationBlock = $currentUser->isBlockedFromCreateAccount();
380 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
381 throw new PermissionsError( 'createaccount' );
382 } elseif ( $creationBlock instanceof Block
) {
383 // Throws an ErrorPageError.
384 $this->userBlockedMessage( $creationBlock );
385 // This should never be reached.
389 # Include checks that will include GlobalBlocking (Bug 38333)
390 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'createaccount', $currentUser, true );
391 if ( count( $permErrors ) ) {
392 throw new PermissionsError( 'createaccount', $permErrors );
395 $ip = $this->getRequest()->getIP();
396 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
397 return Status
::newFatal( 'sorbs_create_account_reason' );
400 # Now create a dummy user ($u) and check if it is valid
401 $name = trim( $this->mUsername
);
402 $u = User
::newFromName( $name, 'creatable' );
403 if ( !is_object( $u ) ) {
404 return Status
::newFatal( 'noname' );
405 } elseif ( 0 != $u->idForName() ) {
406 return Status
::newFatal( 'userexists' );
409 if ( $this->mCreateaccountMail
) {
410 # do not force a password for account creation by email
411 # set invalid password, it will be replaced later by a random generated password
412 $this->mPassword
= null;
414 if ( $this->mPassword
!== $this->mRetype
) {
415 return Status
::newFatal( 'badretype' );
418 # check for minimal password length
419 $valid = $u->getPasswordValidity( $this->mPassword
);
420 if ( $valid !== true ) {
421 if ( !is_array( $valid ) ) {
422 $valid = array( $valid, $wgMinimalPasswordLength );
424 return call_user_func_array( 'Status::newFatal', $valid );
428 # if you need a confirmed email address to edit, then obviously you
429 # need an email address.
430 if ( $wgEmailConfirmToEdit && strval( $this->mEmail
) === '' ) {
431 return Status
::newFatal( 'noemailtitle' );
434 if ( strval( $this->mEmail
) !== '' && !Sanitizer
::validateEmail( $this->mEmail
) ) {
435 return Status
::newFatal( 'invalidemailaddress' );
438 # Set some additional data so the AbortNewAccount hook can be used for
439 # more than just username validation
440 $u->setEmail( $this->mEmail
);
441 $u->setRealName( $this->mRealName
);
444 if ( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
445 // Hook point to add extra creation throttles and blocks
446 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
447 return Status
::newFatal( new RawMessage( $abortError ) );
450 // Hook point to check for exempt from account creation throttle
451 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
452 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
454 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
455 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
456 $value = $wgMemc->get( $key );
458 $wgMemc->set( $key, 0, 86400 );
460 if ( $value >= $wgAccountCreationThrottle ) {
461 return Status
::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
463 $wgMemc->incr( $key );
467 if ( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
468 return Status
::newFatal( 'externaldberror' );
471 self
::clearCreateaccountToken();
472 return $this->initUser( $u, false );
476 * Actually add a user to the database.
477 * Give it a User object that has been initialised with a name.
479 * @param $u User object.
480 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
481 * @return Status object, with the User object in the value member on success
484 function initUser( $u, $autocreate ) {
487 $status = $u->addToDatabase();
488 if ( !$status->isOK() ) {
492 if ( $wgAuth->allowPasswordChange() ) {
493 $u->setPassword( $this->mPassword
);
496 $u->setEmail( $this->mEmail
);
497 $u->setRealName( $this->mRealName
);
500 $wgAuth->initUser( $u, $autocreate );
502 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
506 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
508 return Status
::newGood( $u );
512 * Internally authenticate the login request.
514 * This may create a local account as a side effect if the
515 * authentication plugin allows transparent local account
519 public function authenticateUserData() {
520 global $wgUser, $wgAuth;
524 if ( $this->mUsername
== '' ) {
525 return self
::NO_NAME
;
528 // We require a login token to prevent login CSRF
529 // Handle part of this before incrementing the throttle so
530 // token-less login attempts don't count towards the throttle
531 // but wrong-token attempts do.
533 // If the user doesn't have a login token yet, set one.
534 if ( !self
::getLoginToken() ) {
535 self
::setLoginToken();
536 return self
::NEED_TOKEN
;
538 // If the user didn't pass a login token, tell them we need one
539 if ( !$this->mToken
) {
540 return self
::NEED_TOKEN
;
543 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
544 if ( $throttleCount === true ) {
545 return self
::THROTTLED
;
548 // Validate the login token
549 if ( $this->mToken
!== self
::getLoginToken() ) {
550 return self
::WRONG_TOKEN
;
553 // Load the current user now, and check to see if we're logging in as
554 // the same name. This is necessary because loading the current user
555 // (say by calling getName()) calls the UserLoadFromSession hook, which
556 // potentially creates the user in the database. Until we load $wgUser,
557 // checking for user existence using User::newFromName($name)->getId() below
558 // will effectively be using stale data.
559 if ( $this->getUser()->getName() === $this->mUsername
) {
560 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
561 return self
::SUCCESS
;
564 $u = User
::newFromName( $this->mUsername
);
565 if ( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
566 return self
::ILLEGAL
;
569 $isAutoCreated = false;
570 if ( $u->getID() == 0 ) {
571 $status = $this->attemptAutoCreate( $u );
572 if ( $status !== self
::SUCCESS
) {
575 $isAutoCreated = true;
581 // Give general extensions, such as a captcha, a chance to abort logins
582 $abort = self
::ABORTED
;
583 if ( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
587 global $wgBlockDisablesLogin;
588 if ( !$u->checkPassword( $this->mPassword
) ) {
589 if ( $u->checkTemporaryPassword( $this->mPassword
) ) {
590 // The e-mailed temporary password should not be used for actu-
591 // al logins; that's a very sloppy habit, and insecure if an
592 // attacker has a few seconds to click "search" on someone's o-
595 // Allow it to be used only to reset the password a single time
596 // to a new value, which won't be in the user's e-mail ar-
599 // For backwards compatibility, we'll still recognize it at the
600 // login form to minimize surprises for people who have been
601 // logging in with a temporary password for some time.
603 // As a side-effect, we can authenticate the user's e-mail ad-
604 // dress if it's not already done, since the temporary password
605 // was sent via e-mail.
606 if ( !$u->isEmailConfirmed() ) {
611 // At this point we just return an appropriate code/ indicating
612 // that the UI should show a password reset form; bot inter-
613 // faces etc will probably just fail cleanly here.
614 $retval = self
::RESET_PASS
;
616 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
618 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
619 // If we've enabled it, make it so that a blocked user cannot login
620 $retval = self
::USER_BLOCKED
;
622 $wgAuth->updateUser( $u );
624 // This should set it for OutputPage and the Skin
625 // which is needed or the personal links will be
627 $this->getContext()->setUser( $u );
629 // Please reset throttle for successful logins, thanks!
630 if ( $throttleCount ) {
631 self
::clearLoginThrottle( $this->mUsername
);
634 if ( $isAutoCreated ) {
635 // Must be run after $wgUser is set, for correct new user log
636 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
639 $retval = self
::SUCCESS
;
641 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
646 * Increment the login attempt throttle hit count for the (username,current IP)
647 * tuple unless the throttle was already reached.
648 * @param string $username The user name
649 * @return Bool|Integer The integer hit count or True if it is already at the limit
651 public static function incLoginThrottle( $username ) {
652 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
653 $username = trim( $username ); // sanity
656 if ( is_array( $wgPasswordAttemptThrottle ) ) {
657 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
658 $count = $wgPasswordAttemptThrottle['count'];
659 $period = $wgPasswordAttemptThrottle['seconds'];
661 $throttleCount = $wgMemc->get( $throttleKey );
662 if ( !$throttleCount ) {
663 $wgMemc->add( $throttleKey, 1, $period ); // start counter
664 } elseif ( $throttleCount < $count ) {
665 $wgMemc->incr( $throttleKey );
666 } elseif ( $throttleCount >= $count ) {
671 return $throttleCount;
675 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
676 * @param string $username The user name
679 public static function clearLoginThrottle( $username ) {
680 global $wgMemc, $wgRequest;
681 $username = trim( $username ); // sanity
683 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
684 $wgMemc->delete( $throttleKey );
688 * Attempt to automatically create a user on login. Only succeeds if there
689 * is an external authentication method which allows it.
693 * @return integer Status code
695 function attemptAutoCreate( $user ) {
698 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
699 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
700 return self
::CREATE_BLOCKED
;
702 if ( !$wgAuth->autoCreate() ) {
703 return self
::NOT_EXISTS
;
705 if ( !$wgAuth->userExists( $user->getName() ) ) {
706 wfDebug( __METHOD__
. ": user does not exist\n" );
707 return self
::NOT_EXISTS
;
709 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
710 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
711 return self
::WRONG_PLUGIN_PASS
;
715 if ( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
716 // Hook point to add extra creation throttles and blocks
717 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
718 $this->mAbortLoginErrorMsg
= $abortError;
719 return self
::ABORTED
;
722 wfDebug( __METHOD__
. ": creating account\n" );
723 $status = $this->initUser( $user, true );
725 if ( !$status->isOK() ) {
726 $errors = $status->getErrorsByType( 'error' );
727 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
728 return self
::ABORTED
;
731 return self
::SUCCESS
;
734 function processLogin() {
735 global $wgMemc, $wgLang, $wgSecureLogin, $wgPasswordAttemptThrottle;
737 switch ( $this->authenticateUserData() ) {
739 # We've verified now, update the real record
740 $user = $this->getUser();
741 if ( (bool)$this->mRemember
!= $user->getBoolOption( 'rememberpassword' ) ) {
742 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
743 $user->saveSettings();
745 $user->invalidateCache();
748 if ( $user->requiresHTTPS() ) {
749 $this->mStickHTTPS
= true;
752 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
753 $user->setCookies( null, false );
757 self
::clearLoginToken();
759 // Reset the throttle
760 $request = $this->getRequest();
761 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
762 $wgMemc->delete( $key );
764 if ( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
765 /* Replace the language object to provide user interface in
766 * correct language immediately on this first page load.
768 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
769 $userLang = Language
::factory( $code );
771 $this->getContext()->setLanguage( $userLang );
772 // Reset SessionID on Successful login (bug 40995)
773 $this->renewSessionId();
774 $this->successfulLogin();
776 $this->cookieRedirectCheck( 'login' );
780 case self
::NEED_TOKEN
:
781 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
783 case self
::WRONG_TOKEN
:
784 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
788 $this->mainLoginForm( $this->msg( 'noname' )->text() );
790 case self
::WRONG_PLUGIN_PASS
:
791 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
793 case self
::NOT_EXISTS
:
794 if ( $this->getUser()->isAllowed( 'createaccount' ) ) {
795 $this->mainLoginForm( $this->msg( 'nosuchuser',
796 wfEscapeWikiText( $this->mUsername
) )->parse() );
798 $this->mainLoginForm( $this->msg( 'nosuchusershort',
799 wfEscapeWikiText( $this->mUsername
) )->text() );
802 case self
::WRONG_PASS
:
803 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
805 case self
::EMPTY_PASS
:
806 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
808 case self
::RESET_PASS
:
809 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
811 case self
::CREATE_BLOCKED
:
812 $this->userBlockedMessage( $this->getUser()->isBlockedFromCreateAccount() );
814 case self
::THROTTLED
:
815 $this->mainLoginForm( $this->msg( 'login-throttled' )
816 ->params ( $this->getLanguage()->formatDuration( $wgPasswordAttemptThrottle['seconds'] ) )
820 case self
::USER_BLOCKED
:
821 $this->mainLoginForm( $this->msg( 'login-userblocked',
822 $this->mUsername
)->escaped() );
825 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
828 throw new MWException( 'Unhandled case value' );
833 * @param $error string
835 function resetLoginForm( $error ) {
836 $this->getOutput()->addHTML( Xml
::element( 'p', array( 'class' => 'error' ), $error ) );
837 $reset = new SpecialChangePassword();
838 $reset->setContext( $this->getContext() );
839 $reset->execute( null );
843 * @param $u User object
844 * @param $throttle Boolean
845 * @param string $emailTitle message name of email title
846 * @param string $emailText message name of email text
847 * @return Status object
849 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
850 global $wgCanonicalServer, $wgScript, $wgNewPasswordExpiry;
852 if ( $u->getEmail() == '' ) {
853 return Status
::newFatal( 'noemail', $u->getName() );
855 $ip = $this->getRequest()->getIP();
857 return Status
::newFatal( 'badipaddress' );
860 $currentUser = $this->getUser();
861 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
863 $np = $u->randomPassword();
864 $u->setNewpassword( $np, $throttle );
866 $userLanguage = $u->getOption( 'language' );
867 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $wgCanonicalServer . $wgScript . '>',
868 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
869 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
875 * Run any hooks registered for logins, then HTTP redirect to
876 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
877 * nice message here, but that's really not as useful as just being sent to
878 * wherever you logged in from. It should be clear that the action was
879 * successful, given the lack of error messages plus the appearance of your
880 * name in the upper right.
884 function successfulLogin() {
885 # Run any hooks; display injected HTML if any, else redirect
886 $currentUser = $this->getUser();
888 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
890 if ( $injected_html !== '' ) {
891 $this->displaySuccessfulAction( $this->msg( 'loginsuccesstitle' ),
892 'loginsuccess', $injected_html );
894 $this->executeReturnTo( 'successredirect' );
899 * Run any hooks registered for logins, then display a message welcoming
904 function successfulCreation() {
905 # Run any hooks; display injected HTML
906 $currentUser = $this->getUser();
908 $welcome_creation_msg = 'welcomecreation-msg';
910 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
913 * Let any extensions change what message is shown.
914 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
917 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
919 $this->displaySuccessfulAction( $this->msg( 'welcomeuser', $this->getUser()->getName() ),
920 $welcome_creation_msg, $injected_html );
924 * Display an "successful action" page.
926 * @param string|Message $title page's title
927 * @param $msgname string
928 * @param $injected_html string
930 private function displaySuccessfulAction( $title, $msgname, $injected_html ) {
931 $out = $this->getOutput();
932 $out->setPageTitle( $title );
934 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
937 $out->addHTML( $injected_html );
939 $this->executeReturnTo( 'success' );
943 * Output a message that informs the user that they cannot create an account because
944 * there is a block on them or their IP which prevents account creation. Note that
945 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
946 * setting on blocks (bug 13611).
947 * @param $block Block the block causing this error
948 * @throws ErrorPageError
950 function userBlockedMessage( Block
$block ) {
951 # Let's be nice about this, it's likely that this feature will be used
952 # for blocking large numbers of innocent people, e.g. range blocks on
953 # schools. Don't blame it on the user. There's a small chance that it
954 # really is the user's fault, i.e. the username is blocked and they
955 # haven't bothered to log out before trying to create an account to
956 # evade it, but we'll leave that to their guilty conscience to figure
958 throw new ErrorPageError(
959 'cantcreateaccounttitle',
960 'cantcreateaccount-text',
963 $block->mReason ?
$block->mReason
: $this->msg( 'blockednoreason' )->text(),
970 * Add a "return to" link or redirect to it.
971 * Extensions can use this to reuse the "return to" logic after
972 * inject steps (such as redirection) into the login process.
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
978 * @param string $returnTo
979 * @param array|string $returnToQuery
980 * @param bool $stickHTTPs Keep redirect link on HTTPs
983 public function showReturnToPage(
984 $type, $returnTo = '', $returnToQuery = '', $stickHTTPs = false
986 $this->mReturnTo
= $returnTo;
987 $this->mReturnToQuery
= $returnToQuery;
988 $this->mStickHTTPS
= $stickHTTPs;
989 $this->executeReturnTo( $type );
993 * Add a "return to" link or redirect to it.
995 * @param $type string, one of the following:
996 * - error: display a return to link ignoring $wgRedirectOnLogin
997 * - success: display a return to link using $wgRedirectOnLogin if needed
998 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1000 private function executeReturnTo( $type ) {
1001 global $wgRedirectOnLogin, $wgSecureLogin;
1003 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
1004 $returnTo = $wgRedirectOnLogin;
1005 $returnToQuery = array();
1007 $returnTo = $this->mReturnTo
;
1008 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
1011 $returnToTitle = Title
::newFromText( $returnTo );
1012 if ( !$returnToTitle ) {
1013 $returnToTitle = Title
::newMainPage();
1016 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1017 $options = array( 'http' );
1018 $proto = PROTO_HTTP
;
1019 } elseif ( $wgSecureLogin ) {
1020 $options = array( 'https' );
1021 $proto = PROTO_HTTPS
;
1024 $proto = PROTO_RELATIVE
;
1027 if ( $type == 'successredirect' ) {
1028 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1029 $this->getOutput()->redirect( $redirectUrl );
1031 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1038 function mainLoginForm( $msg, $msgtype = 'error' ) {
1039 global $wgEnableEmail, $wgEnableUserEmail;
1040 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1041 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
1042 global $wgSecureLogin, $wgPasswordResetRoutes;
1044 $titleObj = $this->getTitle();
1045 $user = $this->getUser();
1046 $out = $this->getOutput();
1048 if ( $this->mType
== 'signup' ) {
1049 // Block signup here if in readonly. Keeps user from
1050 // going through the process (filling out data, etc)
1051 // and being informed later.
1052 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1053 if ( count( $permErrors ) ) {
1054 throw new PermissionsError( 'createaccount', $permErrors );
1055 } elseif ( $user->isBlockedFromCreateAccount() ) {
1056 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1058 } elseif ( wfReadOnly() ) {
1059 throw new ReadOnlyError
;
1063 // Pre-fill username (if not creating an account, bug 44775).
1064 if ( $this->mUsername
== '' && $this->mType
!= 'signup' ) {
1065 if ( $user->isLoggedIn() ) {
1066 $this->mUsername
= $user->getName();
1068 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1072 if ( $this->mType
== 'signup' ) {
1073 $template = new UsercreateTemplate();
1075 $out->addModuleStyles( array(
1077 'mediawiki.special.createaccount'
1079 // XXX hack pending RL or JS parse() support for complex content messages
1080 // https://bugzilla.wikimedia.org/show_bug.cgi?id=25349
1081 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
1082 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
1083 $out->addModules( array(
1084 'mediawiki.special.createaccount.js'
1086 // Must match number of benefits defined in messages
1087 $template->set( 'benefitCount', 3 );
1089 $q = 'action=submitlogin&type=signup';
1090 $linkq = 'type=login';
1092 $template = new UserloginTemplate();
1094 $out->addModuleStyles( array(
1096 'mediawiki.special.userlogin'
1099 $q = 'action=submitlogin&type=login';
1100 $linkq = 'type=signup';
1103 if ( $this->mReturnTo
!== '' ) {
1104 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1105 if ( $this->mReturnToQuery
!== '' ) {
1106 $returnto .= '&returntoquery=' .
1107 wfUrlencode( $this->mReturnToQuery
);
1110 $linkq .= $returnto;
1113 # Don't show a "create account" link if the user can't.
1114 if ( $this->showCreateOrLoginLink( $user ) ) {
1115 # Pass any language selection on to the mode switch link
1116 if ( $wgLoginLanguageSelector && $this->mLanguage
) {
1117 $linkq .= '&uselang=' . $this->mLanguage
;
1119 // Supply URL, login template creates the button.
1120 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1122 $template->set( 'link', '' );
1125 $resetLink = $this->mType
== 'signup'
1127 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1129 $template->set( 'header', '' );
1130 $template->set( 'skin', $this->getSkin() );
1131 $template->set( 'name', $this->mUsername
);
1132 $template->set( 'password', $this->mPassword
);
1133 $template->set( 'retype', $this->mRetype
);
1134 $template->set( 'createemailset', $this->mCreateaccountMail
);
1135 $template->set( 'email', $this->mEmail
);
1136 $template->set( 'realname', $this->mRealName
);
1137 $template->set( 'domain', $this->mDomain
);
1138 $template->set( 'reason', $this->mReason
);
1140 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1141 $template->set( 'message', $msg );
1142 $template->set( 'messagetype', $msgtype );
1143 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1144 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1145 $template->set( 'useemail', $wgEnableEmail );
1146 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1147 $template->set( 'emailothers', $wgEnableUserEmail );
1148 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1149 $template->set( 'resetlink', $resetLink );
1150 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1151 $template->set( 'usereason', $user->isLoggedIn() );
1152 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1153 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1154 $template->set( 'stickhttps', (int)$this->mStickHTTPS
);
1156 if ( $this->mType
=== 'signup' && $user->isLoggedIn() ) {
1157 $template->set( 'createAnother', true );
1159 $template->set( 'createAnother', false );
1162 if ( $this->mType
== 'signup' ) {
1163 if ( !self
::getCreateaccountToken() ) {
1164 self
::setCreateaccountToken();
1166 $template->set( 'token', self
::getCreateaccountToken() );
1168 if ( !self
::getLoginToken() ) {
1169 self
::setLoginToken();
1171 $template->set( 'token', self
::getLoginToken() );
1174 # Prepare language selection links as needed
1175 if ( $wgLoginLanguageSelector ) {
1176 $template->set( 'languages', $this->makeLanguageSelector() );
1177 if ( $this->mLanguage
) {
1178 $template->set( 'uselang', $this->mLanguage
);
1182 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl
);
1183 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1184 // Ditto for signupend. New forms use neither.
1185 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1186 $loginendHTTPS = $this->msg( 'loginend-https' );
1187 $signupendHTTPS = $this->msg( 'signupend-https' );
1188 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1189 $template->set( 'loginend', $loginendHTTPS->parse() );
1191 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1193 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1194 $template->set( 'signupend', $signupendHTTPS->parse() );
1196 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1199 // Give authentication and captcha plugins a chance to modify the form
1200 $wgAuth->modifyUITemplate( $template, $this->mType
);
1201 if ( $this->mType
== 'signup' ) {
1202 wfRunHooks( 'UserCreateForm', array( &$template ) );
1204 wfRunHooks( 'UserLoginForm', array( &$template ) );
1207 $out->disallowUserJs(); // just in case...
1208 $out->addTemplate( $template );
1212 * Whether the login/create account form should display a link to the
1213 * other form (in addition to whatever the skin provides).
1218 private function showCreateOrLoginLink( &$user ) {
1219 if ( $user->isLoggedIn() ) {
1221 } elseif ( $this->mType
== 'signup' ) {
1223 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1231 * Check if a session cookie is present.
1233 * This will not pick up a cookie set during _this_ request, but is meant
1234 * to ensure that the client is returning the cookie which was set on a
1235 * previous pass through the system.
1240 function hasSessionCookie() {
1241 global $wgDisableCookieCheck;
1242 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1246 * Get the login token from the current session
1249 public static function getLoginToken() {
1251 return $wgRequest->getSessionData( 'wsLoginToken' );
1255 * Randomly generate a new login token and attach it to the current session
1257 public static function setLoginToken() {
1259 // Generate a token directly instead of using $user->editToken()
1260 // because the latter reuses $_SESSION['wsEditToken']
1261 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1265 * Remove any login token attached to the current session
1267 public static function clearLoginToken() {
1269 $wgRequest->setSessionData( 'wsLoginToken', null );
1273 * Get the createaccount token from the current session
1276 public static function getCreateaccountToken() {
1278 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1282 * Randomly generate a new createaccount token and attach it to the current session
1284 public static function setCreateaccountToken() {
1286 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1290 * Remove any createaccount token attached to the current session
1292 public static function clearCreateaccountToken() {
1294 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1298 * Renew the user's session id, using strong entropy
1300 private function renewSessionId() {
1301 global $wgSecureLogin, $wgCookieSecure;
1302 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
1303 $wgCookieSecure = false;
1312 function cookieRedirectCheck( $type ) {
1313 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1314 $query = array( 'wpCookieCheck' => $type );
1315 if ( $this->mReturnTo
!== '' ) {
1316 $query['returnto'] = $this->mReturnTo
;
1317 $query['returntoquery'] = $this->mReturnToQuery
;
1319 $check = $titleObj->getFullURL( $query );
1321 $this->getOutput()->redirect( $check );
1327 function onCookieRedirectCheck( $type ) {
1328 if ( !$this->hasSessionCookie() ) {
1329 if ( $type == 'new' ) {
1330 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1331 } elseif ( $type == 'login' ) {
1332 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1335 $this->mainLoginForm( $this->msg( 'error' )->text() );
1338 $this->successfulLogin();
1343 * Produce a bar of links which allow the user to select another language
1344 * during login/registration but retain "returnto"
1348 function makeLanguageSelector() {
1349 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1350 if ( !$msg->isBlank() ) {
1351 $langs = explode( "\n", $msg->text() );
1353 foreach ( $langs as $lang ) {
1354 $lang = trim( $lang, '* ' );
1355 $parts = explode( '|', $lang );
1356 if ( count( $parts ) >= 2 ) {
1357 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1360 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1361 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1368 * Create a language selector link for a particular language
1369 * Links back to this page preserving type and returnto
1371 * @param string $text Link text
1372 * @param string $lang Language code
1375 function makeLanguageSelectorLink( $text, $lang ) {
1376 if ( $this->getLanguage()->getCode() == $lang ) {
1377 // no link for currently used language
1378 return htmlspecialchars( $text );
1380 $query = array( 'uselang' => $lang );
1381 if ( $this->mType
== 'signup' ) {
1382 $query['type'] = 'signup';
1384 if ( $this->mReturnTo
!== '' ) {
1385 $query['returnto'] = $this->mReturnTo
;
1386 $query['returntoquery'] = $this->mReturnToQuery
;
1390 $targetLanguage = Language
::factory( $lang );
1391 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1393 return Linker
::linkKnown(
1395 htmlspecialchars( $text ),
1401 protected function getGroupName() {