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 $this->mDomain
= $wgAuth->getDomain();
130 $wgAuth->setDomain( $this->mDomain
);
132 # 1. When switching accounts, it sucks to get automatically logged out
133 # 2. Do not return to PasswordReset after a successful password change
134 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
135 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
136 if( is_object( $returnToTitle ) && (
137 $returnToTitle->isSpecial( 'Userlogout' )
138 ||
$returnToTitle->isSpecial( 'PasswordReset' ) ) ) {
139 $this->mReturnTo
= '';
140 $this->mReturnToQuery
= '';
144 function getDescription() {
145 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 $this->addNewAccount();
168 } elseif ( $this->mCreateaccountMail
) {
169 $this->addNewAccountMailPassword();
171 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
172 $this->processLogin();
176 $this->mainLoginForm( '' );
182 function addNewAccountMailPassword() {
183 if ( $this->mEmail
== '' ) {
184 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
188 $u = $this->addNewaccountInternal();
194 // Wipe the initial password and mail a temporary one
195 $u->setPassword( null );
197 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
199 wfRunHooks( 'AddNewAccount', array( $u, true ) );
200 $u->addNewUserLogEntry( true, $this->mReason
);
202 $out = $this->getOutput();
203 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
205 if( !$result->isGood() ) {
206 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
208 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
209 $out->returnToMain( false );
217 function addNewAccount() {
218 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
220 # Create the account and abort if there's a problem doing so
221 $u = $this->addNewAccountInternal();
226 # If we showed up language selection links, and one was in use, be
227 # smart (and sensible) and save that language as the user's preference
228 if( $wgLoginLanguageSelector && $this->mLanguage
) {
229 $u->setOption( 'language', $this->mLanguage
);
232 $out = $this->getOutput();
234 # Send out an email authentication message if needed
235 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
236 $status = $u->sendConfirmationMail();
237 if( $status->isGood() ) {
238 $out->addWikiMsg( 'confirmemail_oncreate' );
240 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
244 # Save settings (including confirmation token)
247 # If not logged in, assume the new account as the current one and set
248 # session cookies then show a "welcome" message or a "need cookies"
250 if( $this->getUser()->isAnon() ) {
253 // This should set it for OutputPage and the Skin
254 // which is needed or the personal links will be
256 $this->getContext()->setUser( $u );
257 wfRunHooks( 'AddNewAccount', array( $u, false ) );
258 $u->addNewUserLogEntry();
259 if( $this->hasSessionCookie() ) {
260 $this->successfulCreation();
262 $this->cookieRedirectCheck( 'new' );
265 # Confirm that the account was created
266 $out->setPageTitle( $this->msg( 'accountcreated' ) );
267 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
268 $out->returnToMain( false, $this->getTitle() );
269 wfRunHooks( 'AddNewAccount', array( $u, false ) );
270 $u->addNewUserLogEntry( false, $this->mReason
);
279 function addNewAccountInternal() {
280 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
281 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
283 // If the user passes an invalid domain, something is fishy
284 if( !$wgAuth->validDomain( $this->mDomain
) ) {
285 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
289 // If we are not allowing users to login locally, we should be checking
290 // to see if the user is actually able to authenticate to the authenti-
291 // cation server before they create an account (otherwise, they can
292 // create a local account and login as any domain user). We only need
293 // to check this for domains that aren't local.
294 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
295 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername
)
296 ||
!$wgAuth->authenticate( $this->mUsername
, $this->mPassword
) ) ) {
297 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
302 if ( wfReadOnly() ) {
303 throw new ReadOnlyError
;
306 # Request forgery checks.
307 if ( !self
::getCreateaccountToken() ) {
308 self
::setCreateaccountToken();
309 $this->mainLoginForm( $this->msg( 'nocookiesfornew' )->parse() );
313 # The user didn't pass a createaccount token
314 if ( !$this->mToken
) {
315 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
319 # Validate the createaccount token
320 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
321 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
326 $currentUser = $this->getUser();
327 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
328 throw new PermissionsError( 'createaccount' );
329 } elseif ( $currentUser->isBlockedFromCreateAccount() ) {
330 $this->userBlockedMessage( $currentUser->isBlockedFromCreateAccount() );
334 # Include checks that will include GlobalBlocking (Bug 38333)
335 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'createaccount', $currentUser, true );
336 if ( count( $permErrors ) ) {
337 throw new PermissionsError( 'createaccount', $permErrors );
340 $ip = $this->getRequest()->getIP();
341 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
342 $this->mainLoginForm( $this->msg( 'sorbs_create_account_reason' )->text() . ' ' . $this->msg( 'parentheses', $ip )->escaped() );
346 # Now create a dummy user ($u) and check if it is valid
347 $name = trim( $this->mUsername
);
348 $u = User
::newFromName( $name, 'creatable' );
349 if ( !is_object( $u ) ) {
350 $this->mainLoginForm( $this->msg( 'noname' )->text() );
354 if ( 0 != $u->idForName() ) {
355 $this->mainLoginForm( $this->msg( 'userexists' )->text() );
359 if ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
360 $this->mainLoginForm( $this->msg( 'badretype' )->text() );
364 # check for minimal password length
365 $valid = $u->getPasswordValidity( $this->mPassword
);
366 if ( $valid !== true ) {
367 if ( !$this->mCreateaccountMail
) {
368 if ( is_array( $valid ) ) {
369 $message = array_shift( $valid );
373 $params = array( $wgMinimalPasswordLength );
375 $this->mainLoginForm( $this->msg( $message, $params )->text() );
378 # do not force a password for account creation by email
379 # set invalid password, it will be replaced later by a random generated password
380 $this->mPassword
= null;
384 # if you need a confirmed email address to edit, then obviously you
385 # need an email address.
386 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
387 $this->mainLoginForm( $this->msg( 'noemailtitle' )->text() );
391 if( !empty( $this->mEmail
) && !Sanitizer
::validateEmail( $this->mEmail
) ) {
392 $this->mainLoginForm( $this->msg( 'invalidemailaddress' )->text() );
396 # Set some additional data so the AbortNewAccount hook can be used for
397 # more than just username validation
398 $u->setEmail( $this->mEmail
);
399 $u->setRealName( $this->mRealName
);
402 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
403 // Hook point to add extra creation throttles and blocks
404 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
405 $this->mainLoginForm( $abortError );
409 // Hook point to check for exempt from account creation throttle
410 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
411 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
413 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
414 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
415 $value = $wgMemc->get( $key );
417 $wgMemc->set( $key, 0, 86400 );
419 if ( $value >= $wgAccountCreationThrottle ) {
420 $this->throttleHit( $wgAccountCreationThrottle );
423 $wgMemc->incr( $key );
427 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
428 $this->mainLoginForm( $this->msg( 'externaldberror' )->text() );
432 self
::clearCreateaccountToken();
433 return $this->initUser( $u, false );
437 * Actually add a user to the database.
438 * Give it a User object that has been initialised with a name.
440 * @param $u User object.
441 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
442 * @return User object.
445 function initUser( $u, $autocreate ) {
450 if ( $wgAuth->allowPasswordChange() ) {
451 $u->setPassword( $this->mPassword
);
454 $u->setEmail( $this->mEmail
);
455 $u->setRealName( $this->mRealName
);
458 $wgAuth->initUser( $u, $autocreate );
460 if ( $this->mExtUser
) {
461 $this->mExtUser
->linkToLocal( $u->getId() );
462 $email = $this->mExtUser
->getPref( 'emailaddress' );
463 if ( $email && !$this->mEmail
) {
464 $u->setEmail( $email );
468 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
472 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
473 $ssUpdate->doUpdate();
479 * Internally authenticate the login request.
481 * This may create a local account as a side effect if the
482 * authentication plugin allows transparent local account
486 public function authenticateUserData() {
487 global $wgUser, $wgAuth;
491 if ( $this->mUsername
== '' ) {
492 return self
::NO_NAME
;
495 // We require a login token to prevent login CSRF
496 // Handle part of this before incrementing the throttle so
497 // token-less login attempts don't count towards the throttle
498 // but wrong-token attempts do.
500 // If the user doesn't have a login token yet, set one.
501 if ( !self
::getLoginToken() ) {
502 self
::setLoginToken();
503 return self
::NEED_TOKEN
;
505 // If the user didn't pass a login token, tell them we need one
506 if ( !$this->mToken
) {
507 return self
::NEED_TOKEN
;
510 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
511 if ( $throttleCount === true ) {
512 return self
::THROTTLED
;
515 // Validate the login token
516 if ( $this->mToken
!== self
::getLoginToken() ) {
517 return self
::WRONG_TOKEN
;
520 // Load the current user now, and check to see if we're logging in as
521 // the same name. This is necessary because loading the current user
522 // (say by calling getName()) calls the UserLoadFromSession hook, which
523 // potentially creates the user in the database. Until we load $wgUser,
524 // checking for user existence using User::newFromName($name)->getId() below
525 // will effectively be using stale data.
526 if ( $this->getUser()->getName() === $this->mUsername
) {
527 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
528 return self
::SUCCESS
;
531 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
533 # TODO: Allow some magic here for invalid external names, e.g., let the
534 # user choose a different wiki name.
535 $u = User
::newFromName( $this->mUsername
);
536 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
537 return self
::ILLEGAL
;
540 $isAutoCreated = false;
541 if ( 0 == $u->getID() ) {
542 $status = $this->attemptAutoCreate( $u );
543 if ( $status !== self
::SUCCESS
) {
546 $isAutoCreated = true;
549 global $wgExternalAuthType, $wgAutocreatePolicy;
550 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
551 && is_object( $this->mExtUser
)
552 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
553 # The external user and local user have the same name and
554 # password, so we assume they're the same.
555 $this->mExtUser
->linkToLocal( $u->getID() );
561 // Give general extensions, such as a captcha, a chance to abort logins
562 $abort = self
::ABORTED
;
563 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
567 global $wgBlockDisablesLogin;
568 if ( !$u->checkPassword( $this->mPassword
) ) {
569 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
570 // The e-mailed temporary password should not be used for actu-
571 // al logins; that's a very sloppy habit, and insecure if an
572 // attacker has a few seconds to click "search" on someone's o-
575 // Allow it to be used only to reset the password a single time
576 // to a new value, which won't be in the user's e-mail ar-
579 // For backwards compatibility, we'll still recognize it at the
580 // login form to minimize surprises for people who have been
581 // logging in with a temporary password for some time.
583 // As a side-effect, we can authenticate the user's e-mail ad-
584 // dress if it's not already done, since the temporary password
585 // was sent via e-mail.
586 if( !$u->isEmailConfirmed() ) {
591 // At this point we just return an appropriate code/ indicating
592 // that the UI should show a password reset form; bot inter-
593 // faces etc will probably just fail cleanly here.
594 $retval = self
::RESET_PASS
;
596 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
598 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
599 // If we've enabled it, make it so that a blocked user cannot login
600 $retval = self
::USER_BLOCKED
;
602 $wgAuth->updateUser( $u );
604 // This should set it for OutputPage and the Skin
605 // which is needed or the personal links will be
607 $this->getContext()->setUser( $u );
609 // Please reset throttle for successful logins, thanks!
610 if ( $throttleCount ) {
611 self
::clearLoginThrottle( $this->mUsername
);
614 if ( $isAutoCreated ) {
615 // Must be run after $wgUser is set, for correct new user log
616 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
619 $retval = self
::SUCCESS
;
621 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
626 * Increment the login attempt throttle hit count for the (username,current IP)
627 * tuple unless the throttle was already reached.
628 * @param $username string The user name
629 * @return Bool|Integer The integer hit count or True if it is already at the limit
631 public static function incLoginThrottle( $username ) {
632 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
633 $username = trim( $username ); // sanity
636 if ( is_array( $wgPasswordAttemptThrottle ) ) {
637 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
638 $count = $wgPasswordAttemptThrottle['count'];
639 $period = $wgPasswordAttemptThrottle['seconds'];
641 $throttleCount = $wgMemc->get( $throttleKey );
642 if ( !$throttleCount ) {
643 $wgMemc->add( $throttleKey, 1, $period ); // start counter
644 } elseif ( $throttleCount < $count ) {
645 $wgMemc->incr( $throttleKey );
646 } elseif ( $throttleCount >= $count ) {
651 return $throttleCount;
655 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
656 * @param $username string The user name
659 public static function clearLoginThrottle( $username ) {
660 global $wgMemc, $wgRequest;
661 $username = trim( $username ); // sanity
663 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
664 $wgMemc->delete( $throttleKey );
668 * Attempt to automatically create a user on login. Only succeeds if there
669 * is an external authentication method which allows it.
673 * @return integer Status code
675 function attemptAutoCreate( $user ) {
676 global $wgAuth, $wgAutocreatePolicy;
678 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
679 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
680 return self
::CREATE_BLOCKED
;
684 * If the external authentication plugin allows it, automatically cre-
685 * ate a new account for users that are externally defined but have not
688 if ( $this->mExtUser
) {
689 # mExtUser is neither null nor false, so use the new ExternalAuth
691 if ( $wgAutocreatePolicy == 'never' ) {
692 return self
::NOT_EXISTS
;
694 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
695 return self
::WRONG_PLUGIN_PASS
;
699 if ( !$wgAuth->autoCreate() ) {
700 return self
::NOT_EXISTS
;
702 if ( !$wgAuth->userExists( $user->getName() ) ) {
703 wfDebug( __METHOD__
. ": user does not exist\n" );
704 return self
::NOT_EXISTS
;
706 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
707 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
708 return self
::WRONG_PLUGIN_PASS
;
713 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
714 // Hook point to add extra creation throttles and blocks
715 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
716 $this->mAbortLoginErrorMsg
= $abortError;
717 return self
::ABORTED
;
720 wfDebug( __METHOD__
. ": creating account\n" );
721 $this->initUser( $user, true );
722 return self
::SUCCESS
;
725 function processLogin() {
726 global $wgMemc, $wgLang;
728 switch ( $this->authenticateUserData() ) {
730 # We've verified now, update the real record
731 $user = $this->getUser();
732 if( (bool)$this->mRemember
!= (bool)$user->getOption( 'rememberpassword' ) ) {
733 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
734 $user->saveSettings();
736 $user->invalidateCache();
739 self
::clearLoginToken();
741 // Reset the throttle
742 $request = $this->getRequest();
743 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
744 $wgMemc->delete( $key );
746 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
747 /* Replace the language object to provide user interface in
748 * correct language immediately on this first page load.
750 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
751 $userLang = Language
::factory( $code );
753 $this->getContext()->setLanguage( $userLang );
754 $this->successfulLogin();
756 $this->cookieRedirectCheck( 'login' );
760 case self
::NEED_TOKEN
:
761 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
763 case self
::WRONG_TOKEN
:
764 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
768 $this->mainLoginForm( $this->msg( 'noname' )->text() );
770 case self
::WRONG_PLUGIN_PASS
:
771 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
773 case self
::NOT_EXISTS
:
774 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
775 $this->mainLoginForm( $this->msg( 'nosuchuser',
776 wfEscapeWikiText( $this->mUsername
) )->parse() );
778 $this->mainLoginForm( $this->msg( 'nosuchusershort',
779 wfEscapeWikiText( $this->mUsername
) )->text() );
782 case self
::WRONG_PASS
:
783 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
785 case self
::EMPTY_PASS
:
786 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
788 case self
::RESET_PASS
:
789 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
791 case self
::CREATE_BLOCKED
:
792 $this->userBlockedMessage( $this->getUser()->mBlock
);
794 case self
::THROTTLED
:
795 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
797 case self
::USER_BLOCKED
:
798 $this->mainLoginForm( $this->msg( 'login-userblocked',
799 $this->mUsername
)->escaped() );
802 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
805 throw new MWException( 'Unhandled case value' );
809 function resetLoginForm( $error ) {
810 $this->getOutput()->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
811 $reset = new SpecialChangePassword();
812 $reset->setContext( $this->getContext() );
813 $reset->execute( null );
817 * @param $u User object
818 * @param $throttle Boolean
819 * @param $emailTitle String: message name of email title
820 * @param $emailText String: message name of email text
821 * @return Status object
823 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
824 global $wgServer, $wgScript, $wgNewPasswordExpiry;
826 if ( $u->getEmail() == '' ) {
827 return Status
::newFatal( 'noemail', $u->getName() );
829 $ip = $this->getRequest()->getIP();
831 return Status
::newFatal( 'badipaddress' );
834 $currentUser = $this->getUser();
835 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
837 $np = $u->randomPassword();
838 $u->setNewpassword( $np, $throttle );
840 $userLanguage = $u->getOption( 'language' );
841 $m = $this->msg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript,
842 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
843 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
850 * Run any hooks registered for logins, then HTTP redirect to
851 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
852 * nice message here, but that's really not as useful as just being sent to
853 * wherever you logged in from. It should be clear that the action was
854 * successful, given the lack of error messages plus the appearance of your
855 * name in the upper right.
859 function successfulLogin() {
860 # Run any hooks; display injected HTML if any, else redirect
861 $currentUser = $this->getUser();
863 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
865 if( $injected_html !== '' ) {
866 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
868 $titleObj = Title
::newFromText( $this->mReturnTo
);
869 if ( !$titleObj instanceof Title
) {
870 $titleObj = Title
::newMainPage();
872 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery
);
873 global $wgSecureLogin;
874 if( $wgSecureLogin && !$this->mStickHTTPS
) {
875 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
877 $this->getOutput()->redirect( $redirectUrl );
882 * Run any hooks registered for logins, then display a message welcoming
887 function successfulCreation() {
888 # Run any hooks; display injected HTML
889 $currentUser = $this->getUser();
891 $welcome_creation_msg = 'welcomecreation';
893 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
896 * Let any extensions change what message is shown.
897 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
900 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
902 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
906 * Display a "login successful" page.
907 * @param $msgname string
908 * @param $injected_html string
910 private function displaySuccessfulLogin( $msgname, $injected_html ) {
911 $out = $this->getOutput();
912 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
914 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
917 $out->addHTML( $injected_html );
919 if ( !empty( $this->mReturnTo
) ) {
920 $out->returnToMain( null, $this->mReturnTo
, $this->mReturnToQuery
);
922 $out->returnToMain( null );
927 * Output a message that informs the user that they cannot create an account because
928 * there is a block on them or their IP which prevents account creation. Note that
929 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
930 * setting on blocks (bug 13611).
931 * @param $block Block the block causing this error
933 function userBlockedMessage( Block
$block ) {
934 # Let's be nice about this, it's likely that this feature will be used
935 # for blocking large numbers of innocent people, e.g. range blocks on
936 # schools. Don't blame it on the user. There's a small chance that it
937 # really is the user's fault, i.e. the username is blocked and they
938 # haven't bothered to log out before trying to create an account to
939 # evade it, but we'll leave that to their guilty conscience to figure
942 $out = $this->getOutput();
943 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
945 $block_reason = $block->mReason
;
946 if ( strval( $block_reason ) === '' ) {
947 $block_reason = $this->msg( 'blockednoreason' )->text();
951 'cantcreateaccount-text',
957 $out->returnToMain( false );
963 function mainLoginForm( $msg, $msgtype = 'error' ) {
964 global $wgEnableEmail, $wgEnableUserEmail;
965 global $wgHiddenPrefs, $wgLoginLanguageSelector;
966 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
967 global $wgSecureLogin, $wgPasswordResetRoutes;
969 $titleObj = $this->getTitle();
970 $user = $this->getUser();
972 if ( $this->mType
== 'signup' ) {
973 // Block signup here if in readonly. Keeps user from
974 // going through the process (filling out data, etc)
975 // and being informed later.
976 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
977 if ( count( $permErrors ) ) {
978 throw new PermissionsError( 'createaccount', $permErrors );
979 } elseif ( $user->isBlockedFromCreateAccount() ) {
980 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
982 } elseif ( wfReadOnly() ) {
983 throw new ReadOnlyError
;
987 if ( $this->mUsername
== '' ) {
988 if ( $user->isLoggedIn() ) {
989 $this->mUsername
= $user->getName();
991 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
995 if ( $this->mType
== 'signup' ) {
996 $template = new UsercreateTemplate();
997 $q = 'action=submitlogin&type=signup';
998 $linkq = 'type=login';
999 $linkmsg = 'gotaccount';
1001 $template = new UserloginTemplate();
1002 $q = 'action=submitlogin&type=login';
1003 $linkq = 'type=signup';
1004 $linkmsg = 'nologin';
1007 if ( !empty( $this->mReturnTo
) ) {
1008 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1009 if ( !empty( $this->mReturnToQuery
) ) {
1010 $returnto .= '&returntoquery=' .
1011 wfUrlencode( $this->mReturnToQuery
);
1014 $linkq .= $returnto;
1017 # Don't show a "create account" link if the user can't
1018 if( $this->showCreateOrLoginLink( $user ) ) {
1019 # Pass any language selection on to the mode switch link
1020 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1021 $linkq .= '&uselang=' . $this->mLanguage
;
1023 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1024 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1026 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1028 $template->set( 'link', '' );
1031 $resetLink = $this->mType
== 'signup'
1033 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1035 $template->set( 'header', '' );
1036 $template->set( 'name', $this->mUsername
);
1037 $template->set( 'password', $this->mPassword
);
1038 $template->set( 'retype', $this->mRetype
);
1039 $template->set( 'email', $this->mEmail
);
1040 $template->set( 'realname', $this->mRealName
);
1041 $template->set( 'domain', $this->mDomain
);
1042 $template->set( 'reason', $this->mReason
);
1044 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1045 $template->set( 'message', $msg );
1046 $template->set( 'messagetype', $msgtype );
1047 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1048 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1049 $template->set( 'useemail', $wgEnableEmail );
1050 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1051 $template->set( 'emailothers', $wgEnableUserEmail );
1052 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1053 $template->set( 'resetlink', $resetLink );
1054 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1055 $template->set( 'usereason', $user->isLoggedIn() );
1056 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1057 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1058 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1060 if ( $this->mType
== 'signup' ) {
1061 if ( !self
::getCreateaccountToken() ) {
1062 self
::setCreateaccountToken();
1064 $template->set( 'token', self
::getCreateaccountToken() );
1066 if ( !self
::getLoginToken() ) {
1067 self
::setLoginToken();
1069 $template->set( 'token', self
::getLoginToken() );
1072 # Prepare language selection links as needed
1073 if( $wgLoginLanguageSelector ) {
1074 $template->set( 'languages', $this->makeLanguageSelector() );
1075 if( $this->mLanguage
) {
1076 $template->set( 'uselang', $this->mLanguage
);
1080 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1081 // Ditto for signupend
1082 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1083 $loginendHTTPS = $this->msg( 'loginend-https' );
1084 $signupendHTTPS = $this->msg( 'signupend-https' );
1085 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1086 $template->set( 'loginend', $loginendHTTPS->parse() );
1088 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1090 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1091 $template->set( 'signupend', $signupendHTTPS->parse() );
1093 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1096 // Give authentication and captcha plugins a chance to modify the form
1097 $wgAuth->modifyUITemplate( $template, $this->mType
);
1098 if ( $this->mType
== 'signup' ) {
1099 wfRunHooks( 'UserCreateForm', array( &$template ) );
1101 wfRunHooks( 'UserLoginForm', array( &$template ) );
1104 $out = $this->getOutput();
1105 $out->disallowUserJs(); // just in case...
1106 $out->addTemplate( $template );
1116 function showCreateOrLoginLink( &$user ) {
1117 if( $this->mType
== 'signup' ) {
1119 } elseif( $user->isAllowed( 'createaccount' ) ) {
1127 * Check if a session cookie is present.
1129 * This will not pick up a cookie set during _this_ request, but is meant
1130 * to ensure that the client is returning the cookie which was set on a
1131 * previous pass through the system.
1136 function hasSessionCookie() {
1137 global $wgDisableCookieCheck;
1138 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1142 * Get the login token from the current session
1145 public static function getLoginToken() {
1147 return $wgRequest->getSessionData( 'wsLoginToken' );
1151 * Randomly generate a new login token and attach it to the current session
1153 public static function setLoginToken() {
1155 // Generate a token directly instead of using $user->editToken()
1156 // because the latter reuses $_SESSION['wsEditToken']
1157 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1161 * Remove any login token attached to the current session
1163 public static function clearLoginToken() {
1165 $wgRequest->setSessionData( 'wsLoginToken', null );
1169 * Get the createaccount token from the current session
1172 public static function getCreateaccountToken() {
1174 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1178 * Randomly generate a new createaccount token and attach it to the current session
1180 public static function setCreateaccountToken() {
1182 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1186 * Remove any createaccount token attached to the current session
1188 public static function clearCreateaccountToken() {
1190 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1196 function cookieRedirectCheck( $type ) {
1197 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1198 $query = array( 'wpCookieCheck' => $type );
1199 if ( $this->mReturnTo
) {
1200 $query['returnto'] = $this->mReturnTo
;
1202 $check = $titleObj->getFullURL( $query );
1204 $this->getOutput()->redirect( $check );
1210 function onCookieRedirectCheck( $type ) {
1211 if ( !$this->hasSessionCookie() ) {
1212 if ( $type == 'new' ) {
1213 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1214 } elseif ( $type == 'login' ) {
1215 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1218 $this->mainLoginForm( $this->msg( 'error' )->text() );
1221 $this->successfulLogin();
1228 function throttleHit( $limit ) {
1229 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1233 * Produce a bar of links which allow the user to select another language
1234 * during login/registration but retain "returnto"
1238 function makeLanguageSelector() {
1239 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1240 if( !$msg->isBlank() ) {
1241 $langs = explode( "\n", $msg->text() );
1243 foreach( $langs as $lang ) {
1244 $lang = trim( $lang, '* ' );
1245 $parts = explode( '|', $lang );
1246 if ( count( $parts ) >= 2 ) {
1247 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1250 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1251 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1258 * Create a language selector link for a particular language
1259 * Links back to this page preserving type and returnto
1261 * @param $text Link text
1262 * @param $lang Language code
1265 function makeLanguageSelectorLink( $text, $lang ) {
1266 if( $this->getLanguage()->getCode() == $lang ) {
1267 // no link for currently used language
1268 return htmlspecialchars( $text );
1270 $attr = array( 'uselang' => $lang );
1271 if( $this->mType
== 'signup' ) {
1272 $attr['type'] = 'signup';
1274 if( $this->mReturnTo
) {
1275 $attr['returnto'] = $this->mReturnTo
;
1277 return Linker
::linkKnown(
1279 htmlspecialchars( $text ),