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