Merge "Warn if stateful ParserOutput transforms are used"
[lhc/web/wiklou.git] / includes / specialpage / LoginSignupSpecialPage.php
1 <?php
2 /**
3 * Holds shared logic for login and account creation pages.
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 use MediaWiki\Auth\AuthenticationRequest;
25 use MediaWiki\Auth\AuthenticationResponse;
26 use MediaWiki\Auth\AuthManager;
27 use MediaWiki\Auth\Throttler;
28 use MediaWiki\Logger\LoggerFactory;
29 use MediaWiki\MediaWikiServices;
30 use MediaWiki\Session\SessionManager;
31 use Wikimedia\ScopedCallback;
32
33 /**
34 * Holds shared logic for login and account creation pages.
35 *
36 * @ingroup SpecialPage
37 */
38 abstract class LoginSignupSpecialPage extends AuthManagerSpecialPage {
39 protected $mReturnTo;
40 protected $mPosted;
41 protected $mAction;
42 protected $mLanguage;
43 protected $mReturnToQuery;
44 protected $mToken;
45 protected $mStickHTTPS;
46 protected $mFromHTTP;
47 protected $mEntryError = '';
48 protected $mEntryErrorType = 'error';
49
50 protected $mLoaded = false;
51 protected $mLoadedRequest = false;
52 protected $mSecureLoginUrl;
53
54 /** @var string */
55 protected $securityLevel;
56
57 /** @var bool True if the user if creating an account for someone else. Flag used for internal
58 * communication, only set at the very end. */
59 protected $proxyAccountCreation;
60 /** @var User FIXME another flag for passing data. */
61 protected $targetUser;
62
63 /** @var HTMLForm */
64 protected $authForm;
65
66 /** @var FakeAuthTemplate */
67 protected $fakeTemplate;
68
69 abstract protected function isSignup();
70
71 /**
72 * @param bool $direct True if the action was successful just now; false if that happened
73 * pre-redirection (so this handler was called already)
74 * @param StatusValue|null $extraMessages
75 * @return void
76 */
77 abstract protected function successfulAction( $direct = false, $extraMessages = null );
78
79 /**
80 * Logs to the authmanager-stats channel.
81 * @param bool $success
82 * @param string|null $status Error message key
83 */
84 abstract protected function logAuthResult( $success, $status = null );
85
86 public function __construct( $name ) {
87 global $wgUseMediaWikiUIEverywhere;
88 parent::__construct( $name );
89
90 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
91 $wgUseMediaWikiUIEverywhere = true;
92 }
93
94 protected function setRequest( array $data, $wasPosted = null ) {
95 parent::setRequest( $data, $wasPosted );
96 $this->mLoadedRequest = false;
97 }
98
99 /**
100 * Load basic request parameters for this Special page.
101 * @param string $subPage
102 */
103 private function loadRequestParameters( $subPage ) {
104 if ( $this->mLoadedRequest ) {
105 return;
106 }
107 $this->mLoadedRequest = true;
108 $request = $this->getRequest();
109
110 $this->mPosted = $request->wasPosted();
111 $this->mIsReturn = $subPage === 'return';
112 $this->mAction = $request->getVal( 'action' );
113 $this->mFromHTTP = $request->getBool( 'fromhttp', false )
114 || $request->getBool( 'wpFromhttp', false );
115 $this->mStickHTTPS = ( !$this->mFromHTTP && $request->getProtocol() === 'https' )
116 || $request->getBool( 'wpForceHttps', false );
117 $this->mLanguage = $request->getText( 'uselang' );
118 $this->mReturnTo = $request->getVal( 'returnto', '' );
119 $this->mReturnToQuery = $request->getVal( 'returntoquery', '' );
120 }
121
122 /**
123 * Load data from request.
124 * @private
125 * @param string $subPage Subpage of Special:Userlogin
126 */
127 protected function load( $subPage ) {
128 global $wgSecureLogin;
129
130 $this->loadRequestParameters( $subPage );
131 if ( $this->mLoaded ) {
132 return;
133 }
134 $this->mLoaded = true;
135 $request = $this->getRequest();
136
137 $securityLevel = $this->getRequest()->getText( 'force' );
138 if (
139 $securityLevel && AuthManager::singleton()->securitySensitiveOperationStatus(
140 $securityLevel ) === AuthManager::SEC_REAUTH
141 ) {
142 $this->securityLevel = $securityLevel;
143 }
144
145 $this->loadAuth( $subPage );
146
147 $this->mToken = $request->getVal( $this->getTokenName() );
148
149 // Show an error or warning passed on from a previous page
150 $entryError = $this->msg( $request->getVal( 'error', '' ) );
151 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
152 // bc: provide login link as a parameter for messages where the translation
153 // was not updated
154 $loginreqlink = $this->getLinkRenderer()->makeKnownLink(
155 $this->getPageTitle(),
156 $this->msg( 'loginreqlink' )->text(),
157 [],
158 [
159 'returnto' => $this->mReturnTo,
160 'returntoquery' => $this->mReturnToQuery,
161 'uselang' => $this->mLanguage ?: null,
162 'fromhttp' => $wgSecureLogin && $this->mFromHTTP ? '1' : null,
163 ]
164 );
165
166 // Only show valid error or warning messages.
167 if ( $entryError->exists()
168 && in_array( $entryError->getKey(), LoginHelper::getValidErrorMessages(), true )
169 ) {
170 $this->mEntryErrorType = 'error';
171 $this->mEntryError = $entryError->rawParams( $loginreqlink )->parse();
172
173 } elseif ( $entryWarning->exists()
174 && in_array( $entryWarning->getKey(), LoginHelper::getValidErrorMessages(), true )
175 ) {
176 $this->mEntryErrorType = 'warning';
177 $this->mEntryError = $entryWarning->rawParams( $loginreqlink )->parse();
178 }
179
180 # 1. When switching accounts, it sucks to get automatically logged out
181 # 2. Do not return to PasswordReset after a successful password change
182 # but goto Wiki start page (Main_Page) instead ( T35997 )
183 $returnToTitle = Title::newFromText( $this->mReturnTo );
184 if ( is_object( $returnToTitle )
185 && ( $returnToTitle->isSpecial( 'Userlogout' )
186 || $returnToTitle->isSpecial( 'PasswordReset' ) )
187 ) {
188 $this->mReturnTo = '';
189 $this->mReturnToQuery = '';
190 }
191 }
192
193 protected function getPreservedParams( $withToken = false ) {
194 global $wgSecureLogin;
195
196 $params = parent::getPreservedParams( $withToken );
197 $params += [
198 'returnto' => $this->mReturnTo ?: null,
199 'returntoquery' => $this->mReturnToQuery ?: null,
200 ];
201 if ( $wgSecureLogin && !$this->isSignup() ) {
202 $params['fromhttp'] = $this->mFromHTTP ? '1' : null;
203 }
204 return $params;
205 }
206
207 protected function beforeExecute( $subPage ) {
208 // finish initializing the class before processing the request - T135924
209 $this->loadRequestParameters( $subPage );
210 return parent::beforeExecute( $subPage );
211 }
212
213 /**
214 * @param string|null $subPage
215 */
216 public function execute( $subPage ) {
217 if ( $this->mPosted ) {
218 $time = microtime( true );
219 $profilingScope = new ScopedCallback( function () use ( $time ) {
220 $time = microtime( true ) - $time;
221 $statsd = MediaWikiServices::getInstance()->getStatsdDataFactory();
222 $statsd->timing( "timing.login.ui.{$this->authAction}", $time * 1000 );
223 } );
224 }
225
226 $authManager = AuthManager::singleton();
227 $session = SessionManager::getGlobalSession();
228
229 // Session data is used for various things in the authentication process, so we must make
230 // sure a session cookie or some equivalent mechanism is set.
231 $session->persist();
232
233 $this->load( $subPage );
234 $this->setHeaders();
235 $this->checkPermissions();
236
237 // Make sure the system configuration allows log in / sign up
238 if ( !$this->isSignup() && !$authManager->canAuthenticateNow() ) {
239 if ( !$session->canSetUser() ) {
240 throw new ErrorPageError( 'cannotloginnow-title', 'cannotloginnow-text', [
241 $session->getProvider()->describe( RequestContext::getMain()->getLanguage() )
242 ] );
243 }
244 throw new ErrorPageError( 'cannotlogin-title', 'cannotlogin-text' );
245 } elseif ( $this->isSignup() && !$authManager->canCreateAccounts() ) {
246 throw new ErrorPageError( 'cannotcreateaccount-title', 'cannotcreateaccount-text' );
247 }
248
249 /*
250 * In the case where the user is already logged in, and was redirected to
251 * the login form from a page that requires login, do not show the login
252 * page. The use case scenario for this is when a user opens a large number
253 * of tabs, is redirected to the login page on all of them, and then logs
254 * in on one, expecting all the others to work properly.
255 *
256 * However, do show the form if it was visited intentionally (no 'returnto'
257 * is present). People who often switch between several accounts have grown
258 * accustomed to this behavior.
259 *
260 * Also make an exception when force=<level> is set in the URL, which means the user must
261 * reauthenticate for security reasons.
262 */
263 if ( !$this->isSignup() && !$this->mPosted && !$this->securityLevel &&
264 ( $this->mReturnTo !== '' || $this->mReturnToQuery !== '' ) &&
265 $this->getUser()->isLoggedIn()
266 ) {
267 $this->successfulAction();
268 }
269
270 // If logging in and not on HTTPS, either redirect to it or offer a link.
271 global $wgSecureLogin;
272 if ( $this->getRequest()->getProtocol() !== 'https' ) {
273 $title = $this->getFullTitle();
274 $query = $this->getPreservedParams( false ) + [
275 'title' => null,
276 ( $this->mEntryErrorType === 'error' ? 'error'
277 : 'warning' ) => $this->mEntryError,
278 ] + $this->getRequest()->getQueryValues();
279 $url = $title->getFullURL( $query, false, PROTO_HTTPS );
280 if ( $wgSecureLogin && !$this->mFromHTTP &&
281 wfCanIPUseHTTPS( $this->getRequest()->getIP() )
282 ) {
283 // Avoid infinite redirect
284 $url = wfAppendQuery( $url, 'fromhttp=1' );
285 $this->getOutput()->redirect( $url );
286 // Since we only do this redir to change proto, always vary
287 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
288
289 return;
290 } else {
291 // A wiki without HTTPS login support should set $wgServer to
292 // http://somehost, in which case the secure URL generated
293 // above won't actually start with https://
294 if ( substr( $url, 0, 8 ) === 'https://' ) {
295 $this->mSecureLoginUrl = $url;
296 }
297 }
298 }
299
300 if ( !$this->isActionAllowed( $this->authAction ) ) {
301 // FIXME how do we explain this to the user? can we handle session loss better?
302 // messages used: authpage-cannot-login, authpage-cannot-login-continue,
303 // authpage-cannot-create, authpage-cannot-create-continue
304 $this->mainLoginForm( [], 'authpage-cannot-' . $this->authAction );
305 return;
306 }
307
308 if ( $this->canBypassForm( $button_name ) ) {
309 $this->setRequest( [], true );
310 $this->getRequest()->setVal( $this->getTokenName(), $this->getToken() );
311 if ( $button_name ) {
312 $this->getRequest()->setVal( $button_name, true );
313 }
314 }
315
316 $status = $this->trySubmit();
317
318 if ( !$status || !$status->isGood() ) {
319 $this->mainLoginForm( $this->authRequests, $status ? $status->getMessage() : '', 'error' );
320 return;
321 }
322
323 /** @var AuthenticationResponse $response */
324 $response = $status->getValue();
325
326 $returnToUrl = $this->getPageTitle( 'return' )
327 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS );
328 switch ( $response->status ) {
329 case AuthenticationResponse::PASS:
330 $this->logAuthResult( true );
331 $this->proxyAccountCreation = $this->isSignup() && !$this->getUser()->isAnon();
332 $this->targetUser = User::newFromName( $response->username );
333
334 if (
335 !$this->proxyAccountCreation
336 && $response->loginRequest
337 && $authManager->canAuthenticateNow()
338 ) {
339 // successful registration; log the user in instantly
340 $response2 = $authManager->beginAuthentication( [ $response->loginRequest ],
341 $returnToUrl );
342 if ( $response2->status !== AuthenticationResponse::PASS ) {
343 LoggerFactory::getInstance( 'login' )
344 ->error( 'Could not log in after account creation' );
345 $this->successfulAction( true, Status::newFatal( 'createacct-loginerror' ) );
346 break;
347 }
348 }
349
350 if ( !$this->proxyAccountCreation ) {
351 // Ensure that the context user is the same as the session user.
352 $this->setSessionUserForCurrentRequest();
353 }
354
355 $this->successfulAction( true );
356 break;
357 case AuthenticationResponse::FAIL:
358 // fall through
359 case AuthenticationResponse::RESTART:
360 unset( $this->authForm );
361 if ( $response->status === AuthenticationResponse::FAIL ) {
362 $action = $this->getDefaultAction( $subPage );
363 $messageType = 'error';
364 } else {
365 $action = $this->getContinueAction( $this->authAction );
366 $messageType = 'warning';
367 }
368 $this->logAuthResult( false, $response->message ? $response->message->getKey() : '-' );
369 $this->loadAuth( $subPage, $action, true );
370 $this->mainLoginForm( $this->authRequests, $response->message, $messageType );
371 break;
372 case AuthenticationResponse::REDIRECT:
373 unset( $this->authForm );
374 $this->getOutput()->redirect( $response->redirectTarget );
375 break;
376 case AuthenticationResponse::UI:
377 unset( $this->authForm );
378 $this->authAction = $this->isSignup() ? AuthManager::ACTION_CREATE_CONTINUE
379 : AuthManager::ACTION_LOGIN_CONTINUE;
380 $this->authRequests = $response->neededRequests;
381 $this->mainLoginForm( $response->neededRequests, $response->message, $response->messageType );
382 break;
383 default:
384 throw new LogicException( 'invalid AuthenticationResponse' );
385 }
386 }
387
388 /**
389 * Determine if the login form can be bypassed. This will be the case when no more than one
390 * button is present and no other user input fields that are not marked as 'skippable' are
391 * present. If the login form were not bypassed, the user would be presented with a
392 * superfluous page on which they must press the single button to proceed with login.
393 * Not only does this cause an additional mouse click and page load, it confuses users,
394 * especially since there are a help link and forgotten password link that are
395 * provided on the login page that do not apply to this situation.
396 *
397 * @param string|null &$button_name if the form has a single button, returns
398 * the name of the button; otherwise, returns null
399 * @return bool
400 */
401 private function canBypassForm( &$button_name ) {
402 $button_name = null;
403 if ( $this->isContinued() ) {
404 return false;
405 }
406 $fields = AuthenticationRequest::mergeFieldInfo( $this->authRequests );
407 foreach ( $fields as $fieldname => $field ) {
408 if ( !isset( $field['type'] ) ) {
409 return false;
410 }
411 if ( !empty( $field['skippable'] ) ) {
412 continue;
413 }
414 if ( $field['type'] === 'button' ) {
415 if ( $button_name !== null ) {
416 $button_name = null;
417 return false;
418 } else {
419 $button_name = $fieldname;
420 }
421 } elseif ( $field['type'] !== 'null' ) {
422 return false;
423 }
424 }
425 return true;
426 }
427
428 /**
429 * Show the success page.
430 *
431 * @param string $type Condition of return to; see `executeReturnTo`
432 * @param string|Message $title Page's title
433 * @param string $msgname
434 * @param string $injected_html
435 * @param StatusValue|null $extraMessages
436 */
437 protected function showSuccessPage(
438 $type, $title, $msgname, $injected_html, $extraMessages
439 ) {
440 $out = $this->getOutput();
441 $out->setPageTitle( $title );
442 if ( $msgname ) {
443 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
444 }
445 if ( $extraMessages ) {
446 $extraMessages = Status::wrap( $extraMessages );
447 $out->addWikiText( $extraMessages->getWikiText() );
448 }
449
450 $out->addHTML( $injected_html );
451
452 $helper = new LoginHelper( $this->getContext() );
453 $helper->showReturnToPage( $type, $this->mReturnTo, $this->mReturnToQuery, $this->mStickHTTPS );
454 }
455
456 /**
457 * Add a "return to" link or redirect to it.
458 * Extensions can use this to reuse the "return to" logic after
459 * inject steps (such as redirection) into the login process.
460 *
461 * @param string $type One of the following:
462 * - error: display a return to link ignoring $wgRedirectOnLogin
463 * - signup: display a return to link using $wgRedirectOnLogin if needed
464 * - success: display a return to link using $wgRedirectOnLogin if needed
465 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
466 * @param string $returnTo
467 * @param array|string $returnToQuery
468 * @param bool $stickHTTPS Keep redirect link on HTTPS
469 * @since 1.22
470 */
471 public function showReturnToPage(
472 $type, $returnTo = '', $returnToQuery = '', $stickHTTPS = false
473 ) {
474 $helper = new LoginHelper( $this->getContext() );
475 $helper->showReturnToPage( $type, $returnTo, $returnToQuery, $stickHTTPS );
476 }
477
478 /**
479 * Replace some globals to make sure the fact that the user has just been logged in is
480 * reflected in the current request.
481 */
482 protected function setSessionUserForCurrentRequest() {
483 global $wgUser, $wgLang;
484
485 $context = RequestContext::getMain();
486 $localContext = $this->getContext();
487 if ( $context !== $localContext ) {
488 // remove AuthManagerSpecialPage context hack
489 $this->setContext( $context );
490 }
491
492 $user = $context->getRequest()->getSession()->getUser();
493
494 $wgUser = $user;
495 $context->setUser( $user );
496
497 $code = $this->getRequest()->getVal( 'uselang', $user->getOption( 'language' ) );
498 $userLang = Language::factory( $code );
499 $wgLang = $userLang;
500 $context->setLanguage( $userLang );
501 }
502
503 /**
504 * @param AuthenticationRequest[] $requests A list of AuthorizationRequest objects,
505 * used to generate the form fields. An empty array means a fatal error
506 * (authentication cannot continue).
507 * @param string|Message $msg
508 * @param string $msgtype
509 * @throws ErrorPageError
510 * @throws Exception
511 * @throws FatalError
512 * @throws MWException
513 * @throws PermissionsError
514 * @throws ReadOnlyError
515 * @private
516 */
517 protected function mainLoginForm( array $requests, $msg = '', $msgtype = 'error' ) {
518 $titleObj = $this->getPageTitle();
519 $user = $this->getUser();
520 $out = $this->getOutput();
521
522 // FIXME how to handle empty $requests - restart, or no form, just an error message?
523 // no form would be better for no session type errors, restart is better when can* fails.
524 if ( !$requests ) {
525 $this->authAction = $this->getDefaultAction( $this->subPage );
526 $this->authForm = null;
527 $requests = AuthManager::singleton()->getAuthenticationRequests( $this->authAction, $user );
528 }
529
530 // Generic styles and scripts for both login and signup form
531 $out->addModuleStyles( [
532 'mediawiki.ui',
533 'mediawiki.ui.button',
534 'mediawiki.ui.checkbox',
535 'mediawiki.ui.input',
536 'mediawiki.special.userlogin.common.styles'
537 ] );
538 if ( $this->isSignup() ) {
539 // XXX hack pending RL or JS parse() support for complex content messages T27349
540 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
541 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
542
543 // Additional styles and scripts for signup form
544 $out->addModules( [
545 'mediawiki.special.userlogin.signup.js'
546 ] );
547 $out->addModuleStyles( [
548 'mediawiki.special.userlogin.signup.styles'
549 ] );
550 } else {
551 // Additional styles for login form
552 $out->addModuleStyles( [
553 'mediawiki.special.userlogin.login.styles'
554 ] );
555 }
556 $out->disallowUserJs(); // just in case...
557
558 $form = $this->getAuthForm( $requests, $this->authAction, $msg, $msgtype );
559 $form->prepareForm();
560
561 $submitStatus = Status::newGood();
562 if ( $msg && $msgtype === 'warning' ) {
563 $submitStatus->warning( $msg );
564 } elseif ( $msg && $msgtype === 'error' ) {
565 $submitStatus->fatal( $msg );
566 }
567
568 // warning header for non-standard workflows (e.g. security reauthentication)
569 if (
570 !$this->isSignup() &&
571 $this->getUser()->isLoggedIn() &&
572 $this->authAction !== AuthManager::ACTION_LOGIN_CONTINUE
573 ) {
574 $reauthMessage = $this->securityLevel ? 'userlogin-reauth' : 'userlogin-loggedin';
575 $submitStatus->warning( $reauthMessage, $this->getUser()->getName() );
576 }
577
578 $formHtml = $form->getHTML( $submitStatus );
579
580 $out->addHTML( $this->getPageHtml( $formHtml ) );
581 }
582
583 /**
584 * Add page elements which are outside the form.
585 * FIXME this should probably be a template, but use a sane language (handlebars?)
586 * @param string $formHtml
587 * @return string
588 */
589 protected function getPageHtml( $formHtml ) {
590 global $wgLoginLanguageSelector;
591
592 $loginPrompt = $this->isSignup() ? '' : Html::rawElement( 'div',
593 [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
594 $languageLinks = $wgLoginLanguageSelector ? $this->makeLanguageSelector() : '';
595 $signupStartMsg = $this->msg( 'signupstart' );
596 $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
597 ? Html::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
598 if ( $languageLinks ) {
599 $languageLinks = Html::rawElement( 'div', [ 'id' => 'languagelinks' ],
600 Html::rawElement( 'p', [], $languageLinks )
601 );
602 }
603
604 $benefitsContainer = '';
605 if ( $this->isSignup() && $this->showExtraInformation() ) {
606 // messages used:
607 // createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-body1
608 // createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-body2
609 // createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-body3
610 $benefitCount = 3;
611 $benefitList = '';
612 for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++ ) {
613 $headUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
614 $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->escaped();
615 $benefitList .= Html::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
616 Html::rawElement( 'h3', [],
617 $this->msg( "createacct-benefit-head$benefitIdx" )->escaped()
618 )
619 . Html::rawElement( 'p', [],
620 $this->msg( "createacct-benefit-body$benefitIdx" )->params( $headUnescaped )->escaped()
621 )
622 );
623 }
624 $benefitsContainer = Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
625 Html::rawElement( 'h2', [], $this->msg( 'createacct-benefit-heading' )->escaped() )
626 . Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ],
627 $benefitList
628 )
629 );
630 }
631
632 $html = Html::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
633 $loginPrompt
634 . $languageLinks
635 . $signupStart
636 . Html::rawElement( 'div', [ 'id' => 'userloginForm' ],
637 $formHtml
638 )
639 . $benefitsContainer
640 );
641
642 return $html;
643 }
644
645 /**
646 * Generates a form from the given request.
647 * @param AuthenticationRequest[] $requests
648 * @param string $action AuthManager action name
649 * @param string|Message $msg
650 * @param string $msgType
651 * @return HTMLForm
652 */
653 protected function getAuthForm( array $requests, $action, $msg = '', $msgType = 'error' ) {
654 global $wgSecureLogin;
655 // FIXME merge this with parent
656
657 if ( isset( $this->authForm ) ) {
658 return $this->authForm;
659 }
660
661 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
662
663 // get basic form description from the auth logic
664 $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
665 $fakeTemplate = $this->getFakeTemplate( $msg, $msgType );
666 $this->fakeTemplate = $fakeTemplate; // FIXME there should be a saner way to pass this to the hook
667 // this will call onAuthChangeFormFields()
668 $formDescriptor = static::fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction );
669 $this->postProcessFormDescriptor( $formDescriptor, $requests );
670
671 $context = $this->getContext();
672 if ( $context->getRequest() !== $this->getRequest() ) {
673 // We have overridden the request, need to make sure the form uses that too.
674 $context = new DerivativeContext( $this->getContext() );
675 $context->setRequest( $this->getRequest() );
676 }
677 $form = HTMLForm::factory( 'vform', $formDescriptor, $context );
678
679 $form->addHiddenField( 'authAction', $this->authAction );
680 if ( $this->mLanguage ) {
681 $form->addHiddenField( 'uselang', $this->mLanguage );
682 }
683 $form->addHiddenField( 'force', $this->securityLevel );
684 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
685 if ( $wgSecureLogin ) {
686 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
687 if ( !$this->isSignup() ) {
688 $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS );
689 $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
690 }
691 }
692
693 // set properties of the form itself
694 $form->setAction( $this->getPageTitle()->getLocalURL( $this->getReturnToQueryStringFragment() ) );
695 $form->setName( 'userlogin' . ( $this->isSignup() ? '2' : '' ) );
696 if ( $this->isSignup() ) {
697 $form->setId( 'userlogin2' );
698 }
699
700 $form->suppressDefaultSubmit();
701
702 $this->authForm = $form;
703
704 return $form;
705 }
706
707 /**
708 * Temporary B/C method to handle extensions using the UserLoginForm/UserCreateForm hooks.
709 * @param string|Message $msg
710 * @param string $msgType
711 * @return FakeAuthTemplate
712 */
713 protected function getFakeTemplate( $msg, $msgType ) {
714 global $wgAuth, $wgEnableEmail, $wgHiddenPrefs, $wgEmailConfirmToEdit, $wgEnableUserEmail,
715 $wgSecureLogin, $wgPasswordResetRoutes;
716
717 // make a best effort to get the value of fields which used to be fixed in the old login
718 // template but now might or might not exist depending on what providers are used
719 $request = $this->getRequest();
720 $data = (object)[
721 'mUsername' => $request->getText( 'wpName' ),
722 'mPassword' => $request->getText( 'wpPassword' ),
723 'mRetype' => $request->getText( 'wpRetype' ),
724 'mEmail' => $request->getText( 'wpEmail' ),
725 'mRealName' => $request->getText( 'wpRealName' ),
726 'mDomain' => $request->getText( 'wpDomain' ),
727 'mReason' => $request->getText( 'wpReason' ),
728 'mRemember' => $request->getCheck( 'wpRemember' ),
729 ];
730
731 // Preserves a bunch of logic from the old code that was rewritten in getAuthForm().
732 // There is no code reuse to make this easier to remove .
733 // If an extension tries to change any of these values, they are out of luck - we only
734 // actually use the domain/usedomain/domainnames, extraInput and extrafields keys.
735
736 $titleObj = $this->getPageTitle();
737 $user = $this->getUser();
738 $template = new FakeAuthTemplate();
739
740 // Pre-fill username (if not creating an account, T46775).
741 if ( $data->mUsername == '' && $this->isSignup() ) {
742 if ( $user->isLoggedIn() ) {
743 $data->mUsername = $user->getName();
744 } else {
745 $data->mUsername = $this->getRequest()->getSession()->suggestLoginUsername();
746 }
747 }
748
749 if ( $this->isSignup() ) {
750 // Must match number of benefits defined in messages
751 $template->set( 'benefitCount', 3 );
752
753 $q = 'action=submitlogin&type=signup';
754 $linkq = 'type=login';
755 } else {
756 $q = 'action=submitlogin&type=login';
757 $linkq = 'type=signup';
758 }
759
760 if ( $this->mReturnTo !== '' ) {
761 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
762 if ( $this->mReturnToQuery !== '' ) {
763 $returnto .= '&returntoquery=' .
764 wfUrlencode( $this->mReturnToQuery );
765 }
766 $q .= $returnto;
767 $linkq .= $returnto;
768 }
769
770 # Don't show a "create account" link if the user can't.
771 if ( $this->showCreateAccountLink() ) {
772 # Pass any language selection on to the mode switch link
773 if ( $this->mLanguage ) {
774 $linkq .= '&uselang=' . urlencode( $this->mLanguage );
775 }
776 // Supply URL, login template creates the button.
777 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
778 } else {
779 $template->set( 'link', '' );
780 }
781
782 $resetLink = $this->isSignup()
783 ? null
784 : is_array( $wgPasswordResetRoutes )
785 && in_array( true, array_values( $wgPasswordResetRoutes ), true );
786
787 $template->set( 'header', '' );
788 $template->set( 'formheader', '' );
789 $template->set( 'skin', $this->getSkin() );
790
791 $template->set( 'name', $data->mUsername );
792 $template->set( 'password', $data->mPassword );
793 $template->set( 'retype', $data->mRetype );
794 $template->set( 'createemailset', false ); // no easy way to get that from AuthManager
795 $template->set( 'email', $data->mEmail );
796 $template->set( 'realname', $data->mRealName );
797 $template->set( 'domain', $data->mDomain );
798 $template->set( 'reason', $data->mReason );
799 $template->set( 'remember', $data->mRemember );
800
801 $template->set( 'action', $titleObj->getLocalURL( $q ) );
802 $template->set( 'message', $msg );
803 $template->set( 'messagetype', $msgType );
804 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
805 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs, true ) );
806 $template->set( 'useemail', $wgEnableEmail );
807 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
808 $template->set( 'emailothers', $wgEnableUserEmail );
809 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
810 $template->set( 'resetlink', $resetLink );
811 $template->set( 'canremember', $request->getSession()->getProvider()
812 ->getRememberUserDuration() !== null );
813 $template->set( 'usereason', $user->isLoggedIn() );
814 $template->set( 'cansecurelogin', ( $wgSecureLogin ) );
815 $template->set( 'stickhttps', (int)$this->mStickHTTPS );
816 $template->set( 'loggedin', $user->isLoggedIn() );
817 $template->set( 'loggedinuser', $user->getName() );
818 $template->set( 'token', $this->getToken()->toString() );
819
820 $action = $this->isSignup() ? 'signup' : 'login';
821 $wgAuth->modifyUITemplate( $template, $action );
822
823 $oldTemplate = $template;
824
825 // Both Hooks::run are explicit here to make findHooks.php happy
826 if ( $this->isSignup() ) {
827 Hooks::run( 'UserCreateForm', [ &$template ] );
828 if ( $oldTemplate !== $template ) {
829 wfDeprecated( "reference in UserCreateForm hook", '1.27' );
830 }
831 } else {
832 Hooks::run( 'UserLoginForm', [ &$template ] );
833 if ( $oldTemplate !== $template ) {
834 wfDeprecated( "reference in UserLoginForm hook", '1.27' );
835 }
836 }
837
838 return $template;
839 }
840
841 public function onAuthChangeFormFields(
842 array $requests, array $fieldInfo, array &$formDescriptor, $action
843 ) {
844 $coreFieldDescriptors = $this->getFieldDefinitions( $this->fakeTemplate );
845 $specialFields = array_merge( [ 'extraInput' ],
846 array_keys( $this->fakeTemplate->getExtraInputDefinitions() ) );
847
848 // keep the ordering from getCoreFieldDescriptors() where there is no explicit weight
849 foreach ( $coreFieldDescriptors as $fieldName => $coreField ) {
850 $requestField = isset( $formDescriptor[$fieldName] ) ?
851 $formDescriptor[$fieldName] : [];
852
853 // remove everything that is not in the fieldinfo, is not marked as a supplemental field
854 // to something in the fieldinfo, is not B/C for the pre-AuthManager templates,
855 // and is not an info field or a submit button
856 if (
857 !isset( $fieldInfo[$fieldName] )
858 && (
859 !isset( $coreField['baseField'] )
860 || !isset( $fieldInfo[$coreField['baseField']] )
861 )
862 && !in_array( $fieldName, $specialFields, true )
863 && (
864 !isset( $coreField['type'] )
865 || !in_array( $coreField['type'], [ 'submit', 'info' ], true )
866 )
867 ) {
868 $coreFieldDescriptors[$fieldName] = null;
869 continue;
870 }
871
872 // core message labels should always take priority
873 if (
874 isset( $coreField['label'] )
875 || isset( $coreField['label-message'] )
876 || isset( $coreField['label-raw'] )
877 ) {
878 unset( $requestField['label'], $requestField['label-message'], $coreField['label-raw'] );
879 }
880
881 $coreFieldDescriptors[$fieldName] += $requestField;
882 }
883
884 $formDescriptor = array_filter( $coreFieldDescriptors + $formDescriptor );
885 return true;
886 }
887
888 /**
889 * Show extra information such as password recovery information, link from login to signup,
890 * CTA etc? Such information should only be shown on the "landing page", ie. when the user
891 * is at the first step of the authentication process.
892 * @return bool
893 */
894 protected function showExtraInformation() {
895 return $this->authAction !== $this->getContinueAction( $this->authAction )
896 && !$this->securityLevel;
897 }
898
899 /**
900 * Create a HTMLForm descriptor for the core login fields.
901 * @param FakeAuthTemplate $template B/C data (not used but needed by getBCFieldDefinitions)
902 * @return array
903 */
904 protected function getFieldDefinitions( $template ) {
905 global $wgEmailConfirmToEdit;
906
907 $isLoggedIn = $this->getUser()->isLoggedIn();
908 $continuePart = $this->isContinued() ? 'continue-' : '';
909 $anotherPart = $isLoggedIn ? 'another-' : '';
910 $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
911 $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
912 $secureLoginLink = '';
913 if ( $this->mSecureLoginUrl ) {
914 $secureLoginLink = Html::element( 'a', [
915 'href' => $this->mSecureLoginUrl,
916 'class' => 'mw-ui-flush-right mw-secure',
917 ], $this->msg( 'userlogin-signwithsecure' )->text() );
918 }
919 $usernameHelpLink = '';
920 if ( !$this->msg( 'createacct-helpusername' )->isDisabled() ) {
921 $usernameHelpLink = Html::rawElement( 'span', [
922 'class' => 'mw-ui-flush-right',
923 ], $this->msg( 'createacct-helpusername' )->parse() );
924 }
925
926 if ( $this->isSignup() ) {
927 $fieldDefinitions = [
928 'statusarea' => [
929 // used by the mediawiki.special.userlogin.signup.js module for error display
930 // FIXME merge this with HTMLForm's normal status (error) area
931 'type' => 'info',
932 'raw' => true,
933 'default' => Html::element( 'div', [ 'id' => 'mw-createacct-status-area' ] ),
934 'weight' => -105,
935 ],
936 'username' => [
937 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $usernameHelpLink,
938 'id' => 'wpName2',
939 'placeholder-message' => $isLoggedIn ? 'createacct-another-username-ph'
940 : 'userlogin-yourname-ph',
941 ],
942 'mailpassword' => [
943 // create account without providing password, a temporary one will be mailed
944 'type' => 'check',
945 'label-message' => 'createaccountmail',
946 'name' => 'wpCreateaccountMail',
947 'id' => 'wpCreateaccountMail',
948 ],
949 'password' => [
950 'id' => 'wpPassword2',
951 'placeholder-message' => 'createacct-yourpassword-ph',
952 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
953 ],
954 'domain' => [],
955 'retype' => [
956 'baseField' => 'password',
957 'type' => 'password',
958 'label-message' => 'createacct-yourpasswordagain',
959 'id' => 'wpRetype',
960 'cssclass' => 'loginPassword',
961 'size' => 20,
962 'validation-callback' => function ( $value, $alldata ) {
963 if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
964 if ( !$value ) {
965 return $this->msg( 'htmlform-required' );
966 } elseif ( $value !== $alldata['password'] ) {
967 return $this->msg( 'badretype' );
968 }
969 }
970 return true;
971 },
972 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
973 'placeholder-message' => 'createacct-yourpasswordagain-ph',
974 ],
975 'email' => [
976 'type' => 'email',
977 'label-message' => $wgEmailConfirmToEdit ? 'createacct-emailrequired'
978 : 'createacct-emailoptional',
979 'id' => 'wpEmail',
980 'cssclass' => 'loginText',
981 'size' => '20',
982 // FIXME will break non-standard providers
983 'required' => $wgEmailConfirmToEdit,
984 'validation-callback' => function ( $value, $alldata ) {
985 global $wgEmailConfirmToEdit;
986
987 // AuthManager will check most of these, but that will make the auth
988 // session fail and this won't, so nicer to do it this way
989 if ( !$value && $wgEmailConfirmToEdit ) {
990 // no point in allowing registration without email when email is
991 // required to edit
992 return $this->msg( 'noemailtitle' );
993 } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
994 // cannot send password via email when there is no email address
995 return $this->msg( 'noemailcreate' );
996 } elseif ( $value && !Sanitizer::validateEmail( $value ) ) {
997 return $this->msg( 'invalidemailaddress' );
998 }
999 return true;
1000 },
1001 'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
1002 ],
1003 'realname' => [
1004 'type' => 'text',
1005 'help-message' => $isLoggedIn ? 'createacct-another-realname-tip'
1006 : 'prefs-help-realname',
1007 'label-message' => 'createacct-realname',
1008 'cssclass' => 'loginText',
1009 'size' => 20,
1010 'id' => 'wpRealName',
1011 ],
1012 'reason' => [
1013 // comment for the user creation log
1014 'type' => 'text',
1015 'label-message' => 'createacct-reason',
1016 'cssclass' => 'loginText',
1017 'id' => 'wpReason',
1018 'size' => '20',
1019 'placeholder-message' => 'createacct-reason-ph',
1020 ],
1021 'extrainput' => [], // placeholder for fields coming from the template
1022 'createaccount' => [
1023 // submit button
1024 'type' => 'submit',
1025 'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
1026 'submit' )->text(),
1027 'name' => 'wpCreateaccount',
1028 'id' => 'wpCreateaccount',
1029 'weight' => 100,
1030 ],
1031 ];
1032 } else {
1033 $fieldDefinitions = [
1034 'username' => [
1035 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
1036 'id' => 'wpName1',
1037 'placeholder-message' => 'userlogin-yourname-ph',
1038 ],
1039 'password' => [
1040 'id' => 'wpPassword1',
1041 'placeholder-message' => 'userlogin-yourpassword-ph',
1042 ],
1043 'domain' => [],
1044 'extrainput' => [],
1045 'rememberMe' => [
1046 // option for saving the user token to a cookie
1047 'type' => 'check',
1048 'name' => 'wpRemember',
1049 'label-message' => $this->msg( 'userlogin-remembermypassword' )
1050 ->numParams( $expirationDays ),
1051 'id' => 'wpRemember',
1052 ],
1053 'loginattempt' => [
1054 // submit button
1055 'type' => 'submit',
1056 'default' => $this->msg( 'pt-login-' . $continuePart . 'button' )->text(),
1057 'id' => 'wpLoginAttempt',
1058 'weight' => 100,
1059 ],
1060 'linkcontainer' => [
1061 // help link
1062 'type' => 'info',
1063 'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
1064 // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
1065 'raw' => true,
1066 'default' => Html::element( 'a', [
1067 'href' => Skin::makeInternalOrExternalUrl( wfMessage( 'helplogin-url' )
1068 ->inContentLanguage()
1069 ->text() ),
1070 ], $this->msg( 'userlogin-helplink2' )->text() ),
1071 'weight' => 200,
1072 ],
1073 // button for ResetPasswordSecondaryAuthenticationProvider
1074 'skipReset' => [
1075 'weight' => 110,
1076 'flags' => [],
1077 ],
1078 ];
1079 }
1080
1081 $fieldDefinitions['username'] += [
1082 'type' => 'text',
1083 'name' => 'wpName',
1084 'cssclass' => 'loginText',
1085 'size' => 20,
1086 // 'required' => true,
1087 ];
1088 $fieldDefinitions['password'] += [
1089 'type' => 'password',
1090 // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
1091 'name' => 'wpPassword',
1092 'cssclass' => 'loginPassword',
1093 'size' => 20,
1094 // 'required' => true,
1095 ];
1096
1097 if ( $template->get( 'header' ) || $template->get( 'formheader' ) ) {
1098 // B/C for old extensions that haven't been converted to AuthManager (or have been
1099 // but somebody is using the old version) and still use templates via the
1100 // UserCreateForm/UserLoginForm hook.
1101 // 'header' used by ConfirmEdit, ConfirmAccount, Persona, WikimediaIncubator, SemanticSignup
1102 // 'formheader' used by MobileFrontend
1103 $fieldDefinitions['header'] = [
1104 'type' => 'info',
1105 'raw' => true,
1106 'default' => $template->get( 'header' ) ?: $template->get( 'formheader' ),
1107 'weight' => -110,
1108 ];
1109 }
1110 if ( $this->mEntryError ) {
1111 $fieldDefinitions['entryError'] = [
1112 'type' => 'info',
1113 'default' => Html::rawElement( 'div', [ 'class' => $this->mEntryErrorType . 'box', ],
1114 $this->mEntryError ),
1115 'raw' => true,
1116 'rawrow' => true,
1117 'weight' => -100,
1118 ];
1119 }
1120 if ( !$this->showExtraInformation() ) {
1121 unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
1122 }
1123 if ( $this->isSignup() && $this->showExtraInformation() ) {
1124 // blank signup footer for site customization
1125 // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
1126 $signupendMsg = $this->msg( 'signupend' );
1127 $signupendHttpsMsg = $this->msg( 'signupend-https' );
1128 if ( !$signupendMsg->isDisabled() ) {
1129 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
1130 $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
1131 ? $signupendHttpsMsg ->parse() : $signupendMsg->parse();
1132 $fieldDefinitions['signupend'] = [
1133 'type' => 'info',
1134 'raw' => true,
1135 'default' => Html::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
1136 'weight' => 225,
1137 ];
1138 }
1139 }
1140 if ( !$this->isSignup() && $this->showExtraInformation() ) {
1141 $passwordReset = new PasswordReset( $this->getConfig(), AuthManager::singleton() );
1142 if ( $passwordReset->isAllowed( $this->getUser() )->isGood() ) {
1143 $fieldDefinitions['passwordReset'] = [
1144 'type' => 'info',
1145 'raw' => true,
1146 'cssclass' => 'mw-form-related-link-container',
1147 'default' => $this->getLinkRenderer()->makeLink(
1148 SpecialPage::getTitleFor( 'PasswordReset' ),
1149 $this->msg( 'userlogin-resetpassword-link' )->text()
1150 ),
1151 'weight' => 230,
1152 ];
1153 }
1154
1155 // Don't show a "create account" link if the user can't.
1156 if ( $this->showCreateAccountLink() ) {
1157 // link to the other action
1158 $linkTitle = $this->getTitleFor( $this->isSignup() ? 'Userlogin' : 'CreateAccount' );
1159 $linkq = $this->getReturnToQueryStringFragment();
1160 // Pass any language selection on to the mode switch link
1161 if ( $this->mLanguage ) {
1162 $linkq .= '&uselang=' . urlencode( $this->mLanguage );
1163 }
1164 $loggedIn = $this->getUser()->isLoggedIn();
1165
1166 $fieldDefinitions['createOrLogin'] = [
1167 'type' => 'info',
1168 'raw' => true,
1169 'linkQuery' => $linkq,
1170 'default' => function ( $params ) use ( $loggedIn, $linkTitle ) {
1171 return Html::rawElement( 'div',
1172 [ 'id' => 'mw-createaccount' . ( !$loggedIn ? '-cta' : '' ),
1173 'class' => ( $loggedIn ? 'mw-form-related-link-container' : 'mw-ui-vform-field' ) ],
1174 ( $loggedIn ? '' : $this->msg( 'userlogin-noaccount' )->escaped() )
1175 . Html::element( 'a',
1176 [
1177 'id' => 'mw-createaccount-join' . ( $loggedIn ? '-loggedin' : '' ),
1178 'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1179 'class' => ( $loggedIn ? '' : 'mw-ui-button' ),
1180 'tabindex' => 100,
1181 ],
1182 $this->msg(
1183 $loggedIn ? 'userlogin-createanother' : 'userlogin-joinproject'
1184 )->text()
1185 )
1186 );
1187 },
1188 'weight' => 235,
1189 ];
1190 }
1191 }
1192
1193 $fieldDefinitions = $this->getBCFieldDefinitions( $fieldDefinitions, $template );
1194 $fieldDefinitions = array_filter( $fieldDefinitions );
1195
1196 return $fieldDefinitions;
1197 }
1198
1199 /**
1200 * Adds fields provided via the deprecated UserLoginForm / UserCreateForm hooks
1201 * @param array $fieldDefinitions
1202 * @param FakeAuthTemplate $template
1203 * @return array
1204 */
1205 protected function getBCFieldDefinitions( $fieldDefinitions, $template ) {
1206 if ( $template->get( 'usedomain', false ) ) {
1207 // TODO probably should be translated to the new domain notation in AuthManager
1208 $fieldDefinitions['domain'] = [
1209 'type' => 'select',
1210 'label-message' => 'yourdomainname',
1211 'options' => array_combine( $template->get( 'domainnames', [] ),
1212 $template->get( 'domainnames', [] ) ),
1213 'default' => $template->get( 'domain', '' ),
1214 'name' => 'wpDomain',
1215 // FIXME id => 'mw-user-domain-section' on the parent div
1216 ];
1217 }
1218
1219 // poor man's associative array_splice
1220 $extraInputPos = array_search( 'extrainput', array_keys( $fieldDefinitions ), true );
1221 $fieldDefinitions = array_slice( $fieldDefinitions, 0, $extraInputPos, true )
1222 + $template->getExtraInputDefinitions()
1223 + array_slice( $fieldDefinitions, $extraInputPos + 1, null, true );
1224
1225 return $fieldDefinitions;
1226 }
1227
1228 /**
1229 * Check if a session cookie is present.
1230 *
1231 * This will not pick up a cookie set during _this_ request, but is meant
1232 * to ensure that the client is returning the cookie which was set on a
1233 * previous pass through the system.
1234 *
1235 * @return bool
1236 */
1237 protected function hasSessionCookie() {
1238 global $wgDisableCookieCheck, $wgInitialSessionId;
1239
1240 return $wgDisableCookieCheck || (
1241 $wgInitialSessionId &&
1242 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1243 );
1244 }
1245
1246 /**
1247 * Returns a string that can be appended to the URL (without encoding) to preserve the
1248 * return target. Does not include leading '?'/'&'.
1249 * @return string
1250 */
1251 protected function getReturnToQueryStringFragment() {
1252 $returnto = '';
1253 if ( $this->mReturnTo !== '' ) {
1254 $returnto = 'returnto=' . wfUrlencode( $this->mReturnTo );
1255 if ( $this->mReturnToQuery !== '' ) {
1256 $returnto .= '&returntoquery=' . wfUrlencode( $this->mReturnToQuery );
1257 }
1258 }
1259 return $returnto;
1260 }
1261
1262 /**
1263 * Whether the login/create account form should display a link to the
1264 * other form (in addition to whatever the skin provides).
1265 * @return bool
1266 */
1267 private function showCreateAccountLink() {
1268 if ( $this->isSignup() ) {
1269 return true;
1270 } elseif ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1271 return true;
1272 } else {
1273 return false;
1274 }
1275 }
1276
1277 protected function getTokenName() {
1278 return $this->isSignup() ? 'wpCreateaccountToken' : 'wpLoginToken';
1279 }
1280
1281 /**
1282 * Produce a bar of links which allow the user to select another language
1283 * during login/registration but retain "returnto"
1284 *
1285 * @return string
1286 */
1287 protected function makeLanguageSelector() {
1288 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1289 if ( $msg->isBlank() ) {
1290 return '';
1291 }
1292 $langs = explode( "\n", $msg->text() );
1293 $links = [];
1294 foreach ( $langs as $lang ) {
1295 $lang = trim( $lang, '* ' );
1296 $parts = explode( '|', $lang );
1297 if ( count( $parts ) >= 2 ) {
1298 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1299 }
1300 }
1301
1302 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1303 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1304 }
1305
1306 /**
1307 * Create a language selector link for a particular language
1308 * Links back to this page preserving type and returnto
1309 *
1310 * @param string $text Link text
1311 * @param string $lang Language code
1312 * @return string
1313 */
1314 protected function makeLanguageSelectorLink( $text, $lang ) {
1315 if ( $this->getLanguage()->getCode() == $lang ) {
1316 // no link for currently used language
1317 return htmlspecialchars( $text );
1318 }
1319 $query = [ 'uselang' => $lang ];
1320 if ( $this->mReturnTo !== '' ) {
1321 $query['returnto'] = $this->mReturnTo;
1322 $query['returntoquery'] = $this->mReturnToQuery;
1323 }
1324
1325 $attr = [];
1326 $targetLanguage = Language::factory( $lang );
1327 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1328
1329 return $this->getLinkRenderer()->makeKnownLink(
1330 $this->getPageTitle(),
1331 $text,
1332 $attr,
1333 $query
1334 );
1335 }
1336
1337 protected function getGroupName() {
1338 return 'login';
1339 }
1340
1341 /**
1342 * @param array &$formDescriptor
1343 * @param array $requests
1344 */
1345 protected function postProcessFormDescriptor( &$formDescriptor, $requests ) {
1346 // Pre-fill username (if not creating an account, T46775).
1347 if (
1348 isset( $formDescriptor['username'] ) &&
1349 !isset( $formDescriptor['username']['default'] ) &&
1350 !$this->isSignup()
1351 ) {
1352 $user = $this->getUser();
1353 if ( $user->isLoggedIn() ) {
1354 $formDescriptor['username']['default'] = $user->getName();
1355 } else {
1356 $formDescriptor['username']['default'] =
1357 $this->getRequest()->getSession()->suggestLoginUsername();
1358 }
1359 }
1360
1361 // don't show a submit button if there is nothing to submit (i.e. the only form content
1362 // is other submit buttons, for redirect flows)
1363 if ( !$this->needsSubmitButton( $requests ) ) {
1364 unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1365 }
1366
1367 if ( !$this->isSignup() ) {
1368 // FIXME HACK don't focus on non-empty field
1369 // maybe there should be an autofocus-if similar to hide-if?
1370 if (
1371 isset( $formDescriptor['username'] )
1372 && empty( $formDescriptor['username']['default'] )
1373 && !$this->getRequest()->getCheck( 'wpName' )
1374 ) {
1375 $formDescriptor['username']['autofocus'] = true;
1376 } elseif ( isset( $formDescriptor['password'] ) ) {
1377 $formDescriptor['password']['autofocus'] = true;
1378 }
1379 }
1380
1381 $this->addTabIndex( $formDescriptor );
1382 }
1383 }
1384
1385 /**
1386 * B/C class to try handling login/signup template modifications even though login/signup does not
1387 * actually happen through a template anymore. Just collects extra field definitions and allows
1388 * some other class to do decide what to do with threm..
1389 * TODO find the right place for adding extra fields and kill this
1390 */
1391 class FakeAuthTemplate extends BaseTemplate {
1392 public function execute() {
1393 throw new LogicException( 'not used' );
1394 }
1395
1396 /**
1397 * Extensions (AntiSpoof and TitleBlacklist) call this in response to
1398 * UserCreateForm hook to add checkboxes to the create account form.
1399 * @param string $name
1400 * @param string $value
1401 * @param string $type
1402 * @param string $msg
1403 * @param string|bool $helptext
1404 */
1405 public function addInputItem( $name, $value, $type, $msg, $helptext = false ) {
1406 // use the same indexes as UserCreateForm just in case someone adds an item manually
1407 $this->data['extrainput'][] = [
1408 'name' => $name,
1409 'value' => $value,
1410 'type' => $type,
1411 'msg' => $msg,
1412 'helptext' => $helptext,
1413 ];
1414 }
1415
1416 /**
1417 * Turns addInputItem-style field definitions into HTMLForm field definitions.
1418 * @return array
1419 */
1420 public function getExtraInputDefinitions() {
1421 $definitions = [];
1422
1423 foreach ( $this->get( 'extrainput', [] ) as $field ) {
1424 $definition = [
1425 'type' => $field['type'] === 'checkbox' ? 'check' : $field['type'],
1426 'name' => $field['name'],
1427 'value' => $field['value'],
1428 'id' => $field['name'],
1429 ];
1430 if ( $field['msg'] ) {
1431 $definition['label-message'] = $this->getMsg( $field['msg'] );
1432 }
1433 if ( $field['helptext'] ) {
1434 $definition['help'] = $this->msgWiki( $field['helptext'] );
1435 }
1436
1437 // the array key doesn't matter much when name is defined explicitly but
1438 // let's try and follow HTMLForm conventions
1439 $name = preg_replace( '/^wp(?=[A-Z])/', '', $field['name'] );
1440 $definitions[$name] = $definition;
1441 }
1442
1443 if ( $this->haveData( 'extrafields' ) ) {
1444 $definitions['extrafields'] = [
1445 'type' => 'info',
1446 'raw' => true,
1447 'default' => $this->get( 'extrafields' ),
1448 ];
1449 }
1450
1451 return $definitions;
1452 }
1453 }
1454
1455 /**
1456 * LoginForm as a special page has been replaced by SpecialUserLogin and SpecialCreateAccount,
1457 * but some extensions called its public methods directly, so the class is retained as a
1458 * B/C wrapper. Anything that used it before should use AuthManager instead.
1459 */
1460 class LoginForm extends SpecialPage {
1461 const SUCCESS = 0;
1462 const NO_NAME = 1;
1463 const ILLEGAL = 2;
1464 const WRONG_PLUGIN_PASS = 3;
1465 const NOT_EXISTS = 4;
1466 const WRONG_PASS = 5;
1467 const EMPTY_PASS = 6;
1468 const RESET_PASS = 7;
1469 const ABORTED = 8;
1470 const CREATE_BLOCKED = 9;
1471 const THROTTLED = 10;
1472 const USER_BLOCKED = 11;
1473 const NEED_TOKEN = 12;
1474 const WRONG_TOKEN = 13;
1475 const USER_MIGRATED = 14;
1476
1477 public static $statusCodes = [
1478 self::SUCCESS => 'success',
1479 self::NO_NAME => 'no_name',
1480 self::ILLEGAL => 'illegal',
1481 self::WRONG_PLUGIN_PASS => 'wrong_plugin_pass',
1482 self::NOT_EXISTS => 'not_exists',
1483 self::WRONG_PASS => 'wrong_pass',
1484 self::EMPTY_PASS => 'empty_pass',
1485 self::RESET_PASS => 'reset_pass',
1486 self::ABORTED => 'aborted',
1487 self::CREATE_BLOCKED => 'create_blocked',
1488 self::THROTTLED => 'throttled',
1489 self::USER_BLOCKED => 'user_blocked',
1490 self::NEED_TOKEN => 'need_token',
1491 self::WRONG_TOKEN => 'wrong_token',
1492 self::USER_MIGRATED => 'user_migrated',
1493 ];
1494
1495 /**
1496 * @param WebRequest $request
1497 */
1498 public function __construct( $request = null ) {
1499 wfDeprecated( 'LoginForm', '1.27' );
1500 parent::__construct();
1501 }
1502
1503 /**
1504 * @deprecated since 1.27 - call LoginHelper::getValidErrorMessages instead.
1505 * @return array
1506 */
1507 public static function getValidErrorMessages() {
1508 return LoginHelper::getValidErrorMessages();
1509 }
1510
1511 /**
1512 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1513 * @param string $username
1514 * @return array|false
1515 */
1516 public static function incrementLoginThrottle( $username ) {
1517 wfDeprecated( __METHOD__, "1.27" );
1518 global $wgRequest;
1519 $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
1520 $throttler = new Throttler();
1521 return $throttler->increase( $username, $wgRequest->getIP(), __METHOD__ );
1522 }
1523
1524 /**
1525 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1526 * @param string $username
1527 * @return bool|int
1528 */
1529 public static function incLoginThrottle( $username ) {
1530 wfDeprecated( __METHOD__, "1.27" );
1531 $res = self::incrementLoginThrottle( $username );
1532 return is_array( $res ) ? true : 0;
1533 }
1534
1535 /**
1536 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1537 * @param string $username
1538 * @return void
1539 */
1540 public static function clearLoginThrottle( $username ) {
1541 wfDeprecated( __METHOD__, "1.27" );
1542 global $wgRequest;
1543 $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
1544 $throttler = new Throttler();
1545 return $throttler->clear( $username, $wgRequest->getIP() );
1546 }
1547
1548 /**
1549 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1550 */
1551 public static function getLoginToken() {
1552 wfDeprecated( __METHOD__, '1.27' );
1553 global $wgRequest;
1554 return $wgRequest->getSession()->getToken( '', 'login' )->toString();
1555 }
1556
1557 /**
1558 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1559 */
1560 public static function setLoginToken() {
1561 wfDeprecated( __METHOD__, '1.27' );
1562 }
1563
1564 /**
1565 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1566 */
1567 public static function clearLoginToken() {
1568 wfDeprecated( __METHOD__, '1.27' );
1569 global $wgRequest;
1570 $wgRequest->getSession()->resetToken( 'login' );
1571 }
1572
1573 /**
1574 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1575 * @return string
1576 */
1577 public static function getCreateaccountToken() {
1578 wfDeprecated( __METHOD__, '1.27' );
1579 global $wgRequest;
1580 return $wgRequest->getSession()->getToken( '', 'createaccount' )->toString();
1581 }
1582
1583 /**
1584 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1585 */
1586 public static function setCreateaccountToken() {
1587 wfDeprecated( __METHOD__, '1.27' );
1588 }
1589
1590 /**
1591 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1592 */
1593 public static function clearCreateaccountToken() {
1594 wfDeprecated( __METHOD__, '1.27' );
1595 global $wgRequest;
1596 $wgRequest->getSession()->resetToken( 'createaccount' );
1597 }
1598 }