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
27 function wfSpecialUserlogin( $par = '' ) {
29 if( session_id() == '' ) {
33 $form = new LoginForm( $wgRequest, $par );
38 * Implements Special:UserLogin
40 * @ingroup SpecialPage
47 const WRONG_PLUGIN_PASS
= 3;
53 const CREATE_BLOCKED
= 9;
55 const USER_BLOCKED
= 11;
56 const NEED_TOKEN
= 12;
57 const WRONG_TOKEN
= 13;
59 var $mName, $mPassword, $mRetype, $mReturnTo, $mCookieCheck, $mPosted;
60 var $mAction, $mCreateaccount, $mCreateaccountMail, $mMailmypassword;
61 var $mLoginattempt, $mRemember, $mEmail, $mDomain, $mLanguage;
62 var $mSkipCookieCheck, $mReturnToQuery, $mToken, $mStickHTTPS;
64 private $mExtUser = null;
68 * @param $request WebRequest: a WebRequest object passed by reference
69 * @param $par String: subpage parameter
71 function __construct( &$request, $par = '' ) {
72 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail, $wgRedirectOnLogin;
74 $this->mType
= ( $par == 'signup' ) ?
$par : $request->getText( 'type' ); # Check for [[Special:Userlogin/signup]]
75 $this->mName
= $request->getText( 'wpName' );
76 $this->mPassword
= $request->getText( 'wpPassword' );
77 $this->mRetype
= $request->getText( 'wpRetype' );
78 $this->mDomain
= $request->getText( 'wpDomain' );
79 $this->mReason
= $request->getText( 'wpReason' );
80 $this->mReturnTo
= $request->getVal( 'returnto' );
81 $this->mReturnToQuery
= $request->getVal( 'returntoquery' );
82 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
83 $this->mPosted
= $request->wasPosted();
84 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' );
85 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
87 $this->mMailmypassword
= $request->getCheck( 'wpMailmypassword' )
89 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
90 $this->mAction
= $request->getVal( 'action' );
91 $this->mRemember
= $request->getCheck( 'wpRemember' );
92 $this->mStickHTTPS
= $request->getCheck( 'wpStickHTTPS' );
93 $this->mLanguage
= $request->getText( 'uselang' );
94 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
95 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
97 if ( $wgRedirectOnLogin ) {
98 $this->mReturnTo
= $wgRedirectOnLogin;
99 $this->mReturnToQuery
= '';
102 if( $wgEnableEmail ) {
103 $this->mEmail
= $request->getText( 'wpEmail' );
107 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
108 $this->mRealName
= $request->getText( 'wpRealName' );
110 $this->mRealName
= '';
113 if( !$wgAuth->validDomain( $this->mDomain
) ) {
114 $this->mDomain
= 'invaliddomain';
116 $wgAuth->setDomain( $this->mDomain
);
118 # When switching accounts, it sucks to get automatically logged out
119 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
120 if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
121 $this->mReturnTo
= '';
122 $this->mReturnToQuery
= '';
127 if ( !is_null( $this->mCookieCheck
) ) {
128 $this->onCookieRedirectCheck( $this->mCookieCheck
);
130 } elseif( $this->mPosted
) {
131 if( $this->mCreateaccount
) {
132 return $this->addNewAccount();
133 } elseif ( $this->mCreateaccountMail
) {
134 return $this->addNewAccountMailPassword();
135 } elseif ( $this->mMailmypassword
) {
136 return $this->mailPassword();
137 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
138 return $this->processLogin();
141 $this->mainLoginForm( '' );
147 function addNewAccountMailPassword() {
150 if ( $this->mEmail
== '' ) {
151 $this->mainLoginForm( wfMsgExt( 'noemail', array( 'parsemag', 'escape' ), $this->mName
) );
155 $u = $this->addNewaccountInternal();
161 // Wipe the initial password and mail a temporary one
162 $u->setPassword( null );
164 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
166 wfRunHooks( 'AddNewAccount', array( $u, true ) );
167 $u->addNewUserLogEntry( true, $this->mReason
);
169 $wgOut->setPageTitle( wfMsg( 'accmailtitle' ) );
170 $wgOut->setRobotPolicy( 'noindex,nofollow' );
171 $wgOut->setArticleRelated( false );
173 if( WikiError
::isError( $result ) ) {
174 $this->mainLoginForm( wfMsg( 'mailerror', $result->getMessage() ) );
176 $wgOut->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
177 $wgOut->returnToMain( false );
185 function addNewAccount() {
186 global $wgUser, $wgEmailAuthentication, $wgOut;
188 # Create the account and abort if there's a problem doing so
189 $u = $this->addNewAccountInternal();
194 # If we showed up language selection links, and one was in use, be
195 # smart (and sensible) and save that language as the user's preference
196 global $wgLoginLanguageSelector;
197 if( $wgLoginLanguageSelector && $this->mLanguage
) {
198 $u->setOption( 'language', $this->mLanguage
);
201 # Send out an email authentication message if needed
202 if( $wgEmailAuthentication && User
::isValidEmailAddr( $u->getEmail() ) ) {
203 $error = $u->sendConfirmationMail();
204 if( WikiError
::isError( $error ) ) {
205 $wgOut->addWikiMsg( 'confirmemail_sendfailed', $error->getMessage() );
207 $wgOut->addWikiMsg( 'confirmemail_oncreate' );
211 # Save settings (including confirmation token)
214 # If not logged in, assume the new account as the current one and set
215 # session cookies then show a "welcome" message or a "need cookies"
217 if( $wgUser->isAnon() ) {
219 $wgUser->setCookies();
220 wfRunHooks( 'AddNewAccount', array( $wgUser, false ) );
221 $wgUser->addNewUserLogEntry();
222 if( $this->hasSessionCookie() ) {
223 return $this->successfulCreation();
225 return $this->cookieRedirectCheck( 'new' );
228 # Confirm that the account was created
229 $self = SpecialPage
::getTitleFor( 'Userlogin' );
230 $wgOut->setPageTitle( wfMsgHtml( 'accountcreated' ) );
231 $wgOut->setArticleRelated( false );
232 $wgOut->setRobotPolicy( 'noindex,nofollow' );
233 $wgOut->addHTML( wfMsgWikiHtml( 'accountcreatedtext', $u->getName() ) );
234 $wgOut->returnToMain( false, $self );
235 wfRunHooks( 'AddNewAccount', array( $u, false ) );
236 $u->addNewUserLogEntry( false, $this->mReason
);
244 function addNewAccountInternal() {
245 global $wgUser, $wgOut;
246 global $wgMemc, $wgAccountCreationThrottle;
247 global $wgAuth, $wgMinimalPasswordLength;
248 global $wgEmailConfirmToEdit;
250 // If the user passes an invalid domain, something is fishy
251 if( !$wgAuth->validDomain( $this->mDomain
) ) {
252 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
256 // If we are not allowing users to login locally, we should be checking
257 // to see if the user is actually able to authenticate to the authenti-
258 // cation server before they create an account (otherwise, they can
259 // create a local account and login as any domain user). We only need
260 // to check this for domains that aren't local.
261 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
262 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mName
) ||
!$wgAuth->authenticate( $this->mName
, $this->mPassword
) ) ) {
263 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
268 if ( wfReadOnly() ) {
269 $wgOut->readOnlyPage();
273 # Request forgery checks.
274 if ( !self
::getCreateaccountToken() ) {
275 self
::setCreateaccountToken();
276 $this->mainLoginForm( wfMsgExt( 'nocookiesnew', array( 'parseinline' ) ) );
280 # The user didn't pass a createaccount token
281 if ( !$this->mToken
) {
282 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
286 # Validate the createaccount token
287 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
288 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
293 if ( !$wgUser->isAllowed( 'createaccount' ) ) {
294 $this->userNotPrivilegedMessage();
296 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
297 $this->userBlockedMessage();
302 if ( $wgUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
303 $this->mainLoginForm( wfMsg( 'sorbs_create_account_reason' ) . ' (' . htmlspecialchars( $ip ) . ')' );
307 # Now create a dummy user ($u) and check if it is valid
308 $name = trim( $this->mName
);
309 $u = User
::newFromName( $name, 'creatable' );
310 if ( !is_object( $u ) ) {
311 $this->mainLoginForm( wfMsg( 'noname' ) );
315 if ( 0 != $u->idForName() ) {
316 $this->mainLoginForm( wfMsg( 'userexists' ) );
320 if ( 0 != strcmp( $this->mPassword
, $this->mRetype
) ) {
321 $this->mainLoginForm( wfMsg( 'badretype' ) );
325 # check for minimal password length
326 $valid = $u->getPasswordValidity( $this->mPassword
);
327 if ( $valid !== true ) {
328 if ( !$this->mCreateaccountMail
) {
329 $this->mainLoginForm( wfMsgExt( $valid, array( 'parsemag' ), $wgMinimalPasswordLength ) );
332 # do not force a password for account creation by email
333 # set invalid password, it will be replaced later by a random generated password
334 $this->mPassword
= null;
338 # if you need a confirmed email address to edit, then obviously you
339 # need an email address.
340 if ( $wgEmailConfirmToEdit && empty( $this->mEmail
) ) {
341 $this->mainLoginForm( wfMsg( 'noemailtitle' ) );
345 if( !empty( $this->mEmail
) && !User
::isValidEmailAddr( $this->mEmail
) ) {
346 $this->mainLoginForm( wfMsg( 'invalidemailaddress' ) );
350 # Set some additional data so the AbortNewAccount hook can be used for
351 # more than just username validation
352 $u->setEmail( $this->mEmail
);
353 $u->setRealName( $this->mRealName
);
356 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
357 // Hook point to add extra creation throttles and blocks
358 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
359 $this->mainLoginForm( $abortError );
363 if ( $wgAccountCreationThrottle && $wgUser->isPingLimitable() ) {
364 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
365 $value = $wgMemc->get( $key );
367 $wgMemc->set( $key, 0, 86400 );
369 if ( $value >= $wgAccountCreationThrottle ) {
370 $this->throttleHit( $wgAccountCreationThrottle );
373 $wgMemc->incr( $key );
376 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
377 $this->mainLoginForm( wfMsg( 'externaldberror' ) );
381 self
::clearCreateaccountToken();
382 return $this->initUser( $u, false );
386 * Actually add a user to the database.
387 * Give it a User object that has been initialised with a name.
389 * @param $u User object.
390 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
391 * @return User object.
394 function initUser( $u, $autocreate ) {
399 if ( $wgAuth->allowPasswordChange() ) {
400 $u->setPassword( $this->mPassword
);
403 $u->setEmail( $this->mEmail
);
404 $u->setRealName( $this->mRealName
);
407 $wgAuth->initUser( $u, $autocreate );
409 if ( $this->mExtUser
) {
410 $this->mExtUser
->linkToLocal( $u->getId() );
411 $email = $this->mExtUser
->getPref( 'emailaddress' );
412 if ( $email && !$this->mEmail
) {
413 $u->setEmail( $email );
417 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
421 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
422 $ssUpdate->doUpdate();
428 * Internally authenticate the login request.
430 * This may create a local account as a side effect if the
431 * authentication plugin allows transparent local account
434 public function authenticateUserData() {
435 global $wgUser, $wgAuth, $wgMemc;
437 if ( $this->mName
== '' ) {
438 return self
::NO_NAME
;
441 // We require a login token to prevent login CSRF
442 // Handle part of this before incrementing the throttle so
443 // token-less login attempts don't count towards the throttle
444 // but wrong-token attempts do.
446 // If the user doesn't have a login token yet, set one.
447 if ( !self
::getLoginToken() ) {
448 self
::setLoginToken();
449 return self
::NEED_TOKEN
;
451 // If the user didn't pass a login token, tell them we need one
452 if ( !$this->mToken
) {
453 return self
::NEED_TOKEN
;
456 global $wgPasswordAttemptThrottle;
459 if ( is_array( $wgPasswordAttemptThrottle ) ) {
460 $throttleKey = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mName
) );
461 $count = $wgPasswordAttemptThrottle['count'];
462 $period = $wgPasswordAttemptThrottle['seconds'];
464 $throttleCount = $wgMemc->get( $throttleKey );
465 if ( !$throttleCount ) {
466 $wgMemc->add( $throttleKey, 1, $period ); // start counter
467 } elseif ( $throttleCount < $count ) {
468 $wgMemc->incr( $throttleKey );
469 } elseif ( $throttleCount >= $count ) {
470 return self
::THROTTLED
;
474 // Validate the login token
475 if ( $this->mToken
!== self
::getLoginToken() ) {
476 return self
::WRONG_TOKEN
;
479 // Load $wgUser now, and check to see if we're logging in as the same
480 // name. This is necessary because loading $wgUser (say by calling
481 // getName()) calls the UserLoadFromSession hook, which potentially
482 // creates the user in the database. Until we load $wgUser, checking
483 // for user existence using User::newFromName($name)->getId() below
484 // will effectively be using stale data.
485 if ( $wgUser->getName() === $this->mName
) {
486 wfDebug( __METHOD__
. ": already logged in as {$this->mName}\n" );
487 return self
::SUCCESS
;
490 $this->mExtUser
= ExternalUser
::newFromName( $this->mName
);
492 # TODO: Allow some magic here for invalid external names, e.g., let the
493 # user choose a different wiki name.
494 $u = User
::newFromName( $this->mName
);
495 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
496 return self
::ILLEGAL
;
499 $isAutoCreated = false;
500 if ( 0 == $u->getID() ) {
501 $status = $this->attemptAutoCreate( $u );
502 if ( $status !== self
::SUCCESS
) {
505 $isAutoCreated = true;
508 global $wgExternalAuthType, $wgAutocreatePolicy;
509 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
510 && is_object( $this->mExtUser
)
511 && $this->mExtUser
->authenticate( $this->mPassword
) ) {
512 # The external user and local user have the same name and
513 # password, so we assume they're the same.
514 $this->mExtUser
->linkToLocal( $u->getID() );
520 // Give general extensions, such as a captcha, a chance to abort logins
521 $abort = self
::ABORTED
;
522 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort ) ) ) {
526 global $wgBlockDisablesLogin;
527 if ( !$u->checkPassword( $this->mPassword
) ) {
528 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
529 // The e-mailed temporary password should not be used for actu-
530 // al logins; that's a very sloppy habit, and insecure if an
531 // attacker has a few seconds to click "search" on someone's o-
534 // Allow it to be used only to reset the password a single time
535 // to a new value, which won't be in the user's e-mail ar-
538 // For backwards compatibility, we'll still recognize it at the
539 // login form to minimize surprises for people who have been
540 // logging in with a temporary password for some time.
542 // As a side-effect, we can authenticate the user's e-mail ad-
543 // dress if it's not already done, since the temporary password
544 // was sent via e-mail.
545 if( !$u->isEmailConfirmed() ) {
550 // At this point we just return an appropriate code/ indicating
551 // that the UI should show a password reset form; bot inter-
552 // faces etc will probably just fail cleanly here.
553 $retval = self
::RESET_PASS
;
555 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
557 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
558 // If we've enabled it, make it so that a blocked user cannot login
559 $retval = self
::USER_BLOCKED
;
561 $wgAuth->updateUser( $u );
564 // Please reset throttle for successful logins, thanks!
565 if( $throttleCount ) {
566 $wgMemc->delete( $throttleKey );
569 if ( $isAutoCreated ) {
570 // Must be run after $wgUser is set, for correct new user log
571 wfRunHooks( 'AuthPluginAutoCreate', array( $wgUser ) );
574 $retval = self
::SUCCESS
;
576 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
581 * Attempt to automatically create a user on login. Only succeeds if there
582 * is an external authentication method which allows it.
583 * @return integer Status code
585 function attemptAutoCreate( $user ) {
586 global $wgAuth, $wgUser, $wgAutocreatePolicy;
588 if ( $wgUser->isBlockedFromCreateAccount() ) {
589 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
590 return self
::CREATE_BLOCKED
;
594 * If the external authentication plugin allows it, automatically cre-
595 * ate a new account for users that are externally defined but have not
598 if ( $this->mExtUser
) {
599 # mExtUser is neither null nor false, so use the new ExternalAuth
601 if ( $wgAutocreatePolicy == 'never' ) {
602 return self
::NOT_EXISTS
;
604 if ( !$this->mExtUser
->authenticate( $this->mPassword
) ) {
605 return self
::WRONG_PLUGIN_PASS
;
609 if ( !$wgAuth->autoCreate() ) {
610 return self
::NOT_EXISTS
;
612 if ( !$wgAuth->userExists( $user->getName() ) ) {
613 wfDebug( __METHOD__
. ": user does not exist\n" );
614 return self
::NOT_EXISTS
;
616 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
617 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
618 return self
::WRONG_PLUGIN_PASS
;
622 wfDebug( __METHOD__
. ": creating account\n" );
623 $user = $this->initUser( $user, true );
624 return self
::SUCCESS
;
627 function processLogin() {
630 switch ( $this->authenticateUserData() ) {
632 # We've verified now, update the real record
633 if( (bool)$this->mRemember
!= (bool)$wgUser->getOption( 'rememberpassword' ) ) {
634 $wgUser->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
635 $wgUser->saveSettings();
637 $wgUser->invalidateCache();
639 $wgUser->setCookies();
640 self
::clearLoginToken();
642 // Reset the throttle
643 $key = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mName
) );
645 $wgMemc->delete( $key );
647 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
648 /* Replace the language object to provide user interface in
649 * correct language immediately on this first page load.
651 global $wgLang, $wgRequest;
652 $code = $wgRequest->getVal( 'uselang', $wgUser->getOption( 'language' ) );
653 $wgLang = Language
::factory( $code );
654 return $this->successfulLogin();
656 return $this->cookieRedirectCheck( 'login' );
660 case self
::NEED_TOKEN
:
661 $this->mainLoginForm( wfMsgExt( 'nocookieslogin', array( 'parseinline' ) ) );
663 case self
::WRONG_TOKEN
:
664 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
668 $this->mainLoginForm( wfMsg( 'noname' ) );
670 case self
::WRONG_PLUGIN_PASS
:
671 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
673 case self
::NOT_EXISTS
:
674 if( $wgUser->isAllowed( 'createaccount' ) ) {
675 $this->mainLoginForm( wfMsgWikiHtml( 'nosuchuser', htmlspecialchars( $this->mName
) ) );
677 $this->mainLoginForm( wfMsg( 'nosuchusershort', htmlspecialchars( $this->mName
) ) );
680 case self
::WRONG_PASS
:
681 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
683 case self
::EMPTY_PASS
:
684 $this->mainLoginForm( wfMsg( 'wrongpasswordempty' ) );
686 case self
::RESET_PASS
:
687 $this->resetLoginForm( wfMsg( 'resetpass_announce' ) );
689 case self
::CREATE_BLOCKED
:
690 $this->userBlockedMessage();
692 case self
::THROTTLED
:
693 $this->mainLoginForm( wfMsg( 'login-throttled' ) );
695 case self
::USER_BLOCKED
:
696 $this->mainLoginForm( wfMsgExt( 'login-userblocked',
697 array( 'parsemag', 'escape' ), $this->mName
) );
700 throw new MWException( 'Unhandled case value' );
704 function resetLoginForm( $error ) {
706 $wgOut->addHTML( Xml
::element('p', array( 'class' => 'error' ), $error ) );
707 $reset = new SpecialResetpass();
708 $reset->execute( null );
714 function mailPassword() {
715 global $wgUser, $wgOut, $wgAuth;
717 if ( wfReadOnly() ) {
718 $wgOut->readOnlyPage();
722 if( !$wgAuth->allowPasswordChange() ) {
723 $this->mainLoginForm( wfMsg( 'resetpass_forbidden' ) );
727 # Check against blocked IPs so blocked users can't flood admins
728 # with password resets
729 if( $wgUser->isBlocked() ) {
730 $this->mainLoginForm( wfMsg( 'blocked-mailpassword' ) );
736 if ( !wfRunHooks( 'UserLoginMailPassword', array( $this->mName
, &$error ) ) ) {
737 $this->mainLoginForm( $error );
741 # If the user doesn't have a login token yet, set one.
742 if ( !self
::getLoginToken() ) {
743 self
::setLoginToken();
744 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
748 # If the user didn't pass a login token, tell them we need one
749 if ( !$this->mToken
) {
750 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
754 # Check against the rate limiter
755 if( $wgUser->pingLimiter( 'mailpassword' ) ) {
756 $wgOut->rateLimited();
760 if ( $this->mName
== '' ) {
761 $this->mainLoginForm( wfMsg( 'noname' ) );
764 $u = User
::newFromName( $this->mName
);
765 if( !$u instanceof User
) {
766 $this->mainLoginForm( wfMsg( 'noname' ) );
769 if ( 0 == $u->getID() ) {
770 $this->mainLoginForm( wfMsgWikiHtml( 'nosuchuser', htmlspecialchars( $u->getName() ) ) );
774 # Validate the login token
775 if ( $this->mToken
!== self
::getLoginToken() ) {
776 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
780 # Check against password throttle
781 if ( $u->isPasswordReminderThrottled() ) {
782 global $wgPasswordReminderResendTime;
783 # Round the time in hours to 3 d.p., in case someone is specifying
784 # minutes or seconds.
785 $this->mainLoginForm( wfMsgExt( 'throttled-mailpassword', array( 'parsemag' ),
786 round( $wgPasswordReminderResendTime, 3 ) ) );
790 $result = $this->mailPasswordInternal( $u, true, 'passwordremindertitle', 'passwordremindertext' );
791 if( WikiError
::isError( $result ) ) {
792 $this->mainLoginForm( wfMsg( 'mailerror', $result->getMessage() ) );
794 $this->mainLoginForm( wfMsg( 'passwordsent', $u->getName() ), 'success' );
795 self
::clearLoginToken();
801 * @param $u User object
802 * @param $throttle Boolean
803 * @param $emailTitle String: message name of email title
804 * @param $emailText String: message name of email text
805 * @return Mixed: true on success, WikiError on failure
808 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
809 global $wgServer, $wgScript, $wgUser, $wgNewPasswordExpiry;
811 if ( $u->getEmail() == '' ) {
812 return new WikiError( wfMsg( 'noemail', $u->getName() ) );
816 return new WikiError( wfMsg( 'badipaddress' ) );
819 wfRunHooks( 'User::mailPasswordInternal', array( &$wgUser, &$ip, &$u ) );
821 $np = $u->randomPassword();
822 $u->setNewpassword( $np, $throttle );
824 $userLanguage = $u->getOption( 'language' );
825 $m = wfMsgExt( $emailText, array( 'parsemag', 'language' => $userLanguage ), $ip, $u->getName(), $np,
826 $wgServer . $wgScript, round( $wgNewPasswordExpiry / 86400 ) );
827 $result = $u->sendMail( wfMsgExt( $emailTitle, array( 'parsemag', 'language' => $userLanguage ) ), $m );
834 * Run any hooks registered for logins, then HTTP redirect to
835 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
836 * nice message here, but that's really not as useful as just being sent to
837 * wherever you logged in from. It should be clear that the action was
838 * successful, given the lack of error messages plus the appearance of your
839 * name in the upper right.
843 function successfulLogin() {
844 global $wgUser, $wgOut;
846 # Run any hooks; display injected HTML if any, else redirect
848 wfRunHooks( 'UserLoginComplete', array( &$wgUser, &$injected_html ) );
850 if( $injected_html !== '' ) {
851 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
853 $titleObj = Title
::newFromText( $this->mReturnTo
);
854 if ( !$titleObj instanceof Title
) {
855 $titleObj = Title
::newMainPage();
857 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery
);
858 global $wgSecureLogin;
859 if( $wgSecureLogin && !$this->mStickHTTPS
) {
860 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
862 $wgOut->redirect( $redirectUrl );
867 * Run any hooks registered for logins, then display a message welcoming
872 function successfulCreation() {
874 # Run any hooks; display injected HTML
876 wfRunHooks( 'UserLoginComplete', array( &$wgUser, &$injected_html ) );
878 $this->displaySuccessfulLogin( 'welcomecreation', $injected_html );
882 * Display a "login successful" page.
884 private function displaySuccessfulLogin( $msgname, $injected_html ) {
885 global $wgOut, $wgUser;
887 $wgOut->setPageTitle( wfMsg( 'loginsuccesstitle' ) );
888 $wgOut->setRobotPolicy( 'noindex,nofollow' );
889 $wgOut->setArticleRelated( false );
890 $wgOut->addWikiMsg( $msgname, $wgUser->getName() );
891 $wgOut->addHTML( $injected_html );
893 if ( !empty( $this->mReturnTo
) ) {
894 $wgOut->returnToMain( null, $this->mReturnTo
, $this->mReturnToQuery
);
896 $wgOut->returnToMain( null );
901 function userNotPrivilegedMessage( $errors ) {
904 $wgOut->setPageTitle( wfMsg( 'permissionserrors' ) );
905 $wgOut->setRobotPolicy( 'noindex,nofollow' );
906 $wgOut->setArticleRelated( false );
908 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $errors, 'createaccount' ) );
909 // Stuff that might want to be added at the end. For example, instruc-
911 $wgOut->addWikiMsg( 'cantcreateaccount-nonblock-text' );
913 $wgOut->returnToMain( false );
917 function userBlockedMessage() {
918 global $wgOut, $wgUser;
920 # Let's be nice about this, it's likely that this feature will be used
921 # for blocking large numbers of innocent people, e.g. range blocks on
922 # schools. Don't blame it on the user. There's a small chance that it
923 # really is the user's fault, i.e. the username is blocked and they
924 # haven't bothered to log out before trying to create an account to
925 # evade it, but we'll leave that to their guilty conscience to figure
928 $wgOut->setPageTitle( wfMsg( 'cantcreateaccounttitle' ) );
929 $wgOut->setRobotPolicy( 'noindex,nofollow' );
930 $wgOut->setArticleRelated( false );
933 $blocker = User
::whoIs( $wgUser->mBlock
->mBy
);
934 $block_reason = $wgUser->mBlock
->mReason
;
936 if ( strval( $block_reason ) === '' ) {
937 $block_reason = wfMsg( 'blockednoreason' );
939 $wgOut->addWikiMsg( 'cantcreateaccount-text', $ip, $block_reason, $blocker );
940 $wgOut->returnToMain( false );
946 function mainLoginForm( $msg, $msgtype = 'error' ) {
947 global $wgUser, $wgOut, $wgHiddenPrefs, $wgEnableEmail;
948 global $wgRequest, $wgLoginLanguageSelector;
949 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
950 global $wgSecureLogin, $wgSecureLoginStickHTTPS;
952 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
954 if ( $this->mType
== 'signup' ) {
955 // Block signup here if in readonly. Keeps user from
956 // going through the process (filling out data, etc)
957 // and being informed later.
958 if ( wfReadOnly() ) {
959 $wgOut->readOnlyPage();
961 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
962 $this->userBlockedMessage();
964 } elseif ( count( $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $wgUser, true ) )>0 ) {
965 $wgOut->showPermissionsErrorPage( $permErrors, 'createaccount' );
970 if ( $this->mName
== '' ) {
971 if ( $wgUser->isLoggedIn() ) {
972 $this->mName
= $wgUser->getName();
974 $this->mName
= $wgRequest->getCookie( 'UserName' );
978 if ( $this->mType
== 'signup' ) {
979 global $wgLivePasswordStrengthChecks;
980 if ( $wgLivePasswordStrengthChecks ) {
981 $wgOut->addPasswordSecurity( 'wpPassword2', 'wpRetype' );
983 $template = new UsercreateTemplate();
984 $q = 'action=submitlogin&type=signup';
985 $linkq = 'type=login';
986 $linkmsg = 'gotaccount';
988 $template = new UserloginTemplate();
989 $q = 'action=submitlogin&type=login';
990 $linkq = 'type=signup';
991 $linkmsg = 'nologin';
994 if ( !empty( $this->mReturnTo
) ) {
995 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
996 if ( !empty( $this->mReturnToQuery
) ) {
997 $returnto .= '&returntoquery=' .
998 wfUrlencode( $this->mReturnToQuery
);
1001 $linkq .= $returnto;
1004 # Pass any language selection on to the mode switch link
1005 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1006 $linkq .= '&uselang=' . $this->mLanguage
;
1009 $link = '<a href="' . htmlspecialchars ( $titleObj->getLocalURL( $linkq ) ) . '">';
1010 $link .= wfMsgHtml( $linkmsg . 'link' ); # Calling either 'gotaccountlink' or 'nologinlink'
1013 # Don't show a "create account" link if the user can't
1014 if( $this->showCreateOrLoginLink( $wgUser ) ) {
1015 $template->set( 'link', wfMsgExt( $linkmsg, array( 'parseinline', 'replaceafter' ), $link ) );
1017 $template->set( 'link', '' );
1020 $template->set( 'header', '' );
1021 $template->set( 'name', $this->mName
);
1022 $template->set( 'password', $this->mPassword
);
1023 $template->set( 'retype', $this->mRetype
);
1024 $template->set( 'email', $this->mEmail
);
1025 $template->set( 'realname', $this->mRealName
);
1026 $template->set( 'domain', $this->mDomain
);
1027 $template->set( 'reason', $this->mReason
);
1029 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1030 $template->set( 'message', $msg );
1031 $template->set( 'messagetype', $msgtype );
1032 $template->set( 'createemail', $wgEnableEmail && $wgUser->isLoggedIn() );
1033 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1034 $template->set( 'useemail', $wgEnableEmail );
1035 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1036 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1037 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1038 $template->set( 'usereason', $wgUser->isLoggedIn() );
1039 $template->set( 'remember', $wgUser->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1040 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1041 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1043 if ( $this->mType
== 'signup' ) {
1044 if ( !self
::getCreateaccountToken() ) {
1045 self
::setCreateaccountToken();
1047 $template->set( 'token', self
::getCreateaccountToken() );
1049 if ( !self
::getLoginToken() ) {
1050 self
::setLoginToken();
1052 $template->set( 'token', self
::getLoginToken() );
1055 # Prepare language selection links as needed
1056 if( $wgLoginLanguageSelector ) {
1057 $template->set( 'languages', $this->makeLanguageSelector() );
1058 if( $this->mLanguage
)
1059 $template->set( 'uselang', $this->mLanguage
);
1062 // Give authentication and captcha plugins a chance to modify the form
1063 $wgAuth->modifyUITemplate( $template, $this->mType
);
1064 if ( $this->mType
== 'signup' ) {
1065 wfRunHooks( 'UserCreateForm', array( &$template ) );
1067 wfRunHooks( 'UserLoginForm', array( &$template ) );
1070 // Changes the title depending on permissions for creating account
1071 if ( $wgUser->isAllowed( 'createaccount' ) ) {
1072 $wgOut->setPageTitle( wfMsg( 'userlogin' ) );
1074 $wgOut->setPageTitle( wfMsg( 'userloginnocreate' ) );
1077 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1078 $wgOut->setArticleRelated( false );
1079 $wgOut->disallowUserJs(); // just in case...
1080 $wgOut->addTemplate( $template );
1086 function showCreateOrLoginLink( &$user ) {
1087 if( $this->mType
== 'signup' ) {
1089 } elseif( $user->isAllowed( 'createaccount' ) ) {
1097 * Check if a session cookie is present.
1099 * This will not pick up a cookie set during _this_ request, but is meant
1100 * to ensure that the client is returning the cookie which was set on a
1101 * previous pass through the system.
1105 function hasSessionCookie() {
1106 global $wgDisableCookieCheck, $wgRequest;
1107 return $wgDisableCookieCheck ?
true : $wgRequest->checkSessionCookie();
1111 * Get the login token from the current session
1113 public static function getLoginToken() {
1115 return $wgRequest->getSessionData( 'wsLoginToken' );
1119 * Randomly generate a new login token and attach it to the current session
1121 public static function setLoginToken() {
1123 // Use User::generateToken() instead of $user->editToken()
1124 // because the latter reuses $_SESSION['wsEditToken']
1125 $wgRequest->setSessionData( 'wsLoginToken', User
::generateToken() );
1129 * Remove any login token attached to the current session
1131 public static function clearLoginToken() {
1133 $wgRequest->setSessionData( 'wsLoginToken', null );
1137 * Get the createaccount token from the current session
1139 public static function getCreateaccountToken() {
1141 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1145 * Randomly generate a new createaccount token and attach it to the current session
1147 public static function setCreateaccountToken() {
1149 $wgRequest->setSessionData( 'wsCreateaccountToken', User
::generateToken() );
1153 * Remove any createaccount token attached to the current session
1155 public static function clearCreateaccountToken() {
1157 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1163 function cookieRedirectCheck( $type ) {
1166 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1167 $query = array( 'wpCookieCheck' => $type );
1168 if ( $this->mReturnTo
) {
1169 $query['returnto'] = $this->mReturnTo
;
1171 $check = $titleObj->getFullURL( $query );
1173 return $wgOut->redirect( $check );
1179 function onCookieRedirectCheck( $type ) {
1180 if ( !$this->hasSessionCookie() ) {
1181 if ( $type == 'new' ) {
1182 return $this->mainLoginForm( wfMsgExt( 'nocookiesnew', array( 'parseinline' ) ) );
1183 } elseif ( $type == 'login' ) {
1184 return $this->mainLoginForm( wfMsgExt( 'nocookieslogin', array( 'parseinline' ) ) );
1187 return $this->mainLoginForm( wfMsg( 'error' ) );
1190 return $this->successfulLogin();
1197 function throttleHit( $limit ) {
1198 $this->mainLoginForm( wfMsgExt( 'acct_creation_throttle_hit', array( 'parseinline' ), $limit ) );
1202 * Produce a bar of links which allow the user to select another language
1203 * during login/registration but retain "returnto"
1207 function makeLanguageSelector() {
1210 $msg = wfMsgForContent( 'loginlanguagelinks' );
1211 if( $msg != '' && !wfEmptyMsg( 'loginlanguagelinks', $msg ) ) {
1212 $langs = explode( "\n", $msg );
1214 foreach( $langs as $lang ) {
1215 $lang = trim( $lang, '* ' );
1216 $parts = explode( '|', $lang );
1217 if ( count( $parts ) >= 2 ) {
1218 $links[] = $this->makeLanguageSelectorLink( $parts[0], $parts[1] );
1221 return count( $links ) > 0 ?
wfMsgHtml( 'loginlanguagelabel', $wgLang->pipeList( $links ) ) : '';
1228 * Create a language selector link for a particular language
1229 * Links back to this page preserving type and returnto
1231 * @param $text Link text
1232 * @param $lang Language code
1234 function makeLanguageSelectorLink( $text, $lang ) {
1236 $self = SpecialPage
::getTitleFor( 'Userlogin' );
1237 $attr = array( 'uselang' => $lang );
1238 if( $this->mType
== 'signup' ) {
1239 $attr['type'] = 'signup';
1241 if( $this->mReturnTo
) {
1242 $attr['returnto'] = $this->mReturnTo
;
1244 $skin = $wgUser->getSkin();
1245 return $skin->linkKnown(
1247 htmlspecialchars( $text ),