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