Revert r103467, r106446 (bug 24464: calling LoginAuthenticateAudit hook more often)
[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 return self::NO_NAME;
481 }
482
483 // We require a login token to prevent login CSRF
484 // Handle part of this before incrementing the throttle so
485 // token-less login attempts don't count towards the throttle
486 // but wrong-token attempts do.
487
488 // If the user doesn't have a login token yet, set one.
489 if ( !self::getLoginToken() ) {
490 self::setLoginToken();
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 return self::NEED_TOKEN;
496 }
497
498 $throttleCount = self::incLoginThrottle( $this->mUsername );
499 if ( $throttleCount === true ) {
500 return self::THROTTLED;
501 }
502
503 // Validate the login token
504 if ( $this->mToken !== self::getLoginToken() ) {
505 return self::WRONG_TOKEN;
506 }
507
508 // Load the current user now, and check to see if we're logging in as
509 // the same name. This is necessary because loading the current user
510 // (say by calling getName()) calls the UserLoadFromSession hook, which
511 // potentially creates the user in the database. Until we load $wgUser,
512 // checking for user existence using User::newFromName($name)->getId() below
513 // will effectively be using stale data.
514 if ( $this->getUser()->getName() === $this->mUsername ) {
515 wfDebug( __METHOD__ . ": already logged in as {$this->mUsername}\n" );
516 return self::SUCCESS;
517 }
518
519 $this->mExtUser = ExternalUser::newFromName( $this->mUsername );
520
521 # TODO: Allow some magic here for invalid external names, e.g., let the
522 # user choose a different wiki name.
523 $u = User::newFromName( $this->mUsername );
524 if( !( $u instanceof User ) || !User::isUsableName( $u->getName() ) ) {
525 return self::ILLEGAL;
526 }
527
528 $isAutoCreated = false;
529 if ( 0 == $u->getID() ) {
530 $status = $this->attemptAutoCreate( $u );
531 if ( $status !== self::SUCCESS ) {
532 return $status;
533 } else {
534 $isAutoCreated = true;
535 }
536 } else {
537 global $wgExternalAuthType, $wgAutocreatePolicy;
538 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
539 && is_object( $this->mExtUser )
540 && $this->mExtUser->authenticate( $this->mPassword ) ) {
541 # The external user and local user have the same name and
542 # password, so we assume they're the same.
543 $this->mExtUser->linkToLocal( $u->getID() );
544 }
545
546 $u->load();
547 }
548
549 // Give general extensions, such as a captcha, a chance to abort logins
550 $abort = self::ABORTED;
551 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword, &$abort, &$this->mAbortLoginErrorMsg ) ) ) {
552 return $abort;
553 }
554
555 global $wgBlockDisablesLogin;
556 if ( !$u->checkPassword( $this->mPassword ) ) {
557 if( $u->checkTemporaryPassword( $this->mPassword ) ) {
558 // The e-mailed temporary password should not be used for actu-
559 // al logins; that's a very sloppy habit, and insecure if an
560 // attacker has a few seconds to click "search" on someone's o-
561 // pen mail reader.
562 //
563 // Allow it to be used only to reset the password a single time
564 // to a new value, which won't be in the user's e-mail ar-
565 // chives.
566 //
567 // For backwards compatibility, we'll still recognize it at the
568 // login form to minimize surprises for people who have been
569 // logging in with a temporary password for some time.
570 //
571 // As a side-effect, we can authenticate the user's e-mail ad-
572 // dress if it's not already done, since the temporary password
573 // was sent via e-mail.
574 if( !$u->isEmailConfirmed() ) {
575 $u->confirmEmail();
576 $u->saveSettings();
577 }
578
579 // At this point we just return an appropriate code/ indicating
580 // that the UI should show a password reset form; bot inter-
581 // faces etc will probably just fail cleanly here.
582 $retval = self::RESET_PASS;
583 } else {
584 $retval = ( $this->mPassword == '' ) ? self::EMPTY_PASS : self::WRONG_PASS;
585 }
586 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
587 // If we've enabled it, make it so that a blocked user cannot login
588 $retval = self::USER_BLOCKED;
589 } else {
590 $wgAuth->updateUser( $u );
591 $wgUser = $u;
592 // This should set it for OutputPage and the Skin
593 // which is needed or the personal links will be
594 // wrong.
595 $this->getContext()->setUser( $u );
596
597 // Please reset throttle for successful logins, thanks!
598 if ( $throttleCount ) {
599 self::clearLoginThrottle( $this->mUsername );
600 }
601
602 if ( $isAutoCreated ) {
603 // Must be run after $wgUser is set, for correct new user log
604 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
605 }
606
607 $retval = self::SUCCESS;
608 }
609 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $retval ) );
610 return $retval;
611 }
612
613 /**
614 * Increment the login attempt throttle hit count for the (username,current IP)
615 * tuple unless the throttle was already reached.
616 * @param $username string The user name
617 * @return Bool|Integer The integer hit count or True if it is already at the limit
618 */
619 public static function incLoginThrottle( $username ) {
620 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
621 $username = trim( $username ); // sanity
622
623 $throttleCount = 0;
624 if ( is_array( $wgPasswordAttemptThrottle ) ) {
625 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
626 $count = $wgPasswordAttemptThrottle['count'];
627 $period = $wgPasswordAttemptThrottle['seconds'];
628
629 $throttleCount = $wgMemc->get( $throttleKey );
630 if ( !$throttleCount ) {
631 $wgMemc->add( $throttleKey, 1, $period ); // start counter
632 } elseif ( $throttleCount < $count ) {
633 $wgMemc->incr( $throttleKey );
634 } elseif ( $throttleCount >= $count ) {
635 return true;
636 }
637 }
638
639 return $throttleCount;
640 }
641
642 /**
643 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
644 * @param $username string The user name
645 * @return void
646 */
647 public static function clearLoginThrottle( $username ) {
648 global $wgMemc, $wgRequest;
649 $username = trim( $username ); // sanity
650
651 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
652 $wgMemc->delete( $throttleKey );
653 }
654
655 /**
656 * Attempt to automatically create a user on login. Only succeeds if there
657 * is an external authentication method which allows it.
658 *
659 * @param $user User
660 *
661 * @return integer Status code
662 */
663 function attemptAutoCreate( $user ) {
664 global $wgAuth, $wgAutocreatePolicy;
665
666 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
667 wfDebug( __METHOD__ . ": user is blocked from account creation\n" );
668 return self::CREATE_BLOCKED;
669 }
670
671 /**
672 * If the external authentication plugin allows it, automatically cre-
673 * ate a new account for users that are externally defined but have not
674 * yet logged in.
675 */
676 if ( $this->mExtUser ) {
677 # mExtUser is neither null nor false, so use the new ExternalAuth
678 # system.
679 if ( $wgAutocreatePolicy == 'never' ) {
680 return self::NOT_EXISTS;
681 }
682 if ( !$this->mExtUser->authenticate( $this->mPassword ) ) {
683 return self::WRONG_PLUGIN_PASS;
684 }
685 } else {
686 # Old AuthPlugin.
687 if ( !$wgAuth->autoCreate() ) {
688 return self::NOT_EXISTS;
689 }
690 if ( !$wgAuth->userExists( $user->getName() ) ) {
691 wfDebug( __METHOD__ . ": user does not exist\n" );
692 return self::NOT_EXISTS;
693 }
694 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
695 wfDebug( __METHOD__ . ": \$wgAuth->authenticate() returned false, aborting\n" );
696 return self::WRONG_PLUGIN_PASS;
697 }
698 }
699
700 $abortError = '';
701 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
702 // Hook point to add extra creation throttles and blocks
703 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
704 $this->mAbortLoginErrorMsg = $abortError;
705 return self::ABORTED;
706 }
707
708 wfDebug( __METHOD__ . ": creating account\n" );
709 $this->initUser( $user, true );
710 return self::SUCCESS;
711 }
712
713 function processLogin() {
714 global $wgMemc, $wgLang;
715
716 switch ( $this->authenticateUserData() ) {
717 case self::SUCCESS:
718 # We've verified now, update the real record
719 $user = $this->getUser();
720 if( (bool)$this->mRemember != (bool)$user->getOption( 'rememberpassword' ) ) {
721 $user->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
722 $user->saveSettings();
723 } else {
724 $user->invalidateCache();
725 }
726 $user->setCookies();
727 self::clearLoginToken();
728
729 // Reset the throttle
730 $request = $this->getRequest();
731 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername ) );
732 $wgMemc->delete( $key );
733
734 if( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
735 /* Replace the language object to provide user interface in
736 * correct language immediately on this first page load.
737 */
738 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
739 $userLang = Language::factory( $code );
740 $wgLang = $userLang;
741 $this->getContext()->setLanguage( $userLang );
742 return $this->successfulLogin();
743 } else {
744 return $this->cookieRedirectCheck( 'login' );
745 }
746 break;
747
748 case self::NEED_TOKEN:
749 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
750 break;
751 case self::WRONG_TOKEN:
752 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
753 break;
754 case self::NO_NAME:
755 case self::ILLEGAL:
756 $this->mainLoginForm( $this->msg( 'noname' )->text() );
757 break;
758 case self::WRONG_PLUGIN_PASS:
759 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
760 break;
761 case self::NOT_EXISTS:
762 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
763 $this->mainLoginForm( $this->msg( 'nosuchuser',
764 wfEscapeWikiText( $this->mUsername ) )->parse() );
765 } else {
766 $this->mainLoginForm( $this->msg( 'nosuchusershort',
767 wfEscapeWikiText( $this->mUsername ) )->text() );
768 }
769 break;
770 case self::WRONG_PASS:
771 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
772 break;
773 case self::EMPTY_PASS:
774 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
775 break;
776 case self::RESET_PASS:
777 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
778 break;
779 case self::CREATE_BLOCKED:
780 $this->userBlockedMessage( $this->getUser()->mBlock );
781 break;
782 case self::THROTTLED:
783 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
784 break;
785 case self::USER_BLOCKED:
786 $this->mainLoginForm( $this->msg( 'login-userblocked',
787 $this->mUsername )->escaped() );
788 break;
789 case self::ABORTED:
790 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg )->text() );
791 break;
792 default:
793 throw new MWException( 'Unhandled case value' );
794 }
795 }
796
797 function resetLoginForm( $error ) {
798 $this->getOutput()->addHTML( Xml::element('p', array( 'class' => 'error' ), $error ) );
799 $reset = new SpecialChangePassword();
800 $reset->setContext( $this );
801 $reset->execute( null );
802 }
803
804 /**
805 * @param $u User object
806 * @param $throttle Boolean
807 * @param $emailTitle String: message name of email title
808 * @param $emailText String: message name of email text
809 * @return Status object
810 */
811 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
812 global $wgServer, $wgScript, $wgNewPasswordExpiry;
813
814 if ( $u->getEmail() == '' ) {
815 return Status::newFatal( 'noemail', $u->getName() );
816 }
817 $ip = $this->getRequest()->getIP();
818 if( !$ip ) {
819 return Status::newFatal( 'badipaddress' );
820 }
821
822 $currentUser = $this->getUser();
823 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
824
825 $np = $u->randomPassword();
826 $u->setNewpassword( $np, $throttle );
827 $u->saveSettings();
828 $userLanguage = $u->getOption( 'language' );
829 $m = $this->msg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript,
830 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
831 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
832
833 return $result;
834 }
835
836
837 /**
838 * Run any hooks registered for logins, then HTTP redirect to
839 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
840 * nice message here, but that's really not as useful as just being sent to
841 * wherever you logged in from. It should be clear that the action was
842 * successful, given the lack of error messages plus the appearance of your
843 * name in the upper right.
844 *
845 * @private
846 */
847 function successfulLogin() {
848 # Run any hooks; display injected HTML if any, else redirect
849 $currentUser = $this->getUser();
850 $injected_html = '';
851 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
852
853 if( $injected_html !== '' ) {
854 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
855 } else {
856 $titleObj = Title::newFromText( $this->mReturnTo );
857 if ( !$titleObj instanceof Title ) {
858 $titleObj = Title::newMainPage();
859 }
860 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery );
861 global $wgSecureLogin;
862 if( $wgSecureLogin && !$this->mStickHTTPS ) {
863 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
864 }
865 $this->getOutput()->redirect( $redirectUrl );
866 }
867 }
868
869 /**
870 * Run any hooks registered for logins, then display a message welcoming
871 * the user.
872 *
873 * @private
874 */
875 function successfulCreation() {
876 # Run any hooks; display injected HTML
877 $currentUser = $this->getUser();
878 $injected_html = '';
879 $welcome_creation_msg = 'welcomecreation';
880
881 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
882
883 /**
884 * Let any extensions change what message is shown.
885 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
886 * @since 1.18
887 */
888 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
889
890 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
891 }
892
893 /**
894 * Display a "login successful" page.
895 */
896 private function displaySuccessfulLogin( $msgname, $injected_html ) {
897 $out = $this->getOutput();
898 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
899 if( $msgname ){
900 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
901 }
902
903 $out->addHTML( $injected_html );
904
905 if ( !empty( $this->mReturnTo ) ) {
906 $out->returnToMain( null, $this->mReturnTo, $this->mReturnToQuery );
907 } else {
908 $out->returnToMain( null );
909 }
910 }
911
912 /**
913 * Output a message that informs the user that they cannot create an account because
914 * there is a block on them or their IP which prevents account creation. Note that
915 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
916 * setting on blocks (bug 13611).
917 * @param $block Block the block causing this error
918 */
919 function userBlockedMessage( Block $block ) {
920 # Let's be nice about this, it's likely that this feature will be used
921 # for blocking large numbers of innocent people, e.g. range blocks on
922 # schools. Don't blame it on the user. There's a small chance that it
923 # really is the user's fault, i.e. the username is blocked and they
924 # haven't bothered to log out before trying to create an account to
925 # evade it, but we'll leave that to their guilty conscience to figure
926 # out.
927
928 $out = $this->getOutput();
929 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
930
931 $block_reason = $block->mReason;
932 if ( strval( $block_reason ) === '' ) {
933 $block_reason = $this->msg( 'blockednoreason' )->text();
934 }
935
936 $out->addWikiMsg(
937 'cantcreateaccount-text',
938 $block->getTarget(),
939 $block_reason,
940 $block->getByName()
941 );
942
943 $out->returnToMain( false );
944 }
945
946 /**
947 * @private
948 */
949 function mainLoginForm( $msg, $msgtype = 'error' ) {
950 global $wgEnableEmail, $wgEnableUserEmail;
951 global $wgHiddenPrefs, $wgLoginLanguageSelector;
952 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
953 global $wgSecureLogin, $wgPasswordResetRoutes;
954
955 $titleObj = $this->getTitle();
956 $user = $this->getUser();
957
958 if ( $this->mType == 'signup' ) {
959 // Block signup here if in readonly. Keeps user from
960 // going through the process (filling out data, etc)
961 // and being informed later.
962 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
963 if ( count( $permErrors ) ) {
964 throw new PermissionsError( 'createaccount', $permErrors );
965 } elseif ( $user->isBlockedFromCreateAccount() ) {
966 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
967 return;
968 } elseif ( wfReadOnly() ) {
969 throw new ReadOnlyError;
970 }
971 }
972
973 if ( $this->mUsername == '' ) {
974 if ( $user->isLoggedIn() ) {
975 $this->mUsername = $user->getName();
976 } else {
977 $this->mUsername = $this->getRequest()->getCookie( 'UserName' );
978 }
979 }
980
981 if ( $this->mType == 'signup' ) {
982 $template = new UsercreateTemplate();
983 $q = 'action=submitlogin&type=signup';
984 $linkq = 'type=login';
985 $linkmsg = 'gotaccount';
986 } else {
987 $template = new UserloginTemplate();
988 $q = 'action=submitlogin&type=login';
989 $linkq = 'type=signup';
990 $linkmsg = 'nologin';
991 }
992
993 if ( !empty( $this->mReturnTo ) ) {
994 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
995 if ( !empty( $this->mReturnToQuery ) ) {
996 $returnto .= '&returntoquery=' .
997 wfUrlencode( $this->mReturnToQuery );
998 }
999 $q .= $returnto;
1000 $linkq .= $returnto;
1001 }
1002
1003 # Don't show a "create account" link if the user can't
1004 if( $this->showCreateOrLoginLink( $user ) ) {
1005 # Pass any language selection on to the mode switch link
1006 if( $wgLoginLanguageSelector && $this->mLanguage ) {
1007 $linkq .= '&uselang=' . $this->mLanguage;
1008 }
1009 $link = Html::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1010 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1011
1012 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1013 } else {
1014 $template->set( 'link', '' );
1015 }
1016
1017 $resetLink = $this->mType == 'signup'
1018 ? null
1019 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1020
1021 $template->set( 'header', '' );
1022 $template->set( 'name', $this->mUsername );
1023 $template->set( 'password', $this->mPassword );
1024 $template->set( 'retype', $this->mRetype );
1025 $template->set( 'email', $this->mEmail );
1026 $template->set( 'realname', $this->mRealName );
1027 $template->set( 'domain', $this->mDomain );
1028 $template->set( 'reason', $this->mReason );
1029
1030 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1031 $template->set( 'message', $msg );
1032 $template->set( 'messagetype', $msgtype );
1033 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1034 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1035 $template->set( 'useemail', $wgEnableEmail );
1036 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1037 $template->set( 'emailothers', $wgEnableUserEmail );
1038 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1039 $template->set( 'resetlink', $resetLink );
1040 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1041 $template->set( 'usereason', $user->isLoggedIn() );
1042 $template->set( 'remember', $user->getOption( 'rememberpassword' ) || $this->mRemember );
1043 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1044 $template->set( 'stickHTTPS', $this->mStickHTTPS );
1045
1046 if ( $this->mType == 'signup' ) {
1047 if ( !self::getCreateaccountToken() ) {
1048 self::setCreateaccountToken();
1049 }
1050 $template->set( 'token', self::getCreateaccountToken() );
1051 } else {
1052 if ( !self::getLoginToken() ) {
1053 self::setLoginToken();
1054 }
1055 $template->set( 'token', self::getLoginToken() );
1056 }
1057
1058 # Prepare language selection links as needed
1059 if( $wgLoginLanguageSelector ) {
1060 $template->set( 'languages', $this->makeLanguageSelector() );
1061 if( $this->mLanguage ) {
1062 $template->set( 'uselang', $this->mLanguage );
1063 }
1064 }
1065
1066 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1067 // Ditto for signupend
1068 $usingHTTPS = WebRequest::detectProtocol() == 'https';
1069 $loginendHTTPS = $this->msg( 'loginend-https' );
1070 $signupendHTTPS = $this->msg( 'signupend-https' );
1071 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1072 $template->set( 'loginend', $loginendHTTPS->parse() );
1073 } else {
1074 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1075 }
1076 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1077 $template->set( 'signupend', $signupendHTTPS->parse() );
1078 } else {
1079 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1080 }
1081
1082 // Give authentication and captcha plugins a chance to modify the form
1083 $wgAuth->modifyUITemplate( $template, $this->mType );
1084 if ( $this->mType == 'signup' ) {
1085 wfRunHooks( 'UserCreateForm', array( &$template ) );
1086 } else {
1087 wfRunHooks( 'UserLoginForm', array( &$template ) );
1088 }
1089
1090 $out = $this->getOutput();
1091 $out->disallowUserJs(); // just in case...
1092 $out->addTemplate( $template );
1093 }
1094
1095 /**
1096 * @private
1097 *
1098 * @param $user User
1099 *
1100 * @return Boolean
1101 */
1102 function showCreateOrLoginLink( &$user ) {
1103 if( $this->mType == 'signup' ) {
1104 return true;
1105 } elseif( $user->isAllowed( 'createaccount' ) ) {
1106 return true;
1107 } else {
1108 return false;
1109 }
1110 }
1111
1112 /**
1113 * Check if a session cookie is present.
1114 *
1115 * This will not pick up a cookie set during _this_ request, but is meant
1116 * to ensure that the client is returning the cookie which was set on a
1117 * previous pass through the system.
1118 *
1119 * @private
1120 */
1121 function hasSessionCookie() {
1122 global $wgDisableCookieCheck;
1123 return $wgDisableCookieCheck ? true : $this->getRequest()->checkSessionCookie();
1124 }
1125
1126 /**
1127 * Get the login token from the current session
1128 */
1129 public static function getLoginToken() {
1130 global $wgRequest;
1131 return $wgRequest->getSessionData( 'wsLoginToken' );
1132 }
1133
1134 /**
1135 * Randomly generate a new login token and attach it to the current session
1136 */
1137 public static function setLoginToken() {
1138 global $wgRequest;
1139 // Use User::generateToken() instead of $user->editToken()
1140 // because the latter reuses $_SESSION['wsEditToken']
1141 $wgRequest->setSessionData( 'wsLoginToken', User::generateToken() );
1142 }
1143
1144 /**
1145 * Remove any login token attached to the current session
1146 */
1147 public static function clearLoginToken() {
1148 global $wgRequest;
1149 $wgRequest->setSessionData( 'wsLoginToken', null );
1150 }
1151
1152 /**
1153 * Get the createaccount token from the current session
1154 */
1155 public static function getCreateaccountToken() {
1156 global $wgRequest;
1157 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1158 }
1159
1160 /**
1161 * Randomly generate a new createaccount token and attach it to the current session
1162 */
1163 public static function setCreateaccountToken() {
1164 global $wgRequest;
1165 $wgRequest->setSessionData( 'wsCreateaccountToken', User::generateToken() );
1166 }
1167
1168 /**
1169 * Remove any createaccount token attached to the current session
1170 */
1171 public static function clearCreateaccountToken() {
1172 global $wgRequest;
1173 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1174 }
1175
1176 /**
1177 * @private
1178 */
1179 function cookieRedirectCheck( $type ) {
1180 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
1181 $query = array( 'wpCookieCheck' => $type );
1182 if ( $this->mReturnTo ) {
1183 $query['returnto'] = $this->mReturnTo;
1184 }
1185 $check = $titleObj->getFullURL( $query );
1186
1187 return $this->getOutput()->redirect( $check );
1188 }
1189
1190 /**
1191 * @private
1192 */
1193 function onCookieRedirectCheck( $type ) {
1194 if ( !$this->hasSessionCookie() ) {
1195 if ( $type == 'new' ) {
1196 return $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1197 } elseif ( $type == 'login' ) {
1198 return $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1199 } else {
1200 # shouldn't happen
1201 return $this->mainLoginForm( $this->msg( 'error' )->text() );
1202 }
1203 } else {
1204 return $this->successfulLogin();
1205 }
1206 }
1207
1208 /**
1209 * @private
1210 */
1211 function throttleHit( $limit ) {
1212 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1213 }
1214
1215 /**
1216 * Produce a bar of links which allow the user to select another language
1217 * during login/registration but retain "returnto"
1218 *
1219 * @return string
1220 */
1221 function makeLanguageSelector() {
1222 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1223 if( !$msg->isBlank() ) {
1224 $langs = explode( "\n", $msg->text() );
1225 $links = array();
1226 foreach( $langs as $lang ) {
1227 $lang = trim( $lang, '* ' );
1228 $parts = explode( '|', $lang );
1229 if ( count( $parts ) >= 2 ) {
1230 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1231 }
1232 }
1233 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1234 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1235 } else {
1236 return '';
1237 }
1238 }
1239
1240 /**
1241 * Create a language selector link for a particular language
1242 * Links back to this page preserving type and returnto
1243 *
1244 * @param $text Link text
1245 * @param $lang Language code
1246 */
1247 function makeLanguageSelectorLink( $text, $lang ) {
1248 $attr = array( 'uselang' => $lang );
1249 if( $this->mType == 'signup' ) {
1250 $attr['type'] = 'signup';
1251 }
1252 if( $this->mReturnTo ) {
1253 $attr['returnto'] = $this->mReturnTo;
1254 }
1255 return Linker::linkKnown(
1256 $this->getTitle(),
1257 htmlspecialchars( $text ),
1258 array(),
1259 $attr
1260 );
1261 }
1262 }