Print the whole text instead of having some strange syntax that doesn't work (but...
[mediawiki.git] / includes / specials / SpecialUserlogin.php
blob0a41b1faf2a33de70130b6e271f168e73400de29
1 <?php
2 /**
3 * @file
4 * @ingroup SpecialPage
5 */
7 /**
8 * constructor
9 */
10 function wfSpecialUserlogin( $par = '' ) {
11 global $wgRequest;
12 if( session_id() == '' ) {
13 wfSetupSession();
16 $form = new LoginForm( $wgRequest, $par );
17 $form->execute();
20 /**
21 * implements Special:Login
22 * @ingroup SpecialPage
24 class LoginForm {
26 const SUCCESS = 0;
27 const NO_NAME = 1;
28 const ILLEGAL = 2;
29 const WRONG_PLUGIN_PASS = 3;
30 const NOT_EXISTS = 4;
31 const WRONG_PASS = 5;
32 const EMPTY_PASS = 6;
33 const RESET_PASS = 7;
34 const ABORTED = 8;
35 const CREATE_BLOCKED = 9;
36 const THROTTLED = 10;
37 const USER_BLOCKED = 11;
38 const NEED_TOKEN = 12;
39 const WRONG_TOKEN = 13;
41 var $mName, $mPassword, $mRetype, $mReturnTo, $mCookieCheck, $mPosted;
42 var $mAction, $mCreateaccount, $mCreateaccountMail, $mMailmypassword;
43 var $mLoginattempt, $mRemember, $mEmail, $mDomain, $mLanguage;
44 var $mSkipCookieCheck, $mReturnToQuery, $mToken;
46 private $mExtUser = null;
48 /**
49 * Constructor
50 * @param $request WebRequest: a WebRequest object passed by reference
51 * @param $par String: subpage parameter
53 function LoginForm( &$request, $par = '' ) {
54 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail, $wgRedirectOnLogin;
56 $this->mType = ( $par == 'signup' ) ? $par : $request->getText( 'type' ); # Check for [[Special:Userlogin/signup]]
57 $this->mName = $request->getText( 'wpName' );
58 $this->mPassword = $request->getText( 'wpPassword' );
59 $this->mRetype = $request->getText( 'wpRetype' );
60 $this->mDomain = $request->getText( 'wpDomain' );
61 $this->mReturnTo = $request->getVal( 'returnto' );
62 $this->mReturnToQuery = $request->getVal( 'returntoquery' );
63 $this->mCookieCheck = $request->getVal( 'wpCookieCheck' );
64 $this->mPosted = $request->wasPosted();
65 $this->mCreateaccount = $request->getCheck( 'wpCreateaccount' );
66 $this->mCreateaccountMail = $request->getCheck( 'wpCreateaccountMail' )
67 && $wgEnableEmail;
68 $this->mMailmypassword = $request->getCheck( 'wpMailmypassword' )
69 && $wgEnableEmail;
70 $this->mLoginattempt = $request->getCheck( 'wpLoginattempt' );
71 $this->mAction = $request->getVal( 'action' );
72 $this->mRemember = $request->getCheck( 'wpRemember' );
73 $this->mLanguage = $request->getText( 'uselang' );
74 $this->mSkipCookieCheck = $request->getCheck( 'wpSkipCookieCheck' );
75 $this->mToken = ($this->mType == 'signup' ) ? $request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
77 if ( $wgRedirectOnLogin ) {
78 $this->mReturnTo = $wgRedirectOnLogin;
79 $this->mReturnToQuery = '';
82 if( $wgEnableEmail ) {
83 $this->mEmail = $request->getText( 'wpEmail' );
84 } else {
85 $this->mEmail = '';
87 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
88 $this->mRealName = $request->getText( 'wpRealName' );
89 } else {
90 $this->mRealName = '';
93 if( !$wgAuth->validDomain( $this->mDomain ) ) {
94 $this->mDomain = 'invaliddomain';
96 $wgAuth->setDomain( $this->mDomain );
98 # When switching accounts, it sucks to get automatically logged out
99 $returnToTitle = Title::newFromText( $this->mReturnTo );
100 if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
101 $this->mReturnTo = '';
102 $this->mReturnToQuery = '';
106 function execute() {
107 if ( !is_null( $this->mCookieCheck ) ) {
108 $this->onCookieRedirectCheck( $this->mCookieCheck );
109 return;
110 } else if( $this->mPosted ) {
111 if( $this->mCreateaccount ) {
112 return $this->addNewAccount();
113 } else if ( $this->mCreateaccountMail ) {
114 return $this->addNewAccountMailPassword();
115 } else if ( $this->mMailmypassword ) {
116 return $this->mailPassword();
117 } else if ( ( 'submitlogin' == $this->mAction ) || $this->mLoginattempt ) {
118 return $this->processLogin();
121 $this->mainLoginForm( '' );
125 * @private
127 function addNewAccountMailPassword() {
128 global $wgOut;
130 if ( $this->mEmail == '' ) {
131 $this->mainLoginForm( wfMsgExt( 'noemail', array( 'parsemag', 'escape' ), $this->mName ) );
132 return;
135 $u = $this->addNewaccountInternal();
137 if ($u == null) {
138 return;
141 // Wipe the initial password and mail a temporary one
142 $u->setPassword( null );
143 $u->saveSettings();
144 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
146 wfRunHooks( 'AddNewAccount', array( $u, true ) );
147 $u->addNewUserLogEntry();
149 $wgOut->setPageTitle( wfMsg( 'accmailtitle' ) );
150 $wgOut->setRobotPolicy( 'noindex,nofollow' );
151 $wgOut->setArticleRelated( false );
153 if( WikiError::isError( $result ) ) {
154 $this->mainLoginForm( wfMsg( 'mailerror', $result->getMessage() ) );
155 } else {
156 $wgOut->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
157 $wgOut->returnToMain( false );
159 $u = 0;
164 * @private
166 function addNewAccount() {
167 global $wgUser, $wgEmailAuthentication;
169 # Create the account and abort if there's a problem doing so
170 $u = $this->addNewAccountInternal();
171 if( $u == null )
172 return;
174 # If we showed up language selection links, and one was in use, be
175 # smart (and sensible) and save that language as the user's preference
176 global $wgLoginLanguageSelector;
177 if( $wgLoginLanguageSelector && $this->mLanguage )
178 $u->setOption( 'language', $this->mLanguage );
180 # Send out an email authentication message if needed
181 if( $wgEmailAuthentication && User::isValidEmailAddr( $u->getEmail() ) ) {
182 global $wgOut;
183 $error = $u->sendConfirmationMail();
184 if( WikiError::isError( $error ) ) {
185 $wgOut->addWikiMsg( 'confirmemail_sendfailed', $error->getMessage() );
186 } else {
187 $wgOut->addWikiMsg( 'confirmemail_oncreate' );
191 # Save settings (including confirmation token)
192 $u->saveSettings();
194 # If not logged in, assume the new account as the current one and set
195 # session cookies then show a "welcome" message or a "need cookies"
196 # message as needed
197 if( $wgUser->isAnon() ) {
198 $wgUser = $u;
199 $wgUser->setCookies();
200 wfRunHooks( 'AddNewAccount', array( $wgUser, false ) );
201 $wgUser->addNewUserLogEntry();
202 if( $this->hasSessionCookie() ) {
203 return $this->successfulCreation();
204 } else {
205 return $this->cookieRedirectCheck( 'new' );
207 } else {
208 # Confirm that the account was created
209 global $wgOut;
210 $self = SpecialPage::getTitleFor( 'Userlogin' );
211 $wgOut->setPageTitle( wfMsgHtml( 'accountcreated' ) );
212 $wgOut->setArticleRelated( false );
213 $wgOut->setRobotPolicy( 'noindex,nofollow' );
214 $wgOut->addHTML( wfMsgWikiHtml( 'accountcreatedtext', $u->getName() ) );
215 $wgOut->returnToMain( false, $self );
216 wfRunHooks( 'AddNewAccount', array( $u, false ) );
217 $u->addNewUserLogEntry();
218 return true;
223 * @private
225 function addNewAccountInternal() {
226 global $wgUser, $wgOut;
227 global $wgMemc, $wgAccountCreationThrottle;
228 global $wgAuth, $wgMinimalPasswordLength;
229 global $wgEmailConfirmToEdit;
231 // If the user passes an invalid domain, something is fishy
232 if( !$wgAuth->validDomain( $this->mDomain ) ) {
233 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
234 return false;
237 // If we are not allowing users to login locally, we should be checking
238 // to see if the user is actually able to authenticate to the authenti-
239 // cation server before they create an account (otherwise, they can
240 // create a local account and login as any domain user). We only need
241 // to check this for domains that aren't local.
242 if( 'local' != $this->mDomain && $this->mDomain != '' ) {
243 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mName ) || !$wgAuth->authenticate( $this->mName, $this->mPassword ) ) ) {
244 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
245 return false;
249 if ( wfReadOnly() ) {
250 $wgOut->readOnlyPage();
251 return false;
254 # Request forgery checks.
255 if ( !self::getCreateaccountToken() ) {
256 self::setCreateaccountToken();
257 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
258 return false;
261 # The user didn't pass a createaccount token
262 if ( !$this->mToken ) {
263 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
264 return false;
267 # Validate the createaccount token
268 if ( $this->mToken !== self::getCreateaccountToken() ) {
269 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
270 return false;
273 # Check permissions
274 if ( !$wgUser->isAllowed( 'createaccount' ) ) {
275 $this->userNotPrivilegedMessage();
276 return false;
277 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
278 $this->userBlockedMessage();
279 return false;
282 $ip = wfGetIP();
283 if ( $wgUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
284 $this->mainLoginForm( wfMsg( 'sorbs_create_account_reason' ) . ' (' . htmlspecialchars( $ip ) . ')' );
285 return false;
288 # Now create a dummy user ($u) and check if it is valid
289 $name = trim( $this->mName );
290 $u = User::newFromName( $name, 'creatable' );
291 if ( !is_object( $u ) ) {
292 $this->mainLoginForm( wfMsg( 'noname' ) );
293 return false;
296 if ( 0 != $u->idForName() ) {
297 $this->mainLoginForm( wfMsg( 'userexists' ) );
298 return false;
301 if ( 0 != strcmp( $this->mPassword, $this->mRetype ) ) {
302 $this->mainLoginForm( wfMsg( 'badretype' ) );
303 return false;
306 # check for minimal password length
307 $valid = $u->getPasswordValidity( $this->mPassword );
308 if ( $valid !== true ) {
309 if ( !$this->mCreateaccountMail ) {
310 $this->mainLoginForm( wfMsgExt( $valid, array( 'parsemag' ), $wgMinimalPasswordLength ) );
311 return false;
312 } else {
313 # do not force a password for account creation by email
314 # set invalid password, it will be replaced later by a random generated password
315 $this->mPassword = null;
319 # if you need a confirmed email address to edit, then obviously you
320 # need an email address.
321 if ( $wgEmailConfirmToEdit && empty( $this->mEmail ) ) {
322 $this->mainLoginForm( wfMsg( 'noemailtitle' ) );
323 return false;
326 if( !empty( $this->mEmail ) && !User::isValidEmailAddr( $this->mEmail ) ) {
327 $this->mainLoginForm( wfMsg( 'invalidemailaddress' ) );
328 return false;
331 # Set some additional data so the AbortNewAccount hook can be used for
332 # more than just username validation
333 $u->setEmail( $this->mEmail );
334 $u->setRealName( $this->mRealName );
336 $abortError = '';
337 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
338 // Hook point to add extra creation throttles and blocks
339 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
340 $this->mainLoginForm( $abortError );
341 return false;
344 if ( $wgAccountCreationThrottle && $wgUser->isPingLimitable() ) {
345 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
346 $value = $wgMemc->get( $key );
347 if ( !$value ) {
348 $wgMemc->set( $key, 0, 86400 );
350 if ( $value >= $wgAccountCreationThrottle ) {
351 $this->throttleHit( $wgAccountCreationThrottle );
352 return false;
354 $wgMemc->incr( $key );
357 if( !$wgAuth->addUser( $u, $this->mPassword, $this->mEmail, $this->mRealName ) ) {
358 $this->mainLoginForm( wfMsg( 'externaldberror' ) );
359 return false;
362 self::clearCreateaccountToken();
363 return $this->initUser( $u, false );
367 * Actually add a user to the database.
368 * Give it a User object that has been initialised with a name.
370 * @param $u User object.
371 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
372 * @return User object.
373 * @private
375 function initUser( $u, $autocreate ) {
376 global $wgAuth;
378 $u->addToDatabase();
380 if ( $wgAuth->allowPasswordChange() ) {
381 $u->setPassword( $this->mPassword );
384 $u->setEmail( $this->mEmail );
385 $u->setRealName( $this->mRealName );
386 $u->setToken();
388 $wgAuth->initUser( $u, $autocreate );
390 if ( $this->mExtUser ) {
391 $this->mExtUser->linkToLocal( $u->getId() );
392 $email = $this->mExtUser->getPref( 'emailaddress' );
393 if ( $email && !$this->mEmail ) {
394 $u->setEmail( $email );
398 $u->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
399 $u->saveSettings();
401 # Update user count
402 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
403 $ssUpdate->doUpdate();
405 return $u;
409 * Internally authenticate the login request.
411 * This may create a local account as a side effect if the
412 * authentication plugin allows transparent local account
413 * creation.
415 public function authenticateUserData() {
416 global $wgUser, $wgAuth;
417 if ( $this->mName == '' ) {
418 return self::NO_NAME;
421 // We require a login token to prevent login CSRF
422 // Handle part of this before incrementing the throttle so
423 // token-less login attempts don't count towards the throttle
424 // but wrong-token attempts do.
426 // If the user doesn't have a login token yet, set one.
427 if ( !self::getLoginToken() ) {
428 self::setLoginToken();
429 return self::NEED_TOKEN;
431 // If the user didn't pass a login token, tell them we need one
432 if ( !$this->mToken ) {
433 return self::NEED_TOKEN;
436 global $wgPasswordAttemptThrottle;
438 $throttleCount = 0;
439 if ( is_array( $wgPasswordAttemptThrottle ) ) {
440 $throttleKey = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mName ) );
441 $count = $wgPasswordAttemptThrottle['count'];
442 $period = $wgPasswordAttemptThrottle['seconds'];
444 global $wgMemc;
445 $throttleCount = $wgMemc->get( $throttleKey );
446 if ( !$throttleCount ) {
447 $wgMemc->add( $throttleKey, 1, $period ); // start counter
448 } else if ( $throttleCount < $count ) {
449 $wgMemc->incr($throttleKey);
450 } else if ( $throttleCount >= $count ) {
451 return self::THROTTLED;
455 // Validate the login token
456 if ( $this->mToken !== self::getLoginToken() ) {
457 return self::WRONG_TOKEN;
460 // Load $wgUser now, and check to see if we're logging in as the same
461 // name. This is necessary because loading $wgUser (say by calling
462 // getName()) calls the UserLoadFromSession hook, which potentially
463 // creates the user in the database. Until we load $wgUser, checking
464 // for user existence using User::newFromName($name)->getId() below
465 // will effectively be using stale data.
466 if ( $wgUser->getName() === $this->mName ) {
467 wfDebug( __METHOD__.": already logged in as {$this->mName}\n" );
468 return self::SUCCESS;
471 $this->mExtUser = ExternalUser::newFromName( $this->mName );
473 # TODO: Allow some magic here for invalid external names, e.g., let the
474 # user choose a different wiki name.
475 $u = User::newFromName( $this->mName );
476 if( !( $u instanceof User ) || !User::isUsableName( $u->getName() ) ) {
477 return self::ILLEGAL;
480 $isAutoCreated = false;
481 if ( 0 == $u->getID() ) {
482 $status = $this->attemptAutoCreate( $u );
483 if ( $status !== self::SUCCESS ) {
484 return $status;
485 } else {
486 $isAutoCreated = true;
488 } else {
489 global $wgExternalAuthType, $wgAutocreatePolicy;
490 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
491 && is_object( $this->mExtUser )
492 && $this->mExtUser->authenticate( $this->mPassword ) ) {
493 # The external user and local user have the same name and
494 # password, so we assume they're the same.
495 $this->mExtUser->linkToLocal( $u->getID() );
498 $u->load();
501 // Give general extensions, such as a captcha, a chance to abort logins
502 $abort = self::ABORTED;
503 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword, &$abort ) ) ) {
504 return $abort;
507 global $wgBlockDisablesLogin;
508 if (!$u->checkPassword( $this->mPassword )) {
509 if( $u->checkTemporaryPassword( $this->mPassword ) ) {
510 // The e-mailed temporary password should not be used for actu-
511 // al logins; that's a very sloppy habit, and insecure if an
512 // attacker has a few seconds to click "search" on someone's o-
513 // pen mail reader.
515 // Allow it to be used only to reset the password a single time
516 // to a new value, which won't be in the user's e-mail ar-
517 // chives.
519 // For backwards compatibility, we'll still recognize it at the
520 // login form to minimize surprises for people who have been
521 // logging in with a temporary password for some time.
523 // As a side-effect, we can authenticate the user's e-mail ad-
524 // dress if it's not already done, since the temporary password
525 // was sent via e-mail.
526 if( !$u->isEmailConfirmed() ) {
527 $u->confirmEmail();
528 $u->saveSettings();
531 // At this point we just return an appropriate code/ indicating
532 // that the UI should show a password reset form; bot inter-
533 // faces etc will probably just fail cleanly here.
534 $retval = self::RESET_PASS;
535 } else {
536 $retval = ($this->mPassword == '') ? self::EMPTY_PASS : self::WRONG_PASS;
538 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
539 // If we've enabled it, make it so that a blocked user cannot login
540 $retval = self::USER_BLOCKED;
541 } else {
542 $wgAuth->updateUser( $u );
543 $wgUser = $u;
545 // Please reset throttle for successful logins, thanks!
546 if($throttleCount) {
547 $wgMemc->delete($throttleKey);
550 if ( $isAutoCreated ) {
551 // Must be run after $wgUser is set, for correct new user log
552 wfRunHooks( 'AuthPluginAutoCreate', array( $wgUser ) );
555 $retval = self::SUCCESS;
557 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $retval ) );
558 return $retval;
562 * Attempt to automatically create a user on login. Only succeeds if there
563 * is an external authentication method which allows it.
564 * @return integer Status code
566 function attemptAutoCreate( $user ) {
567 global $wgAuth, $wgUser, $wgAutocreatePolicy;
569 if ( $wgUser->isBlockedFromCreateAccount() ) {
570 wfDebug( __METHOD__.": user is blocked from account creation\n" );
571 return self::CREATE_BLOCKED;
575 * If the external authentication plugin allows it, automatically cre-
576 * ate a new account for users that are externally defined but have not
577 * yet logged in.
579 if ( $this->mExtUser ) {
580 # mExtUser is neither null nor false, so use the new ExternalAuth
581 # system.
582 if ( $wgAutocreatePolicy == 'never' ) {
583 return self::NOT_EXISTS;
585 if ( !$this->mExtUser->authenticate( $this->mPassword ) ) {
586 return self::WRONG_PLUGIN_PASS;
588 } else {
589 # Old AuthPlugin.
590 if ( !$wgAuth->autoCreate() ) {
591 return self::NOT_EXISTS;
593 if ( !$wgAuth->userExists( $user->getName() ) ) {
594 wfDebug( __METHOD__.": user does not exist\n" );
595 return self::NOT_EXISTS;
597 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
598 wfDebug( __METHOD__.": \$wgAuth->authenticate() returned false, aborting\n" );
599 return self::WRONG_PLUGIN_PASS;
603 wfDebug( __METHOD__.": creating account\n" );
604 $user = $this->initUser( $user, true );
605 return self::SUCCESS;
608 function processLogin() {
609 global $wgUser, $wgAuth;
611 switch ( $this->authenticateUserData() ) {
612 case self::SUCCESS:
613 # We've verified now, update the real record
614 if( (bool)$this->mRemember != (bool)$wgUser->getOption( 'rememberpassword' ) ) {
615 $wgUser->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
616 $wgUser->saveSettings();
617 } else {
618 $wgUser->invalidateCache();
620 $wgUser->setCookies();
621 self::clearLoginToken();
623 // Reset the throttle
624 $key = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mName ) );
625 global $wgMemc;
626 $wgMemc->delete( $key );
628 if( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
629 /* Replace the language object to provide user interface in
630 * correct language immediately on this first page load.
632 global $wgLang, $wgRequest;
633 $code = $wgRequest->getVal( 'uselang', $wgUser->getOption( 'language' ) );
634 $wgLang = Language::factory( $code );
635 return $this->successfulLogin();
636 } else {
637 return $this->cookieRedirectCheck( 'login' );
639 break;
641 case self::NEED_TOKEN:
642 case self::WRONG_TOKEN:
643 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
644 break;
645 case self::NO_NAME:
646 case self::ILLEGAL:
647 $this->mainLoginForm( wfMsg( 'noname' ) );
648 break;
649 case self::WRONG_PLUGIN_PASS:
650 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
651 break;
652 case self::NOT_EXISTS:
653 if( $wgUser->isAllowed( 'createaccount' ) ){
654 $this->mainLoginForm( wfMsgWikiHtml( 'nosuchuser', htmlspecialchars( $this->mName ) ) );
655 } else {
656 $this->mainLoginForm( wfMsg( 'nosuchusershort', htmlspecialchars( $this->mName ) ) );
658 break;
659 case self::WRONG_PASS:
660 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
661 break;
662 case self::EMPTY_PASS:
663 $this->mainLoginForm( wfMsg( 'wrongpasswordempty' ) );
664 break;
665 case self::RESET_PASS:
666 $this->resetLoginForm( wfMsg( 'resetpass_announce' ) );
667 break;
668 case self::CREATE_BLOCKED:
669 $this->userBlockedMessage();
670 break;
671 case self::THROTTLED:
672 $this->mainLoginForm( wfMsg( 'login-throttled' ) );
673 break;
674 case self::USER_BLOCKED:
675 $this->mainLoginForm( wfMsgExt( 'login-userblocked',
676 array( 'parsemag', 'escape' ), $this->mName ) );
677 break;
678 default:
679 throw new MWException( "Unhandled case value" );
683 function resetLoginForm( $error ) {
684 global $wgOut;
685 $wgOut->addHTML( Xml::element('p', array( 'class' => 'error' ), $error ) );
686 $reset = new SpecialResetpass();
687 $reset->execute( null );
691 * @private
693 function mailPassword() {
694 global $wgUser, $wgOut, $wgAuth;
696 if ( wfReadOnly() ) {
697 $wgOut->readOnlyPage();
698 return false;
701 if( !$wgAuth->allowPasswordChange() ) {
702 $this->mainLoginForm( wfMsg( 'resetpass_forbidden' ) );
703 return;
706 # Check against blocked IPs so blocked users can't flood admins
707 # with password resets
708 if( $wgUser->isBlocked() ) {
709 $this->mainLoginForm( wfMsg( 'blocked-mailpassword' ) );
710 return;
713 # Check for hooks
714 $error = null;
715 if ( ! wfRunHooks( 'UserLoginMailPassword', array( $this->mName, &$error ) ) ) {
716 $this->mainLoginForm( $error );
717 return;
720 # If the user doesn't have a login token yet, set one.
721 if ( !self::getLoginToken() ) {
722 self::setLoginToken();
723 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
724 return;
727 # If the user didn't pass a login token, tell them we need one
728 if ( !$this->mToken ) {
729 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
730 return;
733 # Check against the rate limiter
734 if( $wgUser->pingLimiter( 'mailpassword' ) ) {
735 $wgOut->rateLimited();
736 return;
739 if ( $this->mName == '' ) {
740 $this->mainLoginForm( wfMsg( 'noname' ) );
741 return;
743 $u = User::newFromName( $this->mName );
744 if( !$u instanceof User ) {
745 $this->mainLoginForm( wfMsg( 'noname' ) );
746 return;
748 if ( 0 == $u->getID() ) {
749 $this->mainLoginForm( wfMsgWikiHtml( 'nosuchuser', htmlspecialchars( $u->getName() ) ) );
750 return;
753 # Validate the login token
754 if ( $this->mToken !== self::getLoginToken() ) {
755 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
756 return;
759 # Check against password throttle
760 if ( $u->isPasswordReminderThrottled() ) {
761 global $wgPasswordReminderResendTime;
762 # Round the time in hours to 3 d.p., in case someone is specifying
763 # minutes or seconds.
764 $this->mainLoginForm( wfMsgExt( 'throttled-mailpassword', array( 'parsemag' ),
765 round( $wgPasswordReminderResendTime, 3 ) ) );
766 return;
769 $result = $this->mailPasswordInternal( $u, true, 'passwordremindertitle', 'passwordremindertext' );
770 if( WikiError::isError( $result ) ) {
771 $this->mainLoginForm( wfMsg( 'mailerror', $result->getMessage() ) );
772 } else {
773 $this->mainLoginForm( wfMsg( 'passwordsent', $u->getName() ), 'success' );
774 self::clearLoginToken();
780 * @param $u User object
781 * @param $throttle Boolean
782 * @param $emailTitle String: message name of email title
783 * @param $emailText String: message name of email text
784 * @return Mixed: true on success, WikiError on failure
785 * @private
787 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
788 global $wgServer, $wgScript, $wgUser, $wgNewPasswordExpiry;
790 if ( $u->getEmail() == '' ) {
791 return new WikiError( wfMsg( 'noemail', $u->getName() ) );
793 $ip = wfGetIP();
794 if( !$ip ) {
795 return new WikiError( wfMsg( 'badipaddress' ) );
798 wfRunHooks( 'User::mailPasswordInternal', array(&$wgUser, &$ip, &$u) );
800 $np = $u->randomPassword();
801 $u->setNewpassword( $np, $throttle );
802 $u->saveSettings();
803 $userLanguage = $u->getOption( 'language' );
804 $m = wfMsgExt( $emailText, array( 'parsemag', 'language' => $userLanguage ), $ip, $u->getName(), $np,
805 $wgServer . $wgScript, round( $wgNewPasswordExpiry / 86400 ) );
806 $result = $u->sendMail( wfMsgExt( $emailTitle, array( 'parsemag', 'language' => $userLanguage ) ), $m );
808 return $result;
813 * Run any hooks registered for logins, then HTTP redirect to
814 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
815 * nice message here, but that's really not as useful as just being sent to
816 * wherever you logged in from. It should be clear that the action was
817 * successful, given the lack of error messages plus the appearance of your
818 * name in the upper right.
820 * @private
822 function successfulLogin() {
823 global $wgUser, $wgOut;
825 # Run any hooks; display injected HTML if any, else redirect
826 $injected_html = '';
827 wfRunHooks('UserLoginComplete', array(&$wgUser, &$injected_html));
829 if( $injected_html !== '' ) {
830 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
831 } else {
832 $titleObj = Title::newFromText( $this->mReturnTo );
833 if ( !$titleObj instanceof Title ) {
834 $titleObj = Title::newMainPage();
836 $wgOut->redirect( $titleObj->getFullURL( $this->mReturnToQuery ) );
841 * Run any hooks registered for logins, then display a message welcoming
842 * the user.
844 * @private
846 function successfulCreation() {
847 global $wgUser, $wgOut;
849 # Run any hooks; display injected HTML
850 $injected_html = '';
851 wfRunHooks('UserLoginComplete', array(&$wgUser, &$injected_html));
853 $this->displaySuccessfulLogin( 'welcomecreation', $injected_html );
857 * Display a "login successful" page.
859 private function displaySuccessfulLogin( $msgname, $injected_html ) {
860 global $wgOut, $wgUser;
862 $wgOut->setPageTitle( wfMsg( 'loginsuccesstitle' ) );
863 $wgOut->setRobotPolicy( 'noindex,nofollow' );
864 $wgOut->setArticleRelated( false );
865 $wgOut->addWikiMsg( $msgname, $wgUser->getName() );
866 $wgOut->addHTML( $injected_html );
868 if ( !empty( $this->mReturnTo ) ) {
869 $wgOut->returnToMain( null, $this->mReturnTo, $this->mReturnToQuery );
870 } else {
871 $wgOut->returnToMain( null );
875 /** */
876 function userNotPrivilegedMessage($errors) {
877 global $wgOut;
879 $wgOut->setPageTitle( wfMsg( 'permissionserrors' ) );
880 $wgOut->setRobotPolicy( 'noindex,nofollow' );
881 $wgOut->setArticleRelated( false );
883 $wgOut->addWikitext( $wgOut->formatPermissionsErrorMessage( $errors, 'createaccount' ) );
884 // Stuff that might want to be added at the end. For example, instruc-
885 // tions if blocked.
886 $wgOut->addWikiMsg( 'cantcreateaccount-nonblock-text' );
888 $wgOut->returnToMain( false );
891 /** */
892 function userBlockedMessage() {
893 global $wgOut, $wgUser;
895 # Let's be nice about this, it's likely that this feature will be used
896 # for blocking large numbers of innocent people, e.g. range blocks on
897 # schools. Don't blame it on the user. There's a small chance that it
898 # really is the user's fault, i.e. the username is blocked and they
899 # haven't bothered to log out before trying to create an account to
900 # evade it, but we'll leave that to their guilty conscience to figure
901 # out.
903 $wgOut->setPageTitle( wfMsg( 'cantcreateaccounttitle' ) );
904 $wgOut->setRobotPolicy( 'noindex,nofollow' );
905 $wgOut->setArticleRelated( false );
907 $ip = wfGetIP();
908 $blocker = User::whoIs( $wgUser->mBlock->mBy );
909 $block_reason = $wgUser->mBlock->mReason;
911 if ( strval( $block_reason ) === '' ) {
912 $block_reason = wfMsg( 'blockednoreason' );
914 $wgOut->addWikiMsg( 'cantcreateaccount-text', $ip, $block_reason, $blocker );
915 $wgOut->returnToMain( false );
919 * @private
921 function mainLoginForm( $msg, $msgtype = 'error' ) {
922 global $wgUser, $wgOut, $wgHiddenPrefs, $wgEnableEmail;
923 global $wgCookiePrefix, $wgLoginLanguageSelector;
924 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
926 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
928 if ( $this->mType == 'signup' ) {
929 // Block signup here if in readonly. Keeps user from
930 // going through the process (filling out data, etc)
931 // and being informed later.
932 if ( wfReadOnly() ) {
933 $wgOut->readOnlyPage();
934 return;
935 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
936 $this->userBlockedMessage();
937 return;
938 } elseif ( count( $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $wgUser, true ) )>0 ) {
939 $wgOut->showPermissionsErrorPage( $permErrors, 'createaccount' );
940 return;
944 if ( $this->mName == '' ) {
945 if ( $wgUser->isLoggedIn() ) {
946 $this->mName = $wgUser->getName();
947 } else {
948 $this->mName = isset( $_COOKIE[$wgCookiePrefix.'UserName'] ) ? $_COOKIE[$wgCookiePrefix.'UserName'] : null;
952 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
954 if ( $this->mType == 'signup' ) {
955 $template = new UsercreateTemplate();
956 $q = 'action=submitlogin&type=signup';
957 $linkq = 'type=login';
958 $linkmsg = 'gotaccount';
959 } else {
960 $template = new UserloginTemplate();
961 $q = 'action=submitlogin&type=login';
962 $linkq = 'type=signup';
963 $linkmsg = 'nologin';
966 if ( !empty( $this->mReturnTo ) ) {
967 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
968 if ( !empty( $this->mReturnToQuery ) )
969 $returnto .= '&returntoquery=' .
970 wfUrlencode( $this->mReturnToQuery );
971 $q .= $returnto;
972 $linkq .= $returnto;
975 # Pass any language selection on to the mode switch link
976 if( $wgLoginLanguageSelector && $this->mLanguage )
977 $linkq .= '&uselang=' . $this->mLanguage;
979 $link = '<a href="' . htmlspecialchars ( $titleObj->getLocalUrl( $linkq ) ) . '">';
980 $link .= wfMsgHtml( $linkmsg . 'link' ); # Calling either 'gotaccountlink' or 'nologinlink'
981 $link .= '</a>';
983 # Don't show a "create account" link if the user can't
984 if( $this->showCreateOrLoginLink( $wgUser ) )
985 $template->set( 'link', wfMsgWikiHtml( $linkmsg, $link ) );
986 else
987 $template->set( 'link', '' );
989 $template->set( 'header', '' );
990 $template->set( 'name', $this->mName );
991 $template->set( 'password', $this->mPassword );
992 $template->set( 'retype', $this->mRetype );
993 $template->set( 'email', $this->mEmail );
994 $template->set( 'realname', $this->mRealName );
995 $template->set( 'domain', $this->mDomain );
997 $template->set( 'action', $titleObj->getLocalUrl( $q ) );
998 $template->set( 'message', $msg );
999 $template->set( 'messagetype', $msgtype );
1000 $template->set( 'createemail', $wgEnableEmail && $wgUser->isLoggedIn() );
1001 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1002 $template->set( 'useemail', $wgEnableEmail );
1003 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1004 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1005 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1006 $template->set( 'remember', $wgUser->getOption( 'rememberpassword' ) or $this->mRemember );
1008 if ( $this->mType == 'signup' ) {
1009 if ( !self::getCreateaccountToken() ) {
1010 self::setCreateaccountToken();
1012 $template->set( 'token', self::getCreateaccountToken() );
1013 } else {
1014 if ( !self::getLoginToken() ) {
1015 self::setLoginToken();
1017 $template->set( 'token', self::getLoginToken() );
1020 # Prepare language selection links as needed
1021 if( $wgLoginLanguageSelector ) {
1022 $template->set( 'languages', $this->makeLanguageSelector() );
1023 if( $this->mLanguage )
1024 $template->set( 'uselang', $this->mLanguage );
1027 // Give authentication and captcha plugins a chance to modify the form
1028 $wgAuth->modifyUITemplate( $template, $this->mType );
1029 if ( $this->mType == 'signup' ) {
1030 wfRunHooks( 'UserCreateForm', array( &$template ) );
1031 } else {
1032 wfRunHooks( 'UserLoginForm', array( &$template ) );
1035 //Changes the title depending on permissions for creating account
1036 if ( $wgUser->isAllowed( 'createaccount' ) ) {
1037 $wgOut->setPageTitle( wfMsg( 'userlogin' ) );
1038 } else {
1039 $wgOut->setPageTitle( wfMsg( 'userloginnocreate' ) );
1042 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1043 $wgOut->setArticleRelated( false );
1044 $wgOut->disallowUserJs(); // just in case...
1045 $wgOut->addTemplate( $template );
1049 * @private
1051 function showCreateOrLoginLink( &$user ) {
1052 if( $this->mType == 'signup' ) {
1053 return( true );
1054 } elseif( $user->isAllowed( 'createaccount' ) ) {
1055 return( true );
1056 } else {
1057 return( false );
1062 * Check if a session cookie is present.
1064 * This will not pick up a cookie set during _this_ request, but is meant
1065 * to ensure that the client is returning the cookie which was set on a
1066 * previous pass through the system.
1068 * @private
1070 function hasSessionCookie() {
1071 global $wgDisableCookieCheck, $wgRequest;
1072 return $wgDisableCookieCheck ? true : $wgRequest->checkSessionCookie();
1076 * Get the login token from the current session
1078 public static function getLoginToken() {
1079 global $wgRequest;
1080 return $wgRequest->getSessionData( 'wsLoginToken' );
1084 * Randomly generate a new login token and attach it to the current session
1086 public static function setLoginToken() {
1087 global $wgRequest;
1088 // Use User::generateToken() instead of $user->editToken()
1089 // because the latter reuses $_SESSION['wsEditToken']
1090 $wgRequest->setSessionData( 'wsLoginToken', User::generateToken() );
1094 * Remove any login token attached to the current session
1096 public static function clearLoginToken() {
1097 global $wgRequest;
1098 $wgRequest->setSessionData( 'wsLoginToken', null );
1102 * Get the createaccount token from the current session
1104 public static function getCreateaccountToken() {
1105 global $wgRequest;
1106 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1110 * Randomly generate a new createaccount token and attach it to the current session
1112 public static function setCreateaccountToken() {
1113 global $wgRequest;
1114 $wgRequest->setSessionData( 'wsCreateaccountToken', User::generateToken() );
1118 * Remove any createaccount token attached to the current session
1120 public static function clearCreateaccountToken() {
1121 global $wgRequest;
1122 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1126 * @private
1128 function cookieRedirectCheck( $type ) {
1129 global $wgOut;
1131 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
1132 $query = array( 'wpCookieCheck' => $type );
1133 if ( $this->mReturnTo ) $query['returnto'] = $this->mReturnTo;
1134 $check = $titleObj->getFullURL( $query );
1136 return $wgOut->redirect( $check );
1140 * @private
1142 function onCookieRedirectCheck( $type ) {
1143 if ( !$this->hasSessionCookie() ) {
1144 if ( $type == 'new' ) {
1145 return $this->mainLoginForm( wfMsgExt( 'nocookiesnew', array( 'parseinline' ) ) );
1146 } else if ( $type == 'login' ) {
1147 return $this->mainLoginForm( wfMsgExt( 'nocookieslogin', array( 'parseinline' ) ) );
1148 } else {
1149 # shouldn't happen
1150 return $this->mainLoginForm( wfMsg( 'error' ) );
1152 } else {
1153 return $this->successfulLogin();
1158 * @private
1160 function throttleHit( $limit ) {
1161 $this->mainLoginForm( wfMsgExt( 'acct_creation_throttle_hit', array( 'parseinline' ), $limit ) );
1165 * Produce a bar of links which allow the user to select another language
1166 * during login/registration but retain "returnto"
1168 * @return string
1170 function makeLanguageSelector() {
1171 global $wgLang;
1173 $msg = wfMsgForContent( 'loginlanguagelinks' );
1174 if( $msg != '' && !wfEmptyMsg( 'loginlanguagelinks', $msg ) ) {
1175 $langs = explode( "\n", $msg );
1176 $links = array();
1177 foreach( $langs as $lang ) {
1178 $lang = trim( $lang, '* ' );
1179 $parts = explode( '|', $lang );
1180 if (count($parts) >= 2) {
1181 $links[] = $this->makeLanguageSelectorLink( $parts[0], $parts[1] );
1184 return count( $links ) > 0 ? wfMsgHtml( 'loginlanguagelabel', $wgLang->pipeList( $links ) ) : '';
1185 } else {
1186 return '';
1191 * Create a language selector link for a particular language
1192 * Links back to this page preserving type and returnto
1194 * @param $text Link text
1195 * @param $lang Language code
1197 function makeLanguageSelectorLink( $text, $lang ) {
1198 global $wgUser;
1199 $self = SpecialPage::getTitleFor( 'Userlogin' );
1200 $attr = array( 'uselang' => $lang );
1201 if( $this->mType == 'signup' )
1202 $attr['type'] = 'signup';
1203 if( $this->mReturnTo )
1204 $attr['returnto'] = $this->mReturnTo;
1205 $skin = $wgUser->getSkin();
1206 return $skin->linkKnown(
1207 $self,
1208 htmlspecialchars( $text ),
1209 array(),
1210 $attr