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;
77 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail, $wgRedirectOnLogin;
79 if ( $this->mLoaded
) {
82 $this->mLoaded
= true;
84 if ( $this->mOverrideRequest
=== null ) {
85 $request = $this->getRequest();
87 $request = $this->mOverrideRequest
;
90 $this->mType
= $request->getText( 'type' );
91 $this->mUsername
= $request->getText( 'wpName' );
92 $this->mPassword
= $request->getText( 'wpPassword' );
93 $this->mRetype
= $request->getText( 'wpRetype' );
94 $this->mDomain
= $request->getText( 'wpDomain' );
95 $this->mReason
= $request->getText( 'wpReason' );
96 $this->mReturnTo
= $request->getVal( 'returnto' );
97 $this->mReturnToQuery
= $request->getVal( 'returntoquery' );
98 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
99 $this->mPosted
= $request->wasPosted();
100 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' );
101 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
103 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
104 $this->mAction
= $request->getVal( 'action' );
105 $this->mRemember
= $request->getCheck( 'wpRemember' );
106 $this->mStickHTTPS
= $request->getCheck( 'wpStickHTTPS' );
107 $this->mLanguage
= $request->getText( 'uselang' );
108 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
109 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
111 if ( $wgRedirectOnLogin ) {
112 $this->mReturnTo
= $wgRedirectOnLogin;
113 $this->mReturnToQuery
= '';
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 if ( isset( $_SESSION['wsDomain'] ) ) {
129 $this->mDomain
= $_SESSION['wsDomain'];
131 $this->mDomain
= 'invaliddomain';
134 $wgAuth->setDomain( $this->mDomain
);
136 # When switching accounts, it sucks to get automatically logged out
137 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
138 if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
139 $this->mReturnTo
= '';
140 $this->mReturnToQuery
= '';
144 function getDescription() {
145 return $this->msg( $this->getUser()->isAllowed( 'createaccount' ) ?
146 'userlogin' : 'userloginnocreate' )->text();
149 public function execute( $par ) {
150 if ( session_id() == '' ) {
157 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
158 $this->mType
= 'signup';
161 if ( !is_null( $this->mCookieCheck
) ) {
162 $this->onCookieRedirectCheck( $this->mCookieCheck
);
164 } elseif( $this->mPosted
) {
165 if( $this->mCreateaccount
) {
166 return $this->addNewAccount();
167 } elseif ( $this->mCreateaccountMail
) {
168 return $this->addNewAccountMailPassword();
169 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
170 return $this->processLogin();
173 $this->mainLoginForm( '' );
179 function addNewAccountMailPassword() {
180 if ( $this->mEmail
== '' ) {
181 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
185 $u = $this->addNewaccountInternal();
191 // Wipe the initial password and mail a temporary one
192 $u->setPassword( null );
194 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
196 wfRunHooks( 'AddNewAccount', array( $u, true ) );
197 $u->addNewUserLogEntry( true, $this->mReason
);
199 $out = $this->getOutput();
200 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
202 if( !$result->isGood() ) {
203 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
205 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
206 $out->returnToMain( false );
213 function addNewAccount() {
214 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
216 # Create the account and abort if there's a problem doing so
217 $u = $this->addNewAccountInternal();
222 # If we showed up language selection links, and one was in use, be
223 # smart (and sensible) and save that language as the user's preference
224 if( $wgLoginLanguageSelector && $this->mLanguage
) {
225 $u->setOption( 'language', $this->mLanguage
);
228 $out = $this->getOutput();
230 # Send out an email authentication message if needed
231 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
232 $status = $u->sendConfirmationMail();
233 if( $status->isGood() ) {
234 $out->addWikiMsg( 'confirmemail_oncreate' );
236 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
240 # Save settings (including confirmation token)
243 # If not logged in, assume the new account as the current one and set
244 # session cookies then show a "welcome" message or a "need cookies"
246 if( $this->getUser()->isAnon() ) {
249 // This should set it for OutputPage and the Skin
250 // which is needed or the personal links will be
252 $this->getContext()->setUser( $u );
253 wfRunHooks( 'AddNewAccount', array( $u, false ) );
254 $u->addNewUserLogEntry();
255 if( $this->hasSessionCookie() ) {
256 return $this->successfulCreation();
258 return $this->cookieRedirectCheck( 'new' );
261 # Confirm that the account was created
262 $out->setPageTitle( $this->msg( 'accountcreated' ) );
263 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
264 $out->returnToMain( false, $this->getTitle() );
265 wfRunHooks( 'AddNewAccount', array( $u, false ) );
266 $u->addNewUserLogEntry( false, $this->mReason
);
274 function addNewAccountInternal() {
275 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
276 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
278 // If the user passes an invalid domain, something is fishy
279 if( !$wgAuth->validDomain( $this->mDomain
) ) {
280 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
284 // If we are not allowing users to login locally, we should be checking
285 // to see if the user is actually able to authenticate to the authenti-
286 // cation server before they create an account (otherwise, they can
287 // create a local account and login as any domain user). We only need
288 // to check this for domains that aren't local.
289 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
290 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername
)
291 ||
!$wgAuth->authenticate( $this->mUsername
, $this->mPassword
) ) ) {
292 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
297 if ( wfReadOnly() ) {
298 throw new ReadOnlyError
;
301 # Request forgery checks.
302 if ( !self
::getCreateaccountToken() ) {
303 self
::setCreateaccountToken();
304 $this->mainLoginForm( $this->msg( 'nocookiesfornew' )->parse() );
308 # The user didn't pass a createaccount token
309 if ( !$this->mToken
) {
310 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
314 # Validate the createaccount token
315 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
316 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
321 $currentUser = $this->getUser();
322 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
323 throw new PermissionsError( 'createaccount' );
324 } elseif ( $currentUser->isBlockedFromCreateAccount() ) {
325 $this->userBlockedMessage( $currentUser->isBlockedFromCreateAccount() );
329 $ip = $this->getRequest()->getIP();
330 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
331 $this->mainLoginForm( $this->msg( 'sorbs_create_account_reason' )->text() . ' (' . htmlspecialchars( $ip ) . ')' );
335 # Now create a dummy user ($u) and check if it is valid
336 $name = trim( $this->mUsername
);
337 $u = User
::newFromName( $name, 'creatable' );
338 if ( !is_object( $u ) ) {
339 $this->mainLoginForm( $this->msg( 'noname' )->text() );
343 if ( 0 != $u->idForName() ) {
344 $this->mainLoginForm( $this->msg( 'userexists' )->text() );
348 if ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
349 $this->mainLoginForm( $this->msg( 'badretype' )->text() );
353 # check for minimal password length
354 $valid = $u->getPasswordValidity( $this->mPassword
);
355 if ( $valid !== true ) {
356 if ( !$this->mCreateaccountMail
) {
357 if ( is_array( $valid ) ) {
358 $message = array_shift( $valid );
362 $params = array( $wgMinimalPasswordLength );
364 $this->mainLoginForm( $this->msg( $message, $params )->text() );
367 # do not force a password for account creation by email
368 # set invalid password, it will be replaced later by a random generated password
369 $this->mPassword
= null;
373 # if you need a confirmed email address to edit, then obviously you
374 # need an email address.
375 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
376 $this->mainLoginForm( $this->msg( 'noemailtitle' )->text() );
380 if( !empty( $this->mEmail
) && !Sanitizer
::validateEmail( $this->mEmail
) ) {
381 $this->mainLoginForm( $this->msg( 'invalidemailaddress' )->text() );
385 # Set some additional data so the AbortNewAccount hook can be used for
386 # more than just username validation
387 $u->setEmail( $this->mEmail
);
388 $u->setRealName( $this->mRealName
);
391 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
392 // Hook point to add extra creation throttles and blocks
393 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
394 $this->mainLoginForm( $abortError );
398 // Hook point to check for exempt from account creation throttle
399 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
400 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
402 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
403 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
404 $value = $wgMemc->get( $key );
406 $wgMemc->set( $key, 0, 86400 );
408 if ( $value >= $wgAccountCreationThrottle ) {
409 $this->throttleHit( $wgAccountCreationThrottle );
412 $wgMemc->incr( $key );
416 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
417 $this->mainLoginForm( $this->msg( 'externaldberror' )->text() );
421 self
::clearCreateaccountToken();
422 return $this->initUser( $u, false );
426 * Actually add a user to the database.
427 * Give it a User object that has been initialised with a name.
429 * @param $u User object.
430 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
431 * @return User object.
434 function initUser( $u, $autocreate ) {
439 if ( $wgAuth->allowPasswordChange() ) {
440 $u->setPassword( $this->mPassword
);
443 $u->setEmail( $this->mEmail
);
444 $u->setRealName( $this->mRealName
);
447 $wgAuth->initUser( $u, $autocreate );
449 if ( $this->mExtUser
) {
450 $this->mExtUser
->linkToLocal( $u->getId() );
451 $email = $this->mExtUser
->getPref( 'emailaddress' );
452 if ( $email && !$this->mEmail
) {
453 $u->setEmail( $email );
457 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
461 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
462 $ssUpdate->doUpdate();
468 * Internally authenticate the login request.
470 * This may create a local account as a side effect if the
471 * authentication plugin allows transparent local account
474 public function authenticateUserData() {
475 global $wgUser, $wgAuth;
479 if ( $this->mUsername
== '' ) {
480 return self
::NO_NAME
;
483 // We require a login token to prevent login CSRF
484 // Handle part of this before incrementing the throttle so
485 // token-less login attempts don't count towards the throttle
486 // but wrong-token attempts do.
488 // If the user doesn't have a login token yet, set one.
489 if ( !self
::getLoginToken() ) {
490 self
::setLoginToken();
491 return self
::NEED_TOKEN
;
493 // If the user didn't pass a login token, tell them we need one
494 if ( !$this->mToken
) {
495 return self
::NEED_TOKEN
;
498 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
499 if ( $throttleCount === true ) {
500 return self
::THROTTLED
;
503 // Validate the login token
504 if ( $this->mToken
!== self
::getLoginToken() ) {
505 return self
::WRONG_TOKEN
;
508 // Load the current user now, and check to see if we're logging in as
509 // the same name. This is necessary because loading the current user
510 // (say by calling getName()) calls the UserLoadFromSession hook, which
511 // potentially creates the user in the database. Until we load $wgUser,
512 // checking for user existence using User::newFromName($name)->getId() below
513 // will effectively be using stale data.
514 if ( $this->getUser()->getName() === $this->mUsername
) {
515 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
516 return self
::SUCCESS
;
519 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
521 # TODO: Allow some magic here for invalid external names, e.g., let the
522 # user choose a different wiki name.
523 $u = User
::newFromName( $this->mUsername
);
524 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
525 return self
::ILLEGAL
;
528 $isAutoCreated = false;
529 if ( 0 == $u->getID() ) {
530 $status = $this->attemptAutoCreate( $u );
531 if ( $status !== self
::SUCCESS
) {
534 $isAutoCreated = true;
537 global $wgExternalAuthType, $wgAutocreatePolicy;
538 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
539 && is_object( $this->mExtUser
)
540 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
541 # The external user and local user have the same name and
542 # password, so we assume they're the same.
543 $this->mExtUser
->linkToLocal( $u->getID() );
549 // Give general extensions, such as a captcha, a chance to abort logins
550 $abort = self
::ABORTED
;
551 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
555 global $wgBlockDisablesLogin;
556 if ( !$u->checkPassword( $this->mPassword
) ) {
557 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
558 // The e-mailed temporary password should not be used for actu-
559 // al logins; that's a very sloppy habit, and insecure if an
560 // attacker has a few seconds to click "search" on someone's o-
563 // Allow it to be used only to reset the password a single time
564 // to a new value, which won't be in the user's e-mail ar-
567 // For backwards compatibility, we'll still recognize it at the
568 // login form to minimize surprises for people who have been
569 // logging in with a temporary password for some time.
571 // As a side-effect, we can authenticate the user's e-mail ad-
572 // dress if it's not already done, since the temporary password
573 // was sent via e-mail.
574 if( !$u->isEmailConfirmed() ) {
579 // At this point we just return an appropriate code/ indicating
580 // that the UI should show a password reset form; bot inter-
581 // faces etc will probably just fail cleanly here.
582 $retval = self
::RESET_PASS
;
584 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
586 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
587 // If we've enabled it, make it so that a blocked user cannot login
588 $retval = self
::USER_BLOCKED
;
590 $wgAuth->updateUser( $u );
592 // This should set it for OutputPage and the Skin
593 // which is needed or the personal links will be
595 $this->getContext()->setUser( $u );
597 // Please reset throttle for successful logins, thanks!
598 if ( $throttleCount ) {
599 self
::clearLoginThrottle( $this->mUsername
);
602 if ( $isAutoCreated ) {
603 // Must be run after $wgUser is set, for correct new user log
604 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
607 $retval = self
::SUCCESS
;
609 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
614 * Increment the login attempt throttle hit count for the (username,current IP)
615 * tuple unless the throttle was already reached.
616 * @param $username string The user name
617 * @return Bool|Integer The integer hit count or True if it is already at the limit
619 public static function incLoginThrottle( $username ) {
620 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
621 $username = trim( $username ); // sanity
624 if ( is_array( $wgPasswordAttemptThrottle ) ) {
625 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
626 $count = $wgPasswordAttemptThrottle['count'];
627 $period = $wgPasswordAttemptThrottle['seconds'];
629 $throttleCount = $wgMemc->get( $throttleKey );
630 if ( !$throttleCount ) {
631 $wgMemc->add( $throttleKey, 1, $period ); // start counter
632 } elseif ( $throttleCount < $count ) {
633 $wgMemc->incr( $throttleKey );
634 } elseif ( $throttleCount >= $count ) {
639 return $throttleCount;
643 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
644 * @param $username string The user name
647 public static function clearLoginThrottle( $username ) {
648 global $wgMemc, $wgRequest;
649 $username = trim( $username ); // sanity
651 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
652 $wgMemc->delete( $throttleKey );
656 * Attempt to automatically create a user on login. Only succeeds if there
657 * is an external authentication method which allows it.
661 * @return integer Status code
663 function attemptAutoCreate( $user ) {
664 global $wgAuth, $wgAutocreatePolicy;
666 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
667 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
668 return self
::CREATE_BLOCKED
;
672 * If the external authentication plugin allows it, automatically cre-
673 * ate a new account for users that are externally defined but have not
676 if ( $this->mExtUser
) {
677 # mExtUser is neither null nor false, so use the new ExternalAuth
679 if ( $wgAutocreatePolicy == 'never' ) {
680 return self
::NOT_EXISTS
;
682 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
683 return self
::WRONG_PLUGIN_PASS
;
687 if ( !$wgAuth->autoCreate() ) {
688 return self
::NOT_EXISTS
;
690 if ( !$wgAuth->userExists( $user->getName() ) ) {
691 wfDebug( __METHOD__
. ": user does not exist\n" );
692 return self
::NOT_EXISTS
;
694 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
695 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
696 return self
::WRONG_PLUGIN_PASS
;
701 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
702 // Hook point to add extra creation throttles and blocks
703 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
704 $this->mAbortLoginErrorMsg
= $abortError;
705 return self
::ABORTED
;
708 wfDebug( __METHOD__
. ": creating account\n" );
709 $this->initUser( $user, true );
710 return self
::SUCCESS
;
713 function processLogin() {
714 global $wgMemc, $wgLang;
716 switch ( $this->authenticateUserData() ) {
718 # We've verified now, update the real record
719 $user = $this->getUser();
720 if( (bool)$this->mRemember
!= (bool)$user->getOption( 'rememberpassword' ) ) {
721 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
722 $user->saveSettings();
724 $user->invalidateCache();
727 self
::clearLoginToken();
729 // Reset the throttle
730 $request = $this->getRequest();
731 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
732 $wgMemc->delete( $key );
734 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
735 /* Replace the language object to provide user interface in
736 * correct language immediately on this first page load.
738 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
739 $userLang = Language
::factory( $code );
741 $this->getContext()->setLanguage( $userLang );
742 return $this->successfulLogin();
744 return $this->cookieRedirectCheck( 'login' );
748 case self
::NEED_TOKEN
:
749 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
751 case self
::WRONG_TOKEN
:
752 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
756 $this->mainLoginForm( $this->msg( 'noname' )->text() );
758 case self
::WRONG_PLUGIN_PASS
:
759 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
761 case self
::NOT_EXISTS
:
762 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
763 $this->mainLoginForm( $this->msg( 'nosuchuser',
764 wfEscapeWikiText( $this->mUsername
) )->parse() );
766 $this->mainLoginForm( $this->msg( 'nosuchusershort',
767 wfEscapeWikiText( $this->mUsername
) )->text() );
770 case self
::WRONG_PASS
:
771 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
773 case self
::EMPTY_PASS
:
774 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
776 case self
::RESET_PASS
:
777 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
779 case self
::CREATE_BLOCKED
:
780 $this->userBlockedMessage( $this->getUser()->mBlock
);
782 case self
::THROTTLED
:
783 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
785 case self
::USER_BLOCKED
:
786 $this->mainLoginForm( $this->msg( 'login-userblocked',
787 $this->mUsername
)->escaped() );
790 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
793 throw new MWException( 'Unhandled case value' );
797 function resetLoginForm( $error ) {
798 $this->getOutput()->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
799 $reset = new SpecialChangePassword();
800 $reset->setContext( $this );
801 $reset->execute( null );
805 * @param $u User object
806 * @param $throttle Boolean
807 * @param $emailTitle String: message name of email title
808 * @param $emailText String: message name of email text
809 * @return Status object
811 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
812 global $wgServer, $wgScript, $wgNewPasswordExpiry;
814 if ( $u->getEmail() == '' ) {
815 return Status
::newFatal( 'noemail', $u->getName() );
817 $ip = $this->getRequest()->getIP();
819 return Status
::newFatal( 'badipaddress' );
822 $currentUser = $this->getUser();
823 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
825 $np = $u->randomPassword();
826 $u->setNewpassword( $np, $throttle );
828 $userLanguage = $u->getOption( 'language' );
829 $m = $this->msg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript,
830 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
831 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
838 * Run any hooks registered for logins, then HTTP redirect to
839 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
840 * nice message here, but that's really not as useful as just being sent to
841 * wherever you logged in from. It should be clear that the action was
842 * successful, given the lack of error messages plus the appearance of your
843 * name in the upper right.
847 function successfulLogin() {
848 # Run any hooks; display injected HTML if any, else redirect
849 $currentUser = $this->getUser();
851 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
853 if( $injected_html !== '' ) {
854 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
856 $titleObj = Title
::newFromText( $this->mReturnTo
);
857 if ( !$titleObj instanceof Title
) {
858 $titleObj = Title
::newMainPage();
860 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery
);
861 global $wgSecureLogin;
862 if( $wgSecureLogin && !$this->mStickHTTPS
) {
863 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
865 $this->getOutput()->redirect( $redirectUrl );
870 * Run any hooks registered for logins, then display a message welcoming
875 function successfulCreation() {
876 # Run any hooks; display injected HTML
877 $currentUser = $this->getUser();
879 $welcome_creation_msg = 'welcomecreation';
881 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
884 * Let any extensions change what message is shown.
885 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
888 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
890 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
894 * Display a "login successful" page.
896 private function displaySuccessfulLogin( $msgname, $injected_html ) {
897 $out = $this->getOutput();
898 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
900 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
903 $out->addHTML( $injected_html );
905 if ( !empty( $this->mReturnTo
) ) {
906 $out->returnToMain( null, $this->mReturnTo
, $this->mReturnToQuery
);
908 $out->returnToMain( null );
913 * Output a message that informs the user that they cannot create an account because
914 * there is a block on them or their IP which prevents account creation. Note that
915 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
916 * setting on blocks (bug 13611).
917 * @param $block Block the block causing this error
919 function userBlockedMessage( Block
$block ) {
920 # Let's be nice about this, it's likely that this feature will be used
921 # for blocking large numbers of innocent people, e.g. range blocks on
922 # schools. Don't blame it on the user. There's a small chance that it
923 # really is the user's fault, i.e. the username is blocked and they
924 # haven't bothered to log out before trying to create an account to
925 # evade it, but we'll leave that to their guilty conscience to figure
928 $out = $this->getOutput();
929 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
931 $block_reason = $block->mReason
;
932 if ( strval( $block_reason ) === '' ) {
933 $block_reason = $this->msg( 'blockednoreason' )->text();
937 'cantcreateaccount-text',
943 $out->returnToMain( false );
949 function mainLoginForm( $msg, $msgtype = 'error' ) {
950 global $wgEnableEmail, $wgEnableUserEmail;
951 global $wgHiddenPrefs, $wgLoginLanguageSelector;
952 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
953 global $wgSecureLogin, $wgPasswordResetRoutes;
955 $titleObj = $this->getTitle();
956 $user = $this->getUser();
958 if ( $this->mType
== 'signup' ) {
959 // Block signup here if in readonly. Keeps user from
960 // going through the process (filling out data, etc)
961 // and being informed later.
962 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
963 if ( count( $permErrors ) ) {
964 throw new PermissionsError( 'createaccount', $permErrors );
965 } elseif ( $user->isBlockedFromCreateAccount() ) {
966 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
968 } elseif ( wfReadOnly() ) {
969 throw new ReadOnlyError
;
973 if ( $this->mUsername
== '' ) {
974 if ( $user->isLoggedIn() ) {
975 $this->mUsername
= $user->getName();
977 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
981 if ( $this->mType
== 'signup' ) {
982 $template = new UsercreateTemplate();
983 $q = 'action=submitlogin&type=signup';
984 $linkq = 'type=login';
985 $linkmsg = 'gotaccount';
987 $template = new UserloginTemplate();
988 $q = 'action=submitlogin&type=login';
989 $linkq = 'type=signup';
990 $linkmsg = 'nologin';
993 if ( !empty( $this->mReturnTo
) ) {
994 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
995 if ( !empty( $this->mReturnToQuery
) ) {
996 $returnto .= '&returntoquery=' .
997 wfUrlencode( $this->mReturnToQuery
);
1000 $linkq .= $returnto;
1003 # Don't show a "create account" link if the user can't
1004 if( $this->showCreateOrLoginLink( $user ) ) {
1005 # Pass any language selection on to the mode switch link
1006 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1007 $linkq .= '&uselang=' . $this->mLanguage
;
1009 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1010 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1012 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1014 $template->set( 'link', '' );
1017 $resetLink = $this->mType
== 'signup'
1019 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1021 $template->set( 'header', '' );
1022 $template->set( 'name', $this->mUsername
);
1023 $template->set( 'password', $this->mPassword
);
1024 $template->set( 'retype', $this->mRetype
);
1025 $template->set( 'email', $this->mEmail
);
1026 $template->set( 'realname', $this->mRealName
);
1027 $template->set( 'domain', $this->mDomain
);
1028 $template->set( 'reason', $this->mReason
);
1030 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1031 $template->set( 'message', $msg );
1032 $template->set( 'messagetype', $msgtype );
1033 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1034 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1035 $template->set( 'useemail', $wgEnableEmail );
1036 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1037 $template->set( 'emailothers', $wgEnableUserEmail );
1038 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1039 $template->set( 'resetlink', $resetLink );
1040 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1041 $template->set( 'usereason', $user->isLoggedIn() );
1042 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1043 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1044 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1046 if ( $this->mType
== 'signup' ) {
1047 if ( !self
::getCreateaccountToken() ) {
1048 self
::setCreateaccountToken();
1050 $template->set( 'token', self
::getCreateaccountToken() );
1052 if ( !self
::getLoginToken() ) {
1053 self
::setLoginToken();
1055 $template->set( 'token', self
::getLoginToken() );
1058 # Prepare language selection links as needed
1059 if( $wgLoginLanguageSelector ) {
1060 $template->set( 'languages', $this->makeLanguageSelector() );
1061 if( $this->mLanguage
) {
1062 $template->set( 'uselang', $this->mLanguage
);
1066 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1067 // Ditto for signupend
1068 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1069 $loginendHTTPS = $this->msg( 'loginend-https' );
1070 $signupendHTTPS = $this->msg( 'signupend-https' );
1071 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1072 $template->set( 'loginend', $loginendHTTPS->parse() );
1074 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1076 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1077 $template->set( 'signupend', $signupendHTTPS->parse() );
1079 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1082 // Give authentication and captcha plugins a chance to modify the form
1083 $wgAuth->modifyUITemplate( $template, $this->mType
);
1084 if ( $this->mType
== 'signup' ) {
1085 wfRunHooks( 'UserCreateForm', array( &$template ) );
1087 wfRunHooks( 'UserLoginForm', array( &$template ) );
1090 $out = $this->getOutput();
1091 $out->disallowUserJs(); // just in case...
1092 $out->addTemplate( $template );
1102 function showCreateOrLoginLink( &$user ) {
1103 if( $this->mType
== 'signup' ) {
1105 } elseif( $user->isAllowed( 'createaccount' ) ) {
1113 * Check if a session cookie is present.
1115 * This will not pick up a cookie set during _this_ request, but is meant
1116 * to ensure that the client is returning the cookie which was set on a
1117 * previous pass through the system.
1121 function hasSessionCookie() {
1122 global $wgDisableCookieCheck;
1123 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1127 * Get the login token from the current session
1129 public static function getLoginToken() {
1131 return $wgRequest->getSessionData( 'wsLoginToken' );
1135 * Randomly generate a new login token and attach it to the current session
1137 public static function setLoginToken() {
1139 // Use User::generateToken() instead of $user->editToken()
1140 // because the latter reuses $_SESSION['wsEditToken']
1141 $wgRequest->setSessionData( 'wsLoginToken', User
::generateToken() );
1145 * Remove any login token attached to the current session
1147 public static function clearLoginToken() {
1149 $wgRequest->setSessionData( 'wsLoginToken', null );
1153 * Get the createaccount token from the current session
1155 public static function getCreateaccountToken() {
1157 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1161 * Randomly generate a new createaccount token and attach it to the current session
1163 public static function setCreateaccountToken() {
1165 $wgRequest->setSessionData( 'wsCreateaccountToken', User
::generateToken() );
1169 * Remove any createaccount token attached to the current session
1171 public static function clearCreateaccountToken() {
1173 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1179 function cookieRedirectCheck( $type ) {
1180 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1181 $query = array( 'wpCookieCheck' => $type );
1182 if ( $this->mReturnTo
) {
1183 $query['returnto'] = $this->mReturnTo
;
1185 $check = $titleObj->getFullURL( $query );
1187 return $this->getOutput()->redirect( $check );
1193 function onCookieRedirectCheck( $type ) {
1194 if ( !$this->hasSessionCookie() ) {
1195 if ( $type == 'new' ) {
1196 return $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1197 } elseif ( $type == 'login' ) {
1198 return $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1201 return $this->mainLoginForm( $this->msg( 'error' )->text() );
1204 return $this->successfulLogin();
1211 function throttleHit( $limit ) {
1212 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1216 * Produce a bar of links which allow the user to select another language
1217 * during login/registration but retain "returnto"
1221 function makeLanguageSelector() {
1222 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1223 if( !$msg->isBlank() ) {
1224 $langs = explode( "\n", $msg->text() );
1226 foreach( $langs as $lang ) {
1227 $lang = trim( $lang, '* ' );
1228 $parts = explode( '|', $lang );
1229 if ( count( $parts ) >= 2 ) {
1230 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1233 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1234 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1241 * Create a language selector link for a particular language
1242 * Links back to this page preserving type and returnto
1244 * @param $text Link text
1245 * @param $lang Language code
1247 function makeLanguageSelectorLink( $text, $lang ) {
1248 $attr = array( 'uselang' => $lang );
1249 if( $this->mType
== 'signup' ) {
1250 $attr['type'] = 'signup';
1252 if( $this->mReturnTo
) {
1253 $attr['returnto'] = $this->mReturnTo
;
1255 return Linker
::linkKnown(
1257 htmlspecialchars( $text ),