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;
51 private $mExtUser = null;
53 public function __construct( $request = null ) {
54 parent
::__construct( 'Userlogin' );
56 if ( $request === null ) {
58 $this->load( $wgRequest );
60 $this->load( $request );
67 * @param $request WebRequest object
69 function load( $request ) {
70 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail, $wgRedirectOnLogin;
72 $this->mType
= $request->getText( 'type' );
73 $this->mUsername
= $request->getText( 'wpName' );
74 $this->mPassword
= $request->getText( 'wpPassword' );
75 $this->mRetype
= $request->getText( 'wpRetype' );
76 $this->mDomain
= $request->getText( 'wpDomain' );
77 $this->mReason
= $request->getText( 'wpReason' );
78 $this->mReturnTo
= $request->getVal( 'returnto' );
79 $this->mReturnToQuery
= $request->getVal( 'returntoquery' );
80 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
81 $this->mPosted
= $request->wasPosted();
82 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' );
83 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
85 $this->mMailmypassword
= $request->getCheck( 'wpMailmypassword' )
87 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
88 $this->mAction
= $request->getVal( 'action' );
89 $this->mRemember
= $request->getCheck( 'wpRemember' );
90 $this->mStickHTTPS
= $request->getCheck( 'wpStickHTTPS' );
91 $this->mLanguage
= $request->getText( 'uselang' );
92 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
93 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
95 if ( $wgRedirectOnLogin ) {
96 $this->mReturnTo
= $wgRedirectOnLogin;
97 $this->mReturnToQuery
= '';
100 if( $wgEnableEmail ) {
101 $this->mEmail
= $request->getText( 'wpEmail' );
105 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
106 $this->mRealName
= $request->getText( 'wpRealName' );
108 $this->mRealName
= '';
111 if( !$wgAuth->validDomain( $this->mDomain
) ) {
112 $this->mDomain
= 'invaliddomain';
114 $wgAuth->setDomain( $this->mDomain
);
116 # When switching accounts, it sucks to get automatically logged out
117 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
118 if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
119 $this->mReturnTo
= '';
120 $this->mReturnToQuery
= '';
124 public function execute( $par ) {
125 if ( session_id() == '' ) {
129 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
130 $this->mType
= 'signup';
133 if ( !is_null( $this->mCookieCheck
) ) {
134 $this->onCookieRedirectCheck( $this->mCookieCheck
);
136 } elseif( $this->mPosted
) {
137 if( $this->mCreateaccount
) {
138 return $this->addNewAccount();
139 } elseif ( $this->mCreateaccountMail
) {
140 return $this->addNewAccountMailPassword();
141 } elseif ( $this->mMailmypassword
) {
142 return $this->mailPassword();
143 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
144 return $this->processLogin();
147 $this->mainLoginForm( '' );
153 function addNewAccountMailPassword() {
156 if ( $this->mEmail
== '' ) {
157 $this->mainLoginForm( wfMsgExt( 'noemail', array( 'parsemag', 'escape' ), $this->mUsername
) );
161 $u = $this->addNewaccountInternal();
167 // Wipe the initial password and mail a temporary one
168 $u->setPassword( null );
170 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
172 wfRunHooks( 'AddNewAccount', array( $u, true ) );
173 $u->addNewUserLogEntry( true, $this->mReason
);
175 $wgOut->setPageTitle( wfMsg( 'accmailtitle' ) );
177 if( !$result->isGood() ) {
178 $this->mainLoginForm( wfMsg( 'mailerror', $result->getWikiText() ) );
180 $wgOut->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
181 $wgOut->returnToMain( false );
188 function addNewAccount() {
189 global $wgUser, $wgEmailAuthentication, $wgOut;
191 # Create the account and abort if there's a problem doing so
192 $u = $this->addNewAccountInternal();
197 # If we showed up language selection links, and one was in use, be
198 # smart (and sensible) and save that language as the user's preference
199 global $wgLoginLanguageSelector;
200 if( $wgLoginLanguageSelector && $this->mLanguage
) {
201 $u->setOption( 'language', $this->mLanguage
);
204 # Send out an email authentication message if needed
205 if( $wgEmailAuthentication && User
::isValidEmailAddr( $u->getEmail() ) ) {
206 $status = $u->sendConfirmationMail();
207 if( $status->isGood() ) {
208 $wgOut->addWikiMsg( 'confirmemail_oncreate' );
210 $wgOut->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
214 # Save settings (including confirmation token)
217 # If not logged in, assume the new account as the current one and set
218 # session cookies then show a "welcome" message or a "need cookies"
220 if( $wgUser->isAnon() ) {
222 $wgUser->setCookies();
223 wfRunHooks( 'AddNewAccount', array( $wgUser, false ) );
224 $wgUser->addNewUserLogEntry();
225 if( $this->hasSessionCookie() ) {
226 return $this->successfulCreation();
228 return $this->cookieRedirectCheck( 'new' );
231 # Confirm that the account was created
232 $self = SpecialPage
::getTitleFor( 'Userlogin' );
233 $wgOut->setPageTitle( wfMsgHtml( 'accountcreated' ) );
234 $wgOut->addWikiMsg( 'accountcreatedtext', $u->getName() );
235 $wgOut->returnToMain( false, $self );
236 wfRunHooks( 'AddNewAccount', array( $u, false ) );
237 $u->addNewUserLogEntry( false, $this->mReason
);
245 function addNewAccountInternal() {
246 global $wgUser, $wgOut;
247 global $wgMemc, $wgAccountCreationThrottle;
248 global $wgAuth, $wgMinimalPasswordLength;
249 global $wgEmailConfirmToEdit;
251 // If the user passes an invalid domain, something is fishy
252 if( !$wgAuth->validDomain( $this->mDomain
) ) {
253 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
257 // If we are not allowing users to login locally, we should be checking
258 // to see if the user is actually able to authenticate to the authenti-
259 // cation server before they create an account (otherwise, they can
260 // create a local account and login as any domain user). We only need
261 // to check this for domains that aren't local.
262 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
263 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername
) ||
!$wgAuth->authenticate( $this->mUsername
, $this->mPassword
) ) ) {
264 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
269 if ( wfReadOnly() ) {
270 $wgOut->readOnlyPage();
274 # Request forgery checks.
275 if ( !self
::getCreateaccountToken() ) {
276 self
::setCreateaccountToken();
277 $this->mainLoginForm( wfMsgExt( 'nocookiesfornew', array( 'parseinline' ) ) );
281 # The user didn't pass a createaccount token
282 if ( !$this->mToken
) {
283 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
287 # Validate the createaccount token
288 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
289 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
294 if ( !$wgUser->isAllowed( 'createaccount' ) ) {
295 $wgOut->permissionRequired( 'createaccount' );
297 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
298 $this->userBlockedMessage();
303 if ( $wgUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
304 $this->mainLoginForm( wfMsg( 'sorbs_create_account_reason' ) . ' (' . htmlspecialchars( $ip ) . ')' );
308 # Now create a dummy user ($u) and check if it is valid
309 $name = trim( $this->mUsername
);
310 $u = User
::newFromName( $name, 'creatable' );
311 if ( !is_object( $u ) ) {
312 $this->mainLoginForm( wfMsg( 'noname' ) );
316 if ( 0 != $u->idForName() ) {
317 $this->mainLoginForm( wfMsg( 'userexists' ) );
321 if ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
322 $this->mainLoginForm( wfMsg( 'badretype' ) );
326 # check for minimal password length
327 $valid = $u->getPasswordValidity( $this->mPassword
);
328 if ( $valid !== true ) {
329 if ( !$this->mCreateaccountMail
) {
330 if ( is_array( $valid ) ) {
331 $message = array_shift( $valid );
335 $params = array( $wgMinimalPasswordLength );
337 $this->mainLoginForm( wfMsgExt( $message, array( 'parsemag' ), $params ) );
340 # do not force a password for account creation by email
341 # set invalid password, it will be replaced later by a random generated password
342 $this->mPassword
= null;
346 # if you need a confirmed email address to edit, then obviously you
347 # need an email address.
348 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
349 $this->mainLoginForm( wfMsg( 'noemailtitle' ) );
353 if( !empty( $this->mEmail
) && !User
::isValidEmailAddr( $this->mEmail
) ) {
354 $this->mainLoginForm( wfMsg( 'invalidemailaddress' ) );
358 # Set some additional data so the AbortNewAccount hook can be used for
359 # more than just username validation
360 $u->setEmail( $this->mEmail
);
361 $u->setRealName( $this->mRealName
);
364 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
365 // Hook point to add extra creation throttles and blocks
366 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
367 $this->mainLoginForm( $abortError );
371 if ( $wgAccountCreationThrottle && $wgUser->isPingLimitable() ) {
372 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
373 $value = $wgMemc->get( $key );
375 $wgMemc->set( $key, 0, 86400 );
377 if ( $value >= $wgAccountCreationThrottle ) {
378 $this->throttleHit( $wgAccountCreationThrottle );
381 $wgMemc->incr( $key );
384 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
385 $this->mainLoginForm( wfMsg( 'externaldberror' ) );
389 self
::clearCreateaccountToken();
390 return $this->initUser( $u, false );
394 * Actually add a user to the database.
395 * Give it a User object that has been initialised with a name.
397 * @param $u User object.
398 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
399 * @return User object.
402 function initUser( $u, $autocreate ) {
407 if ( $wgAuth->allowPasswordChange() ) {
408 $u->setPassword( $this->mPassword
);
411 $u->setEmail( $this->mEmail
);
412 $u->setRealName( $this->mRealName
);
415 $wgAuth->initUser( $u, $autocreate );
417 if ( $this->mExtUser
) {
418 $this->mExtUser
->linkToLocal( $u->getId() );
419 $email = $this->mExtUser
->getPref( 'emailaddress' );
420 if ( $email && !$this->mEmail
) {
421 $u->setEmail( $email );
425 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
429 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
430 $ssUpdate->doUpdate();
436 * Internally authenticate the login request.
438 * This may create a local account as a side effect if the
439 * authentication plugin allows transparent local account
442 public function authenticateUserData() {
443 global $wgUser, $wgAuth, $wgMemc;
445 if ( $this->mUsername
== '' ) {
446 return self
::NO_NAME
;
449 // We require a login token to prevent login CSRF
450 // Handle part of this before incrementing the throttle so
451 // token-less login attempts don't count towards the throttle
452 // but wrong-token attempts do.
454 // If the user doesn't have a login token yet, set one.
455 if ( !self
::getLoginToken() ) {
456 self
::setLoginToken();
457 return self
::NEED_TOKEN
;
459 // If the user didn't pass a login token, tell them we need one
460 if ( !$this->mToken
) {
461 return self
::NEED_TOKEN
;
464 global $wgPasswordAttemptThrottle;
467 if ( is_array( $wgPasswordAttemptThrottle ) ) {
468 $throttleKey = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mUsername
) );
469 $count = $wgPasswordAttemptThrottle['count'];
470 $period = $wgPasswordAttemptThrottle['seconds'];
472 $throttleCount = $wgMemc->get( $throttleKey );
473 if ( !$throttleCount ) {
474 $wgMemc->add( $throttleKey, 1, $period ); // start counter
475 } elseif ( $throttleCount < $count ) {
476 $wgMemc->incr( $throttleKey );
477 } elseif ( $throttleCount >= $count ) {
478 return self
::THROTTLED
;
482 // Validate the login token
483 if ( $this->mToken
!== self
::getLoginToken() ) {
484 return self
::WRONG_TOKEN
;
487 // Load $wgUser now, and check to see if we're logging in as the same
488 // name. This is necessary because loading $wgUser (say by calling
489 // getName()) calls the UserLoadFromSession hook, which potentially
490 // creates the user in the database. Until we load $wgUser, checking
491 // for user existence using User::newFromName($name)->getId() below
492 // will effectively be using stale data.
493 if ( $wgUser->getName() === $this->mUsername
) {
494 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
495 return self
::SUCCESS
;
498 $this->mExtUser
= ExternalUser
::newFromName( $this->mUsername
);
500 # TODO: Allow some magic here for invalid external names, e.g., let the
501 # user choose a different wiki name.
502 $u = User
::newFromName( $this->mUsername
);
503 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
504 return self
::ILLEGAL
;
507 $isAutoCreated = false;
508 if ( 0 == $u->getID() ) {
509 $status = $this->attemptAutoCreate( $u );
510 if ( $status !== self
::SUCCESS
) {
513 $isAutoCreated = true;
516 global $wgExternalAuthType, $wgAutocreatePolicy;
517 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
518 && is_object( $this->mExtUser
)
519 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
520 # The external user and local user have the same name and
521 # password, so we assume they're the same.
522 $this->mExtUser
->linkToLocal( $u->getID() );
528 // Give general extensions, such as a captcha, a chance to abort logins
529 $abort = self
::ABORTED
;
530 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort ) ) ) {
534 global $wgBlockDisablesLogin;
535 if ( !$u->checkPassword( $this->mPassword
) ) {
536 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
537 // The e-mailed temporary password should not be used for actu-
538 // al logins; that's a very sloppy habit, and insecure if an
539 // attacker has a few seconds to click "search" on someone's o-
542 // Allow it to be used only to reset the password a single time
543 // to a new value, which won't be in the user's e-mail ar-
546 // For backwards compatibility, we'll still recognize it at the
547 // login form to minimize surprises for people who have been
548 // logging in with a temporary password for some time.
550 // As a side-effect, we can authenticate the user's e-mail ad-
551 // dress if it's not already done, since the temporary password
552 // was sent via e-mail.
553 if( !$u->isEmailConfirmed() ) {
558 // At this point we just return an appropriate code/ indicating
559 // that the UI should show a password reset form; bot inter-
560 // faces etc will probably just fail cleanly here.
561 $retval = self
::RESET_PASS
;
563 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
565 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
566 // If we've enabled it, make it so that a blocked user cannot login
567 $retval = self
::USER_BLOCKED
;
569 $wgAuth->updateUser( $u );
572 // Please reset throttle for successful logins, thanks!
573 if( $throttleCount ) {
574 $wgMemc->delete( $throttleKey );
577 if ( $isAutoCreated ) {
578 // Must be run after $wgUser is set, for correct new user log
579 wfRunHooks( 'AuthPluginAutoCreate', array( $wgUser ) );
582 $retval = self
::SUCCESS
;
584 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
589 * Attempt to automatically create a user on login. Only succeeds if there
590 * is an external authentication method which allows it.
594 * @return integer Status code
596 function attemptAutoCreate( $user ) {
597 global $wgAuth, $wgUser, $wgAutocreatePolicy;
599 if ( $wgUser->isBlockedFromCreateAccount() ) {
600 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
601 return self
::CREATE_BLOCKED
;
605 * If the external authentication plugin allows it, automatically cre-
606 * ate a new account for users that are externally defined but have not
609 if ( $this->mExtUser
) {
610 # mExtUser is neither null nor false, so use the new ExternalAuth
612 if ( $wgAutocreatePolicy == 'never' ) {
613 return self
::NOT_EXISTS
;
615 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
616 return self
::WRONG_PLUGIN_PASS
;
620 if ( !$wgAuth->autoCreate() ) {
621 return self
::NOT_EXISTS
;
623 if ( !$wgAuth->userExists( $user->getName() ) ) {
624 wfDebug( __METHOD__
. ": user does not exist\n" );
625 return self
::NOT_EXISTS
;
627 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
628 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
629 return self
::WRONG_PLUGIN_PASS
;
633 wfDebug( __METHOD__
. ": creating account\n" );
634 $this->initUser( $user, true );
635 return self
::SUCCESS
;
638 function processLogin() {
641 switch ( $this->authenticateUserData() ) {
643 # We've verified now, update the real record
644 if( (bool)$this->mRemember
!= (bool)$wgUser->getOption( 'rememberpassword' ) ) {
645 $wgUser->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
646 $wgUser->saveSettings();
648 $wgUser->invalidateCache();
650 $wgUser->setCookies();
651 self
::clearLoginToken();
653 // Reset the throttle
654 $key = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mUsername
) );
656 $wgMemc->delete( $key );
658 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
659 /* Replace the language object to provide user interface in
660 * correct language immediately on this first page load.
662 global $wgLang, $wgRequest;
663 $code = $wgRequest->getVal( 'uselang', $wgUser->getOption( 'language' ) );
664 $wgLang = Language
::factory( $code );
665 return $this->successfulLogin();
667 return $this->cookieRedirectCheck( 'login' );
671 case self
::NEED_TOKEN
:
672 $this->mainLoginForm( wfMsgExt( 'nocookiesforlogin', array( 'parseinline' ) ) );
674 case self
::WRONG_TOKEN
:
675 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
679 $this->mainLoginForm( wfMsg( 'noname' ) );
681 case self
::WRONG_PLUGIN_PASS
:
682 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
684 case self
::NOT_EXISTS
:
685 if( $wgUser->isAllowed( 'createaccount' ) ) {
686 $this->mainLoginForm( wfMsgExt( 'nosuchuser', 'parseinline', $this->mUsername
) );
688 $this->mainLoginForm( wfMsg( 'nosuchusershort', htmlspecialchars( $this->mUsername
) ) );
691 case self
::WRONG_PASS
:
692 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
694 case self
::EMPTY_PASS
:
695 $this->mainLoginForm( wfMsg( 'wrongpasswordempty' ) );
697 case self
::RESET_PASS
:
698 $this->resetLoginForm( wfMsg( 'resetpass_announce' ) );
700 case self
::CREATE_BLOCKED
:
701 $this->userBlockedMessage();
703 case self
::THROTTLED
:
704 $this->mainLoginForm( wfMsg( 'login-throttled' ) );
706 case self
::USER_BLOCKED
:
707 $this->mainLoginForm( wfMsgExt( 'login-userblocked',
708 array( 'parsemag', 'escape' ), $this->mUsername
) );
711 throw new MWException( 'Unhandled case value' );
715 function resetLoginForm( $error ) {
717 $wgOut->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
718 $reset = new SpecialResetpass();
719 $reset->execute( null );
725 function mailPassword() {
726 global $wgUser, $wgOut, $wgAuth;
728 if ( wfReadOnly() ) {
729 $wgOut->readOnlyPage();
733 if( !$wgAuth->allowPasswordChange() ) {
734 $this->mainLoginForm( wfMsg( 'resetpass_forbidden' ) );
738 # Check against blocked IPs so blocked users can't flood admins
739 # with password resets
740 if( $wgUser->isBlocked() ) {
741 $this->mainLoginForm( wfMsg( 'blocked-mailpassword' ) );
747 if ( !wfRunHooks( 'UserLoginMailPassword', array( $this->mUsername
, &$error ) ) ) {
748 $this->mainLoginForm( $error );
752 # If the user doesn't have a login token yet, set one.
753 if ( !self
::getLoginToken() ) {
754 self
::setLoginToken();
755 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
759 # If the user didn't pass a login token, tell them we need one
760 if ( !$this->mToken
) {
761 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
765 # Check against the rate limiter
766 if( $wgUser->pingLimiter( 'mailpassword' ) ) {
767 $wgOut->rateLimited();
771 if ( $this->mUsername
== '' ) {
772 $this->mainLoginForm( wfMsg( 'noname' ) );
775 $u = User
::newFromName( $this->mUsername
);
776 if( !$u instanceof User
) {
777 $this->mainLoginForm( wfMsg( 'noname' ) );
780 if ( 0 == $u->getID() ) {
781 $this->mainLoginForm( wfMsgExt( 'nosuchuser', 'parseinline', $u->getName() ) );
785 # Validate the login token
786 if ( $this->mToken
!== self
::getLoginToken() ) {
787 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
791 # Check against password throttle
792 if ( $u->isPasswordReminderThrottled() ) {
793 global $wgPasswordReminderResendTime;
794 # Round the time in hours to 3 d.p., in case someone is specifying
795 # minutes or seconds.
796 $this->mainLoginForm( wfMsgExt( 'throttled-mailpassword', array( 'parsemag' ),
797 round( $wgPasswordReminderResendTime, 3 ) ) );
801 $result = $this->mailPasswordInternal( $u, true, 'passwordremindertitle', 'passwordremindertext' );
802 if( $result->isGood() ) {
803 $this->mainLoginForm( wfMsg( 'passwordsent', $u->getName() ), 'success' );
804 self
::clearLoginToken();
806 $this->mainLoginForm( $result->getWikiText( 'mailerror' ) );
812 * @param $u User object
813 * @param $throttle Boolean
814 * @param $emailTitle String: message name of email title
815 * @param $emailText String: message name of email text
816 * @return Status object
819 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
820 global $wgServer, $wgScript, $wgUser, $wgNewPasswordExpiry;
822 if ( $u->getEmail() == '' ) {
823 return Status
::newFatal( 'noemail', $u->getName() );
827 return Status
::newFatal( 'badipaddress' );
830 wfRunHooks( 'User::mailPasswordInternal', array( &$wgUser, &$ip, &$u ) );
832 $np = $u->randomPassword();
833 $u->setNewpassword( $np, $throttle );
835 $userLanguage = $u->getOption( 'language' );
836 $m = wfMsgExt( $emailText, array( 'parsemag', 'language' => $userLanguage ), $ip, $u->getName(), $np,
837 $wgServer . $wgScript, round( $wgNewPasswordExpiry / 86400 ) );
838 $result = $u->sendMail( wfMsgExt( $emailTitle, array( 'parsemag', 'language' => $userLanguage ) ), $m );
845 * Run any hooks registered for logins, then HTTP redirect to
846 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
847 * nice message here, but that's really not as useful as just being sent to
848 * wherever you logged in from. It should be clear that the action was
849 * successful, given the lack of error messages plus the appearance of your
850 * name in the upper right.
854 function successfulLogin() {
855 global $wgUser, $wgOut;
857 # Run any hooks; display injected HTML if any, else redirect
859 wfRunHooks( 'UserLoginComplete', array( &$wgUser, &$injected_html ) );
861 if( $injected_html !== '' ) {
862 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
864 $titleObj = Title
::newFromText( $this->mReturnTo
);
865 if ( !$titleObj instanceof Title
) {
866 $titleObj = Title
::newMainPage();
868 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery
);
869 global $wgSecureLogin;
870 if( $wgSecureLogin && !$this->mStickHTTPS
) {
871 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
873 $wgOut->redirect( $redirectUrl );
878 * Run any hooks registered for logins, then display a message welcoming
883 function successfulCreation() {
885 # Run any hooks; display injected HTML
887 wfRunHooks( 'UserLoginComplete', array( &$wgUser, &$injected_html ) );
889 $this->displaySuccessfulLogin( 'welcomecreation', $injected_html );
893 * Display a "login successful" page.
895 private function displaySuccessfulLogin( $msgname, $injected_html ) {
896 global $wgOut, $wgUser;
898 $wgOut->setPageTitle( wfMsg( 'loginsuccesstitle' ) );
899 $wgOut->addWikiMsg( $msgname, $wgUser->getName() );
900 $wgOut->addHTML( $injected_html );
902 if ( !empty( $this->mReturnTo
) ) {
903 $wgOut->returnToMain( null, $this->mReturnTo
, $this->mReturnToQuery
);
905 $wgOut->returnToMain( null );
910 function userBlockedMessage() {
911 global $wgOut, $wgUser;
913 # Let's be nice about this, it's likely that this feature will be used
914 # for blocking large numbers of innocent people, e.g. range blocks on
915 # schools. Don't blame it on the user. There's a small chance that it
916 # really is the user's fault, i.e. the username is blocked and they
917 # haven't bothered to log out before trying to create an account to
918 # evade it, but we'll leave that to their guilty conscience to figure
921 $wgOut->setPageTitle( wfMsg( 'cantcreateaccounttitle' ) );
924 $blocker = User
::whoIs( $wgUser->mBlock
->mBy
);
925 $block_reason = $wgUser->mBlock
->mReason
;
927 if ( strval( $block_reason ) === '' ) {
928 $block_reason = wfMsg( 'blockednoreason' );
930 $wgOut->addWikiMsg( 'cantcreateaccount-text', $ip, $block_reason, $blocker );
931 $wgOut->returnToMain( false );
937 function mainLoginForm( $msg, $msgtype = 'error' ) {
938 global $wgUser, $wgOut, $wgHiddenPrefs;
939 global $wgEnableEmail, $wgEnableUserEmail;
940 global $wgRequest, $wgLoginLanguageSelector;
941 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
942 global $wgSecureLogin;
944 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
946 if ( $this->mType
== 'signup' ) {
947 // Block signup here if in readonly. Keeps user from
948 // going through the process (filling out data, etc)
949 // and being informed later.
950 if ( wfReadOnly() ) {
951 $wgOut->readOnlyPage();
953 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
954 $this->userBlockedMessage();
956 } elseif ( count( $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $wgUser, true ) )>0 ) {
957 $wgOut->showPermissionsErrorPage( $permErrors, 'createaccount' );
962 if ( $this->mUsername
== '' ) {
963 if ( $wgUser->isLoggedIn() ) {
964 $this->mUsername
= $wgUser->getName();
966 $this->mUsername
= $wgRequest->getCookie( 'UserName' );
970 if ( $this->mType
== 'signup' ) {
971 global $wgLivePasswordStrengthChecks;
972 if ( $wgLivePasswordStrengthChecks ) {
973 $wgOut->addPasswordSecurity( 'wpPassword2', 'wpRetype' );
975 $template = new UsercreateTemplate();
976 $q = 'action=submitlogin&type=signup';
977 $linkq = 'type=login';
978 $linkmsg = 'gotaccount';
980 $template = new UserloginTemplate();
981 $q = 'action=submitlogin&type=login';
982 $linkq = 'type=signup';
983 $linkmsg = 'nologin';
986 if ( !empty( $this->mReturnTo
) ) {
987 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
988 if ( !empty( $this->mReturnToQuery
) ) {
989 $returnto .= '&returntoquery=' .
990 wfUrlencode( $this->mReturnToQuery
);
996 # Pass any language selection on to the mode switch link
997 if( $wgLoginLanguageSelector && $this->mLanguage
) {
998 $linkq .= '&uselang=' . $this->mLanguage
;
1001 $link = '<a href="' . htmlspecialchars ( $titleObj->getLocalURL( $linkq ) ) . '">';
1002 $link .= wfMsgHtml( $linkmsg . 'link' ); # Calling either 'gotaccountlink' or 'nologinlink'
1005 # Don't show a "create account" link if the user can't
1006 if( $this->showCreateOrLoginLink( $wgUser ) ) {
1007 $template->set( 'link', wfMsgExt( $linkmsg, array( 'parseinline', 'replaceafter' ), $link ) );
1009 $template->set( 'link', '' );
1012 $template->set( 'header', '' );
1013 $template->set( 'name', $this->mUsername
);
1014 $template->set( 'password', $this->mPassword
);
1015 $template->set( 'retype', $this->mRetype
);
1016 $template->set( 'email', $this->mEmail
);
1017 $template->set( 'realname', $this->mRealName
);
1018 $template->set( 'domain', $this->mDomain
);
1019 $template->set( 'reason', $this->mReason
);
1021 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1022 $template->set( 'message', $msg );
1023 $template->set( 'messagetype', $msgtype );
1024 $template->set( 'createemail', $wgEnableEmail && $wgUser->isLoggedIn() );
1025 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1026 $template->set( 'useemail', $wgEnableEmail );
1027 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1028 $template->set( 'emailothers', $wgEnableUserEmail );
1029 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1030 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1031 $template->set( 'usereason', $wgUser->isLoggedIn() );
1032 $template->set( 'remember', $wgUser->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1033 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1034 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1036 if ( $this->mType
== 'signup' ) {
1037 if ( !self
::getCreateaccountToken() ) {
1038 self
::setCreateaccountToken();
1040 $template->set( 'token', self
::getCreateaccountToken() );
1042 if ( !self
::getLoginToken() ) {
1043 self
::setLoginToken();
1045 $template->set( 'token', self
::getLoginToken() );
1048 # Prepare language selection links as needed
1049 if( $wgLoginLanguageSelector ) {
1050 $template->set( 'languages', $this->makeLanguageSelector() );
1051 if( $this->mLanguage
)
1052 $template->set( 'uselang', $this->mLanguage
);
1055 // Give authentication and captcha plugins a chance to modify the form
1056 $wgAuth->modifyUITemplate( $template, $this->mType
);
1057 if ( $this->mType
== 'signup' ) {
1058 wfRunHooks( 'UserCreateForm', array( &$template ) );
1060 wfRunHooks( 'UserLoginForm', array( &$template ) );
1063 // Changes the title depending on permissions for creating account
1064 if ( $wgUser->isAllowed( 'createaccount' ) ) {
1065 $wgOut->setPageTitle( wfMsg( 'userlogin' ) );
1067 $wgOut->setPageTitle( wfMsg( 'userloginnocreate' ) );
1070 $wgOut->disallowUserJs(); // just in case...
1071 $wgOut->addTemplate( $template );
1081 function showCreateOrLoginLink( &$user ) {
1082 if( $this->mType
== 'signup' ) {
1084 } elseif( $user->isAllowed( 'createaccount' ) ) {
1092 * Check if a session cookie is present.
1094 * This will not pick up a cookie set during _this_ request, but is meant
1095 * to ensure that the client is returning the cookie which was set on a
1096 * previous pass through the system.
1100 function hasSessionCookie() {
1101 global $wgDisableCookieCheck, $wgRequest;
1102 return $wgDisableCookieCheck ?
true : $wgRequest->checkSessionCookie();
1106 * Get the login token from the current session
1108 public static function getLoginToken() {
1110 return $wgRequest->getSessionData( 'wsLoginToken' );
1114 * Randomly generate a new login token and attach it to the current session
1116 public static function setLoginToken() {
1118 // Use User::generateToken() instead of $user->editToken()
1119 // because the latter reuses $_SESSION['wsEditToken']
1120 $wgRequest->setSessionData( 'wsLoginToken', User
::generateToken() );
1124 * Remove any login token attached to the current session
1126 public static function clearLoginToken() {
1128 $wgRequest->setSessionData( 'wsLoginToken', null );
1132 * Get the createaccount token from the current session
1134 public static function getCreateaccountToken() {
1136 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1140 * Randomly generate a new createaccount token and attach it to the current session
1142 public static function setCreateaccountToken() {
1144 $wgRequest->setSessionData( 'wsCreateaccountToken', User
::generateToken() );
1148 * Remove any createaccount token attached to the current session
1150 public static function clearCreateaccountToken() {
1152 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1158 function cookieRedirectCheck( $type ) {
1161 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1162 $query = array( 'wpCookieCheck' => $type );
1163 if ( $this->mReturnTo
) {
1164 $query['returnto'] = $this->mReturnTo
;
1166 $check = $titleObj->getFullURL( $query );
1168 return $wgOut->redirect( $check );
1174 function onCookieRedirectCheck( $type ) {
1175 if ( !$this->hasSessionCookie() ) {
1176 if ( $type == 'new' ) {
1177 return $this->mainLoginForm( wfMsgExt( 'nocookiesnew', array( 'parseinline' ) ) );
1178 } elseif ( $type == 'login' ) {
1179 return $this->mainLoginForm( wfMsgExt( 'nocookieslogin', array( 'parseinline' ) ) );
1182 return $this->mainLoginForm( wfMsg( 'error' ) );
1185 return $this->successfulLogin();
1192 function throttleHit( $limit ) {
1193 $this->mainLoginForm( wfMsgExt( 'acct_creation_throttle_hit', array( 'parseinline' ), $limit ) );
1197 * Produce a bar of links which allow the user to select another language
1198 * during login/registration but retain "returnto"
1202 function makeLanguageSelector() {
1205 $msg = wfMessage( 'loginlanguagelinks' )->inContentLanguage();
1206 if( !$msg->isBlank() ) {
1207 $langs = explode( "\n", $msg->text() );
1209 foreach( $langs as $lang ) {
1210 $lang = trim( $lang, '* ' );
1211 $parts = explode( '|', $lang );
1212 if ( count( $parts ) >= 2 ) {
1213 $links[] = $this->makeLanguageSelectorLink( $parts[0], $parts[1] );
1216 return count( $links ) > 0 ?
wfMsgHtml( 'loginlanguagelabel', $wgLang->pipeList( $links ) ) : '';
1223 * Create a language selector link for a particular language
1224 * Links back to this page preserving type and returnto
1226 * @param $text Link text
1227 * @param $lang Language code
1229 function makeLanguageSelectorLink( $text, $lang ) {
1231 $self = SpecialPage
::getTitleFor( 'Userlogin' );
1232 $attr = array( 'uselang' => $lang );
1233 if( $this->mType
== 'signup' ) {
1234 $attr['type'] = 'signup';
1236 if( $this->mReturnTo
) {
1237 $attr['returnto'] = $this->mReturnTo
;
1239 $skin = $wgUser->getSkin();
1240 return $skin->linkKnown(
1242 htmlspecialchars( $text ),