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