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, $mMailmypassword;
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->mMailmypassword
= $request->getCheck( 'wpMailmypassword' )
95 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
96 $this->mAction
= $request->getVal( 'action' );
97 $this->mRemember
= $request->getCheck( 'wpRemember' );
98 $this->mStickHTTPS
= $request->getCheck( 'wpStickHTTPS' );
99 $this->mLanguage
= $request->getText( 'uselang' );
100 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
101 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
103 if ( $wgRedirectOnLogin ) {
104 $this->mReturnTo
= $wgRedirectOnLogin;
105 $this->mReturnToQuery
= '';
108 if( $wgEnableEmail ) {
109 $this->mEmail
= $request->getText( 'wpEmail' );
113 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
114 $this->mRealName
= $request->getText( 'wpRealName' );
116 $this->mRealName
= '';
119 if( !$wgAuth->validDomain( $this->mDomain
) ) {
120 $this->mDomain
= 'invaliddomain';
122 $wgAuth->setDomain( $this->mDomain
);
124 # When switching accounts, it sucks to get automatically logged out
125 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
126 if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
127 $this->mReturnTo
= '';
128 $this->mReturnToQuery
= '';
132 public function execute( $par ) {
133 if ( session_id() == '' ) {
137 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
138 $this->mType
= 'signup';
141 if ( !is_null( $this->mCookieCheck
) ) {
142 $this->onCookieRedirectCheck( $this->mCookieCheck
);
144 } elseif( $this->mPosted
) {
145 if( $this->mCreateaccount
) {
146 return $this->addNewAccount();
147 } elseif ( $this->mCreateaccountMail
) {
148 return $this->addNewAccountMailPassword();
149 } elseif ( $this->mMailmypassword
) {
150 return $this->mailPassword();
151 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
152 return $this->processLogin();
155 $this->mainLoginForm( '' );
161 function addNewAccountMailPassword() {
164 if ( $this->mEmail
== '' ) {
165 $this->mainLoginForm( wfMsgExt( 'noemail', array( 'parsemag', 'escape' ), $this->mUsername
) );
169 $u = $this->addNewaccountInternal();
175 // Wipe the initial password and mail a temporary one
176 $u->setPassword( null );
178 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
180 wfRunHooks( 'AddNewAccount', array( $u, true ) );
181 $u->addNewUserLogEntry( true, $this->mReason
);
183 $wgOut->setPageTitle( wfMsg( 'accmailtitle' ) );
185 if( !$result->isGood() ) {
186 $this->mainLoginForm( wfMsg( 'mailerror', $result->getWikiText() ) );
188 $wgOut->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
189 $wgOut->returnToMain( false );
196 function addNewAccount() {
197 global $wgUser, $wgEmailAuthentication, $wgOut;
199 # Create the account and abort if there's a problem doing so
200 $u = $this->addNewAccountInternal();
205 # If we showed up language selection links, and one was in use, be
206 # smart (and sensible) and save that language as the user's preference
207 global $wgLoginLanguageSelector;
208 if( $wgLoginLanguageSelector && $this->mLanguage
) {
209 $u->setOption( 'language', $this->mLanguage
);
212 # Send out an email authentication message if needed
213 if( $wgEmailAuthentication && User
::isValidEmailAddr( $u->getEmail() ) ) {
214 $status = $u->sendConfirmationMail();
215 if( $status->isGood() ) {
216 $wgOut->addWikiMsg( 'confirmemail_oncreate' );
218 $wgOut->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
222 # Save settings (including confirmation token)
225 # If not logged in, assume the new account as the current one and set
226 # session cookies then show a "welcome" message or a "need cookies"
228 if( $wgUser->isAnon() ) {
230 $wgUser->setCookies();
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;
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();
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
) && !User
::isValidEmailAddr( $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 if ( $wgAccountCreationThrottle && $wgUser->isPingLimitable() ) {
381 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
382 $value = $wgMemc->get( $key );
384 $wgMemc->set( $key, 0, 86400 );
386 if ( $value >= $wgAccountCreationThrottle ) {
387 $this->throttleHit( $wgAccountCreationThrottle );
390 $wgMemc->incr( $key );
393 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
394 $this->mainLoginForm( wfMsg( 'externaldberror' ) );
398 self
::clearCreateaccountToken();
399 return $this->initUser( $u, false );
403 * Actually add a user to the database.
404 * Give it a User object that has been initialised with a name.
406 * @param $u User object.
407 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
408 * @return User object.
411 function initUser( $u, $autocreate ) {
416 if ( $wgAuth->allowPasswordChange() ) {
417 $u->setPassword( $this->mPassword
);
420 $u->setEmail( $this->mEmail
);
421 $u->setRealName( $this->mRealName
);
424 $wgAuth->initUser( $u, $autocreate );
426 if ( $this->mExtUser
) {
427 $this->mExtUser
->linkToLocal( $u->getId() );
428 $email = $this->mExtUser
->getPref( 'emailaddress' );
429 if ( $email && !$this->mEmail
) {
430 $u->setEmail( $email );
434 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
438 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
439 $ssUpdate->doUpdate();
445 * Internally authenticate the login request.
447 * This may create a local account as a side effect if the
448 * authentication plugin allows transparent local account
451 public function authenticateUserData() {
452 global $wgUser, $wgAuth, $wgMemc;
454 if ( $this->mUsername
== '' ) {
455 return self
::NO_NAME
;
458 // We require a login token to prevent login CSRF
459 // Handle part of this before incrementing the throttle so
460 // token-less login attempts don't count towards the throttle
461 // but wrong-token attempts do.
463 // If the user doesn't have a login token yet, set one.
464 if ( !self
::getLoginToken() ) {
465 self
::setLoginToken();
466 return self
::NEED_TOKEN
;
468 // If the user didn't pass a login token, tell them we need one
469 if ( !$this->mToken
) {
470 return self
::NEED_TOKEN
;
473 global $wgPasswordAttemptThrottle;
476 if ( is_array( $wgPasswordAttemptThrottle ) ) {
477 $throttleKey = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mUsername
) );
478 $count = $wgPasswordAttemptThrottle['count'];
479 $period = $wgPasswordAttemptThrottle['seconds'];
481 $throttleCount = $wgMemc->get( $throttleKey );
482 if ( !$throttleCount ) {
483 $wgMemc->add( $throttleKey, 1, $period ); // start counter
484 } elseif ( $throttleCount < $count ) {
485 $wgMemc->incr( $throttleKey );
486 } elseif ( $throttleCount >= $count ) {
487 return self
::THROTTLED
;
491 // Validate the login token
492 if ( $this->mToken
!== self
::getLoginToken() ) {
493 return self
::WRONG_TOKEN
;
496 // Load $wgUser now, and check to see if we're logging in as the same
497 // name. This is necessary because loading $wgUser (say by calling
498 // getName()) calls the UserLoadFromSession hook, which potentially
499 // creates the user in the database. Until we load $wgUser, checking
500 // for user existence using User::newFromName($name)->getId() below
501 // will effectively be using stale data.
502 if ( $wgUser->getName() === $this->mUsername
) {
503 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
504 return self
::SUCCESS
;
507 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
509 # TODO: Allow some magic here for invalid external names, e.g., let the
510 # user choose a different wiki name.
511 $u = User
::newFromName( $this->mUsername
);
512 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
513 return self
::ILLEGAL
;
516 $isAutoCreated = false;
517 if ( 0 == $u->getID() ) {
518 $status = $this->attemptAutoCreate( $u );
519 if ( $status !== self
::SUCCESS
) {
522 $isAutoCreated = true;
525 global $wgExternalAuthType, $wgAutocreatePolicy;
526 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
527 && is_object( $this->mExtUser
)
528 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
529 # The external user and local user have the same name and
530 # password, so we assume they're the same.
531 $this->mExtUser
->linkToLocal( $u->getID() );
537 // Give general extensions, such as a captcha, a chance to abort logins
538 $abort = self
::ABORTED
;
539 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
543 global $wgBlockDisablesLogin;
544 if ( !$u->checkPassword( $this->mPassword
) ) {
545 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
546 // The e-mailed temporary password should not be used for actu-
547 // al logins; that's a very sloppy habit, and insecure if an
548 // attacker has a few seconds to click "search" on someone's o-
551 // Allow it to be used only to reset the password a single time
552 // to a new value, which won't be in the user's e-mail ar-
555 // For backwards compatibility, we'll still recognize it at the
556 // login form to minimize surprises for people who have been
557 // logging in with a temporary password for some time.
559 // As a side-effect, we can authenticate the user's e-mail ad-
560 // dress if it's not already done, since the temporary password
561 // was sent via e-mail.
562 if( !$u->isEmailConfirmed() ) {
567 // At this point we just return an appropriate code/ indicating
568 // that the UI should show a password reset form; bot inter-
569 // faces etc will probably just fail cleanly here.
570 $retval = self
::RESET_PASS
;
572 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
574 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
575 // If we've enabled it, make it so that a blocked user cannot login
576 $retval = self
::USER_BLOCKED
;
578 $wgAuth->updateUser( $u );
581 // Please reset throttle for successful logins, thanks!
582 if( $throttleCount ) {
583 $wgMemc->delete( $throttleKey );
586 if ( $isAutoCreated ) {
587 // Must be run after $wgUser is set, for correct new user log
588 wfRunHooks( 'AuthPluginAutoCreate', array( $wgUser ) );
591 $retval = self
::SUCCESS
;
593 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
598 * Attempt to automatically create a user on login. Only succeeds if there
599 * is an external authentication method which allows it.
603 * @return integer Status code
605 function attemptAutoCreate( $user ) {
606 global $wgAuth, $wgUser, $wgAutocreatePolicy;
608 if ( $wgUser->isBlockedFromCreateAccount() ) {
609 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
610 return self
::CREATE_BLOCKED
;
614 * If the external authentication plugin allows it, automatically cre-
615 * ate a new account for users that are externally defined but have not
618 if ( $this->mExtUser
) {
619 # mExtUser is neither null nor false, so use the new ExternalAuth
621 if ( $wgAutocreatePolicy == 'never' ) {
622 return self
::NOT_EXISTS
;
624 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
625 return self
::WRONG_PLUGIN_PASS
;
629 if ( !$wgAuth->autoCreate() ) {
630 return self
::NOT_EXISTS
;
632 if ( !$wgAuth->userExists( $user->getName() ) ) {
633 wfDebug( __METHOD__
. ": user does not exist\n" );
634 return self
::NOT_EXISTS
;
636 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
637 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
638 return self
::WRONG_PLUGIN_PASS
;
642 wfDebug( __METHOD__
. ": creating account\n" );
643 $this->initUser( $user, true );
644 return self
::SUCCESS
;
647 function processLogin() {
650 switch ( $this->authenticateUserData() ) {
652 # We've verified now, update the real record
653 if( (bool)$this->mRemember
!= (bool)$wgUser->getOption( 'rememberpassword' ) ) {
654 $wgUser->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
655 $wgUser->saveSettings();
657 $wgUser->invalidateCache();
659 $wgUser->setCookies();
660 self
::clearLoginToken();
662 // Reset the throttle
663 $key = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mUsername
) );
665 $wgMemc->delete( $key );
667 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
668 /* Replace the language object to provide user interface in
669 * correct language immediately on this first page load.
671 global $wgLang, $wgRequest;
672 $code = $wgRequest->getVal( 'uselang', $wgUser->getOption( 'language' ) );
673 $wgLang = Language
::factory( $code );
674 return $this->successfulLogin();
676 return $this->cookieRedirectCheck( 'login' );
680 case self
::NEED_TOKEN
:
681 $this->mainLoginForm( wfMsgExt( 'nocookiesforlogin', array( 'parseinline' ) ) );
683 case self
::WRONG_TOKEN
:
684 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
688 $this->mainLoginForm( wfMsg( 'noname' ) );
690 case self
::WRONG_PLUGIN_PASS
:
691 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
693 case self
::NOT_EXISTS
:
694 if( $wgUser->isAllowed( 'createaccount' ) ) {
695 $this->mainLoginForm( wfMsgExt( 'nosuchuser', 'parseinline', $this->mUsername
) );
697 $this->mainLoginForm( wfMsg( 'nosuchusershort', htmlspecialchars( $this->mUsername
) ) );
700 case self
::WRONG_PASS
:
701 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
703 case self
::EMPTY_PASS
:
704 $this->mainLoginForm( wfMsg( 'wrongpasswordempty' ) );
706 case self
::RESET_PASS
:
707 $this->resetLoginForm( wfMsg( 'resetpass_announce' ) );
709 case self
::CREATE_BLOCKED
:
710 $this->userBlockedMessage();
712 case self
::THROTTLED
:
713 $this->mainLoginForm( wfMsg( 'login-throttled' ) );
715 case self
::USER_BLOCKED
:
716 $this->mainLoginForm( wfMsgExt( 'login-userblocked',
717 array( 'parsemag', 'escape' ), $this->mUsername
) );
720 $this->mainLoginForm( wfMsg( $this->mAbortLoginErrorMsg
) );
723 throw new MWException( 'Unhandled case value' );
727 function resetLoginForm( $error ) {
729 $wgOut->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
730 $reset = new SpecialResetpass();
731 $reset->execute( null );
737 function mailPassword() {
738 global $wgUser, $wgOut, $wgAuth;
740 if ( wfReadOnly() ) {
741 $wgOut->readOnlyPage();
745 if( !$wgAuth->allowPasswordChange() ) {
746 $this->mainLoginForm( wfMsg( 'resetpass_forbidden' ) );
750 # Check against blocked IPs so blocked users can't flood admins
751 # with password resets
752 if( $wgUser->isBlocked() ) {
753 $this->mainLoginForm( wfMsg( 'blocked-mailpassword' ) );
759 if ( !wfRunHooks( 'UserLoginMailPassword', array( $this->mUsername
, &$error ) ) ) {
760 $this->mainLoginForm( $error );
764 # If the user doesn't have a login token yet, set one.
765 if ( !self
::getLoginToken() ) {
766 self
::setLoginToken();
767 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
771 # If the user didn't pass a login token, tell them we need one
772 if ( !$this->mToken
) {
773 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
777 # Check against the rate limiter
778 if( $wgUser->pingLimiter( 'mailpassword' ) ) {
779 $wgOut->rateLimited();
783 if ( $this->mUsername
== '' ) {
784 $this->mainLoginForm( wfMsg( 'noname' ) );
787 $u = User
::newFromName( $this->mUsername
);
788 if( !$u instanceof User
) {
789 $this->mainLoginForm( wfMsg( 'noname' ) );
792 if ( 0 == $u->getID() ) {
793 $this->mainLoginForm( wfMsgExt( 'nosuchuser', 'parseinline', $u->getName() ) );
797 # Validate the login token
798 if ( $this->mToken
!== self
::getLoginToken() ) {
799 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
803 # Check against password throttle
804 if ( $u->isPasswordReminderThrottled() ) {
805 global $wgPasswordReminderResendTime;
806 # Round the time in hours to 3 d.p., in case someone is specifying
807 # minutes or seconds.
808 $this->mainLoginForm( wfMsgExt( 'throttled-mailpassword', array( 'parsemag' ),
809 round( $wgPasswordReminderResendTime, 3 ) ) );
813 $result = $this->mailPasswordInternal( $u, true, 'passwordremindertitle', 'passwordremindertext' );
814 if( $result->isGood() ) {
815 $this->mainLoginForm( wfMsg( 'passwordsent', $u->getName() ), 'success' );
816 self
::clearLoginToken();
818 $this->mainLoginForm( $result->getWikiText( 'mailerror' ) );
824 * @param $u User object
825 * @param $throttle Boolean
826 * @param $emailTitle String: message name of email title
827 * @param $emailText String: message name of email text
828 * @return Status object
831 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
832 global $wgServer, $wgScript, $wgUser, $wgNewPasswordExpiry;
834 if ( $u->getEmail() == '' ) {
835 return Status
::newFatal( 'noemail', $u->getName() );
839 return Status
::newFatal( 'badipaddress' );
842 wfRunHooks( 'User::mailPasswordInternal', array( &$wgUser, &$ip, &$u ) );
844 $np = $u->randomPassword();
845 $u->setNewpassword( $np, $throttle );
847 $userLanguage = $u->getOption( 'language' );
848 $m = wfMsgExt( $emailText, array( 'parsemag', 'language' => $userLanguage ), $ip, $u->getName(), $np,
849 $wgServer . $wgScript, round( $wgNewPasswordExpiry / 86400 ) );
850 $result = $u->sendMail( wfMsgExt( $emailTitle, array( 'parsemag', 'language' => $userLanguage ) ), $m );
857 * Run any hooks registered for logins, then HTTP redirect to
858 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
859 * nice message here, but that's really not as useful as just being sent to
860 * wherever you logged in from. It should be clear that the action was
861 * successful, given the lack of error messages plus the appearance of your
862 * name in the upper right.
866 function successfulLogin() {
867 global $wgUser, $wgOut;
869 # Run any hooks; display injected HTML if any, else redirect
871 wfRunHooks( 'UserLoginComplete', array( &$wgUser, &$injected_html ) );
873 if( $injected_html !== '' ) {
874 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
876 $titleObj = Title
::newFromText( $this->mReturnTo
);
877 if ( !$titleObj instanceof Title
) {
878 $titleObj = Title
::newMainPage();
880 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery
);
881 global $wgSecureLogin;
882 if( $wgSecureLogin && !$this->mStickHTTPS
) {
883 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
885 $wgOut->redirect( $redirectUrl );
890 * Run any hooks registered for logins, then display a message welcoming
895 function successfulCreation() {
897 # Run any hooks; display injected HTML
899 wfRunHooks( 'UserLoginComplete', array( &$wgUser, &$injected_html ) );
901 $this->displaySuccessfulLogin( 'welcomecreation', $injected_html );
905 * Display a "login successful" page.
907 private function displaySuccessfulLogin( $msgname, $injected_html ) {
908 global $wgOut, $wgUser;
910 $wgOut->setPageTitle( wfMsg( 'loginsuccesstitle' ) );
911 $wgOut->addWikiMsg( $msgname, $wgUser->getName() );
912 $wgOut->addHTML( $injected_html );
914 if ( !empty( $this->mReturnTo
) ) {
915 $wgOut->returnToMain( null, $this->mReturnTo
, $this->mReturnToQuery
);
917 $wgOut->returnToMain( null );
922 function userBlockedMessage() {
923 global $wgOut, $wgUser;
925 # Let's be nice about this, it's likely that this feature will be used
926 # for blocking large numbers of innocent people, e.g. range blocks on
927 # schools. Don't blame it on the user. There's a small chance that it
928 # really is the user's fault, i.e. the username is blocked and they
929 # haven't bothered to log out before trying to create an account to
930 # evade it, but we'll leave that to their guilty conscience to figure
933 $wgOut->setPageTitle( wfMsg( 'cantcreateaccounttitle' ) );
936 $blocker = User
::whoIs( $wgUser->mBlock
->mBy
);
937 $block_reason = $wgUser->mBlock
->mReason
;
939 if ( strval( $block_reason ) === '' ) {
940 $block_reason = wfMsg( 'blockednoreason' );
942 $wgOut->addWikiMsg( 'cantcreateaccount-text', $ip, $block_reason, $blocker );
943 $wgOut->returnToMain( false );
949 function mainLoginForm( $msg, $msgtype = 'error' ) {
950 global $wgUser, $wgOut, $wgHiddenPrefs;
951 global $wgEnableEmail, $wgEnableUserEmail;
952 global $wgRequest, $wgLoginLanguageSelector;
953 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
954 global $wgSecureLogin;
956 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
958 if ( $this->mType
== 'signup' ) {
959 // Block signup here if in readonly. Keeps user from
960 // going through the process (filling out data, etc)
961 // and being informed later.
962 if ( wfReadOnly() ) {
963 $wgOut->readOnlyPage();
965 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
966 $this->userBlockedMessage();
968 } elseif ( count( $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $wgUser, true ) )>0 ) {
969 $wgOut->showPermissionsErrorPage( $permErrors, 'createaccount' );
974 if ( $this->mUsername
== '' ) {
975 if ( $wgUser->isLoggedIn() ) {
976 $this->mUsername
= $wgUser->getName();
978 $this->mUsername
= $wgRequest->getCookie( 'UserName' );
982 if ( $this->mType
== 'signup' ) {
983 global $wgLivePasswordStrengthChecks;
984 if ( $wgLivePasswordStrengthChecks ) {
985 $wgOut->addPasswordSecurity( 'wpPassword2', 'wpRetype' );
987 $template = new UsercreateTemplate();
988 $q = 'action=submitlogin&type=signup';
989 $linkq = 'type=login';
990 $linkmsg = 'gotaccount';
992 $template = new UserloginTemplate();
993 $q = 'action=submitlogin&type=login';
994 $linkq = 'type=signup';
995 $linkmsg = 'nologin';
998 if ( !empty( $this->mReturnTo
) ) {
999 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1000 if ( !empty( $this->mReturnToQuery
) ) {
1001 $returnto .= '&returntoquery=' .
1002 wfUrlencode( $this->mReturnToQuery
);
1005 $linkq .= $returnto;
1008 # Pass any language selection on to the mode switch link
1009 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1010 $linkq .= '&uselang=' . $this->mLanguage
;
1013 $link = '<a href="' . htmlspecialchars ( $titleObj->getLocalURL( $linkq ) ) . '">';
1014 $link .= wfMsgHtml( $linkmsg . 'link' ); # Calling either 'gotaccountlink' or 'nologinlink'
1017 # Don't show a "create account" link if the user can't
1018 if( $this->showCreateOrLoginLink( $wgUser ) ) {
1019 $template->set( 'link', wfMsgExt( $linkmsg, array( 'parseinline', 'replaceafter' ), $link ) );
1021 $template->set( 'link', '' );
1024 $template->set( 'header', '' );
1025 $template->set( 'name', $this->mUsername
);
1026 $template->set( 'password', $this->mPassword
);
1027 $template->set( 'retype', $this->mRetype
);
1028 $template->set( 'email', $this->mEmail
);
1029 $template->set( 'realname', $this->mRealName
);
1030 $template->set( 'domain', $this->mDomain
);
1031 $template->set( 'reason', $this->mReason
);
1033 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1034 $template->set( 'message', $msg );
1035 $template->set( 'messagetype', $msgtype );
1036 $template->set( 'createemail', $wgEnableEmail && $wgUser->isLoggedIn() );
1037 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1038 $template->set( 'useemail', $wgEnableEmail );
1039 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1040 $template->set( 'emailothers', $wgEnableUserEmail );
1041 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1042 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1043 $template->set( 'usereason', $wgUser->isLoggedIn() );
1044 $template->set( 'remember', $wgUser->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1045 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1046 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1048 if ( $this->mType
== 'signup' ) {
1049 if ( !self
::getCreateaccountToken() ) {
1050 self
::setCreateaccountToken();
1052 $template->set( 'token', self
::getCreateaccountToken() );
1054 if ( !self
::getLoginToken() ) {
1055 self
::setLoginToken();
1057 $template->set( 'token', self
::getLoginToken() );
1060 # Prepare language selection links as needed
1061 if( $wgLoginLanguageSelector ) {
1062 $template->set( 'languages', $this->makeLanguageSelector() );
1063 if( $this->mLanguage
)
1064 $template->set( 'uselang', $this->mLanguage
);
1067 // Give authentication and captcha plugins a chance to modify the form
1068 $wgAuth->modifyUITemplate( $template, $this->mType
);
1069 if ( $this->mType
== 'signup' ) {
1070 wfRunHooks( 'UserCreateForm', array( &$template ) );
1072 wfRunHooks( 'UserLoginForm', array( &$template ) );
1075 // Changes the title depending on permissions for creating account
1076 if ( $wgUser->isAllowed( 'createaccount' ) ) {
1077 $wgOut->setPageTitle( wfMsg( 'userlogin' ) );
1079 $wgOut->setPageTitle( wfMsg( 'userloginnocreate' ) );
1082 $wgOut->disallowUserJs(); // just in case...
1083 $wgOut->addTemplate( $template );
1093 function showCreateOrLoginLink( &$user ) {
1094 if( $this->mType
== 'signup' ) {
1096 } elseif( $user->isAllowed( 'createaccount' ) ) {
1104 * Check if a session cookie is present.
1106 * This will not pick up a cookie set during _this_ request, but is meant
1107 * to ensure that the client is returning the cookie which was set on a
1108 * previous pass through the system.
1112 function hasSessionCookie() {
1113 global $wgDisableCookieCheck, $wgRequest;
1114 return $wgDisableCookieCheck ?
true : $wgRequest->checkSessionCookie();
1118 * Get the login token from the current session
1120 public static function getLoginToken() {
1122 return $wgRequest->getSessionData( 'wsLoginToken' );
1126 * Randomly generate a new login token and attach it to the current session
1128 public static function setLoginToken() {
1130 // Use User::generateToken() instead of $user->editToken()
1131 // because the latter reuses $_SESSION['wsEditToken']
1132 $wgRequest->setSessionData( 'wsLoginToken', User
::generateToken() );
1136 * Remove any login token attached to the current session
1138 public static function clearLoginToken() {
1140 $wgRequest->setSessionData( 'wsLoginToken', null );
1144 * Get the createaccount token from the current session
1146 public static function getCreateaccountToken() {
1148 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1152 * Randomly generate a new createaccount token and attach it to the current session
1154 public static function setCreateaccountToken() {
1156 $wgRequest->setSessionData( 'wsCreateaccountToken', User
::generateToken() );
1160 * Remove any createaccount token attached to the current session
1162 public static function clearCreateaccountToken() {
1164 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1170 function cookieRedirectCheck( $type ) {
1173 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1174 $query = array( 'wpCookieCheck' => $type );
1175 if ( $this->mReturnTo
) {
1176 $query['returnto'] = $this->mReturnTo
;
1178 $check = $titleObj->getFullURL( $query );
1180 return $wgOut->redirect( $check );
1186 function onCookieRedirectCheck( $type ) {
1187 if ( !$this->hasSessionCookie() ) {
1188 if ( $type == 'new' ) {
1189 return $this->mainLoginForm( wfMsgExt( 'nocookiesnew', array( 'parseinline' ) ) );
1190 } elseif ( $type == 'login' ) {
1191 return $this->mainLoginForm( wfMsgExt( 'nocookieslogin', array( 'parseinline' ) ) );
1194 return $this->mainLoginForm( wfMsg( 'error' ) );
1197 return $this->successfulLogin();
1204 function throttleHit( $limit ) {
1205 $this->mainLoginForm( wfMsgExt( 'acct_creation_throttle_hit', array( 'parseinline' ), $limit ) );
1209 * Produce a bar of links which allow the user to select another language
1210 * during login/registration but retain "returnto"
1214 function makeLanguageSelector() {
1217 $msg = wfMessage( 'loginlanguagelinks' )->inContentLanguage();
1218 if( !$msg->isBlank() ) {
1219 $langs = explode( "\n", $msg->text() );
1221 foreach( $langs as $lang ) {
1222 $lang = trim( $lang, '* ' );
1223 $parts = explode( '|', $lang );
1224 if ( count( $parts ) >= 2 ) {
1225 $links[] = $this->makeLanguageSelectorLink( $parts[0], $parts[1] );
1228 return count( $links ) > 0 ?
wfMsgHtml( 'loginlanguagelabel', $wgLang->pipeList( $links ) ) : '';
1235 * Create a language selector link for a particular language
1236 * Links back to this page preserving type and returnto
1238 * @param $text Link text
1239 * @param $lang Language code
1241 function makeLanguageSelectorLink( $text, $lang ) {
1243 $self = SpecialPage
::getTitleFor( 'Userlogin' );
1244 $attr = array( 'uselang' => $lang );
1245 if( $this->mType
== 'signup' ) {
1246 $attr['type'] = 'signup';
1248 if( $this->mReturnTo
) {
1249 $attr['returnto'] = $this->mReturnTo
;
1251 $skin = $wgUser->getSkin();
1252 return $skin->linkKnown(
1254 htmlspecialchars( $text ),