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 );
214 function addNewAccount() {
215 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
217 # Create the account and abort if there's a problem doing so
218 $u = $this->addNewAccountInternal();
223 # If we showed up language selection links, and one was in use, be
224 # smart (and sensible) and save that language as the user's preference
225 if( $wgLoginLanguageSelector && $this->mLanguage
) {
226 $u->setOption( 'language', $this->mLanguage
);
229 $out = $this->getOutput();
231 # Send out an email authentication message if needed
232 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
233 $status = $u->sendConfirmationMail();
234 if( $status->isGood() ) {
235 $out->addWikiMsg( 'confirmemail_oncreate' );
237 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
241 # Save settings (including confirmation token)
244 # If not logged in, assume the new account as the current one and set
245 # session cookies then show a "welcome" message or a "need cookies"
247 if( $this->getUser()->isAnon() ) {
250 // This should set it for OutputPage and the Skin
251 // which is needed or the personal links will be
253 $this->getContext()->setUser( $u );
254 wfRunHooks( 'AddNewAccount', array( $u, false ) );
255 $u->addNewUserLogEntry();
256 if( $this->hasSessionCookie() ) {
257 return $this->successfulCreation();
259 return $this->cookieRedirectCheck( 'new' );
262 # Confirm that the account was created
263 $out->setPageTitle( $this->msg( 'accountcreated' ) );
264 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
265 $out->returnToMain( false, $this->getTitle() );
266 wfRunHooks( 'AddNewAccount', array( $u, false ) );
267 $u->addNewUserLogEntry( false, $this->mReason
);
276 function addNewAccountInternal() {
277 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
278 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
280 // If the user passes an invalid domain, something is fishy
281 if( !$wgAuth->validDomain( $this->mDomain
) ) {
282 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
286 // If we are not allowing users to login locally, we should be checking
287 // to see if the user is actually able to authenticate to the authenti-
288 // cation server before they create an account (otherwise, they can
289 // create a local account and login as any domain user). We only need
290 // to check this for domains that aren't local.
291 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
292 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername
)
293 ||
!$wgAuth->authenticate( $this->mUsername
, $this->mPassword
) ) ) {
294 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
299 if ( wfReadOnly() ) {
300 throw new ReadOnlyError
;
303 # Request forgery checks.
304 if ( !self
::getCreateaccountToken() ) {
305 self
::setCreateaccountToken();
306 $this->mainLoginForm( $this->msg( 'nocookiesfornew' )->parse() );
310 # The user didn't pass a createaccount token
311 if ( !$this->mToken
) {
312 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
316 # Validate the createaccount token
317 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
318 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
323 $currentUser = $this->getUser();
324 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
325 throw new PermissionsError( 'createaccount' );
326 } elseif ( $currentUser->isBlockedFromCreateAccount() ) {
327 $this->userBlockedMessage( $currentUser->isBlockedFromCreateAccount() );
331 $ip = $this->getRequest()->getIP();
332 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
333 $this->mainLoginForm( $this->msg( 'sorbs_create_account_reason' )->text() . ' (' . htmlspecialchars( $ip ) . ')' );
337 # Now create a dummy user ($u) and check if it is valid
338 $name = trim( $this->mUsername
);
339 $u = User
::newFromName( $name, 'creatable' );
340 if ( !is_object( $u ) ) {
341 $this->mainLoginForm( $this->msg( 'noname' )->text() );
345 if ( 0 != $u->idForName() ) {
346 $this->mainLoginForm( $this->msg( 'userexists' )->text() );
350 if ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
351 $this->mainLoginForm( $this->msg( 'badretype' )->text() );
355 # check for minimal password length
356 $valid = $u->getPasswordValidity( $this->mPassword
);
357 if ( $valid !== true ) {
358 if ( !$this->mCreateaccountMail
) {
359 if ( is_array( $valid ) ) {
360 $message = array_shift( $valid );
364 $params = array( $wgMinimalPasswordLength );
366 $this->mainLoginForm( $this->msg( $message, $params )->text() );
369 # do not force a password for account creation by email
370 # set invalid password, it will be replaced later by a random generated password
371 $this->mPassword
= null;
375 # if you need a confirmed email address to edit, then obviously you
376 # need an email address.
377 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
378 $this->mainLoginForm( $this->msg( 'noemailtitle' )->text() );
382 if( !empty( $this->mEmail
) && !Sanitizer
::validateEmail( $this->mEmail
) ) {
383 $this->mainLoginForm( $this->msg( 'invalidemailaddress' )->text() );
387 # Set some additional data so the AbortNewAccount hook can be used for
388 # more than just username validation
389 $u->setEmail( $this->mEmail
);
390 $u->setRealName( $this->mRealName
);
393 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
394 // Hook point to add extra creation throttles and blocks
395 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
396 $this->mainLoginForm( $abortError );
400 // Hook point to check for exempt from account creation throttle
401 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
402 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
404 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
405 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
406 $value = $wgMemc->get( $key );
408 $wgMemc->set( $key, 0, 86400 );
410 if ( $value >= $wgAccountCreationThrottle ) {
411 $this->throttleHit( $wgAccountCreationThrottle );
414 $wgMemc->incr( $key );
418 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
419 $this->mainLoginForm( $this->msg( 'externaldberror' )->text() );
423 self
::clearCreateaccountToken();
424 return $this->initUser( $u, false );
428 * Actually add a user to the database.
429 * Give it a User object that has been initialised with a name.
431 * @param $u User object.
432 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
433 * @return User object.
436 function initUser( $u, $autocreate ) {
441 if ( $wgAuth->allowPasswordChange() ) {
442 $u->setPassword( $this->mPassword
);
445 $u->setEmail( $this->mEmail
);
446 $u->setRealName( $this->mRealName
);
449 $wgAuth->initUser( $u, $autocreate );
451 if ( $this->mExtUser
) {
452 $this->mExtUser
->linkToLocal( $u->getId() );
453 $email = $this->mExtUser
->getPref( 'emailaddress' );
454 if ( $email && !$this->mEmail
) {
455 $u->setEmail( $email );
459 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
463 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
464 $ssUpdate->doUpdate();
470 * Internally authenticate the login request.
472 * This may create a local account as a side effect if the
473 * authentication plugin allows transparent local account
477 public function authenticateUserData() {
478 global $wgUser, $wgAuth;
482 if ( $this->mUsername
== '' ) {
483 return self
::NO_NAME
;
486 // We require a login token to prevent login CSRF
487 // Handle part of this before incrementing the throttle so
488 // token-less login attempts don't count towards the throttle
489 // but wrong-token attempts do.
491 // If the user doesn't have a login token yet, set one.
492 if ( !self
::getLoginToken() ) {
493 self
::setLoginToken();
494 return self
::NEED_TOKEN
;
496 // If the user didn't pass a login token, tell them we need one
497 if ( !$this->mToken
) {
498 return self
::NEED_TOKEN
;
501 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
502 if ( $throttleCount === true ) {
503 return self
::THROTTLED
;
506 // Validate the login token
507 if ( $this->mToken
!== self
::getLoginToken() ) {
508 return self
::WRONG_TOKEN
;
511 // Load the current user now, and check to see if we're logging in as
512 // the same name. This is necessary because loading the current user
513 // (say by calling getName()) calls the UserLoadFromSession hook, which
514 // potentially creates the user in the database. Until we load $wgUser,
515 // checking for user existence using User::newFromName($name)->getId() below
516 // will effectively be using stale data.
517 if ( $this->getUser()->getName() === $this->mUsername
) {
518 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
519 return self
::SUCCESS
;
522 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
524 # TODO: Allow some magic here for invalid external names, e.g., let the
525 # user choose a different wiki name.
526 $u = User
::newFromName( $this->mUsername
);
527 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
528 return self
::ILLEGAL
;
531 $isAutoCreated = false;
532 if ( 0 == $u->getID() ) {
533 $status = $this->attemptAutoCreate( $u );
534 if ( $status !== self
::SUCCESS
) {
537 $isAutoCreated = true;
540 global $wgExternalAuthType, $wgAutocreatePolicy;
541 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
542 && is_object( $this->mExtUser
)
543 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
544 # The external user and local user have the same name and
545 # password, so we assume they're the same.
546 $this->mExtUser
->linkToLocal( $u->getID() );
552 // Give general extensions, such as a captcha, a chance to abort logins
553 $abort = self
::ABORTED
;
554 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
558 global $wgBlockDisablesLogin;
559 if ( !$u->checkPassword( $this->mPassword
) ) {
560 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
561 // The e-mailed temporary password should not be used for actu-
562 // al logins; that's a very sloppy habit, and insecure if an
563 // attacker has a few seconds to click "search" on someone's o-
566 // Allow it to be used only to reset the password a single time
567 // to a new value, which won't be in the user's e-mail ar-
570 // For backwards compatibility, we'll still recognize it at the
571 // login form to minimize surprises for people who have been
572 // logging in with a temporary password for some time.
574 // As a side-effect, we can authenticate the user's e-mail ad-
575 // dress if it's not already done, since the temporary password
576 // was sent via e-mail.
577 if( !$u->isEmailConfirmed() ) {
582 // At this point we just return an appropriate code/ indicating
583 // that the UI should show a password reset form; bot inter-
584 // faces etc will probably just fail cleanly here.
585 $retval = self
::RESET_PASS
;
587 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
589 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
590 // If we've enabled it, make it so that a blocked user cannot login
591 $retval = self
::USER_BLOCKED
;
593 $wgAuth->updateUser( $u );
595 // This should set it for OutputPage and the Skin
596 // which is needed or the personal links will be
598 $this->getContext()->setUser( $u );
600 // Please reset throttle for successful logins, thanks!
601 if ( $throttleCount ) {
602 self
::clearLoginThrottle( $this->mUsername
);
605 if ( $isAutoCreated ) {
606 // Must be run after $wgUser is set, for correct new user log
607 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
610 $retval = self
::SUCCESS
;
612 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
617 * Increment the login attempt throttle hit count for the (username,current IP)
618 * tuple unless the throttle was already reached.
619 * @param $username string The user name
620 * @return Bool|Integer The integer hit count or True if it is already at the limit
622 public static function incLoginThrottle( $username ) {
623 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
624 $username = trim( $username ); // sanity
627 if ( is_array( $wgPasswordAttemptThrottle ) ) {
628 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
629 $count = $wgPasswordAttemptThrottle['count'];
630 $period = $wgPasswordAttemptThrottle['seconds'];
632 $throttleCount = $wgMemc->get( $throttleKey );
633 if ( !$throttleCount ) {
634 $wgMemc->add( $throttleKey, 1, $period ); // start counter
635 } elseif ( $throttleCount < $count ) {
636 $wgMemc->incr( $throttleKey );
637 } elseif ( $throttleCount >= $count ) {
642 return $throttleCount;
646 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
647 * @param $username string The user name
650 public static function clearLoginThrottle( $username ) {
651 global $wgMemc, $wgRequest;
652 $username = trim( $username ); // sanity
654 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
655 $wgMemc->delete( $throttleKey );
659 * Attempt to automatically create a user on login. Only succeeds if there
660 * is an external authentication method which allows it.
664 * @return integer Status code
666 function attemptAutoCreate( $user ) {
667 global $wgAuth, $wgAutocreatePolicy;
669 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
670 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
671 return self
::CREATE_BLOCKED
;
675 * If the external authentication plugin allows it, automatically cre-
676 * ate a new account for users that are externally defined but have not
679 if ( $this->mExtUser
) {
680 # mExtUser is neither null nor false, so use the new ExternalAuth
682 if ( $wgAutocreatePolicy == 'never' ) {
683 return self
::NOT_EXISTS
;
685 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
686 return self
::WRONG_PLUGIN_PASS
;
690 if ( !$wgAuth->autoCreate() ) {
691 return self
::NOT_EXISTS
;
693 if ( !$wgAuth->userExists( $user->getName() ) ) {
694 wfDebug( __METHOD__
. ": user does not exist\n" );
695 return self
::NOT_EXISTS
;
697 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
698 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
699 return self
::WRONG_PLUGIN_PASS
;
704 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
705 // Hook point to add extra creation throttles and blocks
706 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
707 $this->mAbortLoginErrorMsg
= $abortError;
708 return self
::ABORTED
;
711 wfDebug( __METHOD__
. ": creating account\n" );
712 $this->initUser( $user, true );
713 return self
::SUCCESS
;
716 function processLogin() {
717 global $wgMemc, $wgLang;
719 switch ( $this->authenticateUserData() ) {
721 # We've verified now, update the real record
722 $user = $this->getUser();
723 if( (bool)$this->mRemember
!= (bool)$user->getOption( 'rememberpassword' ) ) {
724 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
725 $user->saveSettings();
727 $user->invalidateCache();
730 self
::clearLoginToken();
732 // Reset the throttle
733 $request = $this->getRequest();
734 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
735 $wgMemc->delete( $key );
737 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
738 /* Replace the language object to provide user interface in
739 * correct language immediately on this first page load.
741 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
742 $userLang = Language
::factory( $code );
744 $this->getContext()->setLanguage( $userLang );
745 return $this->successfulLogin();
747 return $this->cookieRedirectCheck( 'login' );
751 case self
::NEED_TOKEN
:
752 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
754 case self
::WRONG_TOKEN
:
755 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
759 $this->mainLoginForm( $this->msg( 'noname' )->text() );
761 case self
::WRONG_PLUGIN_PASS
:
762 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
764 case self
::NOT_EXISTS
:
765 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
766 $this->mainLoginForm( $this->msg( 'nosuchuser',
767 wfEscapeWikiText( $this->mUsername
) )->parse() );
769 $this->mainLoginForm( $this->msg( 'nosuchusershort',
770 wfEscapeWikiText( $this->mUsername
) )->text() );
773 case self
::WRONG_PASS
:
774 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
776 case self
::EMPTY_PASS
:
777 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
779 case self
::RESET_PASS
:
780 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
782 case self
::CREATE_BLOCKED
:
783 $this->userBlockedMessage( $this->getUser()->mBlock
);
785 case self
::THROTTLED
:
786 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
788 case self
::USER_BLOCKED
:
789 $this->mainLoginForm( $this->msg( 'login-userblocked',
790 $this->mUsername
)->escaped() );
793 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
796 throw new MWException( 'Unhandled case value' );
800 function resetLoginForm( $error ) {
801 $this->getOutput()->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
802 $reset = new SpecialChangePassword();
803 $reset->setContext( $this );
804 $reset->execute( null );
808 * @param $u User object
809 * @param $throttle Boolean
810 * @param $emailTitle String: message name of email title
811 * @param $emailText String: message name of email text
812 * @return Status object
814 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
815 global $wgServer, $wgScript, $wgNewPasswordExpiry;
817 if ( $u->getEmail() == '' ) {
818 return Status
::newFatal( 'noemail', $u->getName() );
820 $ip = $this->getRequest()->getIP();
822 return Status
::newFatal( 'badipaddress' );
825 $currentUser = $this->getUser();
826 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
828 $np = $u->randomPassword();
829 $u->setNewpassword( $np, $throttle );
831 $userLanguage = $u->getOption( 'language' );
832 $m = $this->msg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript,
833 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
834 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
841 * Run any hooks registered for logins, then HTTP redirect to
842 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
843 * nice message here, but that's really not as useful as just being sent to
844 * wherever you logged in from. It should be clear that the action was
845 * successful, given the lack of error messages plus the appearance of your
846 * name in the upper right.
850 function successfulLogin() {
851 # Run any hooks; display injected HTML if any, else redirect
852 $currentUser = $this->getUser();
854 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
856 if( $injected_html !== '' ) {
857 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
859 $titleObj = Title
::newFromText( $this->mReturnTo
);
860 if ( !$titleObj instanceof Title
) {
861 $titleObj = Title
::newMainPage();
863 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery
);
864 global $wgSecureLogin;
865 if( $wgSecureLogin && !$this->mStickHTTPS
) {
866 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
868 $this->getOutput()->redirect( $redirectUrl );
873 * Run any hooks registered for logins, then display a message welcoming
878 function successfulCreation() {
879 # Run any hooks; display injected HTML
880 $currentUser = $this->getUser();
882 $welcome_creation_msg = 'welcomecreation';
884 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
887 * Let any extensions change what message is shown.
888 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
891 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
893 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
897 * Display a "login successful" page.
899 private function displaySuccessfulLogin( $msgname, $injected_html ) {
900 $out = $this->getOutput();
901 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
903 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
906 $out->addHTML( $injected_html );
908 if ( !empty( $this->mReturnTo
) ) {
909 $out->returnToMain( null, $this->mReturnTo
, $this->mReturnToQuery
);
911 $out->returnToMain( null );
916 * Output a message that informs the user that they cannot create an account because
917 * there is a block on them or their IP which prevents account creation. Note that
918 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
919 * setting on blocks (bug 13611).
920 * @param $block Block the block causing this error
922 function userBlockedMessage( Block
$block ) {
923 # Let's be nice about this, it's likely that this feature will be used
924 # for blocking large numbers of innocent people, e.g. range blocks on
925 # schools. Don't blame it on the user. There's a small chance that it
926 # really is the user's fault, i.e. the username is blocked and they
927 # haven't bothered to log out before trying to create an account to
928 # evade it, but we'll leave that to their guilty conscience to figure
931 $out = $this->getOutput();
932 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
934 $block_reason = $block->mReason
;
935 if ( strval( $block_reason ) === '' ) {
936 $block_reason = $this->msg( 'blockednoreason' )->text();
940 'cantcreateaccount-text',
946 $out->returnToMain( false );
952 function mainLoginForm( $msg, $msgtype = 'error' ) {
953 global $wgEnableEmail, $wgEnableUserEmail;
954 global $wgHiddenPrefs, $wgLoginLanguageSelector;
955 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
956 global $wgSecureLogin, $wgPasswordResetRoutes;
958 $titleObj = $this->getTitle();
959 $user = $this->getUser();
961 if ( $this->mType
== 'signup' ) {
962 // Block signup here if in readonly. Keeps user from
963 // going through the process (filling out data, etc)
964 // and being informed later.
965 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
966 if ( count( $permErrors ) ) {
967 throw new PermissionsError( 'createaccount', $permErrors );
968 } elseif ( $user->isBlockedFromCreateAccount() ) {
969 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
971 } elseif ( wfReadOnly() ) {
972 throw new ReadOnlyError
;
976 if ( $this->mUsername
== '' ) {
977 if ( $user->isLoggedIn() ) {
978 $this->mUsername
= $user->getName();
980 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
984 if ( $this->mType
== 'signup' ) {
985 $template = new UsercreateTemplate();
986 $q = 'action=submitlogin&type=signup';
987 $linkq = 'type=login';
988 $linkmsg = 'gotaccount';
990 $template = new UserloginTemplate();
991 $q = 'action=submitlogin&type=login';
992 $linkq = 'type=signup';
993 $linkmsg = 'nologin';
996 if ( !empty( $this->mReturnTo
) ) {
997 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
998 if ( !empty( $this->mReturnToQuery
) ) {
999 $returnto .= '&returntoquery=' .
1000 wfUrlencode( $this->mReturnToQuery
);
1003 $linkq .= $returnto;
1006 # Don't show a "create account" link if the user can't
1007 if( $this->showCreateOrLoginLink( $user ) ) {
1008 # Pass any language selection on to the mode switch link
1009 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1010 $linkq .= '&uselang=' . $this->mLanguage
;
1012 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1013 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1015 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1017 $template->set( 'link', '' );
1020 $resetLink = $this->mType
== 'signup'
1022 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1024 $template->set( 'header', '' );
1025 $template->set( 'name', $this->mUsername
);
1026 $template->set( 'password', $this->mPassword
);
1027 $template->set( 'retype', $this->mRetype
);
1028 $template->set( 'email', $this->mEmail
);
1029 $template->set( 'realname', $this->mRealName
);
1030 $template->set( 'domain', $this->mDomain
);
1031 $template->set( 'reason', $this->mReason
);
1033 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1034 $template->set( 'message', $msg );
1035 $template->set( 'messagetype', $msgtype );
1036 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1037 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1038 $template->set( 'useemail', $wgEnableEmail );
1039 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1040 $template->set( 'emailothers', $wgEnableUserEmail );
1041 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1042 $template->set( 'resetlink', $resetLink );
1043 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1044 $template->set( 'usereason', $user->isLoggedIn() );
1045 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1046 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1047 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1049 if ( $this->mType
== 'signup' ) {
1050 if ( !self
::getCreateaccountToken() ) {
1051 self
::setCreateaccountToken();
1053 $template->set( 'token', self
::getCreateaccountToken() );
1055 if ( !self
::getLoginToken() ) {
1056 self
::setLoginToken();
1058 $template->set( 'token', self
::getLoginToken() );
1061 # Prepare language selection links as needed
1062 if( $wgLoginLanguageSelector ) {
1063 $template->set( 'languages', $this->makeLanguageSelector() );
1064 if( $this->mLanguage
) {
1065 $template->set( 'uselang', $this->mLanguage
);
1069 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1070 // Ditto for signupend
1071 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1072 $loginendHTTPS = $this->msg( 'loginend-https' );
1073 $signupendHTTPS = $this->msg( 'signupend-https' );
1074 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1075 $template->set( 'loginend', $loginendHTTPS->parse() );
1077 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1079 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1080 $template->set( 'signupend', $signupendHTTPS->parse() );
1082 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1085 // Give authentication and captcha plugins a chance to modify the form
1086 $wgAuth->modifyUITemplate( $template, $this->mType
);
1087 if ( $this->mType
== 'signup' ) {
1088 wfRunHooks( 'UserCreateForm', array( &$template ) );
1090 wfRunHooks( 'UserLoginForm', array( &$template ) );
1093 $out = $this->getOutput();
1094 $out->disallowUserJs(); // just in case...
1095 $out->addTemplate( $template );
1105 function showCreateOrLoginLink( &$user ) {
1106 if( $this->mType
== 'signup' ) {
1108 } elseif( $user->isAllowed( 'createaccount' ) ) {
1116 * Check if a session cookie is present.
1118 * This will not pick up a cookie set during _this_ request, but is meant
1119 * to ensure that the client is returning the cookie which was set on a
1120 * previous pass through the system.
1125 function hasSessionCookie() {
1126 global $wgDisableCookieCheck;
1127 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1131 * Get the login token from the current session
1134 public static function getLoginToken() {
1136 return $wgRequest->getSessionData( 'wsLoginToken' );
1140 * Randomly generate a new login token and attach it to the current session
1142 public static function setLoginToken() {
1144 // Use User::generateToken() instead of $user->editToken()
1145 // because the latter reuses $_SESSION['wsEditToken']
1146 $wgRequest->setSessionData( 'wsLoginToken', User
::generateToken() );
1150 * Remove any login token attached to the current session
1152 public static function clearLoginToken() {
1154 $wgRequest->setSessionData( 'wsLoginToken', null );
1158 * Get the createaccount token from the current session
1161 public static function getCreateaccountToken() {
1163 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1167 * Randomly generate a new createaccount token and attach it to the current session
1169 public static function setCreateaccountToken() {
1171 $wgRequest->setSessionData( 'wsCreateaccountToken', User
::generateToken() );
1175 * Remove any createaccount token attached to the current session
1177 public static function clearCreateaccountToken() {
1179 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1186 function cookieRedirectCheck( $type ) {
1187 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1188 $query = array( 'wpCookieCheck' => $type );
1189 if ( $this->mReturnTo
) {
1190 $query['returnto'] = $this->mReturnTo
;
1192 $check = $titleObj->getFullURL( $query );
1194 return $this->getOutput()->redirect( $check );
1200 function onCookieRedirectCheck( $type ) {
1201 if ( !$this->hasSessionCookie() ) {
1202 if ( $type == 'new' ) {
1203 return $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1204 } elseif ( $type == 'login' ) {
1205 return $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1208 return $this->mainLoginForm( $this->msg( 'error' )->text() );
1211 return $this->successfulLogin();
1218 function throttleHit( $limit ) {
1219 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1223 * Produce a bar of links which allow the user to select another language
1224 * during login/registration but retain "returnto"
1228 function makeLanguageSelector() {
1229 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1230 if( !$msg->isBlank() ) {
1231 $langs = explode( "\n", $msg->text() );
1233 foreach( $langs as $lang ) {
1234 $lang = trim( $lang, '* ' );
1235 $parts = explode( '|', $lang );
1236 if ( count( $parts ) >= 2 ) {
1237 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1240 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1241 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1248 * Create a language selector link for a particular language
1249 * Links back to this page preserving type and returnto
1251 * @param $text Link text
1252 * @param $lang Language code
1255 function makeLanguageSelectorLink( $text, $lang ) {
1256 $attr = array( 'uselang' => $lang );
1257 if( $this->mType
== 'signup' ) {
1258 $attr['type'] = 'signup';
1260 if( $this->mReturnTo
) {
1261 $attr['returnto'] = $this->mReturnTo
;
1263 return Linker
::linkKnown(
1265 htmlspecialchars( $text ),