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