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';
56 private $mExtUser = null;
59 * @param WebRequest $request
61 public function __construct( $request = null ) {
62 parent
::__construct( 'Userlogin' );
64 if ( $request === null ) {
66 $this->load( $wgRequest );
68 $this->load( $request );
75 * @param $request WebRequest object
77 function load( $request ) {
78 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail, $wgRedirectOnLogin;
80 $this->mType
= $request->getText( 'type' );
81 $this->mUsername
= $request->getText( 'wpName' );
82 $this->mPassword
= $request->getText( 'wpPassword' );
83 $this->mRetype
= $request->getText( 'wpRetype' );
84 $this->mDomain
= $request->getText( 'wpDomain' );
85 $this->mReason
= $request->getText( 'wpReason' );
86 $this->mReturnTo
= $request->getVal( 'returnto' );
87 $this->mReturnToQuery
= $request->getVal( 'returntoquery' );
88 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
89 $this->mPosted
= $request->wasPosted();
90 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' );
91 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
93 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
94 $this->mAction
= $request->getVal( 'action' );
95 $this->mRemember
= $request->getCheck( 'wpRemember' );
96 $this->mStickHTTPS
= $request->getCheck( 'wpStickHTTPS' );
97 $this->mLanguage
= $request->getText( 'uselang' );
98 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
99 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
101 if ( $wgRedirectOnLogin ) {
102 $this->mReturnTo
= $wgRedirectOnLogin;
103 $this->mReturnToQuery
= '';
106 if( $wgEnableEmail ) {
107 $this->mEmail
= $request->getText( 'wpEmail' );
111 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
112 $this->mRealName
= $request->getText( 'wpRealName' );
114 $this->mRealName
= '';
117 if( !$wgAuth->validDomain( $this->mDomain
) ) {
118 $this->mDomain
= 'invaliddomain';
120 $wgAuth->setDomain( $this->mDomain
);
122 # When switching accounts, it sucks to get automatically logged out
123 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
124 if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
125 $this->mReturnTo
= '';
126 $this->mReturnToQuery
= '';
130 public function execute( $par ) {
131 if ( session_id() == '' ) {
135 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
136 $this->mType
= 'signup';
139 if ( !is_null( $this->mCookieCheck
) ) {
140 $this->onCookieRedirectCheck( $this->mCookieCheck
);
142 } elseif( $this->mPosted
) {
143 if( $this->mCreateaccount
) {
144 return $this->addNewAccount();
145 } elseif ( $this->mCreateaccountMail
) {
146 return $this->addNewAccountMailPassword();
147 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
148 return $this->processLogin();
151 $this->mainLoginForm( '' );
157 function addNewAccountMailPassword() {
160 if ( $this->mEmail
== '' ) {
161 $this->mainLoginForm( wfMsgExt( 'noemailcreate', array( 'parsemag', 'escape' ) ) );
165 $u = $this->addNewaccountInternal();
171 // Wipe the initial password and mail a temporary one
172 $u->setPassword( null );
174 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
176 wfRunHooks( 'AddNewAccount', array( $u, true ) );
177 $u->addNewUserLogEntry( true, $this->mReason
);
179 $wgOut->setPageTitle( wfMsg( 'accmailtitle' ) );
181 if( !$result->isGood() ) {
182 $this->mainLoginForm( wfMsg( 'mailerror', $result->getWikiText() ) );
184 $wgOut->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
185 $wgOut->returnToMain( false );
192 function addNewAccount() {
193 global $wgUser, $wgEmailAuthentication, $wgOut;
195 # Create the account and abort if there's a problem doing so
196 $u = $this->addNewAccountInternal();
201 # If we showed up language selection links, and one was in use, be
202 # smart (and sensible) and save that language as the user's preference
203 global $wgLoginLanguageSelector;
204 if( $wgLoginLanguageSelector && $this->mLanguage
) {
205 $u->setOption( 'language', $this->mLanguage
);
208 # Send out an email authentication message if needed
209 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
210 $status = $u->sendConfirmationMail();
211 if( $status->isGood() ) {
212 $wgOut->addWikiMsg( 'confirmemail_oncreate' );
214 $wgOut->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
218 # Save settings (including confirmation token)
221 # If not logged in, assume the new account as the current one and set
222 # session cookies then show a "welcome" message or a "need cookies"
224 if( $wgUser->isAnon() ) {
226 $wgUser->setCookies();
227 // This should set it for OutputPage and the Skin
228 // which is needed or the personal links will be
230 RequestContext
::getMain()->setUser( $u );
231 wfRunHooks( 'AddNewAccount', array( $wgUser, false ) );
232 $wgUser->addNewUserLogEntry();
233 if( $this->hasSessionCookie() ) {
234 return $this->successfulCreation();
236 return $this->cookieRedirectCheck( 'new' );
239 # Confirm that the account was created
240 $self = SpecialPage
::getTitleFor( 'Userlogin' );
241 $wgOut->setPageTitle( wfMsgHtml( 'accountcreated' ) );
242 $wgOut->addWikiMsg( 'accountcreatedtext', $u->getName() );
243 $wgOut->returnToMain( false, $self );
244 wfRunHooks( 'AddNewAccount', array( $u, false ) );
245 $u->addNewUserLogEntry( false, $this->mReason
);
253 function addNewAccountInternal() {
254 global $wgUser, $wgOut, $wgRequest;
255 global $wgMemc, $wgAccountCreationThrottle;
256 global $wgAuth, $wgMinimalPasswordLength;
257 global $wgEmailConfirmToEdit;
259 // If the user passes an invalid domain, something is fishy
260 if( !$wgAuth->validDomain( $this->mDomain
) ) {
261 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
265 // If we are not allowing users to login locally, we should be checking
266 // to see if the user is actually able to authenticate to the authenti-
267 // cation server before they create an account (otherwise, they can
268 // create a local account and login as any domain user). We only need
269 // to check this for domains that aren't local.
270 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
271 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername
)
272 ||
!$wgAuth->authenticate( $this->mUsername
, $this->mPassword
) ) ) {
273 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
278 if ( wfReadOnly() ) {
279 $wgOut->readOnlyPage();
283 # Request forgery checks.
284 if ( !self
::getCreateaccountToken() ) {
285 self
::setCreateaccountToken();
286 $this->mainLoginForm( wfMsgExt( 'nocookiesfornew', array( 'parseinline' ) ) );
290 # The user didn't pass a createaccount token
291 if ( !$this->mToken
) {
292 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
296 # Validate the createaccount token
297 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
298 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
303 if ( !$wgUser->isAllowed( 'createaccount' ) ) {
304 $wgOut->permissionRequired( 'createaccount' );
306 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
307 $this->userBlockedMessage( $wgUser->isBlockedFromCreateAccount() );
311 $ip = $wgRequest->getIP();
312 if ( $wgUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
313 $this->mainLoginForm( wfMsg( 'sorbs_create_account_reason' ) . ' (' . htmlspecialchars( $ip ) . ')' );
317 # Now create a dummy user ($u) and check if it is valid
318 $name = trim( $this->mUsername
);
319 $u = User
::newFromName( $name, 'creatable' );
320 if ( !is_object( $u ) ) {
321 $this->mainLoginForm( wfMsg( 'noname' ) );
325 if ( 0 != $u->idForName() ) {
326 $this->mainLoginForm( wfMsg( 'userexists' ) );
330 if ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
331 $this->mainLoginForm( wfMsg( 'badretype' ) );
335 # check for minimal password length
336 $valid = $u->getPasswordValidity( $this->mPassword
);
337 if ( $valid !== true ) {
338 if ( !$this->mCreateaccountMail
) {
339 if ( is_array( $valid ) ) {
340 $message = array_shift( $valid );
344 $params = array( $wgMinimalPasswordLength );
346 $this->mainLoginForm( wfMsgExt( $message, array( 'parsemag' ), $params ) );
349 # do not force a password for account creation by email
350 # set invalid password, it will be replaced later by a random generated password
351 $this->mPassword
= null;
355 # if you need a confirmed email address to edit, then obviously you
356 # need an email address.
357 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
358 $this->mainLoginForm( wfMsg( 'noemailtitle' ) );
362 if( !empty( $this->mEmail
) && !Sanitizer
::validateEmail( $this->mEmail
) ) {
363 $this->mainLoginForm( wfMsg( 'invalidemailaddress' ) );
367 # Set some additional data so the AbortNewAccount hook can be used for
368 # more than just username validation
369 $u->setEmail( $this->mEmail
);
370 $u->setRealName( $this->mRealName
);
373 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
374 // Hook point to add extra creation throttles and blocks
375 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
376 $this->mainLoginForm( $abortError );
380 // Hook point to change $wgAccountCreationThrottle
381 wfRunHooks( 'ChangeAccountCreationThrottle', array( $ip, &$wgAccountCreationThrottle ) );
383 if ( $wgAccountCreationThrottle && $wgUser->isPingLimitable() ) {
384 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
385 $value = $wgMemc->get( $key );
387 $wgMemc->set( $key, 0, 86400 );
389 if ( $value >= $wgAccountCreationThrottle ) {
390 $this->throttleHit( $wgAccountCreationThrottle );
393 $wgMemc->incr( $key );
396 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
397 $this->mainLoginForm( wfMsg( 'externaldberror' ) );
401 self
::clearCreateaccountToken();
402 return $this->initUser( $u, false );
406 * Actually add a user to the database.
407 * Give it a User object that has been initialised with a name.
409 * @param $u User object.
410 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
411 * @return User object.
414 function initUser( $u, $autocreate ) {
419 if ( $wgAuth->allowPasswordChange() ) {
420 $u->setPassword( $this->mPassword
);
423 $u->setEmail( $this->mEmail
);
424 $u->setRealName( $this->mRealName
);
427 $wgAuth->initUser( $u, $autocreate );
429 if ( $this->mExtUser
) {
430 $this->mExtUser
->linkToLocal( $u->getId() );
431 $email = $this->mExtUser
->getPref( 'emailaddress' );
432 if ( $email && !$this->mEmail
) {
433 $u->setEmail( $email );
437 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
441 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
442 $ssUpdate->doUpdate();
448 * Internally authenticate the login request.
450 * This may create a local account as a side effect if the
451 * authentication plugin allows transparent local account
454 public function authenticateUserData() {
455 global $wgUser, $wgAuth;
457 if ( $this->mUsername
== '' ) {
458 return self
::NO_NAME
;
461 // We require a login token to prevent login CSRF
462 // Handle part of this before incrementing the throttle so
463 // token-less login attempts don't count towards the throttle
464 // but wrong-token attempts do.
466 // If the user doesn't have a login token yet, set one.
467 if ( !self
::getLoginToken() ) {
468 self
::setLoginToken();
469 return self
::NEED_TOKEN
;
471 // If the user didn't pass a login token, tell them we need one
472 if ( !$this->mToken
) {
473 return self
::NEED_TOKEN
;
476 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
477 if ( $throttleCount === true ) {
478 return self
::THROTTLED
;
481 // Validate the login token
482 if ( $this->mToken
!== self
::getLoginToken() ) {
483 return self
::WRONG_TOKEN
;
486 // Load $wgUser now, and check to see if we're logging in as the same
487 // name. This is necessary because loading $wgUser (say by calling
488 // getName()) calls the UserLoadFromSession hook, which potentially
489 // creates the user in the database. Until we load $wgUser, checking
490 // for user existence using User::newFromName($name)->getId() below
491 // will effectively be using stale data.
492 if ( $wgUser->getName() === $this->mUsername
) {
493 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
494 return self
::SUCCESS
;
497 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
499 # TODO: Allow some magic here for invalid external names, e.g., let the
500 # user choose a different wiki name.
501 $u = User
::newFromName( $this->mUsername
);
502 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
503 return self
::ILLEGAL
;
506 $isAutoCreated = false;
507 if ( 0 == $u->getID() ) {
508 $status = $this->attemptAutoCreate( $u );
509 if ( $status !== self
::SUCCESS
) {
512 $isAutoCreated = true;
515 global $wgExternalAuthType, $wgAutocreatePolicy;
516 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
517 && is_object( $this->mExtUser
)
518 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
519 # The external user and local user have the same name and
520 # password, so we assume they're the same.
521 $this->mExtUser
->linkToLocal( $u->getID() );
527 // Give general extensions, such as a captcha, a chance to abort logins
528 $abort = self
::ABORTED
;
529 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
533 global $wgBlockDisablesLogin;
534 if ( !$u->checkPassword( $this->mPassword
) ) {
535 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
536 // The e-mailed temporary password should not be used for actu-
537 // al logins; that's a very sloppy habit, and insecure if an
538 // attacker has a few seconds to click "search" on someone's o-
541 // Allow it to be used only to reset the password a single time
542 // to a new value, which won't be in the user's e-mail ar-
545 // For backwards compatibility, we'll still recognize it at the
546 // login form to minimize surprises for people who have been
547 // logging in with a temporary password for some time.
549 // As a side-effect, we can authenticate the user's e-mail ad-
550 // dress if it's not already done, since the temporary password
551 // was sent via e-mail.
552 if( !$u->isEmailConfirmed() ) {
557 // At this point we just return an appropriate code/ indicating
558 // that the UI should show a password reset form; bot inter-
559 // faces etc will probably just fail cleanly here.
560 $retval = self
::RESET_PASS
;
562 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
564 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
565 // If we've enabled it, make it so that a blocked user cannot login
566 $retval = self
::USER_BLOCKED
;
568 $wgAuth->updateUser( $u );
571 // Please reset throttle for successful logins, thanks!
572 if ( $throttleCount ) {
573 self
::clearLoginThrottle( $this->mUsername
);
576 if ( $isAutoCreated ) {
577 // Must be run after $wgUser is set, for correct new user log
578 wfRunHooks( 'AuthPluginAutoCreate', array( $wgUser ) );
581 $retval = self
::SUCCESS
;
583 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
588 * Increment the login attempt throttle hit count for the (username,current IP)
589 * tuple unless the throttle was already reached.
590 * @param $username string The user name
591 * @return Bool|Integer The integer hit count or True if it is already at the limit
593 public static function incLoginThrottle( $username ) {
594 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
595 $username = trim( $username ); // sanity
598 if ( is_array( $wgPasswordAttemptThrottle ) ) {
599 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
600 $count = $wgPasswordAttemptThrottle['count'];
601 $period = $wgPasswordAttemptThrottle['seconds'];
603 $throttleCount = $wgMemc->get( $throttleKey );
604 if ( !$throttleCount ) {
605 $wgMemc->add( $throttleKey, 1, $period ); // start counter
606 } elseif ( $throttleCount < $count ) {
607 $wgMemc->incr( $throttleKey );
608 } elseif ( $throttleCount >= $count ) {
613 return $throttleCount;
617 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
618 * @param $username string The user name
621 public static function clearLoginThrottle( $username ) {
622 global $wgMemc, $wgRequest;
623 $username = trim( $username ); // sanity
625 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
626 $wgMemc->delete( $throttleKey );
630 * Attempt to automatically create a user on login. Only succeeds if there
631 * is an external authentication method which allows it.
635 * @return integer Status code
637 function attemptAutoCreate( $user ) {
638 global $wgAuth, $wgUser, $wgAutocreatePolicy;
640 if ( $wgUser->isBlockedFromCreateAccount() ) {
641 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
642 return self
::CREATE_BLOCKED
;
646 * If the external authentication plugin allows it, automatically cre-
647 * ate a new account for users that are externally defined but have not
650 if ( $this->mExtUser
) {
651 # mExtUser is neither null nor false, so use the new ExternalAuth
653 if ( $wgAutocreatePolicy == 'never' ) {
654 return self
::NOT_EXISTS
;
656 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
657 return self
::WRONG_PLUGIN_PASS
;
661 if ( !$wgAuth->autoCreate() ) {
662 return self
::NOT_EXISTS
;
664 if ( !$wgAuth->userExists( $user->getName() ) ) {
665 wfDebug( __METHOD__
. ": user does not exist\n" );
666 return self
::NOT_EXISTS
;
668 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
669 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
670 return self
::WRONG_PLUGIN_PASS
;
675 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
676 // Hook point to add extra creation throttles and blocks
677 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
678 $this->mAbortLoginErrorMsg
= $abortError;
679 return self
::ABORTED
;
682 wfDebug( __METHOD__
. ": creating account\n" );
683 $this->initUser( $user, true );
684 return self
::SUCCESS
;
687 function processLogin() {
688 global $wgUser, $wgRequest, $wgLang;
690 switch ( $this->authenticateUserData() ) {
692 # We've verified now, update the real record
693 if( (bool)$this->mRemember
!= (bool)$wgUser->getOption( 'rememberpassword' ) ) {
694 $wgUser->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
695 $wgUser->saveSettings();
697 $wgUser->invalidateCache();
699 $wgUser->setCookies();
700 self
::clearLoginToken();
702 // Reset the throttle
703 $key = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $this->mUsername
) );
705 $wgMemc->delete( $key );
707 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
708 /* Replace the language object to provide user interface in
709 * correct language immediately on this first page load.
711 $code = $wgRequest->getVal( 'uselang', $wgUser->getOption( 'language' ) );
712 $wgLang = Language
::factory( $code );
713 return $this->successfulLogin();
715 return $this->cookieRedirectCheck( 'login' );
719 case self
::NEED_TOKEN
:
720 $this->mainLoginForm( wfMsgExt( 'nocookiesforlogin', array( 'parseinline' ) ) );
722 case self
::WRONG_TOKEN
:
723 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
727 $this->mainLoginForm( wfMsg( 'noname' ) );
729 case self
::WRONG_PLUGIN_PASS
:
730 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
732 case self
::NOT_EXISTS
:
733 if( $wgUser->isAllowed( 'createaccount' ) ) {
734 $this->mainLoginForm( wfMsgExt( 'nosuchuser', 'parseinline',
735 wfEscapeWikiText( $this->mUsername
) ) );
737 $this->mainLoginForm( wfMsg( 'nosuchusershort',
738 wfEscapeWikiText( $this->mUsername
) ) );
741 case self
::WRONG_PASS
:
742 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
744 case self
::EMPTY_PASS
:
745 $this->mainLoginForm( wfMsg( 'wrongpasswordempty' ) );
747 case self
::RESET_PASS
:
748 $this->resetLoginForm( wfMsg( 'resetpass_announce' ) );
750 case self
::CREATE_BLOCKED
:
751 $this->userBlockedMessage( $wgUser->mBlock
);
753 case self
::THROTTLED
:
754 $this->mainLoginForm( wfMsg( 'login-throttled' ) );
756 case self
::USER_BLOCKED
:
757 $this->mainLoginForm( wfMsgExt( 'login-userblocked',
758 array( 'parsemag', 'escape' ), $this->mUsername
) );
761 $this->mainLoginForm( wfMsg( $this->mAbortLoginErrorMsg
) );
764 throw new MWException( 'Unhandled case value' );
768 function resetLoginForm( $error ) {
770 $wgOut->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
771 $reset = new SpecialChangePassword();
772 $reset->execute( null );
776 * @param $u User object
777 * @param $throttle Boolean
778 * @param $emailTitle String: message name of email title
779 * @param $emailText String: message name of email text
780 * @return Status object
783 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
784 global $wgServer, $wgScript, $wgUser, $wgNewPasswordExpiry, $wgRequest;
786 if ( $u->getEmail() == '' ) {
787 return Status
::newFatal( 'noemail', $u->getName() );
789 $ip = $wgRequest->getIP();
791 return Status
::newFatal( 'badipaddress' );
794 wfRunHooks( 'User::mailPasswordInternal', array( &$wgUser, &$ip, &$u ) );
796 $np = $u->randomPassword();
797 $u->setNewpassword( $np, $throttle );
799 $userLanguage = $u->getOption( 'language' );
800 $m = wfMsgExt( $emailText, array( 'parsemag', 'language' => $userLanguage ), $ip, $u->getName(), $np,
801 $wgServer . $wgScript, round( $wgNewPasswordExpiry / 86400 ) );
802 $result = $u->sendMail( wfMsgExt( $emailTitle, array( 'parsemag', 'language' => $userLanguage ) ), $m );
809 * Run any hooks registered for logins, then HTTP redirect to
810 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
811 * nice message here, but that's really not as useful as just being sent to
812 * wherever you logged in from. It should be clear that the action was
813 * successful, given the lack of error messages plus the appearance of your
814 * name in the upper right.
818 function successfulLogin() {
819 global $wgUser, $wgOut;
821 # Run any hooks; display injected HTML if any, else redirect
823 wfRunHooks( 'UserLoginComplete', array( &$wgUser, &$injected_html ) );
825 if( $injected_html !== '' ) {
826 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
828 $titleObj = Title
::newFromText( $this->mReturnTo
);
829 if ( !$titleObj instanceof Title
) {
830 $titleObj = Title
::newMainPage();
832 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery
);
833 global $wgSecureLogin;
834 if( $wgSecureLogin && !$this->mStickHTTPS
) {
835 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
837 $wgOut->redirect( $redirectUrl );
842 * Run any hooks registered for logins, then display a message welcoming
847 function successfulCreation() {
849 # Run any hooks; display injected HTML
851 $welcome_creation_msg = 'welcomecreation';
853 wfRunHooks( 'UserLoginComplete', array( &$wgUser, &$injected_html ) );
855 //let any extensions change what message is shown
856 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
858 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
862 * Display a "login successful" page.
864 private function displaySuccessfulLogin( $msgname, $injected_html ) {
865 global $wgOut, $wgUser;
867 $wgOut->setPageTitle( wfMsg( 'loginsuccesstitle' ) );
869 $wgOut->addWikiMsg( $msgname, wfEscapeWikiText( $wgUser->getName() ) );
872 $wgOut->addHTML( $injected_html );
874 if ( !empty( $this->mReturnTo
) ) {
875 $wgOut->returnToMain( null, $this->mReturnTo
, $this->mReturnToQuery
);
877 $wgOut->returnToMain( null );
882 * Output a message that informs the user that they cannot create an account because
883 * there is a block on them or their IP which prevents account creation. Note that
884 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
885 * setting on blocks (bug 13611).
886 * @param $block Block the block causing this error
888 function userBlockedMessage( Block
$block ) {
891 # Let's be nice about this, it's likely that this feature will be used
892 # for blocking large numbers of innocent people, e.g. range blocks on
893 # schools. Don't blame it on the user. There's a small chance that it
894 # really is the user's fault, i.e. the username is blocked and they
895 # haven't bothered to log out before trying to create an account to
896 # evade it, but we'll leave that to their guilty conscience to figure
899 $wgOut->setPageTitle( wfMsg( 'cantcreateaccounttitle' ) );
901 $block_reason = $block->mReason
;
902 if ( strval( $block_reason ) === '' ) {
903 $block_reason = wfMsg( 'blockednoreason' );
907 'cantcreateaccount-text',
910 $block->getBlocker()->getName()
913 $wgOut->returnToMain( false );
919 function mainLoginForm( $msg, $msgtype = 'error' ) {
920 global $wgUser, $wgOut, $wgHiddenPrefs;
921 global $wgEnableEmail, $wgEnableUserEmail;
922 global $wgRequest, $wgLoginLanguageSelector;
923 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
924 global $wgSecureLogin, $wgPasswordResetRoutes;
926 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
928 if ( $this->mType
== 'signup' ) {
929 // Block signup here if in readonly. Keeps user from
930 // going through the process (filling out data, etc)
931 // and being informed later.
932 if ( wfReadOnly() ) {
933 $wgOut->readOnlyPage();
935 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
936 $this->userBlockedMessage( $wgUser->isBlockedFromCreateAccount() );
938 } elseif ( count( $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $wgUser, true ) )>0 ) {
939 $wgOut->showPermissionsErrorPage( $permErrors, 'createaccount' );
944 if ( $this->mUsername
== '' ) {
945 if ( $wgUser->isLoggedIn() ) {
946 $this->mUsername
= $wgUser->getName();
948 $this->mUsername
= $wgRequest->getCookie( 'UserName' );
952 if ( $this->mType
== 'signup' ) {
953 $template = new UsercreateTemplate();
954 $q = 'action=submitlogin&type=signup';
955 $linkq = 'type=login';
956 $linkmsg = 'gotaccount';
958 $template = new UserloginTemplate();
959 $q = 'action=submitlogin&type=login';
960 $linkq = 'type=signup';
961 $linkmsg = 'nologin';
964 if ( !empty( $this->mReturnTo
) ) {
965 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
966 if ( !empty( $this->mReturnToQuery
) ) {
967 $returnto .= '&returntoquery=' .
968 wfUrlencode( $this->mReturnToQuery
);
974 # Pass any language selection on to the mode switch link
975 if( $wgLoginLanguageSelector && $this->mLanguage
) {
976 $linkq .= '&uselang=' . $this->mLanguage
;
979 $link = '<a href="' . htmlspecialchars ( $titleObj->getLocalURL( $linkq ) ) . '">';
980 $link .= wfMsgHtml( $linkmsg . 'link' ); # Calling either 'gotaccountlink' or 'nologinlink'
983 # Don't show a "create account" link if the user can't
984 if( $this->showCreateOrLoginLink( $wgUser ) ) {
985 $template->set( 'link', wfMsgExt( $linkmsg, array( 'parseinline', 'replaceafter' ), $link ) );
987 $template->set( 'link', '' );
990 $resetLink = $this->mType
== 'signup'
992 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
994 $template->set( 'header', '' );
995 $template->set( 'name', $this->mUsername
);
996 $template->set( 'password', $this->mPassword
);
997 $template->set( 'retype', $this->mRetype
);
998 $template->set( 'email', $this->mEmail
);
999 $template->set( 'realname', $this->mRealName
);
1000 $template->set( 'domain', $this->mDomain
);
1001 $template->set( 'reason', $this->mReason
);
1003 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1004 $template->set( 'message', $msg );
1005 $template->set( 'messagetype', $msgtype );
1006 $template->set( 'createemail', $wgEnableEmail && $wgUser->isLoggedIn() );
1007 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1008 $template->set( 'useemail', $wgEnableEmail );
1009 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1010 $template->set( 'emailothers', $wgEnableUserEmail );
1011 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1012 $template->set( 'resetlink', $resetLink );
1013 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1014 $template->set( 'usereason', $wgUser->isLoggedIn() );
1015 $template->set( 'remember', $wgUser->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1016 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1017 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1019 if ( $this->mType
== 'signup' ) {
1020 if ( !self
::getCreateaccountToken() ) {
1021 self
::setCreateaccountToken();
1023 $template->set( 'token', self
::getCreateaccountToken() );
1025 if ( !self
::getLoginToken() ) {
1026 self
::setLoginToken();
1028 $template->set( 'token', self
::getLoginToken() );
1031 # Prepare language selection links as needed
1032 if( $wgLoginLanguageSelector ) {
1033 $template->set( 'languages', $this->makeLanguageSelector() );
1034 if( $this->mLanguage
)
1035 $template->set( 'uselang', $this->mLanguage
);
1038 // Give authentication and captcha plugins a chance to modify the form
1039 $wgAuth->modifyUITemplate( $template, $this->mType
);
1040 if ( $this->mType
== 'signup' ) {
1041 wfRunHooks( 'UserCreateForm', array( &$template ) );
1043 wfRunHooks( 'UserLoginForm', array( &$template ) );
1046 // Changes the title depending on permissions for creating account
1047 if ( $wgUser->isAllowed( 'createaccount' ) ) {
1048 $wgOut->setPageTitle( wfMsg( 'userlogin' ) );
1050 $wgOut->setPageTitle( wfMsg( 'userloginnocreate' ) );
1053 $wgOut->disallowUserJs(); // just in case...
1054 $wgOut->addTemplate( $template );
1064 function showCreateOrLoginLink( &$user ) {
1065 if( $this->mType
== 'signup' ) {
1067 } elseif( $user->isAllowed( 'createaccount' ) ) {
1075 * Check if a session cookie is present.
1077 * This will not pick up a cookie set during _this_ request, but is meant
1078 * to ensure that the client is returning the cookie which was set on a
1079 * previous pass through the system.
1083 function hasSessionCookie() {
1084 global $wgDisableCookieCheck, $wgRequest;
1085 return $wgDisableCookieCheck ?
true : $wgRequest->checkSessionCookie();
1089 * Get the login token from the current session
1091 public static function getLoginToken() {
1093 return $wgRequest->getSessionData( 'wsLoginToken' );
1097 * Randomly generate a new login token and attach it to the current session
1099 public static function setLoginToken() {
1101 // Use User::generateToken() instead of $user->editToken()
1102 // because the latter reuses $_SESSION['wsEditToken']
1103 $wgRequest->setSessionData( 'wsLoginToken', User
::generateToken() );
1107 * Remove any login token attached to the current session
1109 public static function clearLoginToken() {
1111 $wgRequest->setSessionData( 'wsLoginToken', null );
1115 * Get the createaccount token from the current session
1117 public static function getCreateaccountToken() {
1119 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1123 * Randomly generate a new createaccount token and attach it to the current session
1125 public static function setCreateaccountToken() {
1127 $wgRequest->setSessionData( 'wsCreateaccountToken', User
::generateToken() );
1131 * Remove any createaccount token attached to the current session
1133 public static function clearCreateaccountToken() {
1135 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1141 function cookieRedirectCheck( $type ) {
1144 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1145 $query = array( 'wpCookieCheck' => $type );
1146 if ( $this->mReturnTo
) {
1147 $query['returnto'] = $this->mReturnTo
;
1149 $check = $titleObj->getFullURL( $query );
1151 return $wgOut->redirect( $check );
1157 function onCookieRedirectCheck( $type ) {
1158 if ( !$this->hasSessionCookie() ) {
1159 if ( $type == 'new' ) {
1160 return $this->mainLoginForm( wfMsgExt( 'nocookiesnew', array( 'parseinline' ) ) );
1161 } elseif ( $type == 'login' ) {
1162 return $this->mainLoginForm( wfMsgExt( 'nocookieslogin', array( 'parseinline' ) ) );
1165 return $this->mainLoginForm( wfMsg( 'error' ) );
1168 return $this->successfulLogin();
1175 function throttleHit( $limit ) {
1176 $this->mainLoginForm( wfMsgExt( 'acct_creation_throttle_hit', array( 'parseinline' ), $limit ) );
1180 * Produce a bar of links which allow the user to select another language
1181 * during login/registration but retain "returnto"
1185 function makeLanguageSelector() {
1188 $msg = wfMessage( 'loginlanguagelinks' )->inContentLanguage();
1189 if( !$msg->isBlank() ) {
1190 $langs = explode( "\n", $msg->text() );
1192 foreach( $langs as $lang ) {
1193 $lang = trim( $lang, '* ' );
1194 $parts = explode( '|', $lang );
1195 if ( count( $parts ) >= 2 ) {
1196 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1199 return count( $links ) > 0 ?
wfMsgHtml( 'loginlanguagelabel', $wgLang->pipeList( $links ) ) : '';
1206 * Create a language selector link for a particular language
1207 * Links back to this page preserving type and returnto
1209 * @param $text Link text
1210 * @param $lang Language code
1212 function makeLanguageSelectorLink( $text, $lang ) {
1213 $self = SpecialPage
::getTitleFor( 'Userlogin' );
1214 $attr = array( 'uselang' => $lang );
1215 if( $this->mType
== 'signup' ) {
1216 $attr['type'] = 'signup';
1218 if( $this->mReturnTo
) {
1219 $attr['returnto'] = $this->mReturnTo
;
1221 return Linker
::linkKnown(
1223 htmlspecialchars( $text ),