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