Reverted r108743 per CR comment. This should at least be discussed first.
[lhc/web/wiklou.git] / includes / specials / SpecialUserlogin.php
1 <?php
2 /**
3 * Implements Special:UserLogin
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 /**
25 * Implements Special:UserLogin
26 *
27 * @ingroup SpecialPage
28 */
29 class LoginForm extends SpecialPage {
30
31 const SUCCESS = 0;
32 const NO_NAME = 1;
33 const ILLEGAL = 2;
34 const WRONG_PLUGIN_PASS = 3;
35 const NOT_EXISTS = 4;
36 const WRONG_PASS = 5;
37 const EMPTY_PASS = 6;
38 const RESET_PASS = 7;
39 const ABORTED = 8;
40 const CREATE_BLOCKED = 9;
41 const THROTTLED = 10;
42 const USER_BLOCKED = 11;
43 const NEED_TOKEN = 12;
44 const WRONG_TOKEN = 13;
45
46 var $mUsername, $mPassword, $mRetype, $mReturnTo, $mCookieCheck, $mPosted;
47 var $mAction, $mCreateaccount, $mCreateaccountMail;
48 var $mLoginattempt, $mRemember, $mEmail, $mDomain, $mLanguage;
49 var $mSkipCookieCheck, $mReturnToQuery, $mToken, $mStickHTTPS;
50 var $mType, $mReason, $mRealName;
51 var $mAbortLoginErrorMsg = 'login-abort-generic';
52 private $mLoaded = false;
53
54 /**
55 * @var ExternalUser
56 */
57 private $mExtUser = null;
58
59 /**
60 * @ var WebRequest
61 */
62 private $mOverrideRequest = null;
63
64 /**
65 * @param WebRequest $request
66 */
67 public function __construct( $request = null ) {
68 parent::__construct( 'Userlogin' );
69
70 $this->mOverrideRequest = $request;
71 }
72
73 /**
74 * Loader
75 *
76 * @param $request WebRequest object
77 */
78 function load() {
79 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail, $wgRedirectOnLogin;
80
81 if ( $this->mLoaded ) {
82 return;
83 }
84 $this->mLoaded = true;
85
86 if ( $this->mOverrideRequest === null ) {
87 $request = $this->getRequest();
88 } else {
89 $request = $this->mOverrideRequest;
90 }
91
92 $this->mType = $request->getText( 'type' );
93 $this->mUsername = $request->getText( 'wpName' );
94 $this->mPassword = $request->getText( 'wpPassword' );
95 $this->mRetype = $request->getText( 'wpRetype' );
96 $this->mDomain = $request->getText( 'wpDomain' );
97 $this->mReason = $request->getText( 'wpReason' );
98 $this->mReturnTo = $request->getVal( 'returnto' );
99 $this->mReturnToQuery = $request->getVal( 'returntoquery' );
100 $this->mCookieCheck = $request->getVal( 'wpCookieCheck' );
101 $this->mPosted = $request->wasPosted();
102 $this->mCreateaccount = $request->getCheck( 'wpCreateaccount' );
103 $this->mCreateaccountMail = $request->getCheck( 'wpCreateaccountMail' )
104 && $wgEnableEmail;
105 $this->mLoginattempt = $request->getCheck( 'wpLoginattempt' );
106 $this->mAction = $request->getVal( 'action' );
107 $this->mRemember = $request->getCheck( 'wpRemember' );
108 $this->mStickHTTPS = $request->getCheck( 'wpStickHTTPS' );
109 $this->mLanguage = $request->getText( 'uselang' );
110 $this->mSkipCookieCheck = $request->getCheck( 'wpSkipCookieCheck' );
111 $this->mToken = ( $this->mType == 'signup' ) ? $request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
112
113 if ( $wgRedirectOnLogin ) {
114 $this->mReturnTo = $wgRedirectOnLogin;
115 $this->mReturnToQuery = '';
116 }
117
118 if( $wgEnableEmail ) {
119 $this->mEmail = $request->getText( 'wpEmail' );
120 } else {
121 $this->mEmail = '';
122 }
123 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
124 $this->mRealName = $request->getText( 'wpRealName' );
125 } else {
126 $this->mRealName = '';
127 }
128
129 if( !$wgAuth->validDomain( $this->mDomain ) ) {
130 if ( isset( $_SESSION['wsDomain'] ) ) {
131 $this->mDomain = $_SESSION['wsDomain'];
132 } else {
133 $this->mDomain = 'invaliddomain';
134 }
135 }
136 $wgAuth->setDomain( $this->mDomain );
137
138 # When switching accounts, it sucks to get automatically logged out
139 $returnToTitle = Title::newFromText( $this->mReturnTo );
140 if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
141 $this->mReturnTo = '';
142 $this->mReturnToQuery = '';
143 }
144 }
145
146 function getDescription() {
147 return $this->msg( $this->getUser()->isAllowed( 'createaccount' ) ?
148 'userlogin' : 'userloginnocreate' )->text();
149 }
150
151 public function execute( $par ) {
152 if ( session_id() == '' ) {
153 wfSetupSession();
154 }
155
156 $this->load();
157 $this->setHeaders();
158
159 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
160 $this->mType = 'signup';
161 }
162
163 if ( !is_null( $this->mCookieCheck ) ) {
164 $this->onCookieRedirectCheck( $this->mCookieCheck );
165 return;
166 } elseif( $this->mPosted ) {
167 if( $this->mCreateaccount ) {
168 return $this->addNewAccount();
169 } elseif ( $this->mCreateaccountMail ) {
170 return $this->addNewAccountMailPassword();
171 } elseif ( ( 'submitlogin' == $this->mAction ) || $this->mLoginattempt ) {
172 return $this->processLogin();
173 }
174 }
175 $this->mainLoginForm( '' );
176 }
177
178 /**
179 * @private
180 */
181 function addNewAccountMailPassword() {
182 if ( $this->mEmail == '' ) {
183 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
184 return;
185 }
186
187 $u = $this->addNewaccountInternal();
188
189 if ( $u == null ) {
190 return;
191 }
192
193 // Wipe the initial password and mail a temporary one
194 $u->setPassword( null );
195 $u->saveSettings();
196 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
197
198 wfRunHooks( 'AddNewAccount', array( $u, true ) );
199 $u->addNewUserLogEntry( true, $this->mReason );
200
201 $out = $this->getOutput();
202 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
203
204 if( !$result->isGood() ) {
205 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
206 } else {
207 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
208 $out->returnToMain( false );
209 }
210 }
211
212 /**
213 * @private
214 */
215 function addNewAccount() {
216 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
217
218 # Create the account and abort if there's a problem doing so
219 $u = $this->addNewAccountInternal();
220 if( $u == null ) {
221 return;
222 }
223
224 # If we showed up language selection links, and one was in use, be
225 # smart (and sensible) and save that language as the user's preference
226 if( $wgLoginLanguageSelector && $this->mLanguage ) {
227 $u->setOption( 'language', $this->mLanguage );
228 }
229
230 $out = $this->getOutput();
231
232 # Send out an email authentication message if needed
233 if( $wgEmailAuthentication && Sanitizer::validateEmail( $u->getEmail() ) ) {
234 $status = $u->sendConfirmationMail();
235 if( $status->isGood() ) {
236 $out->addWikiMsg( 'confirmemail_oncreate' );
237 } else {
238 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
239 }
240 }
241
242 # Save settings (including confirmation token)
243 $u->saveSettings();
244
245 # If not logged in, assume the new account as the current one and set
246 # session cookies then show a "welcome" message or a "need cookies"
247 # message as needed
248 if( $this->getUser()->isAnon() ) {
249 $u->setCookies();
250 $wgUser = $u;
251 // This should set it for OutputPage and the Skin
252 // which is needed or the personal links will be
253 // wrong.
254 $this->getContext()->setUser( $u );
255 wfRunHooks( 'AddNewAccount', array( $u, false ) );
256 $u->addNewUserLogEntry();
257 if( $this->hasSessionCookie() ) {
258 return $this->successfulCreation();
259 } else {
260 return $this->cookieRedirectCheck( 'new' );
261 }
262 } else {
263 # Confirm that the account was created
264 $out->setPageTitle( $this->msg( 'accountcreated' ) );
265 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
266 $out->returnToMain( false, $this->getTitle() );
267 wfRunHooks( 'AddNewAccount', array( $u, false ) );
268 $u->addNewUserLogEntry( false, $this->mReason );
269 return true;
270 }
271 }
272
273 /**
274 * @private
275 */
276 function addNewAccountInternal() {
277 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
278 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
279
280 // If the user passes an invalid domain, something is fishy
281 if( !$wgAuth->validDomain( $this->mDomain ) ) {
282 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
283 return false;
284 }
285
286 // If we are not allowing users to login locally, we should be checking
287 // to see if the user is actually able to authenticate to the authenti-
288 // cation server before they create an account (otherwise, they can
289 // create a local account and login as any domain user). We only need
290 // to check this for domains that aren't local.
291 if( 'local' != $this->mDomain && $this->mDomain != '' ) {
292 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername )
293 || !$wgAuth->authenticate( $this->mUsername, $this->mPassword ) ) ) {
294 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
295 return false;
296 }
297 }
298
299 if ( wfReadOnly() ) {
300 throw new ReadOnlyError;
301 }
302
303 # Request forgery checks.
304 if ( !self::getCreateaccountToken() ) {
305 self::setCreateaccountToken();
306 $this->mainLoginForm( $this->msg( 'nocookiesfornew' )->parse() );
307 return false;
308 }
309
310 # The user didn't pass a createaccount token
311 if ( !$this->mToken ) {
312 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
313 return false;
314 }
315
316 # Validate the createaccount token
317 if ( $this->mToken !== self::getCreateaccountToken() ) {
318 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
319 return false;
320 }
321
322 # Check permissions
323 $currentUser = $this->getUser();
324 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
325 throw new PermissionsError( 'createaccount' );
326 } elseif ( $currentUser->isBlockedFromCreateAccount() ) {
327 $this->userBlockedMessage( $currentUser->isBlockedFromCreateAccount() );
328 return false;
329 }
330
331 $ip = $this->getRequest()->getIP();
332 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
333 $this->mainLoginForm( $this->msg( 'sorbs_create_account_reason' )->text() . ' (' . htmlspecialchars( $ip ) . ')' );
334 return false;
335 }
336
337 # Now create a dummy user ($u) and check if it is valid
338 $name = trim( $this->mUsername );
339 $u = User::newFromName( $name, 'creatable' );
340 if ( !is_object( $u ) ) {
341 $this->mainLoginForm( $this->msg( 'noname' )->text() );
342 return false;
343 }
344
345 if ( 0 != $u->idForName() ) {
346 $this->mainLoginForm( $this->msg( 'userexists' )->text() );
347 return false;
348 }
349
350 if ( 0 != strcmp( $this->mPassword, $this->mRetype ) ) {
351 $this->mainLoginForm( $this->msg( 'badretype' )->text() );
352 return false;
353 }
354
355 # check for minimal password length
356 $valid = $u->getPasswordValidity( $this->mPassword );
357 if ( $valid !== true ) {
358 if ( !$this->mCreateaccountMail ) {
359 if ( is_array( $valid ) ) {
360 $message = array_shift( $valid );
361 $params = $valid;
362 } else {
363 $message = $valid;
364 $params = array( $wgMinimalPasswordLength );
365 }
366 $this->mainLoginForm( $this->msg( $message, $params )->text() );
367 return false;
368 } else {
369 # do not force a password for account creation by email
370 # set invalid password, it will be replaced later by a random generated password
371 $this->mPassword = null;
372 }
373 }
374
375 # if you need a confirmed email address to edit, then obviously you
376 # need an email address.
377 if ( $wgEmailConfirmToEdit && empty( $this->mEmail ) ) {
378 $this->mainLoginForm( $this->msg( 'noemailtitle' )->text() );
379 return false;
380 }
381
382 if( !empty( $this->mEmail ) && !Sanitizer::validateEmail( $this->mEmail ) ) {
383 $this->mainLoginForm( $this->msg( 'invalidemailaddress' )->text() );
384 return false;
385 }
386
387 # Set some additional data so the AbortNewAccount hook can be used for
388 # more than just username validation
389 $u->setEmail( $this->mEmail );
390 $u->setRealName( $this->mRealName );
391
392 $abortError = '';
393 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
394 // Hook point to add extra creation throttles and blocks
395 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
396 $this->mainLoginForm( $abortError );
397 return false;
398 }
399
400 // Hook point to check for exempt from account creation throttle
401 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
402 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
403 } else {
404 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
405 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
406 $value = $wgMemc->get( $key );
407 if ( !$value ) {
408 $wgMemc->set( $key, 0, 86400 );
409 }
410 if ( $value >= $wgAccountCreationThrottle ) {
411 $this->throttleHit( $wgAccountCreationThrottle );
412 return false;
413 }
414 $wgMemc->incr( $key );
415 }
416 }
417
418 if( !$wgAuth->addUser( $u, $this->mPassword, $this->mEmail, $this->mRealName ) ) {
419 $this->mainLoginForm( $this->msg( 'externaldberror' )->text() );
420 return false;
421 }
422
423 self::clearCreateaccountToken();
424 return $this->initUser( $u, false );
425 }
426
427 /**
428 * Actually add a user to the database.
429 * Give it a User object that has been initialised with a name.
430 *
431 * @param $u User object.
432 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
433 * @return User object.
434 * @private
435 */
436 function initUser( $u, $autocreate ) {
437 global $wgAuth;
438
439 $u->addToDatabase();
440
441 if ( $wgAuth->allowPasswordChange() ) {
442 $u->setPassword( $this->mPassword );
443 }
444
445 $u->setEmail( $this->mEmail );
446 $u->setRealName( $this->mRealName );
447 $u->setToken();
448
449 $wgAuth->initUser( $u, $autocreate );
450
451 if ( $this->mExtUser ) {
452 $this->mExtUser->linkToLocal( $u->getId() );
453 $email = $this->mExtUser->getPref( 'emailaddress' );
454 if ( $email && !$this->mEmail ) {
455 $u->setEmail( $email );
456 }
457 }
458
459 $u->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
460 $u->saveSettings();
461
462 # Update user count
463 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
464 $ssUpdate->doUpdate();
465
466 return $u;
467 }
468
469 /**
470 * Internally authenticate the login request.
471 *
472 * This may create a local account as a side effect if the
473 * authentication plugin allows transparent local account
474 * creation.
475 */
476 public function authenticateUserData() {
477 global $wgUser, $wgAuth;
478
479 $this->load();
480
481 if ( $this->mUsername == '' ) {
482 wfRunHooks( 'LoginAuthenticateAudit', array( new User, $this->mPassword, self::NO_NAME ) );
483 return self::NO_NAME;
484 }
485
486 // We require a login token to prevent login CSRF
487 // Handle part of this before incrementing the throttle so
488 // token-less login attempts don't count towards the throttle
489 // but wrong-token attempts do.
490
491 // If the user doesn't have a login token yet, set one.
492 if ( !self::getLoginToken() ) {
493 self::setLoginToken();
494 wfRunHooks( 'LoginAuthenticateAudit', array( new User, $this->mPassword, self::NEED_TOKEN ) );
495 return self::NEED_TOKEN;
496 }
497 // If the user didn't pass a login token, tell them we need one
498 if ( !$this->mToken ) {
499 wfRunHooks( 'LoginAuthenticateAudit', array( new User, $this->mPassword, self::NEED_TOKEN ) );
500 return self::NEED_TOKEN;
501 }
502
503 $throttleCount = self::incLoginThrottle( $this->mUsername );
504 if ( $throttleCount === true ) {
505 wfRunHooks( 'LoginAuthenticateAudit', array( new User, $this->mPassword, self::THROTTLED ) );
506 return self::THROTTLED;
507 }
508
509 // Validate the login token
510 if ( $this->mToken !== self::getLoginToken() ) {
511 wfRunHooks( 'LoginAuthenticateAudit', array( new User, $this->mPassword, self::WRONG_TOKEN ) );
512 return self::WRONG_TOKEN;
513 }
514
515 // Load the current user now, and check to see if we're logging in as
516 // the same name. This is necessary because loading the current user
517 // (say by calling getName()) calls the UserLoadFromSession hook, which
518 // potentially creates the user in the database. Until we load $wgUser,
519 // checking for user existence using User::newFromName($name)->getId() below
520 // will effectively be using stale data.
521 if ( $this->getUser()->getName() === $this->mUsername ) {
522 wfDebug( __METHOD__ . ": already logged in as {$this->mUsername}\n" );
523 return self::SUCCESS;
524 }
525
526 $this->mExtUser = ExternalUser::newFromName( $this->mUsername );
527
528 # TODO: Allow some magic here for invalid external names, e.g., let the
529 # user choose a different wiki name.
530 $u = User::newFromName( $this->mUsername );
531 if( !( $u instanceof User ) ) {
532 wfRunHooks( 'LoginAuthenticateAudit', array( new User, $this->mPassword, self::ILLEGAL ) );
533 return self::ILLEGAL;
534 }
535 if( !User::isUsableName( $u->getName() ) ) {
536 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, self::ILLEGAL ) );
537 return self::ILLEGAL;
538 }
539
540 $isAutoCreated = false;
541 if ( 0 == $u->getID() ) {
542 $status = $this->attemptAutoCreate( $u );
543 if ( $status !== self::SUCCESS ) {
544 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $status ) );
545 return $status;
546 } else {
547 $isAutoCreated = true;
548 }
549 } else {
550 global $wgExternalAuthType, $wgAutocreatePolicy;
551 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
552 && is_object( $this->mExtUser )
553 && $this->mExtUser->authenticate( $this->mPassword ) ) {
554 # The external user and local user have the same name and
555 # password, so we assume they're the same.
556 $this->mExtUser->linkToLocal( $u->getID() );
557 }
558
559 $u->load();
560 }
561
562 // Give general extensions, such as a captcha, a chance to abort logins
563 $abort = self::ABORTED;
564 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword, &$abort, &$this->mAbortLoginErrorMsg ) ) ) {
565 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $abort ) );
566 return $abort;
567 }
568
569 global $wgBlockDisablesLogin;
570 if ( !$u->checkPassword( $this->mPassword ) ) {
571 if( $u->checkTemporaryPassword( $this->mPassword ) ) {
572 // The e-mailed temporary password should not be used for actu-
573 // al logins; that's a very sloppy habit, and insecure if an
574 // attacker has a few seconds to click "search" on someone's o-
575 // pen mail reader.
576 //
577 // Allow it to be used only to reset the password a single time
578 // to a new value, which won't be in the user's e-mail ar-
579 // chives.
580 //
581 // For backwards compatibility, we'll still recognize it at the
582 // login form to minimize surprises for people who have been
583 // logging in with a temporary password for some time.
584 //
585 // As a side-effect, we can authenticate the user's e-mail ad-
586 // dress if it's not already done, since the temporary password
587 // was sent via e-mail.
588 if( !$u->isEmailConfirmed() ) {
589 $u->confirmEmail();
590 $u->saveSettings();
591 }
592
593 // At this point we just return an appropriate code/ indicating
594 // that the UI should show a password reset form; bot inter-
595 // faces etc will probably just fail cleanly here.
596 $retval = self::RESET_PASS;
597 } else {
598 $retval = ( $this->mPassword == '' ) ? self::EMPTY_PASS : self::WRONG_PASS;
599 }
600 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
601 // If we've enabled it, make it so that a blocked user cannot login
602 $retval = self::USER_BLOCKED;
603 } else {
604 $wgAuth->updateUser( $u );
605 $wgUser = $u;
606 // This should set it for OutputPage and the Skin
607 // which is needed or the personal links will be
608 // wrong.
609 $this->getContext()->setUser( $u );
610
611 // Please reset throttle for successful logins, thanks!
612 if ( $throttleCount ) {
613 self::clearLoginThrottle( $this->mUsername );
614 }
615
616 if ( $isAutoCreated ) {
617 // Must be run after $wgUser is set, for correct new user log
618 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
619 }
620
621 $retval = self::SUCCESS;
622 }
623 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $retval ) );
624 return $retval;
625 }
626
627 /**
628 * Increment the login attempt throttle hit count for the (username,current IP)
629 * tuple unless the throttle was already reached.
630 * @param $username string The user name
631 * @return Bool|Integer The integer hit count or True if it is already at the limit
632 */
633 public static function incLoginThrottle( $username ) {
634 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
635 $username = trim( $username ); // sanity
636
637 $throttleCount = 0;
638 if ( is_array( $wgPasswordAttemptThrottle ) ) {
639 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
640 $count = $wgPasswordAttemptThrottle['count'];
641 $period = $wgPasswordAttemptThrottle['seconds'];
642
643 $throttleCount = $wgMemc->get( $throttleKey );
644 if ( !$throttleCount ) {
645 $wgMemc->add( $throttleKey, 1, $period ); // start counter
646 } elseif ( $throttleCount < $count ) {
647 $wgMemc->incr( $throttleKey );
648 } elseif ( $throttleCount >= $count ) {
649 return true;
650 }
651 }
652
653 return $throttleCount;
654 }
655
656 /**
657 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
658 * @param $username string The user name
659 * @return void
660 */
661 public static function clearLoginThrottle( $username ) {
662 global $wgMemc, $wgRequest;
663 $username = trim( $username ); // sanity
664
665 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
666 $wgMemc->delete( $throttleKey );
667 }
668
669 /**
670 * Attempt to automatically create a user on login. Only succeeds if there
671 * is an external authentication method which allows it.
672 *
673 * @param $user User
674 *
675 * @return integer Status code
676 */
677 function attemptAutoCreate( $user ) {
678 global $wgAuth, $wgAutocreatePolicy;
679
680 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
681 wfDebug( __METHOD__ . ": user is blocked from account creation\n" );
682 return self::CREATE_BLOCKED;
683 }
684
685 /**
686 * If the external authentication plugin allows it, automatically cre-
687 * ate a new account for users that are externally defined but have not
688 * yet logged in.
689 */
690 if ( $this->mExtUser ) {
691 # mExtUser is neither null nor false, so use the new ExternalAuth
692 # system.
693 if ( $wgAutocreatePolicy == 'never' ) {
694 return self::NOT_EXISTS;
695 }
696 if ( !$this->mExtUser->authenticate( $this->mPassword ) ) {
697 return self::WRONG_PLUGIN_PASS;
698 }
699 } else {
700 # Old AuthPlugin.
701 if ( !$wgAuth->autoCreate() ) {
702 return self::NOT_EXISTS;
703 }
704 if ( !$wgAuth->userExists( $user->getName() ) ) {
705 wfDebug( __METHOD__ . ": user does not exist\n" );
706 return self::NOT_EXISTS;
707 }
708 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
709 wfDebug( __METHOD__ . ": \$wgAuth->authenticate() returned false, aborting\n" );
710 return self::WRONG_PLUGIN_PASS;
711 }
712 }
713
714 $abortError = '';
715 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
716 // Hook point to add extra creation throttles and blocks
717 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
718 $this->mAbortLoginErrorMsg = $abortError;
719 return self::ABORTED;
720 }
721
722 wfDebug( __METHOD__ . ": creating account\n" );
723 $this->initUser( $user, true );
724 return self::SUCCESS;
725 }
726
727 function processLogin() {
728 global $wgMemc, $wgLang;
729
730 switch ( $this->authenticateUserData() ) {
731 case self::SUCCESS:
732 # We've verified now, update the real record
733 $user = $this->getUser();
734 if( (bool)$this->mRemember != (bool)$user->getOption( 'rememberpassword' ) ) {
735 $user->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
736 $user->saveSettings();
737 } else {
738 $user->invalidateCache();
739 }
740 $user->setCookies();
741 self::clearLoginToken();
742
743 // Reset the throttle
744 $request = $this->getRequest();
745 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername ) );
746 $wgMemc->delete( $key );
747
748 if( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
749 /* Replace the language object to provide user interface in
750 * correct language immediately on this first page load.
751 */
752 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
753 $userLang = Language::factory( $code );
754 $wgLang = $userLang;
755 $this->getContext()->setLanguage( $userLang );
756 return $this->successfulLogin();
757 } else {
758 return $this->cookieRedirectCheck( 'login' );
759 }
760 break;
761
762 case self::NEED_TOKEN:
763 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
764 break;
765 case self::WRONG_TOKEN:
766 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
767 break;
768 case self::NO_NAME:
769 case self::ILLEGAL:
770 $this->mainLoginForm( $this->msg( 'noname' )->text() );
771 break;
772 case self::WRONG_PLUGIN_PASS:
773 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
774 break;
775 case self::NOT_EXISTS:
776 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
777 $this->mainLoginForm( $this->msg( 'nosuchuser',
778 wfEscapeWikiText( $this->mUsername ) )->parse() );
779 } else {
780 $this->mainLoginForm( $this->msg( 'nosuchusershort',
781 wfEscapeWikiText( $this->mUsername ) )->text() );
782 }
783 break;
784 case self::WRONG_PASS:
785 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
786 break;
787 case self::EMPTY_PASS:
788 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
789 break;
790 case self::RESET_PASS:
791 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
792 break;
793 case self::CREATE_BLOCKED:
794 $this->userBlockedMessage( $this->getUser()->mBlock );
795 break;
796 case self::THROTTLED:
797 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
798 break;
799 case self::USER_BLOCKED:
800 $this->mainLoginForm( $this->msg( 'login-userblocked',
801 $this->mUsername )->escaped() );
802 break;
803 case self::ABORTED:
804 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg )->text() );
805 break;
806 default:
807 throw new MWException( 'Unhandled case value' );
808 }
809 }
810
811 function resetLoginForm( $error ) {
812 $this->getOutput()->addHTML( Xml::element('p', array( 'class' => 'error' ), $error ) );
813 $reset = new SpecialChangePassword();
814 $reset->setContext( $this );
815 $reset->execute( null );
816 }
817
818 /**
819 * @param $u User object
820 * @param $throttle Boolean
821 * @param $emailTitle String: message name of email title
822 * @param $emailText String: message name of email text
823 * @return Status object
824 */
825 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
826 global $wgServer, $wgScript, $wgNewPasswordExpiry;
827
828 if ( $u->getEmail() == '' ) {
829 return Status::newFatal( 'noemail', $u->getName() );
830 }
831 $ip = $this->getRequest()->getIP();
832 if( !$ip ) {
833 return Status::newFatal( 'badipaddress' );
834 }
835
836 $currentUser = $this->getUser();
837 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
838
839 $np = $u->randomPassword();
840 $u->setNewpassword( $np, $throttle );
841 $u->saveSettings();
842 $userLanguage = $u->getOption( 'language' );
843 $m = $this->msg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript,
844 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
845 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
846
847 return $result;
848 }
849
850
851 /**
852 * Run any hooks registered for logins, then HTTP redirect to
853 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
854 * nice message here, but that's really not as useful as just being sent to
855 * wherever you logged in from. It should be clear that the action was
856 * successful, given the lack of error messages plus the appearance of your
857 * name in the upper right.
858 *
859 * @private
860 */
861 function successfulLogin() {
862 # Run any hooks; display injected HTML if any, else redirect
863 $currentUser = $this->getUser();
864 $injected_html = '';
865 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
866
867 if( $injected_html !== '' ) {
868 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
869 } else {
870 $titleObj = Title::newFromText( $this->mReturnTo );
871 if ( !$titleObj instanceof Title ) {
872 $titleObj = Title::newMainPage();
873 }
874 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery );
875 global $wgSecureLogin;
876 if( $wgSecureLogin && !$this->mStickHTTPS ) {
877 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
878 }
879 $this->getOutput()->redirect( $redirectUrl );
880 }
881 }
882
883 /**
884 * Run any hooks registered for logins, then display a message welcoming
885 * the user.
886 *
887 * @private
888 */
889 function successfulCreation() {
890 # Run any hooks; display injected HTML
891 $currentUser = $this->getUser();
892 $injected_html = '';
893 $welcome_creation_msg = 'welcomecreation';
894
895 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
896
897 /**
898 * Let any extensions change what message is shown.
899 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
900 * @since 1.18
901 */
902 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
903
904 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
905 }
906
907 /**
908 * Display a "login successful" page.
909 */
910 private function displaySuccessfulLogin( $msgname, $injected_html ) {
911 $out = $this->getOutput();
912 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
913 if( $msgname ){
914 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
915 }
916
917 $out->addHTML( $injected_html );
918
919 if ( !empty( $this->mReturnTo ) ) {
920 $out->returnToMain( null, $this->mReturnTo, $this->mReturnToQuery );
921 } else {
922 $out->returnToMain( null );
923 }
924 }
925
926 /**
927 * Output a message that informs the user that they cannot create an account because
928 * there is a block on them or their IP which prevents account creation. Note that
929 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
930 * setting on blocks (bug 13611).
931 * @param $block Block the block causing this error
932 */
933 function userBlockedMessage( Block $block ) {
934 # Let's be nice about this, it's likely that this feature will be used
935 # for blocking large numbers of innocent people, e.g. range blocks on
936 # schools. Don't blame it on the user. There's a small chance that it
937 # really is the user's fault, i.e. the username is blocked and they
938 # haven't bothered to log out before trying to create an account to
939 # evade it, but we'll leave that to their guilty conscience to figure
940 # out.
941
942 $out = $this->getOutput();
943 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
944
945 $block_reason = $block->mReason;
946 if ( strval( $block_reason ) === '' ) {
947 $block_reason = $this->msg( 'blockednoreason' )->text();
948 }
949
950 $out->addWikiMsg(
951 'cantcreateaccount-text',
952 $block->getTarget(),
953 $block_reason,
954 $block->getByName()
955 );
956
957 $out->returnToMain( false );
958 }
959
960 /**
961 * @private
962 */
963 function mainLoginForm( $msg, $msgtype = 'error' ) {
964 global $wgEnableEmail, $wgEnableUserEmail;
965 global $wgHiddenPrefs, $wgLoginLanguageSelector;
966 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
967 global $wgSecureLogin, $wgPasswordResetRoutes;
968
969 $titleObj = $this->getTitle();
970 $user = $this->getUser();
971
972 if ( $this->mType == 'signup' ) {
973 // Block signup here if in readonly. Keeps user from
974 // going through the process (filling out data, etc)
975 // and being informed later.
976 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
977 if ( count( $permErrors ) ) {
978 throw new PermissionsError( 'createaccount', $permErrors );
979 } elseif ( $user->isBlockedFromCreateAccount() ) {
980 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
981 return;
982 } elseif ( wfReadOnly() ) {
983 throw new ReadOnlyError;
984 }
985 }
986
987 if ( $this->mUsername == '' ) {
988 if ( $user->isLoggedIn() ) {
989 $this->mUsername = $user->getName();
990 } else {
991 $this->mUsername = $this->getRequest()->getCookie( 'UserName' );
992 }
993 }
994
995 if ( $this->mType == 'signup' ) {
996 $template = new UsercreateTemplate();
997 $q = 'action=submitlogin&type=signup';
998 $linkq = 'type=login';
999 $linkmsg = 'gotaccount';
1000 } else {
1001 $template = new UserloginTemplate();
1002 $q = 'action=submitlogin&type=login';
1003 $linkq = 'type=signup';
1004 $linkmsg = 'nologin';
1005 }
1006
1007 if ( !empty( $this->mReturnTo ) ) {
1008 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
1009 if ( !empty( $this->mReturnToQuery ) ) {
1010 $returnto .= '&returntoquery=' .
1011 wfUrlencode( $this->mReturnToQuery );
1012 }
1013 $q .= $returnto;
1014 $linkq .= $returnto;
1015 }
1016
1017 # Don't show a "create account" link if the user can't
1018 if( $this->showCreateOrLoginLink( $user ) ) {
1019 # Pass any language selection on to the mode switch link
1020 if( $wgLoginLanguageSelector && $this->mLanguage ) {
1021 $linkq .= '&uselang=' . $this->mLanguage;
1022 }
1023 $link = Html::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1024 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1025
1026 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1027 } else {
1028 $template->set( 'link', '' );
1029 }
1030
1031 $resetLink = $this->mType == 'signup'
1032 ? null
1033 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1034
1035 $template->set( 'header', '' );
1036 $template->set( 'name', $this->mUsername );
1037 $template->set( 'password', $this->mPassword );
1038 $template->set( 'retype', $this->mRetype );
1039 $template->set( 'email', $this->mEmail );
1040 $template->set( 'realname', $this->mRealName );
1041 $template->set( 'domain', $this->mDomain );
1042 $template->set( 'reason', $this->mReason );
1043
1044 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1045 $template->set( 'message', $msg );
1046 $template->set( 'messagetype', $msgtype );
1047 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1048 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1049 $template->set( 'useemail', $wgEnableEmail );
1050 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1051 $template->set( 'emailothers', $wgEnableUserEmail );
1052 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1053 $template->set( 'resetlink', $resetLink );
1054 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1055 $template->set( 'usereason', $user->isLoggedIn() );
1056 $template->set( 'remember', $user->getOption( 'rememberpassword' ) || $this->mRemember );
1057 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1058 $template->set( 'stickHTTPS', $this->mStickHTTPS );
1059
1060 if ( $this->mType == 'signup' ) {
1061 if ( !self::getCreateaccountToken() ) {
1062 self::setCreateaccountToken();
1063 }
1064 $template->set( 'token', self::getCreateaccountToken() );
1065 } else {
1066 if ( !self::getLoginToken() ) {
1067 self::setLoginToken();
1068 }
1069 $template->set( 'token', self::getLoginToken() );
1070 }
1071
1072 # Prepare language selection links as needed
1073 if( $wgLoginLanguageSelector ) {
1074 $template->set( 'languages', $this->makeLanguageSelector() );
1075 if( $this->mLanguage ) {
1076 $template->set( 'uselang', $this->mLanguage );
1077 }
1078 }
1079
1080 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1081 // Ditto for signupend
1082 $usingHTTPS = WebRequest::detectProtocol() == 'https';
1083 $loginendHTTPS = $this->msg( 'loginend-https' );
1084 $signupendHTTPS = $this->msg( 'signupend-https' );
1085 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1086 $template->set( 'loginend', $loginendHTTPS->parse() );
1087 } else {
1088 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1089 }
1090 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1091 $template->set( 'signupend', $signupendHTTPS->parse() );
1092 } else {
1093 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1094 }
1095
1096 // Give authentication and captcha plugins a chance to modify the form
1097 $wgAuth->modifyUITemplate( $template, $this->mType );
1098 if ( $this->mType == 'signup' ) {
1099 wfRunHooks( 'UserCreateForm', array( &$template ) );
1100 } else {
1101 wfRunHooks( 'UserLoginForm', array( &$template ) );
1102 }
1103
1104 $out = $this->getOutput();
1105 $out->disallowUserJs(); // just in case...
1106 $out->addTemplate( $template );
1107 }
1108
1109 /**
1110 * @private
1111 *
1112 * @param $user User
1113 *
1114 * @return Boolean
1115 */
1116 function showCreateOrLoginLink( &$user ) {
1117 if( $this->mType == 'signup' ) {
1118 return true;
1119 } elseif( $user->isAllowed( 'createaccount' ) ) {
1120 return true;
1121 } else {
1122 return false;
1123 }
1124 }
1125
1126 /**
1127 * Check if a session cookie is present.
1128 *
1129 * This will not pick up a cookie set during _this_ request, but is meant
1130 * to ensure that the client is returning the cookie which was set on a
1131 * previous pass through the system.
1132 *
1133 * @private
1134 */
1135 function hasSessionCookie() {
1136 global $wgDisableCookieCheck;
1137 return $wgDisableCookieCheck ? true : $this->getRequest()->checkSessionCookie();
1138 }
1139
1140 /**
1141 * Get the login token from the current session
1142 */
1143 public static function getLoginToken() {
1144 global $wgRequest;
1145 return $wgRequest->getSessionData( 'wsLoginToken' );
1146 }
1147
1148 /**
1149 * Randomly generate a new login token and attach it to the current session
1150 */
1151 public static function setLoginToken() {
1152 global $wgRequest;
1153 // Use User::generateToken() instead of $user->editToken()
1154 // because the latter reuses $_SESSION['wsEditToken']
1155 $wgRequest->setSessionData( 'wsLoginToken', User::generateToken() );
1156 }
1157
1158 /**
1159 * Remove any login token attached to the current session
1160 */
1161 public static function clearLoginToken() {
1162 global $wgRequest;
1163 $wgRequest->setSessionData( 'wsLoginToken', null );
1164 }
1165
1166 /**
1167 * Get the createaccount token from the current session
1168 */
1169 public static function getCreateaccountToken() {
1170 global $wgRequest;
1171 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1172 }
1173
1174 /**
1175 * Randomly generate a new createaccount token and attach it to the current session
1176 */
1177 public static function setCreateaccountToken() {
1178 global $wgRequest;
1179 $wgRequest->setSessionData( 'wsCreateaccountToken', User::generateToken() );
1180 }
1181
1182 /**
1183 * Remove any createaccount token attached to the current session
1184 */
1185 public static function clearCreateaccountToken() {
1186 global $wgRequest;
1187 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1188 }
1189
1190 /**
1191 * @private
1192 */
1193 function cookieRedirectCheck( $type ) {
1194 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
1195 $query = array( 'wpCookieCheck' => $type );
1196 if ( $this->mReturnTo ) {
1197 $query['returnto'] = $this->mReturnTo;
1198 }
1199 $check = $titleObj->getFullURL( $query );
1200
1201 return $this->getOutput()->redirect( $check );
1202 }
1203
1204 /**
1205 * @private
1206 */
1207 function onCookieRedirectCheck( $type ) {
1208 if ( !$this->hasSessionCookie() ) {
1209 if ( $type == 'new' ) {
1210 return $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1211 } elseif ( $type == 'login' ) {
1212 return $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1213 } else {
1214 # shouldn't happen
1215 return $this->mainLoginForm( $this->msg( 'error' )->text() );
1216 }
1217 } else {
1218 return $this->successfulLogin();
1219 }
1220 }
1221
1222 /**
1223 * @private
1224 */
1225 function throttleHit( $limit ) {
1226 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1227 }
1228
1229 /**
1230 * Produce a bar of links which allow the user to select another language
1231 * during login/registration but retain "returnto"
1232 *
1233 * @return string
1234 */
1235 function makeLanguageSelector() {
1236 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1237 if( !$msg->isBlank() ) {
1238 $langs = explode( "\n", $msg->text() );
1239 $links = array();
1240 foreach( $langs as $lang ) {
1241 $lang = trim( $lang, '* ' );
1242 $parts = explode( '|', $lang );
1243 if ( count( $parts ) >= 2 ) {
1244 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1245 }
1246 }
1247 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1248 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1249 } else {
1250 return '';
1251 }
1252 }
1253
1254 /**
1255 * Create a language selector link for a particular language
1256 * Links back to this page preserving type and returnto
1257 *
1258 * @param $text Link text
1259 * @param $lang Language code
1260 */
1261 function makeLanguageSelectorLink( $text, $lang ) {
1262 $attr = array( 'uselang' => $lang );
1263 if( $this->mType == 'signup' ) {
1264 $attr['type'] = 'signup';
1265 }
1266 if( $this->mReturnTo ) {
1267 $attr['returnto'] = $this->mReturnTo;
1268 }
1269 return Linker::linkKnown(
1270 $this->getTitle(),
1271 htmlspecialchars( $text ),
1272 array(),
1273 $attr
1274 );
1275 }
1276 }