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