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