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