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;
57 private $mExtUser = null;
62 private $mOverrideRequest = null;
65 * @param WebRequest $request
67 public function __construct( $request = null ) {
68 parent
::__construct( 'Userlogin' );
70 $this->mOverrideRequest
= $request;
76 * @param $request WebRequest object
79 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail, $wgRedirectOnLogin;
81 if ( $this->mLoaded
) {
84 $this->mLoaded
= true;
86 if ( $this->mOverrideRequest
=== null ) {
87 $request = $this->getRequest();
89 $request = $this->mOverrideRequest
;
92 $this->mType
= $request->getText( 'type' );
93 $this->mUsername
= $request->getText( 'wpName' );
94 $this->mPassword
= $request->getText( 'wpPassword' );
95 $this->mRetype
= $request->getText( 'wpRetype' );
96 $this->mDomain
= $request->getText( 'wpDomain' );
97 $this->mReason
= $request->getText( 'wpReason' );
98 $this->mReturnTo
= $request->getVal( 'returnto' );
99 $this->mReturnToQuery
= $request->getVal( 'returntoquery' );
100 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
101 $this->mPosted
= $request->wasPosted();
102 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' );
103 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
105 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
106 $this->mAction
= $request->getVal( 'action' );
107 $this->mRemember
= $request->getCheck( 'wpRemember' );
108 $this->mStickHTTPS
= $request->getCheck( 'wpStickHTTPS' );
109 $this->mLanguage
= $request->getText( 'uselang' );
110 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
111 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
113 if ( $wgRedirectOnLogin ) {
114 $this->mReturnTo
= $wgRedirectOnLogin;
115 $this->mReturnToQuery
= '';
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
= 'invaliddomain';
132 $wgAuth->setDomain( $this->mDomain
);
134 # When switching accounts, it sucks to get automatically logged out
135 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
136 if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
137 $this->mReturnTo
= '';
138 $this->mReturnToQuery
= '';
142 function getDescription() {
143 return $this->msg( $this->getUser()->isAllowed( 'createaccount' ) ?
144 'userlogin' : 'userloginnocreate' )->text();
147 public function execute( $par ) {
148 if ( session_id() == '' ) {
155 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
156 $this->mType
= 'signup';
159 if ( !is_null( $this->mCookieCheck
) ) {
160 $this->onCookieRedirectCheck( $this->mCookieCheck
);
162 } elseif( $this->mPosted
) {
163 if( $this->mCreateaccount
) {
164 return $this->addNewAccount();
165 } elseif ( $this->mCreateaccountMail
) {
166 return $this->addNewAccountMailPassword();
167 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
168 return $this->processLogin();
171 $this->mainLoginForm( '' );
177 function addNewAccountMailPassword() {
178 if ( $this->mEmail
== '' ) {
179 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
183 $u = $this->addNewaccountInternal();
189 // Wipe the initial password and mail a temporary one
190 $u->setPassword( null );
192 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
194 wfRunHooks( 'AddNewAccount', array( $u, true ) );
195 $u->addNewUserLogEntry( true, $this->mReason
);
197 $out = $this->getOutput();
198 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
200 if( !$result->isGood() ) {
201 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
203 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
204 $out->returnToMain( false );
211 function addNewAccount() {
212 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
214 # Create the account and abort if there's a problem doing so
215 $u = $this->addNewAccountInternal();
220 # If we showed up language selection links, and one was in use, be
221 # smart (and sensible) and save that language as the user's preference
222 if( $wgLoginLanguageSelector && $this->mLanguage
) {
223 $u->setOption( 'language', $this->mLanguage
);
226 $out = $this->getOutput();
228 # Send out an email authentication message if needed
229 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
230 $status = $u->sendConfirmationMail();
231 if( $status->isGood() ) {
232 $out->addWikiMsg( 'confirmemail_oncreate' );
234 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
238 # Save settings (including confirmation token)
241 # If not logged in, assume the new account as the current one and set
242 # session cookies then show a "welcome" message or a "need cookies"
244 if( $this->getUser()->isAnon() ) {
247 // This should set it for OutputPage and the Skin
248 // which is needed or the personal links will be
250 $this->getContext()->setUser( $u );
251 wfRunHooks( 'AddNewAccount', array( $u, false ) );
252 $u->addNewUserLogEntry();
253 if( $this->hasSessionCookie() ) {
254 return $this->successfulCreation();
256 return $this->cookieRedirectCheck( 'new' );
259 # Confirm that the account was created
260 $out->setPageTitle( $this->msg( 'accountcreated' ) );
261 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
262 $out->returnToMain( false, $this->getTitle() );
263 wfRunHooks( 'AddNewAccount', array( $u, false ) );
264 $u->addNewUserLogEntry( false, $this->mReason
);
272 function addNewAccountInternal() {
273 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
274 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
276 // If the user passes an invalid domain, something is fishy
277 if( !$wgAuth->validDomain( $this->mDomain
) ) {
278 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
282 // If we are not allowing users to login locally, we should be checking
283 // to see if the user is actually able to authenticate to the authenti-
284 // cation server before they create an account (otherwise, they can
285 // create a local account and login as any domain user). We only need
286 // to check this for domains that aren't local.
287 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
288 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername
)
289 ||
!$wgAuth->authenticate( $this->mUsername
, $this->mPassword
) ) ) {
290 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
295 if ( wfReadOnly() ) {
296 throw new ReadOnlyError
;
299 # Request forgery checks.
300 if ( !self
::getCreateaccountToken() ) {
301 self
::setCreateaccountToken();
302 $this->mainLoginForm( $this->msg( 'nocookiesfornew' )->parse() );
306 # The user didn't pass a createaccount token
307 if ( !$this->mToken
) {
308 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
312 # Validate the createaccount token
313 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
314 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
319 $currentUser = $this->getUser();
320 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
321 throw new PermissionsError( 'createaccount' );
322 } elseif ( $currentUser->isBlockedFromCreateAccount() ) {
323 $this->userBlockedMessage( $currentUser->isBlockedFromCreateAccount() );
327 $ip = $this->getRequest()->getIP();
328 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
329 $this->mainLoginForm( $this->msg( 'sorbs_create_account_reason' )->text() . ' (' . htmlspecialchars( $ip ) . ')' );
333 # Now create a dummy user ($u) and check if it is valid
334 $name = trim( $this->mUsername
);
335 $u = User
::newFromName( $name, 'creatable' );
336 if ( !is_object( $u ) ) {
337 $this->mainLoginForm( $this->msg( 'noname' )->text() );
341 if ( 0 != $u->idForName() ) {
342 $this->mainLoginForm( $this->msg( 'userexists' )->text() );
346 if ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
347 $this->mainLoginForm( $this->msg( 'badretype' )->text() );
351 # check for minimal password length
352 $valid = $u->getPasswordValidity( $this->mPassword
);
353 if ( $valid !== true ) {
354 if ( !$this->mCreateaccountMail
) {
355 if ( is_array( $valid ) ) {
356 $message = array_shift( $valid );
360 $params = array( $wgMinimalPasswordLength );
362 $this->mainLoginForm( $this->msg( $message, $params )->text() );
365 # do not force a password for account creation by email
366 # set invalid password, it will be replaced later by a random generated password
367 $this->mPassword
= null;
371 # if you need a confirmed email address to edit, then obviously you
372 # need an email address.
373 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
374 $this->mainLoginForm( $this->msg( 'noemailtitle' )->text() );
378 if( !empty( $this->mEmail
) && !Sanitizer
::validateEmail( $this->mEmail
) ) {
379 $this->mainLoginForm( $this->msg( 'invalidemailaddress' )->text() );
383 # Set some additional data so the AbortNewAccount hook can be used for
384 # more than just username validation
385 $u->setEmail( $this->mEmail
);
386 $u->setRealName( $this->mRealName
);
389 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
390 // Hook point to add extra creation throttles and blocks
391 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
392 $this->mainLoginForm( $abortError );
396 // Hook point to check for exempt from account creation throttle
397 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
398 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
400 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
401 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
402 $value = $wgMemc->get( $key );
404 $wgMemc->set( $key, 0, 86400 );
406 if ( $value >= $wgAccountCreationThrottle ) {
407 $this->throttleHit( $wgAccountCreationThrottle );
410 $wgMemc->incr( $key );
414 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
415 $this->mainLoginForm( $this->msg( 'externaldberror' )->text() );
419 self
::clearCreateaccountToken();
420 return $this->initUser( $u, false );
424 * Actually add a user to the database.
425 * Give it a User object that has been initialised with a name.
427 * @param $u User object.
428 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
429 * @return User object.
432 function initUser( $u, $autocreate ) {
437 if ( $wgAuth->allowPasswordChange() ) {
438 $u->setPassword( $this->mPassword
);
441 $u->setEmail( $this->mEmail
);
442 $u->setRealName( $this->mRealName
);
445 $wgAuth->initUser( $u, $autocreate );
447 if ( $this->mExtUser
) {
448 $this->mExtUser
->linkToLocal( $u->getId() );
449 $email = $this->mExtUser
->getPref( 'emailaddress' );
450 if ( $email && !$this->mEmail
) {
451 $u->setEmail( $email );
455 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
459 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
460 $ssUpdate->doUpdate();
466 * Internally authenticate the login request.
468 * This may create a local account as a side effect if the
469 * authentication plugin allows transparent local account
472 public function authenticateUserData() {
473 global $wgUser, $wgAuth;
477 if ( $this->mUsername
== '' ) {
478 return self
::NO_NAME
;
481 // We require a login token to prevent login CSRF
482 // Handle part of this before incrementing the throttle so
483 // token-less login attempts don't count towards the throttle
484 // but wrong-token attempts do.
486 // If the user doesn't have a login token yet, set one.
487 if ( !self
::getLoginToken() ) {
488 self
::setLoginToken();
489 return self
::NEED_TOKEN
;
491 // If the user didn't pass a login token, tell them we need one
492 if ( !$this->mToken
) {
493 return self
::NEED_TOKEN
;
496 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
497 if ( $throttleCount === true ) {
498 return self
::THROTTLED
;
501 // Validate the login token
502 if ( $this->mToken
!== self
::getLoginToken() ) {
503 return self
::WRONG_TOKEN
;
506 // Load the current user now, and check to see if we're logging in as
507 // the same name. This is necessary because loading the current user
508 // (say by calling getName()) calls the UserLoadFromSession hook, which
509 // potentially creates the user in the database. Until we load $wgUser,
510 // checking for user existence using User::newFromName($name)->getId() below
511 // will effectively be using stale data.
512 if ( $this->getUser()->getName() === $this->mUsername
) {
513 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
514 return self
::SUCCESS
;
517 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
519 # TODO: Allow some magic here for invalid external names, e.g., let the
520 # user choose a different wiki name.
521 $u = User
::newFromName( $this->mUsername
);
522 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
523 return self
::ILLEGAL
;
526 $isAutoCreated = false;
527 if ( 0 == $u->getID() ) {
528 $status = $this->attemptAutoCreate( $u );
529 if ( $status !== self
::SUCCESS
) {
532 $isAutoCreated = true;
535 global $wgExternalAuthType, $wgAutocreatePolicy;
536 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
537 && is_object( $this->mExtUser
)
538 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
539 # The external user and local user have the same name and
540 # password, so we assume they're the same.
541 $this->mExtUser
->linkToLocal( $u->getID() );
547 // Give general extensions, such as a captcha, a chance to abort logins
548 $abort = self
::ABORTED
;
549 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
553 global $wgBlockDisablesLogin;
554 if ( !$u->checkPassword( $this->mPassword
) ) {
555 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
556 // The e-mailed temporary password should not be used for actu-
557 // al logins; that's a very sloppy habit, and insecure if an
558 // attacker has a few seconds to click "search" on someone's o-
561 // Allow it to be used only to reset the password a single time
562 // to a new value, which won't be in the user's e-mail ar-
565 // For backwards compatibility, we'll still recognize it at the
566 // login form to minimize surprises for people who have been
567 // logging in with a temporary password for some time.
569 // As a side-effect, we can authenticate the user's e-mail ad-
570 // dress if it's not already done, since the temporary password
571 // was sent via e-mail.
572 if( !$u->isEmailConfirmed() ) {
577 // At this point we just return an appropriate code/ indicating
578 // that the UI should show a password reset form; bot inter-
579 // faces etc will probably just fail cleanly here.
580 $retval = self
::RESET_PASS
;
582 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
584 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
585 // If we've enabled it, make it so that a blocked user cannot login
586 $retval = self
::USER_BLOCKED
;
588 $wgAuth->updateUser( $u );
590 // This should set it for OutputPage and the Skin
591 // which is needed or the personal links will be
593 $this->getContext()->setUser( $u );
595 // Please reset throttle for successful logins, thanks!
596 if ( $throttleCount ) {
597 self
::clearLoginThrottle( $this->mUsername
);
600 if ( $isAutoCreated ) {
601 // Must be run after $wgUser is set, for correct new user log
602 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
605 $retval = self
::SUCCESS
;
607 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
612 * Increment the login attempt throttle hit count for the (username,current IP)
613 * tuple unless the throttle was already reached.
614 * @param $username string The user name
615 * @return Bool|Integer The integer hit count or True if it is already at the limit
617 public static function incLoginThrottle( $username ) {
618 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
619 $username = trim( $username ); // sanity
622 if ( is_array( $wgPasswordAttemptThrottle ) ) {
623 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
624 $count = $wgPasswordAttemptThrottle['count'];
625 $period = $wgPasswordAttemptThrottle['seconds'];
627 $throttleCount = $wgMemc->get( $throttleKey );
628 if ( !$throttleCount ) {
629 $wgMemc->add( $throttleKey, 1, $period ); // start counter
630 } elseif ( $throttleCount < $count ) {
631 $wgMemc->incr( $throttleKey );
632 } elseif ( $throttleCount >= $count ) {
637 return $throttleCount;
641 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
642 * @param $username string The user name
645 public static function clearLoginThrottle( $username ) {
646 global $wgMemc, $wgRequest;
647 $username = trim( $username ); // sanity
649 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
650 $wgMemc->delete( $throttleKey );
654 * Attempt to automatically create a user on login. Only succeeds if there
655 * is an external authentication method which allows it.
659 * @return integer Status code
661 function attemptAutoCreate( $user ) {
662 global $wgAuth, $wgAutocreatePolicy;
664 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
665 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
666 return self
::CREATE_BLOCKED
;
670 * If the external authentication plugin allows it, automatically cre-
671 * ate a new account for users that are externally defined but have not
674 if ( $this->mExtUser
) {
675 # mExtUser is neither null nor false, so use the new ExternalAuth
677 if ( $wgAutocreatePolicy == 'never' ) {
678 return self
::NOT_EXISTS
;
680 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
681 return self
::WRONG_PLUGIN_PASS
;
685 if ( !$wgAuth->autoCreate() ) {
686 return self
::NOT_EXISTS
;
688 if ( !$wgAuth->userExists( $user->getName() ) ) {
689 wfDebug( __METHOD__
. ": user does not exist\n" );
690 return self
::NOT_EXISTS
;
692 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
693 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
694 return self
::WRONG_PLUGIN_PASS
;
699 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
700 // Hook point to add extra creation throttles and blocks
701 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
702 $this->mAbortLoginErrorMsg
= $abortError;
703 return self
::ABORTED
;
706 wfDebug( __METHOD__
. ": creating account\n" );
707 $this->initUser( $user, true );
708 return self
::SUCCESS
;
711 function processLogin() {
712 global $wgMemc, $wgLang;
714 switch ( $this->authenticateUserData() ) {
716 # We've verified now, update the real record
717 $user = $this->getUser();
718 if( (bool)$this->mRemember
!= (bool)$user->getOption( 'rememberpassword' ) ) {
719 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
720 $user->saveSettings();
722 $user->invalidateCache();
725 self
::clearLoginToken();
727 // Reset the throttle
728 $request = $this->getRequest();
729 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
730 $wgMemc->delete( $key );
732 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
733 /* Replace the language object to provide user interface in
734 * correct language immediately on this first page load.
736 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
737 $userLang = Language
::factory( $code );
739 $this->getContext()->setLang( $userLang );
740 return $this->successfulLogin();
742 return $this->cookieRedirectCheck( 'login' );
746 case self
::NEED_TOKEN
:
747 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
749 case self
::WRONG_TOKEN
:
750 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
754 $this->mainLoginForm( $this->msg( 'noname' )->text() );
756 case self
::WRONG_PLUGIN_PASS
:
757 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
759 case self
::NOT_EXISTS
:
760 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
761 $this->mainLoginForm( $this->msg( 'nosuchuser',
762 wfEscapeWikiText( $this->mUsername
) )->parse() );
764 $this->mainLoginForm( $this->msg( 'nosuchusershort',
765 wfEscapeWikiText( $this->mUsername
) )->text() );
768 case self
::WRONG_PASS
:
769 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
771 case self
::EMPTY_PASS
:
772 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
774 case self
::RESET_PASS
:
775 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
777 case self
::CREATE_BLOCKED
:
778 $this->userBlockedMessage( $this->getUser()->mBlock
);
780 case self
::THROTTLED
:
781 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
783 case self
::USER_BLOCKED
:
784 $this->mainLoginForm( $this->msg( 'login-userblocked',
785 $this->mUsername
)->escaped() );
788 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
791 throw new MWException( 'Unhandled case value' );
795 function resetLoginForm( $error ) {
796 $this->getOutput()->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
797 $reset = new SpecialChangePassword();
798 $reset->setContext( $this );
799 $reset->execute( null );
803 * @param $u User object
804 * @param $throttle Boolean
805 * @param $emailTitle String: message name of email title
806 * @param $emailText String: message name of email text
807 * @return Status object
809 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
810 global $wgServer, $wgScript, $wgNewPasswordExpiry;
812 if ( $u->getEmail() == '' ) {
813 return Status
::newFatal( 'noemail', $u->getName() );
815 $ip = $this->getRequest()->getIP();
817 return Status
::newFatal( 'badipaddress' );
820 $currentUser = $this->getUser();
821 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
823 $np = $u->randomPassword();
824 $u->setNewpassword( $np, $throttle );
826 $userLanguage = $u->getOption( 'language' );
827 $m = $this->msg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript,
828 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
829 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
836 * Run any hooks registered for logins, then HTTP redirect to
837 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
838 * nice message here, but that's really not as useful as just being sent to
839 * wherever you logged in from. It should be clear that the action was
840 * successful, given the lack of error messages plus the appearance of your
841 * name in the upper right.
845 function successfulLogin() {
846 # Run any hooks; display injected HTML if any, else redirect
847 $currentUser = $this->getUser();
849 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
851 if( $injected_html !== '' ) {
852 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
854 $titleObj = Title
::newFromText( $this->mReturnTo
);
855 if ( !$titleObj instanceof Title
) {
856 $titleObj = Title
::newMainPage();
858 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery
);
859 global $wgSecureLogin;
860 if( $wgSecureLogin && !$this->mStickHTTPS
) {
861 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
863 $this->getOutput()->redirect( $redirectUrl );
868 * Run any hooks registered for logins, then display a message welcoming
873 function successfulCreation() {
874 # Run any hooks; display injected HTML
875 $currentUser = $this->getUser();
877 $welcome_creation_msg = 'welcomecreation';
879 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
881 //let any extensions change what message is shown
882 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
884 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
888 * Display a "login successful" page.
890 private function displaySuccessfulLogin( $msgname, $injected_html ) {
891 $out = $this->getOutput();
892 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
894 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
897 $out->addHTML( $injected_html );
899 if ( !empty( $this->mReturnTo
) ) {
900 $out->returnToMain( null, $this->mReturnTo
, $this->mReturnToQuery
);
902 $out->returnToMain( null );
907 * Output a message that informs the user that they cannot create an account because
908 * there is a block on them or their IP which prevents account creation. Note that
909 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
910 * setting on blocks (bug 13611).
911 * @param $block Block the block causing this error
913 function userBlockedMessage( Block
$block ) {
914 # Let's be nice about this, it's likely that this feature will be used
915 # for blocking large numbers of innocent people, e.g. range blocks on
916 # schools. Don't blame it on the user. There's a small chance that it
917 # really is the user's fault, i.e. the username is blocked and they
918 # haven't bothered to log out before trying to create an account to
919 # evade it, but we'll leave that to their guilty conscience to figure
922 $out = $this->getOutput();
923 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
925 $block_reason = $block->mReason
;
926 if ( strval( $block_reason ) === '' ) {
927 $block_reason = $this->msg( 'blockednoreason' )->text();
931 'cantcreateaccount-text',
937 $out->returnToMain( false );
943 function mainLoginForm( $msg, $msgtype = 'error' ) {
944 global $wgEnableEmail, $wgEnableUserEmail;
945 global $wgHiddenPrefs, $wgLoginLanguageSelector;
946 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
947 global $wgSecureLogin, $wgPasswordResetRoutes;
949 $titleObj = $this->getTitle();
950 $user = $this->getUser();
952 if ( $this->mType
== 'signup' ) {
953 // Block signup here if in readonly. Keeps user from
954 // going through the process (filling out data, etc)
955 // and being informed later.
956 if ( wfReadOnly() ) {
957 throw new ReadOnlyError
;
958 } elseif ( $user->isBlockedFromCreateAccount() ) {
959 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
961 } elseif ( count( $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true ) )>0 ) {
962 $this->getOutput()->showPermissionsErrorPage( $permErrors, 'createaccount' );
967 if ( $this->mUsername
== '' ) {
968 if ( $user->isLoggedIn() ) {
969 $this->mUsername
= $user->getName();
971 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
975 if ( $this->mType
== 'signup' ) {
976 $template = new UsercreateTemplate();
977 $q = 'action=submitlogin&type=signup';
978 $linkq = 'type=login';
979 $linkmsg = 'gotaccount';
981 $template = new UserloginTemplate();
982 $q = 'action=submitlogin&type=login';
983 $linkq = 'type=signup';
984 $linkmsg = 'nologin';
987 if ( !empty( $this->mReturnTo
) ) {
988 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
989 if ( !empty( $this->mReturnToQuery
) ) {
990 $returnto .= '&returntoquery=' .
991 wfUrlencode( $this->mReturnToQuery
);
997 # Don't show a "create account" link if the user can't
998 if( $this->showCreateOrLoginLink( $user ) ) {
999 # Pass any language selection on to the mode switch link
1000 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1001 $linkq .= '&uselang=' . $this->mLanguage
;
1003 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1004 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1006 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1008 $template->set( 'link', '' );
1011 $resetLink = $this->mType
== 'signup'
1013 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1015 $template->set( 'header', '' );
1016 $template->set( 'name', $this->mUsername
);
1017 $template->set( 'password', $this->mPassword
);
1018 $template->set( 'retype', $this->mRetype
);
1019 $template->set( 'email', $this->mEmail
);
1020 $template->set( 'realname', $this->mRealName
);
1021 $template->set( 'domain', $this->mDomain
);
1022 $template->set( 'reason', $this->mReason
);
1024 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1025 $template->set( 'message', $msg );
1026 $template->set( 'messagetype', $msgtype );
1027 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1028 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1029 $template->set( 'useemail', $wgEnableEmail );
1030 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1031 $template->set( 'emailothers', $wgEnableUserEmail );
1032 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1033 $template->set( 'resetlink', $resetLink );
1034 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1035 $template->set( 'usereason', $user->isLoggedIn() );
1036 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1037 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1038 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1040 if ( $this->mType
== 'signup' ) {
1041 if ( !self
::getCreateaccountToken() ) {
1042 self
::setCreateaccountToken();
1044 $template->set( 'token', self
::getCreateaccountToken() );
1046 if ( !self
::getLoginToken() ) {
1047 self
::setLoginToken();
1049 $template->set( 'token', self
::getLoginToken() );
1052 # Prepare language selection links as needed
1053 if( $wgLoginLanguageSelector ) {
1054 $template->set( 'languages', $this->makeLanguageSelector() );
1055 if( $this->mLanguage
)
1056 $template->set( 'uselang', $this->mLanguage
);
1059 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1060 // Ditto for signupend
1061 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1062 $loginendHTTPS = $this->msg( 'loginend-https' );
1063 $signupendHTTPS = $this->msg( 'signupend-https' );
1064 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1065 $template->set( 'loginend', $loginendHTTPS->parse() );
1067 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1069 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1070 $template->set( 'signupend', $signupendHTTPS->parse() );
1072 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1075 // Give authentication and captcha plugins a chance to modify the form
1076 $wgAuth->modifyUITemplate( $template, $this->mType
);
1077 if ( $this->mType
== 'signup' ) {
1078 wfRunHooks( 'UserCreateForm', array( &$template ) );
1080 wfRunHooks( 'UserLoginForm', array( &$template ) );
1083 $out = $this->getOutput();
1084 $out->disallowUserJs(); // just in case...
1085 $out->addTemplate( $template );
1095 function showCreateOrLoginLink( &$user ) {
1096 if( $this->mType
== 'signup' ) {
1098 } elseif( $user->isAllowed( 'createaccount' ) ) {
1106 * Check if a session cookie is present.
1108 * This will not pick up a cookie set during _this_ request, but is meant
1109 * to ensure that the client is returning the cookie which was set on a
1110 * previous pass through the system.
1114 function hasSessionCookie() {
1115 global $wgDisableCookieCheck;
1116 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1120 * Get the login token from the current session
1122 public static function getLoginToken() {
1124 return $wgRequest->getSessionData( 'wsLoginToken' );
1128 * Randomly generate a new login token and attach it to the current session
1130 public static function setLoginToken() {
1132 // Use User::generateToken() instead of $user->editToken()
1133 // because the latter reuses $_SESSION['wsEditToken']
1134 $wgRequest->setSessionData( 'wsLoginToken', User
::generateToken() );
1138 * Remove any login token attached to the current session
1140 public static function clearLoginToken() {
1142 $wgRequest->setSessionData( 'wsLoginToken', null );
1146 * Get the createaccount token from the current session
1148 public static function getCreateaccountToken() {
1150 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1154 * Randomly generate a new createaccount token and attach it to the current session
1156 public static function setCreateaccountToken() {
1158 $wgRequest->setSessionData( 'wsCreateaccountToken', User
::generateToken() );
1162 * Remove any createaccount token attached to the current session
1164 public static function clearCreateaccountToken() {
1166 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1172 function cookieRedirectCheck( $type ) {
1173 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1174 $query = array( 'wpCookieCheck' => $type );
1175 if ( $this->mReturnTo
) {
1176 $query['returnto'] = $this->mReturnTo
;
1178 $check = $titleObj->getFullURL( $query );
1180 return $this->getOutput()->redirect( $check );
1186 function onCookieRedirectCheck( $type ) {
1187 if ( !$this->hasSessionCookie() ) {
1188 if ( $type == 'new' ) {
1189 return $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1190 } elseif ( $type == 'login' ) {
1191 return $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1194 return $this->mainLoginForm( $this->msg( 'error' )->text() );
1197 return $this->successfulLogin();
1204 function throttleHit( $limit ) {
1205 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1209 * Produce a bar of links which allow the user to select another language
1210 * during login/registration but retain "returnto"
1214 function makeLanguageSelector() {
1215 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1216 if( !$msg->isBlank() ) {
1217 $langs = explode( "\n", $msg->text() );
1219 foreach( $langs as $lang ) {
1220 $lang = trim( $lang, '* ' );
1221 $parts = explode( '|', $lang );
1222 if ( count( $parts ) >= 2 ) {
1223 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1226 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1227 $this->getLang()->pipeList( $links ) )->escaped() : '';
1234 * Create a language selector link for a particular language
1235 * Links back to this page preserving type and returnto
1237 * @param $text Link text
1238 * @param $lang Language code
1240 function makeLanguageSelectorLink( $text, $lang ) {
1241 $attr = array( 'uselang' => $lang );
1242 if( $this->mType
== 'signup' ) {
1243 $attr['type'] = 'signup';
1245 if( $this->mReturnTo
) {
1246 $attr['returnto'] = $this->mReturnTo
;
1248 return Linker
::linkKnown(
1250 htmlspecialchars( $text ),