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