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