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