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;
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->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
97 $this->mPosted
= $request->wasPosted();
98 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' );
99 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
101 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
102 $this->mAction
= $request->getVal( 'action' );
103 $this->mRemember
= $request->getCheck( 'wpRemember' );
104 $this->mStickHTTPS
= $request->getCheck( 'wpStickHTTPS' );
105 $this->mLanguage
= $request->getText( 'uselang' );
106 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
107 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
108 $this->mReturnTo
= $request->getVal( 'returnto', '' );
109 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
111 if( $wgEnableEmail ) {
112 $this->mEmail
= $request->getText( 'wpEmail' );
116 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
117 $this->mRealName
= $request->getText( 'wpRealName' );
119 $this->mRealName
= '';
122 if( !$wgAuth->validDomain( $this->mDomain
) ) {
123 $this->mDomain
= $wgAuth->getDomain();
125 $wgAuth->setDomain( $this->mDomain
);
127 # 1. When switching accounts, it sucks to get automatically logged out
128 # 2. Do not return to PasswordReset after a successful password change
129 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
130 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
131 if( is_object( $returnToTitle ) && (
132 $returnToTitle->isSpecial( 'Userlogout' )
133 ||
$returnToTitle->isSpecial( 'PasswordReset' ) ) ) {
134 $this->mReturnTo
= '';
135 $this->mReturnToQuery
= '';
139 function getDescription() {
140 return $this->msg( $this->getUser()->isAllowed( 'createaccount' ) ?
141 'userlogin' : 'userloginnocreate' )->text();
144 public function execute( $par ) {
145 if ( session_id() == '' ) {
152 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
153 $this->mType
= 'signup';
156 if ( !is_null( $this->mCookieCheck
) ) {
157 $this->onCookieRedirectCheck( $this->mCookieCheck
);
159 } elseif( $this->mPosted
) {
160 if( $this->mCreateaccount
) {
161 $this->addNewAccount();
163 } elseif ( $this->mCreateaccountMail
) {
164 $this->addNewAccountMailPassword();
166 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
167 $this->processLogin();
171 $this->mainLoginForm( '' );
177 function addNewAccountMailPassword() {
178 if ( $this->mEmail
== '' ) {
179 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
183 $u = $this->addNewaccountInternal();
189 // Wipe the initial password and mail a temporary one
190 $u->setPassword( null );
192 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
194 wfRunHooks( 'AddNewAccount', array( $u, true ) );
195 $u->addNewUserLogEntry( true, $this->mReason
);
197 $out = $this->getOutput();
198 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
200 if( !$result->isGood() ) {
201 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
203 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
204 $this->executeReturnTo( 'success' );
212 function addNewAccount() {
213 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
215 # Create the account and abort if there's a problem doing so
216 $u = $this->addNewAccountInternal();
221 # If we showed up language selection links, and one was in use, be
222 # smart (and sensible) and save that language as the user's preference
223 if( $wgLoginLanguageSelector && $this->mLanguage
) {
224 $u->setOption( 'language', $this->mLanguage
);
227 $out = $this->getOutput();
229 # Send out an email authentication message if needed
230 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
231 $status = $u->sendConfirmationMail();
232 if( $status->isGood() ) {
233 $out->addWikiMsg( 'confirmemail_oncreate' );
235 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
239 # Save settings (including confirmation token)
242 # If not logged in, assume the new account as the current one and set
243 # session cookies then show a "welcome" message or a "need cookies"
245 if( $this->getUser()->isAnon() ) {
248 // This should set it for OutputPage and the Skin
249 // which is needed or the personal links will be
251 $this->getContext()->setUser( $u );
252 wfRunHooks( 'AddNewAccount', array( $u, false ) );
253 $u->addNewUserLogEntry();
254 if( $this->hasSessionCookie() ) {
255 $this->successfulCreation();
257 $this->cookieRedirectCheck( 'new' );
260 # Confirm that the account was created
261 $out->setPageTitle( $this->msg( 'accountcreated' ) );
262 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
263 $out->addReturnTo( $this->getTitle() );
264 wfRunHooks( 'AddNewAccount', array( $u, false ) );
265 $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 # Include checks that will include GlobalBlocking (Bug 38333)
330 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'createaccount', $currentUser, true );
331 if ( count( $permErrors ) ) {
332 throw new PermissionsError( 'createaccount', $permErrors );
335 $ip = $this->getRequest()->getIP();
336 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
337 $this->mainLoginForm( $this->msg( 'sorbs_create_account_reason' )->text() . ' ' . $this->msg( 'parentheses', $ip )->escaped() );
341 # Now create a dummy user ($u) and check if it is valid
342 $name = trim( $this->mUsername
);
343 $u = User
::newFromName( $name, 'creatable' );
344 if ( !is_object( $u ) ) {
345 $this->mainLoginForm( $this->msg( 'noname' )->text() );
349 if ( 0 != $u->idForName() ) {
350 $this->mainLoginForm( $this->msg( 'userexists' )->text() );
354 if ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
355 $this->mainLoginForm( $this->msg( 'badretype' )->text() );
359 # check for minimal password length
360 $valid = $u->getPasswordValidity( $this->mPassword
);
361 if ( $valid !== true ) {
362 if ( !$this->mCreateaccountMail
) {
363 if ( is_array( $valid ) ) {
364 $message = array_shift( $valid );
368 $params = array( $wgMinimalPasswordLength );
370 $this->mainLoginForm( $this->msg( $message, $params )->text() );
373 # do not force a password for account creation by email
374 # set invalid password, it will be replaced later by a random generated password
375 $this->mPassword
= null;
379 # if you need a confirmed email address to edit, then obviously you
380 # need an email address.
381 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
382 $this->mainLoginForm( $this->msg( 'noemailtitle' )->text() );
386 if( !empty( $this->mEmail
) && !Sanitizer
::validateEmail( $this->mEmail
) ) {
387 $this->mainLoginForm( $this->msg( 'invalidemailaddress' )->text() );
391 # Set some additional data so the AbortNewAccount hook can be used for
392 # more than just username validation
393 $u->setEmail( $this->mEmail
);
394 $u->setRealName( $this->mRealName
);
397 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
398 // Hook point to add extra creation throttles and blocks
399 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
400 $this->mainLoginForm( $abortError );
404 // Hook point to check for exempt from account creation throttle
405 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
406 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
408 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
409 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
410 $value = $wgMemc->get( $key );
412 $wgMemc->set( $key, 0, 86400 );
414 if ( $value >= $wgAccountCreationThrottle ) {
415 $this->throttleHit( $wgAccountCreationThrottle );
418 $wgMemc->incr( $key );
422 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
423 $this->mainLoginForm( $this->msg( 'externaldberror' )->text() );
427 self
::clearCreateaccountToken();
428 return $this->initUser( $u, false );
432 * Actually add a user to the database.
433 * Give it a User object that has been initialised with a name.
435 * @param $u User object.
436 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
437 * @return User object.
440 function initUser( $u, $autocreate ) {
445 if ( $wgAuth->allowPasswordChange() ) {
446 $u->setPassword( $this->mPassword
);
449 $u->setEmail( $this->mEmail
);
450 $u->setRealName( $this->mRealName
);
453 $wgAuth->initUser( $u, $autocreate );
455 if ( $this->mExtUser
) {
456 $this->mExtUser
->linkToLocal( $u->getId() );
457 $email = $this->mExtUser
->getPref( 'emailaddress' );
458 if ( $email && !$this->mEmail
) {
459 $u->setEmail( $email );
463 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
467 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
473 * Internally authenticate the login request.
475 * This may create a local account as a side effect if the
476 * authentication plugin allows transparent local account
480 public function authenticateUserData() {
481 global $wgUser, $wgAuth;
485 if ( $this->mUsername
== '' ) {
486 return self
::NO_NAME
;
489 // We require a login token to prevent login CSRF
490 // Handle part of this before incrementing the throttle so
491 // token-less login attempts don't count towards the throttle
492 // but wrong-token attempts do.
494 // If the user doesn't have a login token yet, set one.
495 if ( !self
::getLoginToken() ) {
496 self
::setLoginToken();
497 return self
::NEED_TOKEN
;
499 // If the user didn't pass a login token, tell them we need one
500 if ( !$this->mToken
) {
501 return self
::NEED_TOKEN
;
504 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
505 if ( $throttleCount === true ) {
506 return self
::THROTTLED
;
509 // Validate the login token
510 if ( $this->mToken
!== self
::getLoginToken() ) {
511 return self
::WRONG_TOKEN
;
514 // Load the current user now, and check to see if we're logging in as
515 // the same name. This is necessary because loading the current user
516 // (say by calling getName()) calls the UserLoadFromSession hook, which
517 // potentially creates the user in the database. Until we load $wgUser,
518 // checking for user existence using User::newFromName($name)->getId() below
519 // will effectively be using stale data.
520 if ( $this->getUser()->getName() === $this->mUsername
) {
521 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
522 return self
::SUCCESS
;
525 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
527 # TODO: Allow some magic here for invalid external names, e.g., let the
528 # user choose a different wiki name.
529 $u = User
::newFromName( $this->mUsername
);
530 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
531 return self
::ILLEGAL
;
534 $isAutoCreated = false;
535 if ( 0 == $u->getID() ) {
536 $status = $this->attemptAutoCreate( $u );
537 if ( $status !== self
::SUCCESS
) {
540 $isAutoCreated = true;
543 global $wgExternalAuthType, $wgAutocreatePolicy;
544 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
545 && is_object( $this->mExtUser
)
546 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
547 # The external user and local user have the same name and
548 # password, so we assume they're the same.
549 $this->mExtUser
->linkToLocal( $u->getID() );
555 // Give general extensions, such as a captcha, a chance to abort logins
556 $abort = self
::ABORTED
;
557 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
561 global $wgBlockDisablesLogin;
562 if ( !$u->checkPassword( $this->mPassword
) ) {
563 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
564 // The e-mailed temporary password should not be used for actu-
565 // al logins; that's a very sloppy habit, and insecure if an
566 // attacker has a few seconds to click "search" on someone's o-
569 // Allow it to be used only to reset the password a single time
570 // to a new value, which won't be in the user's e-mail ar-
573 // For backwards compatibility, we'll still recognize it at the
574 // login form to minimize surprises for people who have been
575 // logging in with a temporary password for some time.
577 // As a side-effect, we can authenticate the user's e-mail ad-
578 // dress if it's not already done, since the temporary password
579 // was sent via e-mail.
580 if( !$u->isEmailConfirmed() ) {
585 // At this point we just return an appropriate code/ indicating
586 // that the UI should show a password reset form; bot inter-
587 // faces etc will probably just fail cleanly here.
588 $retval = self
::RESET_PASS
;
590 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
592 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
593 // If we've enabled it, make it so that a blocked user cannot login
594 $retval = self
::USER_BLOCKED
;
596 $wgAuth->updateUser( $u );
598 // This should set it for OutputPage and the Skin
599 // which is needed or the personal links will be
601 $this->getContext()->setUser( $u );
603 // Please reset throttle for successful logins, thanks!
604 if ( $throttleCount ) {
605 self
::clearLoginThrottle( $this->mUsername
);
608 if ( $isAutoCreated ) {
609 // Must be run after $wgUser is set, for correct new user log
610 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
613 $retval = self
::SUCCESS
;
615 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
620 * Increment the login attempt throttle hit count for the (username,current IP)
621 * tuple unless the throttle was already reached.
622 * @param $username string The user name
623 * @return Bool|Integer The integer hit count or True if it is already at the limit
625 public static function incLoginThrottle( $username ) {
626 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
627 $username = trim( $username ); // sanity
630 if ( is_array( $wgPasswordAttemptThrottle ) ) {
631 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
632 $count = $wgPasswordAttemptThrottle['count'];
633 $period = $wgPasswordAttemptThrottle['seconds'];
635 $throttleCount = $wgMemc->get( $throttleKey );
636 if ( !$throttleCount ) {
637 $wgMemc->add( $throttleKey, 1, $period ); // start counter
638 } elseif ( $throttleCount < $count ) {
639 $wgMemc->incr( $throttleKey );
640 } elseif ( $throttleCount >= $count ) {
645 return $throttleCount;
649 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
650 * @param $username string The user name
653 public static function clearLoginThrottle( $username ) {
654 global $wgMemc, $wgRequest;
655 $username = trim( $username ); // sanity
657 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
658 $wgMemc->delete( $throttleKey );
662 * Attempt to automatically create a user on login. Only succeeds if there
663 * is an external authentication method which allows it.
667 * @return integer Status code
669 function attemptAutoCreate( $user ) {
670 global $wgAuth, $wgAutocreatePolicy;
672 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
673 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
674 return self
::CREATE_BLOCKED
;
678 * If the external authentication plugin allows it, automatically cre-
679 * ate a new account for users that are externally defined but have not
682 if ( $this->mExtUser
) {
683 # mExtUser is neither null nor false, so use the new ExternalAuth
685 if ( $wgAutocreatePolicy == 'never' ) {
686 return self
::NOT_EXISTS
;
688 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
689 return self
::WRONG_PLUGIN_PASS
;
693 if ( !$wgAuth->autoCreate() ) {
694 return self
::NOT_EXISTS
;
696 if ( !$wgAuth->userExists( $user->getName() ) ) {
697 wfDebug( __METHOD__
. ": user does not exist\n" );
698 return self
::NOT_EXISTS
;
700 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
701 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
702 return self
::WRONG_PLUGIN_PASS
;
707 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
708 // Hook point to add extra creation throttles and blocks
709 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
710 $this->mAbortLoginErrorMsg
= $abortError;
711 return self
::ABORTED
;
714 wfDebug( __METHOD__
. ": creating account\n" );
715 $this->initUser( $user, true );
716 return self
::SUCCESS
;
719 function processLogin() {
720 global $wgMemc, $wgLang;
722 switch ( $this->authenticateUserData() ) {
724 # We've verified now, update the real record
725 $user = $this->getUser();
726 if( (bool)$this->mRemember
!= (bool)$user->getOption( 'rememberpassword' ) ) {
727 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
728 $user->saveSettings();
730 $user->invalidateCache();
733 self
::clearLoginToken();
735 // Reset the throttle
736 $request = $this->getRequest();
737 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
738 $wgMemc->delete( $key );
740 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
741 /* Replace the language object to provide user interface in
742 * correct language immediately on this first page load.
744 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
745 $userLang = Language
::factory( $code );
747 $this->getContext()->setLanguage( $userLang );
748 $this->successfulLogin();
750 $this->cookieRedirectCheck( 'login' );
754 case self
::NEED_TOKEN
:
755 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
757 case self
::WRONG_TOKEN
:
758 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
762 $this->mainLoginForm( $this->msg( 'noname' )->text() );
764 case self
::WRONG_PLUGIN_PASS
:
765 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
767 case self
::NOT_EXISTS
:
768 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
769 $this->mainLoginForm( $this->msg( 'nosuchuser',
770 wfEscapeWikiText( $this->mUsername
) )->parse() );
772 $this->mainLoginForm( $this->msg( 'nosuchusershort',
773 wfEscapeWikiText( $this->mUsername
) )->text() );
776 case self
::WRONG_PASS
:
777 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
779 case self
::EMPTY_PASS
:
780 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
782 case self
::RESET_PASS
:
783 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
785 case self
::CREATE_BLOCKED
:
786 $this->userBlockedMessage( $this->getUser()->mBlock
);
788 case self
::THROTTLED
:
789 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
791 case self
::USER_BLOCKED
:
792 $this->mainLoginForm( $this->msg( 'login-userblocked',
793 $this->mUsername
)->escaped() );
796 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
799 throw new MWException( 'Unhandled case value' );
803 function resetLoginForm( $error ) {
804 $this->getOutput()->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
805 $reset = new SpecialChangePassword();
806 $reset->setContext( $this->getContext() );
807 $reset->execute( null );
811 * @param $u User object
812 * @param $throttle Boolean
813 * @param $emailTitle String: message name of email title
814 * @param $emailText String: message name of email text
815 * @return Status object
817 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
818 global $wgServer, $wgScript, $wgNewPasswordExpiry;
820 if ( $u->getEmail() == '' ) {
821 return Status
::newFatal( 'noemail', $u->getName() );
823 $ip = $this->getRequest()->getIP();
825 return Status
::newFatal( 'badipaddress' );
828 $currentUser = $this->getUser();
829 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
831 $np = $u->randomPassword();
832 $u->setNewpassword( $np, $throttle );
834 $userLanguage = $u->getOption( 'language' );
835 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $wgServer . $wgScript . '>',
836 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
837 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
844 * Run any hooks registered for logins, then HTTP redirect to
845 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
846 * nice message here, but that's really not as useful as just being sent to
847 * wherever you logged in from. It should be clear that the action was
848 * successful, given the lack of error messages plus the appearance of your
849 * name in the upper right.
853 function successfulLogin() {
854 # Run any hooks; display injected HTML if any, else redirect
855 $currentUser = $this->getUser();
857 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
859 if( $injected_html !== '' ) {
860 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
862 $this->executeReturnTo( 'successredirect' );
867 * Run any hooks registered for logins, then display a message welcoming
872 function successfulCreation() {
873 # Run any hooks; display injected HTML
874 $currentUser = $this->getUser();
876 $welcome_creation_msg = 'welcomecreation';
878 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
881 * Let any extensions change what message is shown.
882 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
885 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
887 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
891 * Display a "login successful" page.
892 * @param $msgname string
893 * @param $injected_html string
895 private function displaySuccessfulLogin( $msgname, $injected_html ) {
896 $out = $this->getOutput();
897 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
899 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
902 $out->addHTML( $injected_html );
904 $this->executeReturnTo( 'success' );
908 * Output a message that informs the user that they cannot create an account because
909 * there is a block on them or their IP which prevents account creation. Note that
910 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
911 * setting on blocks (bug 13611).
912 * @param $block Block the block causing this error
914 function userBlockedMessage( Block
$block ) {
915 # Let's be nice about this, it's likely that this feature will be used
916 # for blocking large numbers of innocent people, e.g. range blocks on
917 # schools. Don't blame it on the user. There's a small chance that it
918 # really is the user's fault, i.e. the username is blocked and they
919 # haven't bothered to log out before trying to create an account to
920 # evade it, but we'll leave that to their guilty conscience to figure
923 $out = $this->getOutput();
924 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
926 $block_reason = $block->mReason
;
927 if ( strval( $block_reason ) === '' ) {
928 $block_reason = $this->msg( 'blockednoreason' )->text();
932 'cantcreateaccount-text',
938 $this->executeReturnTo( 'error' );
942 * Add a "return to" link or redirect to it.
944 * @param $type string, one of the following:
945 * - error: display a return to link ignoring $wgRedirectOnLogin
946 * - success: display a return to link using $wgRedirectOnLogin if needed
947 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
949 private function executeReturnTo( $type ) {
950 global $wgRedirectOnLogin, $wgSecureLogin;
952 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
953 $returnTo = $wgRedirectOnLogin;
954 $returnToQuery = array();
956 $returnTo = $this->mReturnTo
;
957 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
960 $returnToTitle = Title
::newFromText( $returnTo );
961 if ( !$returnToTitle ) {
962 $returnToTitle = Title
::newMainPage();
965 if ( $type == 'successredirect' ) {
966 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery );
967 if( $wgSecureLogin && !$this->mStickHTTPS
) {
968 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
970 $this->getOutput()->redirect( $redirectUrl );
972 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery );
979 function mainLoginForm( $msg, $msgtype = 'error' ) {
980 global $wgEnableEmail, $wgEnableUserEmail;
981 global $wgHiddenPrefs, $wgLoginLanguageSelector;
982 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
983 global $wgSecureLogin, $wgPasswordResetRoutes;
985 $titleObj = $this->getTitle();
986 $user = $this->getUser();
988 if ( $this->mType
== 'signup' ) {
989 // Block signup here if in readonly. Keeps user from
990 // going through the process (filling out data, etc)
991 // and being informed later.
992 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
993 if ( count( $permErrors ) ) {
994 throw new PermissionsError( 'createaccount', $permErrors );
995 } elseif ( $user->isBlockedFromCreateAccount() ) {
996 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
998 } elseif ( wfReadOnly() ) {
999 throw new ReadOnlyError
;
1003 if ( $this->mUsername
== '' ) {
1004 if ( $user->isLoggedIn() ) {
1005 $this->mUsername
= $user->getName();
1007 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1011 if ( $this->mType
== 'signup' ) {
1012 $template = new UsercreateTemplate();
1013 $q = 'action=submitlogin&type=signup';
1014 $linkq = 'type=login';
1015 $linkmsg = 'gotaccount';
1017 $template = new UserloginTemplate();
1018 $q = 'action=submitlogin&type=login';
1019 $linkq = 'type=signup';
1020 $linkmsg = 'nologin';
1023 if ( $this->mReturnTo
!== '' ) {
1024 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1025 if ( $this->mReturnToQuery
!== '' ) {
1026 $returnto .= '&returntoquery=' .
1027 wfUrlencode( $this->mReturnToQuery
);
1030 $linkq .= $returnto;
1033 # Don't show a "create account" link if the user can't
1034 if( $this->showCreateOrLoginLink( $user ) ) {
1035 # Pass any language selection on to the mode switch link
1036 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1037 $linkq .= '&uselang=' . $this->mLanguage
;
1039 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1040 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1042 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1044 $template->set( 'link', '' );
1047 $resetLink = $this->mType
== 'signup'
1049 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1051 $template->set( 'header', '' );
1052 $template->set( 'name', $this->mUsername
);
1053 $template->set( 'password', $this->mPassword
);
1054 $template->set( 'retype', $this->mRetype
);
1055 $template->set( 'email', $this->mEmail
);
1056 $template->set( 'realname', $this->mRealName
);
1057 $template->set( 'domain', $this->mDomain
);
1058 $template->set( 'reason', $this->mReason
);
1060 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1061 $template->set( 'message', $msg );
1062 $template->set( 'messagetype', $msgtype );
1063 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1064 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1065 $template->set( 'useemail', $wgEnableEmail );
1066 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1067 $template->set( 'emailothers', $wgEnableUserEmail );
1068 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1069 $template->set( 'resetlink', $resetLink );
1070 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1071 $template->set( 'usereason', $user->isLoggedIn() );
1072 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1073 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1074 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1076 if ( $this->mType
== 'signup' ) {
1077 if ( !self
::getCreateaccountToken() ) {
1078 self
::setCreateaccountToken();
1080 $template->set( 'token', self
::getCreateaccountToken() );
1082 if ( !self
::getLoginToken() ) {
1083 self
::setLoginToken();
1085 $template->set( 'token', self
::getLoginToken() );
1088 # Prepare language selection links as needed
1089 if( $wgLoginLanguageSelector ) {
1090 $template->set( 'languages', $this->makeLanguageSelector() );
1091 if( $this->mLanguage
) {
1092 $template->set( 'uselang', $this->mLanguage
);
1096 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1097 // Ditto for signupend
1098 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1099 $loginendHTTPS = $this->msg( 'loginend-https' );
1100 $signupendHTTPS = $this->msg( 'signupend-https' );
1101 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1102 $template->set( 'loginend', $loginendHTTPS->parse() );
1104 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1106 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1107 $template->set( 'signupend', $signupendHTTPS->parse() );
1109 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1112 // Give authentication and captcha plugins a chance to modify the form
1113 $wgAuth->modifyUITemplate( $template, $this->mType
);
1114 if ( $this->mType
== 'signup' ) {
1115 wfRunHooks( 'UserCreateForm', array( &$template ) );
1117 wfRunHooks( 'UserLoginForm', array( &$template ) );
1120 $out = $this->getOutput();
1121 $out->disallowUserJs(); // just in case...
1122 $out->addTemplate( $template );
1132 function showCreateOrLoginLink( &$user ) {
1133 if( $this->mType
== 'signup' ) {
1135 } elseif( $user->isAllowed( 'createaccount' ) ) {
1143 * Check if a session cookie is present.
1145 * This will not pick up a cookie set during _this_ request, but is meant
1146 * to ensure that the client is returning the cookie which was set on a
1147 * previous pass through the system.
1152 function hasSessionCookie() {
1153 global $wgDisableCookieCheck;
1154 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1158 * Get the login token from the current session
1161 public static function getLoginToken() {
1163 return $wgRequest->getSessionData( 'wsLoginToken' );
1167 * Randomly generate a new login token and attach it to the current session
1169 public static function setLoginToken() {
1171 // Generate a token directly instead of using $user->editToken()
1172 // because the latter reuses $_SESSION['wsEditToken']
1173 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1177 * Remove any login token attached to the current session
1179 public static function clearLoginToken() {
1181 $wgRequest->setSessionData( 'wsLoginToken', null );
1185 * Get the createaccount token from the current session
1188 public static function getCreateaccountToken() {
1190 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1194 * Randomly generate a new createaccount token and attach it to the current session
1196 public static function setCreateaccountToken() {
1198 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1202 * Remove any createaccount token attached to the current session
1204 public static function clearCreateaccountToken() {
1206 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1212 function cookieRedirectCheck( $type ) {
1213 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1214 $query = array( 'wpCookieCheck' => $type );
1215 if ( $this->mReturnTo
!== '' ) {
1216 $query['returnto'] = $this->mReturnTo
;
1217 $query['returntoquery'] = $this->mReturnToQuery
;
1219 $check = $titleObj->getFullURL( $query );
1221 $this->getOutput()->redirect( $check );
1227 function onCookieRedirectCheck( $type ) {
1228 if ( !$this->hasSessionCookie() ) {
1229 if ( $type == 'new' ) {
1230 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1231 } elseif ( $type == 'login' ) {
1232 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1235 $this->mainLoginForm( $this->msg( 'error' )->text() );
1238 $this->successfulLogin();
1245 function throttleHit( $limit ) {
1246 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1250 * Produce a bar of links which allow the user to select another language
1251 * during login/registration but retain "returnto"
1255 function makeLanguageSelector() {
1256 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1257 if( !$msg->isBlank() ) {
1258 $langs = explode( "\n", $msg->text() );
1260 foreach( $langs as $lang ) {
1261 $lang = trim( $lang, '* ' );
1262 $parts = explode( '|', $lang );
1263 if ( count( $parts ) >= 2 ) {
1264 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1267 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1268 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1275 * Create a language selector link for a particular language
1276 * Links back to this page preserving type and returnto
1278 * @param $text Link text
1279 * @param $lang Language code
1282 function makeLanguageSelectorLink( $text, $lang ) {
1283 if( $this->getLanguage()->getCode() == $lang ) {
1284 // no link for currently used language
1285 return htmlspecialchars( $text );
1287 $query = array( 'uselang' => $lang );
1288 if( $this->mType
== 'signup' ) {
1289 $query['type'] = 'signup';
1291 if( $this->mReturnTo
!== '' ) {
1292 $query['returnto'] = $this->mReturnTo
;
1293 $query['returntoquery'] = $this->mReturnToQuery
;
1297 $targetLanguage = Language
::factory( $lang );
1298 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1300 return Linker
::linkKnown(
1302 htmlspecialchars( $text ),