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