Merge "Use {{int:}} on MediaWiki:Blockedtext and MediaWiki:Autoblockedtext"
[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 $user = $this->getUser();
519 $out = $this->getOutput();
520
521 // FIXME how to handle empty $requests - restart, or no form, just an error message?
522 // no form would be better for no session type errors, restart is better when can* fails.
523 if ( !$requests ) {
524 $this->authAction = $this->getDefaultAction( $this->subPage );
525 $this->authForm = null;
526 $requests = AuthManager::singleton()->getAuthenticationRequests( $this->authAction, $user );
527 }
528
529 // Generic styles and scripts for both login and signup form
530 $out->addModuleStyles( [
531 'mediawiki.ui',
532 'mediawiki.ui.button',
533 'mediawiki.ui.checkbox',
534 'mediawiki.ui.input',
535 'mediawiki.special.userlogin.common.styles'
536 ] );
537 if ( $this->isSignup() ) {
538 // XXX hack pending RL or JS parse() support for complex content messages T27349
539 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
540 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
541
542 // Additional styles and scripts for signup form
543 $out->addModules( [
544 'mediawiki.special.userlogin.signup.js'
545 ] );
546 $out->addModuleStyles( [
547 'mediawiki.special.userlogin.signup.styles'
548 ] );
549 } else {
550 // Additional styles for login form
551 $out->addModuleStyles( [
552 'mediawiki.special.userlogin.login.styles'
553 ] );
554 }
555 $out->disallowUserJs(); // just in case...
556
557 $form = $this->getAuthForm( $requests, $this->authAction, $msg, $msgtype );
558 $form->prepareForm();
559
560 $submitStatus = Status::newGood();
561 if ( $msg && $msgtype === 'warning' ) {
562 $submitStatus->warning( $msg );
563 } elseif ( $msg && $msgtype === 'error' ) {
564 $submitStatus->fatal( $msg );
565 }
566
567 // warning header for non-standard workflows (e.g. security reauthentication)
568 if (
569 !$this->isSignup() &&
570 $this->getUser()->isLoggedIn() &&
571 $this->authAction !== AuthManager::ACTION_LOGIN_CONTINUE
572 ) {
573 $reauthMessage = $this->securityLevel ? 'userlogin-reauth' : 'userlogin-loggedin';
574 $submitStatus->warning( $reauthMessage, $this->getUser()->getName() );
575 }
576
577 $formHtml = $form->getHTML( $submitStatus );
578
579 $out->addHTML( $this->getPageHtml( $formHtml ) );
580 }
581
582 /**
583 * Add page elements which are outside the form.
584 * FIXME this should probably be a template, but use a sane language (handlebars?)
585 * @param string $formHtml
586 * @return string
587 */
588 protected function getPageHtml( $formHtml ) {
589 global $wgLoginLanguageSelector;
590
591 $loginPrompt = $this->isSignup() ? '' : Html::rawElement( 'div',
592 [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
593 $languageLinks = $wgLoginLanguageSelector ? $this->makeLanguageSelector() : '';
594 $signupStartMsg = $this->msg( 'signupstart' );
595 $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
596 ? Html::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
597 if ( $languageLinks ) {
598 $languageLinks = Html::rawElement( 'div', [ 'id' => 'languagelinks' ],
599 Html::rawElement( 'p', [], $languageLinks )
600 );
601 }
602
603 $benefitsContainer = '';
604 if ( $this->isSignup() && $this->showExtraInformation() ) {
605 // messages used:
606 // createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-body1
607 // createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-body2
608 // createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-body3
609 $benefitCount = 3;
610 $benefitList = '';
611 for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++ ) {
612 $headUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
613 $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->escaped();
614 $benefitList .= Html::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
615 Html::rawElement( 'h3', [],
616 $this->msg( "createacct-benefit-head$benefitIdx" )->escaped()
617 )
618 . Html::rawElement( 'p', [],
619 $this->msg( "createacct-benefit-body$benefitIdx" )->params( $headUnescaped )->escaped()
620 )
621 );
622 }
623 $benefitsContainer = Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
624 Html::rawElement( 'h2', [], $this->msg( 'createacct-benefit-heading' )->escaped() )
625 . Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ],
626 $benefitList
627 )
628 );
629 }
630
631 $html = Html::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
632 $loginPrompt
633 . $languageLinks
634 . $signupStart
635 . Html::rawElement( 'div', [ 'id' => 'userloginForm' ],
636 $formHtml
637 )
638 . $benefitsContainer
639 );
640
641 return $html;
642 }
643
644 /**
645 * Generates a form from the given request.
646 * @param AuthenticationRequest[] $requests
647 * @param string $action AuthManager action name
648 * @param string|Message $msg
649 * @param string $msgType
650 * @return HTMLForm
651 */
652 protected function getAuthForm( array $requests, $action, $msg = '', $msgType = 'error' ) {
653 global $wgSecureLogin;
654 // FIXME merge this with parent
655
656 if ( isset( $this->authForm ) ) {
657 return $this->authForm;
658 }
659
660 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
661
662 // get basic form description from the auth logic
663 $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
664 $fakeTemplate = $this->getFakeTemplate( $msg, $msgType );
665 $this->fakeTemplate = $fakeTemplate; // FIXME there should be a saner way to pass this to the hook
666 // this will call onAuthChangeFormFields()
667 $formDescriptor = static::fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction );
668 $this->postProcessFormDescriptor( $formDescriptor, $requests );
669
670 $context = $this->getContext();
671 if ( $context->getRequest() !== $this->getRequest() ) {
672 // We have overridden the request, need to make sure the form uses that too.
673 $context = new DerivativeContext( $this->getContext() );
674 $context->setRequest( $this->getRequest() );
675 }
676 $form = HTMLForm::factory( 'vform', $formDescriptor, $context );
677
678 $form->addHiddenField( 'authAction', $this->authAction );
679 if ( $this->mLanguage ) {
680 $form->addHiddenField( 'uselang', $this->mLanguage );
681 }
682 $form->addHiddenField( 'force', $this->securityLevel );
683 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
684 if ( $wgSecureLogin ) {
685 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
686 if ( !$this->isSignup() ) {
687 $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS );
688 $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
689 }
690 }
691
692 // set properties of the form itself
693 $form->setAction( $this->getPageTitle()->getLocalURL( $this->getReturnToQueryStringFragment() ) );
694 $form->setName( 'userlogin' . ( $this->isSignup() ? '2' : '' ) );
695 if ( $this->isSignup() ) {
696 $form->setId( 'userlogin2' );
697 }
698
699 $form->suppressDefaultSubmit();
700
701 $this->authForm = $form;
702
703 return $form;
704 }
705
706 /**
707 * Temporary B/C method to handle extensions using the UserLoginForm/UserCreateForm hooks.
708 * @param string|Message $msg
709 * @param string $msgType
710 * @return FakeAuthTemplate
711 */
712 protected function getFakeTemplate( $msg, $msgType ) {
713 global $wgAuth, $wgEnableEmail, $wgHiddenPrefs, $wgEmailConfirmToEdit, $wgEnableUserEmail,
714 $wgSecureLogin, $wgPasswordResetRoutes;
715
716 // make a best effort to get the value of fields which used to be fixed in the old login
717 // template but now might or might not exist depending on what providers are used
718 $request = $this->getRequest();
719 $data = (object)[
720 'mUsername' => $request->getText( 'wpName' ),
721 'mPassword' => $request->getText( 'wpPassword' ),
722 'mRetype' => $request->getText( 'wpRetype' ),
723 'mEmail' => $request->getText( 'wpEmail' ),
724 'mRealName' => $request->getText( 'wpRealName' ),
725 'mDomain' => $request->getText( 'wpDomain' ),
726 'mReason' => $request->getText( 'wpReason' ),
727 'mRemember' => $request->getCheck( 'wpRemember' ),
728 ];
729
730 // Preserves a bunch of logic from the old code that was rewritten in getAuthForm().
731 // There is no code reuse to make this easier to remove .
732 // If an extension tries to change any of these values, they are out of luck - we only
733 // actually use the domain/usedomain/domainnames, extraInput and extrafields keys.
734
735 $titleObj = $this->getPageTitle();
736 $user = $this->getUser();
737 $template = new FakeAuthTemplate();
738
739 // Pre-fill username (if not creating an account, T46775).
740 if ( $data->mUsername == '' && $this->isSignup() ) {
741 if ( $user->isLoggedIn() ) {
742 $data->mUsername = $user->getName();
743 } else {
744 $data->mUsername = $this->getRequest()->getSession()->suggestLoginUsername();
745 }
746 }
747
748 if ( $this->isSignup() ) {
749 // Must match number of benefits defined in messages
750 $template->set( 'benefitCount', 3 );
751
752 $q = 'action=submitlogin&type=signup';
753 $linkq = 'type=login';
754 } else {
755 $q = 'action=submitlogin&type=login';
756 $linkq = 'type=signup';
757 }
758
759 if ( $this->mReturnTo !== '' ) {
760 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
761 if ( $this->mReturnToQuery !== '' ) {
762 $returnto .= '&returntoquery=' .
763 wfUrlencode( $this->mReturnToQuery );
764 }
765 $q .= $returnto;
766 $linkq .= $returnto;
767 }
768
769 # Don't show a "create account" link if the user can't.
770 if ( $this->showCreateAccountLink() ) {
771 # Pass any language selection on to the mode switch link
772 if ( $this->mLanguage ) {
773 $linkq .= '&uselang=' . urlencode( $this->mLanguage );
774 }
775 // Supply URL, login template creates the button.
776 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
777 } else {
778 $template->set( 'link', '' );
779 }
780
781 $resetLink = $this->isSignup()
782 ? null
783 : is_array( $wgPasswordResetRoutes )
784 && in_array( true, array_values( $wgPasswordResetRoutes ), true );
785
786 $template->set( 'header', '' );
787 $template->set( 'formheader', '' );
788 $template->set( 'skin', $this->getSkin() );
789
790 $template->set( 'name', $data->mUsername );
791 $template->set( 'password', $data->mPassword );
792 $template->set( 'retype', $data->mRetype );
793 $template->set( 'createemailset', false ); // no easy way to get that from AuthManager
794 $template->set( 'email', $data->mEmail );
795 $template->set( 'realname', $data->mRealName );
796 $template->set( 'domain', $data->mDomain );
797 $template->set( 'reason', $data->mReason );
798 $template->set( 'remember', $data->mRemember );
799
800 $template->set( 'action', $titleObj->getLocalURL( $q ) );
801 $template->set( 'message', $msg );
802 $template->set( 'messagetype', $msgType );
803 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
804 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs, true ) );
805 $template->set( 'useemail', $wgEnableEmail );
806 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
807 $template->set( 'emailothers', $wgEnableUserEmail );
808 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
809 $template->set( 'resetlink', $resetLink );
810 $template->set( 'canremember', $request->getSession()->getProvider()
811 ->getRememberUserDuration() !== null );
812 $template->set( 'usereason', $user->isLoggedIn() );
813 $template->set( 'cansecurelogin', ( $wgSecureLogin ) );
814 $template->set( 'stickhttps', (int)$this->mStickHTTPS );
815 $template->set( 'loggedin', $user->isLoggedIn() );
816 $template->set( 'loggedinuser', $user->getName() );
817 $template->set( 'token', $this->getToken()->toString() );
818
819 $action = $this->isSignup() ? 'signup' : 'login';
820 $wgAuth->modifyUITemplate( $template, $action );
821
822 $oldTemplate = $template;
823
824 // Both Hooks::run are explicit here to make findHooks.php happy
825 if ( $this->isSignup() ) {
826 Hooks::run( 'UserCreateForm', [ &$template ] );
827 if ( $oldTemplate !== $template ) {
828 wfDeprecated( "reference in UserCreateForm hook", '1.27' );
829 }
830 } else {
831 Hooks::run( 'UserLoginForm', [ &$template ] );
832 if ( $oldTemplate !== $template ) {
833 wfDeprecated( "reference in UserLoginForm hook", '1.27' );
834 }
835 }
836
837 return $template;
838 }
839
840 public function onAuthChangeFormFields(
841 array $requests, array $fieldInfo, array &$formDescriptor, $action
842 ) {
843 $coreFieldDescriptors = $this->getFieldDefinitions( $this->fakeTemplate );
844 $specialFields = array_merge( [ 'extraInput' ],
845 array_keys( $this->fakeTemplate->getExtraInputDefinitions() ) );
846
847 // keep the ordering from getCoreFieldDescriptors() where there is no explicit weight
848 foreach ( $coreFieldDescriptors as $fieldName => $coreField ) {
849 $requestField = isset( $formDescriptor[$fieldName] ) ?
850 $formDescriptor[$fieldName] : [];
851
852 // remove everything that is not in the fieldinfo, is not marked as a supplemental field
853 // to something in the fieldinfo, is not B/C for the pre-AuthManager templates,
854 // and is not an info field or a submit button
855 if (
856 !isset( $fieldInfo[$fieldName] )
857 && (
858 !isset( $coreField['baseField'] )
859 || !isset( $fieldInfo[$coreField['baseField']] )
860 )
861 && !in_array( $fieldName, $specialFields, true )
862 && (
863 !isset( $coreField['type'] )
864 || !in_array( $coreField['type'], [ 'submit', 'info' ], true )
865 )
866 ) {
867 $coreFieldDescriptors[$fieldName] = null;
868 continue;
869 }
870
871 // core message labels should always take priority
872 if (
873 isset( $coreField['label'] )
874 || isset( $coreField['label-message'] )
875 || isset( $coreField['label-raw'] )
876 ) {
877 unset( $requestField['label'], $requestField['label-message'], $coreField['label-raw'] );
878 }
879
880 $coreFieldDescriptors[$fieldName] += $requestField;
881 }
882
883 $formDescriptor = array_filter( $coreFieldDescriptors + $formDescriptor );
884 return true;
885 }
886
887 /**
888 * Show extra information such as password recovery information, link from login to signup,
889 * CTA etc? Such information should only be shown on the "landing page", ie. when the user
890 * is at the first step of the authentication process.
891 * @return bool
892 */
893 protected function showExtraInformation() {
894 return $this->authAction !== $this->getContinueAction( $this->authAction )
895 && !$this->securityLevel;
896 }
897
898 /**
899 * Create a HTMLForm descriptor for the core login fields.
900 * @param FakeAuthTemplate $template B/C data (not used but needed by getBCFieldDefinitions)
901 * @return array
902 */
903 protected function getFieldDefinitions( $template ) {
904 global $wgEmailConfirmToEdit;
905
906 $isLoggedIn = $this->getUser()->isLoggedIn();
907 $continuePart = $this->isContinued() ? 'continue-' : '';
908 $anotherPart = $isLoggedIn ? 'another-' : '';
909 $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
910 $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
911 $secureLoginLink = '';
912 if ( $this->mSecureLoginUrl ) {
913 $secureLoginLink = Html::element( 'a', [
914 'href' => $this->mSecureLoginUrl,
915 'class' => 'mw-ui-flush-right mw-secure',
916 ], $this->msg( 'userlogin-signwithsecure' )->text() );
917 }
918 $usernameHelpLink = '';
919 if ( !$this->msg( 'createacct-helpusername' )->isDisabled() ) {
920 $usernameHelpLink = Html::rawElement( 'span', [
921 'class' => 'mw-ui-flush-right',
922 ], $this->msg( 'createacct-helpusername' )->parse() );
923 }
924
925 if ( $this->isSignup() ) {
926 $fieldDefinitions = [
927 'statusarea' => [
928 // used by the mediawiki.special.userlogin.signup.js module for error display
929 // FIXME merge this with HTMLForm's normal status (error) area
930 'type' => 'info',
931 'raw' => true,
932 'default' => Html::element( 'div', [ 'id' => 'mw-createacct-status-area' ] ),
933 'weight' => -105,
934 ],
935 'username' => [
936 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $usernameHelpLink,
937 'id' => 'wpName2',
938 'placeholder-message' => $isLoggedIn ? 'createacct-another-username-ph'
939 : 'userlogin-yourname-ph',
940 ],
941 'mailpassword' => [
942 // create account without providing password, a temporary one will be mailed
943 'type' => 'check',
944 'label-message' => 'createaccountmail',
945 'name' => 'wpCreateaccountMail',
946 'id' => 'wpCreateaccountMail',
947 ],
948 'password' => [
949 'id' => 'wpPassword2',
950 'placeholder-message' => 'createacct-yourpassword-ph',
951 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
952 ],
953 'domain' => [],
954 'retype' => [
955 'baseField' => 'password',
956 'type' => 'password',
957 'label-message' => 'createacct-yourpasswordagain',
958 'id' => 'wpRetype',
959 'cssclass' => 'loginPassword',
960 'size' => 20,
961 'validation-callback' => function ( $value, $alldata ) {
962 if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
963 if ( !$value ) {
964 return $this->msg( 'htmlform-required' );
965 } elseif ( $value !== $alldata['password'] ) {
966 return $this->msg( 'badretype' );
967 }
968 }
969 return true;
970 },
971 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
972 'placeholder-message' => 'createacct-yourpasswordagain-ph',
973 ],
974 'email' => [
975 'type' => 'email',
976 'label-message' => $wgEmailConfirmToEdit ? 'createacct-emailrequired'
977 : 'createacct-emailoptional',
978 'id' => 'wpEmail',
979 'cssclass' => 'loginText',
980 'size' => '20',
981 // FIXME will break non-standard providers
982 'required' => $wgEmailConfirmToEdit,
983 'validation-callback' => function ( $value, $alldata ) {
984 global $wgEmailConfirmToEdit;
985
986 // AuthManager will check most of these, but that will make the auth
987 // session fail and this won't, so nicer to do it this way
988 if ( !$value && $wgEmailConfirmToEdit ) {
989 // no point in allowing registration without email when email is
990 // required to edit
991 return $this->msg( 'noemailtitle' );
992 } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
993 // cannot send password via email when there is no email address
994 return $this->msg( 'noemailcreate' );
995 } elseif ( $value && !Sanitizer::validateEmail( $value ) ) {
996 return $this->msg( 'invalidemailaddress' );
997 }
998 return true;
999 },
1000 'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
1001 ],
1002 'realname' => [
1003 'type' => 'text',
1004 'help-message' => $isLoggedIn ? 'createacct-another-realname-tip'
1005 : 'prefs-help-realname',
1006 'label-message' => 'createacct-realname',
1007 'cssclass' => 'loginText',
1008 'size' => 20,
1009 'id' => 'wpRealName',
1010 ],
1011 'reason' => [
1012 // comment for the user creation log
1013 'type' => 'text',
1014 'label-message' => 'createacct-reason',
1015 'cssclass' => 'loginText',
1016 'id' => 'wpReason',
1017 'size' => '20',
1018 'placeholder-message' => 'createacct-reason-ph',
1019 ],
1020 'extrainput' => [], // placeholder for fields coming from the template
1021 'createaccount' => [
1022 // submit button
1023 'type' => 'submit',
1024 'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
1025 'submit' )->text(),
1026 'name' => 'wpCreateaccount',
1027 'id' => 'wpCreateaccount',
1028 'weight' => 100,
1029 ],
1030 ];
1031 } else {
1032 $fieldDefinitions = [
1033 'username' => [
1034 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
1035 'id' => 'wpName1',
1036 'placeholder-message' => 'userlogin-yourname-ph',
1037 ],
1038 'password' => [
1039 'id' => 'wpPassword1',
1040 'placeholder-message' => 'userlogin-yourpassword-ph',
1041 ],
1042 'domain' => [],
1043 'extrainput' => [],
1044 'rememberMe' => [
1045 // option for saving the user token to a cookie
1046 'type' => 'check',
1047 'name' => 'wpRemember',
1048 'label-message' => $this->msg( 'userlogin-remembermypassword' )
1049 ->numParams( $expirationDays ),
1050 'id' => 'wpRemember',
1051 ],
1052 'loginattempt' => [
1053 // submit button
1054 'type' => 'submit',
1055 'default' => $this->msg( 'pt-login-' . $continuePart . 'button' )->text(),
1056 'id' => 'wpLoginAttempt',
1057 'weight' => 100,
1058 ],
1059 'linkcontainer' => [
1060 // help link
1061 'type' => 'info',
1062 'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
1063 // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
1064 'raw' => true,
1065 'default' => Html::element( 'a', [
1066 'href' => Skin::makeInternalOrExternalUrl( wfMessage( 'helplogin-url' )
1067 ->inContentLanguage()
1068 ->text() ),
1069 ], $this->msg( 'userlogin-helplink2' )->text() ),
1070 'weight' => 200,
1071 ],
1072 // button for ResetPasswordSecondaryAuthenticationProvider
1073 'skipReset' => [
1074 'weight' => 110,
1075 'flags' => [],
1076 ],
1077 ];
1078 }
1079
1080 $fieldDefinitions['username'] += [
1081 'type' => 'text',
1082 'name' => 'wpName',
1083 'cssclass' => 'loginText',
1084 'size' => 20,
1085 // 'required' => true,
1086 ];
1087 $fieldDefinitions['password'] += [
1088 'type' => 'password',
1089 // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
1090 'name' => 'wpPassword',
1091 'cssclass' => 'loginPassword',
1092 'size' => 20,
1093 // 'required' => true,
1094 ];
1095
1096 if ( $template->get( 'header' ) || $template->get( 'formheader' ) ) {
1097 // B/C for old extensions that haven't been converted to AuthManager (or have been
1098 // but somebody is using the old version) and still use templates via the
1099 // UserCreateForm/UserLoginForm hook.
1100 // 'header' used by ConfirmEdit, ConfirmAccount, Persona, WikimediaIncubator, SemanticSignup
1101 // 'formheader' used by MobileFrontend
1102 $fieldDefinitions['header'] = [
1103 'type' => 'info',
1104 'raw' => true,
1105 'default' => $template->get( 'header' ) ?: $template->get( 'formheader' ),
1106 'weight' => -110,
1107 ];
1108 }
1109 if ( $this->mEntryError ) {
1110 $fieldDefinitions['entryError'] = [
1111 'type' => 'info',
1112 'default' => Html::rawElement( 'div', [ 'class' => $this->mEntryErrorType . 'box', ],
1113 $this->mEntryError ),
1114 'raw' => true,
1115 'rawrow' => true,
1116 'weight' => -100,
1117 ];
1118 }
1119 if ( !$this->showExtraInformation() ) {
1120 unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
1121 }
1122 if ( $this->isSignup() && $this->showExtraInformation() ) {
1123 // blank signup footer for site customization
1124 // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
1125 $signupendMsg = $this->msg( 'signupend' );
1126 $signupendHttpsMsg = $this->msg( 'signupend-https' );
1127 if ( !$signupendMsg->isDisabled() ) {
1128 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
1129 $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
1130 ? $signupendHttpsMsg ->parse() : $signupendMsg->parse();
1131 $fieldDefinitions['signupend'] = [
1132 'type' => 'info',
1133 'raw' => true,
1134 'default' => Html::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
1135 'weight' => 225,
1136 ];
1137 }
1138 }
1139 if ( !$this->isSignup() && $this->showExtraInformation() ) {
1140 $passwordReset = new PasswordReset( $this->getConfig(), AuthManager::singleton() );
1141 if ( $passwordReset->isAllowed( $this->getUser() )->isGood() ) {
1142 $fieldDefinitions['passwordReset'] = [
1143 'type' => 'info',
1144 'raw' => true,
1145 'cssclass' => 'mw-form-related-link-container',
1146 'default' => $this->getLinkRenderer()->makeLink(
1147 SpecialPage::getTitleFor( 'PasswordReset' ),
1148 $this->msg( 'userlogin-resetpassword-link' )->text()
1149 ),
1150 'weight' => 230,
1151 ];
1152 }
1153
1154 // Don't show a "create account" link if the user can't.
1155 if ( $this->showCreateAccountLink() ) {
1156 // link to the other action
1157 $linkTitle = $this->getTitleFor( $this->isSignup() ? 'Userlogin' : 'CreateAccount' );
1158 $linkq = $this->getReturnToQueryStringFragment();
1159 // Pass any language selection on to the mode switch link
1160 if ( $this->mLanguage ) {
1161 $linkq .= '&uselang=' . urlencode( $this->mLanguage );
1162 }
1163 $loggedIn = $this->getUser()->isLoggedIn();
1164
1165 $fieldDefinitions['createOrLogin'] = [
1166 'type' => 'info',
1167 'raw' => true,
1168 'linkQuery' => $linkq,
1169 'default' => function ( $params ) use ( $loggedIn, $linkTitle ) {
1170 return Html::rawElement( 'div',
1171 [ 'id' => 'mw-createaccount' . ( !$loggedIn ? '-cta' : '' ),
1172 'class' => ( $loggedIn ? 'mw-form-related-link-container' : 'mw-ui-vform-field' ) ],
1173 ( $loggedIn ? '' : $this->msg( 'userlogin-noaccount' )->escaped() )
1174 . Html::element( 'a',
1175 [
1176 'id' => 'mw-createaccount-join' . ( $loggedIn ? '-loggedin' : '' ),
1177 'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1178 'class' => ( $loggedIn ? '' : 'mw-ui-button' ),
1179 'tabindex' => 100,
1180 ],
1181 $this->msg(
1182 $loggedIn ? 'userlogin-createanother' : 'userlogin-joinproject'
1183 )->text()
1184 )
1185 );
1186 },
1187 'weight' => 235,
1188 ];
1189 }
1190 }
1191
1192 $fieldDefinitions = $this->getBCFieldDefinitions( $fieldDefinitions, $template );
1193 $fieldDefinitions = array_filter( $fieldDefinitions );
1194
1195 return $fieldDefinitions;
1196 }
1197
1198 /**
1199 * Adds fields provided via the deprecated UserLoginForm / UserCreateForm hooks
1200 * @param array $fieldDefinitions
1201 * @param FakeAuthTemplate $template
1202 * @return array
1203 */
1204 protected function getBCFieldDefinitions( $fieldDefinitions, $template ) {
1205 if ( $template->get( 'usedomain', false ) ) {
1206 // TODO probably should be translated to the new domain notation in AuthManager
1207 $fieldDefinitions['domain'] = [
1208 'type' => 'select',
1209 'label-message' => 'yourdomainname',
1210 'options' => array_combine( $template->get( 'domainnames', [] ),
1211 $template->get( 'domainnames', [] ) ),
1212 'default' => $template->get( 'domain', '' ),
1213 'name' => 'wpDomain',
1214 // FIXME id => 'mw-user-domain-section' on the parent div
1215 ];
1216 }
1217
1218 // poor man's associative array_splice
1219 $extraInputPos = array_search( 'extrainput', array_keys( $fieldDefinitions ), true );
1220 $fieldDefinitions = array_slice( $fieldDefinitions, 0, $extraInputPos, true )
1221 + $template->getExtraInputDefinitions()
1222 + array_slice( $fieldDefinitions, $extraInputPos + 1, null, true );
1223
1224 return $fieldDefinitions;
1225 }
1226
1227 /**
1228 * Check if a session cookie is present.
1229 *
1230 * This will not pick up a cookie set during _this_ request, but is meant
1231 * to ensure that the client is returning the cookie which was set on a
1232 * previous pass through the system.
1233 *
1234 * @return bool
1235 */
1236 protected function hasSessionCookie() {
1237 global $wgDisableCookieCheck, $wgInitialSessionId;
1238
1239 return $wgDisableCookieCheck || (
1240 $wgInitialSessionId &&
1241 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1242 );
1243 }
1244
1245 /**
1246 * Returns a string that can be appended to the URL (without encoding) to preserve the
1247 * return target. Does not include leading '?'/'&'.
1248 * @return string
1249 */
1250 protected function getReturnToQueryStringFragment() {
1251 $returnto = '';
1252 if ( $this->mReturnTo !== '' ) {
1253 $returnto = 'returnto=' . wfUrlencode( $this->mReturnTo );
1254 if ( $this->mReturnToQuery !== '' ) {
1255 $returnto .= '&returntoquery=' . wfUrlencode( $this->mReturnToQuery );
1256 }
1257 }
1258 return $returnto;
1259 }
1260
1261 /**
1262 * Whether the login/create account form should display a link to the
1263 * other form (in addition to whatever the skin provides).
1264 * @return bool
1265 */
1266 private function showCreateAccountLink() {
1267 if ( $this->isSignup() ) {
1268 return true;
1269 } elseif ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1270 return true;
1271 } else {
1272 return false;
1273 }
1274 }
1275
1276 protected function getTokenName() {
1277 return $this->isSignup() ? 'wpCreateaccountToken' : 'wpLoginToken';
1278 }
1279
1280 /**
1281 * Produce a bar of links which allow the user to select another language
1282 * during login/registration but retain "returnto"
1283 *
1284 * @return string
1285 */
1286 protected function makeLanguageSelector() {
1287 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1288 if ( $msg->isBlank() ) {
1289 return '';
1290 }
1291 $langs = explode( "\n", $msg->text() );
1292 $links = [];
1293 foreach ( $langs as $lang ) {
1294 $lang = trim( $lang, '* ' );
1295 $parts = explode( '|', $lang );
1296 if ( count( $parts ) >= 2 ) {
1297 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1298 }
1299 }
1300
1301 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1302 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1303 }
1304
1305 /**
1306 * Create a language selector link for a particular language
1307 * Links back to this page preserving type and returnto
1308 *
1309 * @param string $text Link text
1310 * @param string $lang Language code
1311 * @return string
1312 */
1313 protected function makeLanguageSelectorLink( $text, $lang ) {
1314 if ( $this->getLanguage()->getCode() == $lang ) {
1315 // no link for currently used language
1316 return htmlspecialchars( $text );
1317 }
1318 $query = [ 'uselang' => $lang ];
1319 if ( $this->mReturnTo !== '' ) {
1320 $query['returnto'] = $this->mReturnTo;
1321 $query['returntoquery'] = $this->mReturnToQuery;
1322 }
1323
1324 $attr = [];
1325 $targetLanguage = Language::factory( $lang );
1326 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1327
1328 return $this->getLinkRenderer()->makeKnownLink(
1329 $this->getPageTitle(),
1330 $text,
1331 $attr,
1332 $query
1333 );
1334 }
1335
1336 protected function getGroupName() {
1337 return 'login';
1338 }
1339
1340 /**
1341 * @param array &$formDescriptor
1342 * @param array $requests
1343 */
1344 protected function postProcessFormDescriptor( &$formDescriptor, $requests ) {
1345 // Pre-fill username (if not creating an account, T46775).
1346 if (
1347 isset( $formDescriptor['username'] ) &&
1348 !isset( $formDescriptor['username']['default'] ) &&
1349 !$this->isSignup()
1350 ) {
1351 $user = $this->getUser();
1352 if ( $user->isLoggedIn() ) {
1353 $formDescriptor['username']['default'] = $user->getName();
1354 } else {
1355 $formDescriptor['username']['default'] =
1356 $this->getRequest()->getSession()->suggestLoginUsername();
1357 }
1358 }
1359
1360 // don't show a submit button if there is nothing to submit (i.e. the only form content
1361 // is other submit buttons, for redirect flows)
1362 if ( !$this->needsSubmitButton( $requests ) ) {
1363 unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1364 }
1365
1366 if ( !$this->isSignup() ) {
1367 // FIXME HACK don't focus on non-empty field
1368 // maybe there should be an autofocus-if similar to hide-if?
1369 if (
1370 isset( $formDescriptor['username'] )
1371 && empty( $formDescriptor['username']['default'] )
1372 && !$this->getRequest()->getCheck( 'wpName' )
1373 ) {
1374 $formDescriptor['username']['autofocus'] = true;
1375 } elseif ( isset( $formDescriptor['password'] ) ) {
1376 $formDescriptor['password']['autofocus'] = true;
1377 }
1378 }
1379
1380 $this->addTabIndex( $formDescriptor );
1381 }
1382 }
1383
1384 /**
1385 * B/C class to try handling login/signup template modifications even though login/signup does not
1386 * actually happen through a template anymore. Just collects extra field definitions and allows
1387 * some other class to do decide what to do with threm..
1388 * TODO find the right place for adding extra fields and kill this
1389 */
1390 class FakeAuthTemplate extends BaseTemplate {
1391 public function execute() {
1392 throw new LogicException( 'not used' );
1393 }
1394
1395 /**
1396 * Extensions (AntiSpoof and TitleBlacklist) call this in response to
1397 * UserCreateForm hook to add checkboxes to the create account form.
1398 * @param string $name
1399 * @param string $value
1400 * @param string $type
1401 * @param string $msg
1402 * @param string|bool $helptext
1403 */
1404 public function addInputItem( $name, $value, $type, $msg, $helptext = false ) {
1405 // use the same indexes as UserCreateForm just in case someone adds an item manually
1406 $this->data['extrainput'][] = [
1407 'name' => $name,
1408 'value' => $value,
1409 'type' => $type,
1410 'msg' => $msg,
1411 'helptext' => $helptext,
1412 ];
1413 }
1414
1415 /**
1416 * Turns addInputItem-style field definitions into HTMLForm field definitions.
1417 * @return array
1418 */
1419 public function getExtraInputDefinitions() {
1420 $definitions = [];
1421
1422 foreach ( $this->get( 'extrainput', [] ) as $field ) {
1423 $definition = [
1424 'type' => $field['type'] === 'checkbox' ? 'check' : $field['type'],
1425 'name' => $field['name'],
1426 'value' => $field['value'],
1427 'id' => $field['name'],
1428 ];
1429 if ( $field['msg'] ) {
1430 $definition['label-message'] = $this->getMsg( $field['msg'] );
1431 }
1432 if ( $field['helptext'] ) {
1433 $definition['help'] = $this->msgWiki( $field['helptext'] );
1434 }
1435
1436 // the array key doesn't matter much when name is defined explicitly but
1437 // let's try and follow HTMLForm conventions
1438 $name = preg_replace( '/^wp(?=[A-Z])/', '', $field['name'] );
1439 $definitions[$name] = $definition;
1440 }
1441
1442 if ( $this->haveData( 'extrafields' ) ) {
1443 $definitions['extrafields'] = [
1444 'type' => 'info',
1445 'raw' => true,
1446 'default' => $this->get( 'extrafields' ),
1447 ];
1448 }
1449
1450 return $definitions;
1451 }
1452 }
1453
1454 /**
1455 * LoginForm as a special page has been replaced by SpecialUserLogin and SpecialCreateAccount,
1456 * but some extensions called its public methods directly, so the class is retained as a
1457 * B/C wrapper. Anything that used it before should use AuthManager instead.
1458 */
1459 class LoginForm extends SpecialPage {
1460 const SUCCESS = 0;
1461 const NO_NAME = 1;
1462 const ILLEGAL = 2;
1463 const WRONG_PLUGIN_PASS = 3;
1464 const NOT_EXISTS = 4;
1465 const WRONG_PASS = 5;
1466 const EMPTY_PASS = 6;
1467 const RESET_PASS = 7;
1468 const ABORTED = 8;
1469 const CREATE_BLOCKED = 9;
1470 const THROTTLED = 10;
1471 const USER_BLOCKED = 11;
1472 const NEED_TOKEN = 12;
1473 const WRONG_TOKEN = 13;
1474 const USER_MIGRATED = 14;
1475
1476 public static $statusCodes = [
1477 self::SUCCESS => 'success',
1478 self::NO_NAME => 'no_name',
1479 self::ILLEGAL => 'illegal',
1480 self::WRONG_PLUGIN_PASS => 'wrong_plugin_pass',
1481 self::NOT_EXISTS => 'not_exists',
1482 self::WRONG_PASS => 'wrong_pass',
1483 self::EMPTY_PASS => 'empty_pass',
1484 self::RESET_PASS => 'reset_pass',
1485 self::ABORTED => 'aborted',
1486 self::CREATE_BLOCKED => 'create_blocked',
1487 self::THROTTLED => 'throttled',
1488 self::USER_BLOCKED => 'user_blocked',
1489 self::NEED_TOKEN => 'need_token',
1490 self::WRONG_TOKEN => 'wrong_token',
1491 self::USER_MIGRATED => 'user_migrated',
1492 ];
1493
1494 /**
1495 * @param WebRequest $request
1496 */
1497 public function __construct( $request = null ) {
1498 wfDeprecated( 'LoginForm', '1.27' );
1499 parent::__construct();
1500 }
1501
1502 /**
1503 * @deprecated since 1.27 - call LoginHelper::getValidErrorMessages instead.
1504 * @return array
1505 */
1506 public static function getValidErrorMessages() {
1507 return LoginHelper::getValidErrorMessages();
1508 }
1509
1510 /**
1511 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1512 * @param string $username
1513 * @return array|false
1514 */
1515 public static function incrementLoginThrottle( $username ) {
1516 wfDeprecated( __METHOD__, "1.27" );
1517 global $wgRequest;
1518 $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
1519 $throttler = new Throttler();
1520 return $throttler->increase( $username, $wgRequest->getIP(), __METHOD__ );
1521 }
1522
1523 /**
1524 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1525 * @param string $username
1526 * @return bool|int
1527 */
1528 public static function incLoginThrottle( $username ) {
1529 wfDeprecated( __METHOD__, "1.27" );
1530 $res = self::incrementLoginThrottle( $username );
1531 return is_array( $res ) ? true : 0;
1532 }
1533
1534 /**
1535 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1536 * @param string $username
1537 * @return void
1538 */
1539 public static function clearLoginThrottle( $username ) {
1540 wfDeprecated( __METHOD__, "1.27" );
1541 global $wgRequest;
1542 $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
1543 $throttler = new Throttler();
1544 return $throttler->clear( $username, $wgRequest->getIP() );
1545 }
1546
1547 /**
1548 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1549 */
1550 public static function getLoginToken() {
1551 wfDeprecated( __METHOD__, '1.27' );
1552 global $wgRequest;
1553 return $wgRequest->getSession()->getToken( '', 'login' )->toString();
1554 }
1555
1556 /**
1557 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1558 */
1559 public static function setLoginToken() {
1560 wfDeprecated( __METHOD__, '1.27' );
1561 }
1562
1563 /**
1564 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1565 */
1566 public static function clearLoginToken() {
1567 wfDeprecated( __METHOD__, '1.27' );
1568 global $wgRequest;
1569 $wgRequest->getSession()->resetToken( 'login' );
1570 }
1571
1572 /**
1573 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1574 * @return string
1575 */
1576 public static function getCreateaccountToken() {
1577 wfDeprecated( __METHOD__, '1.27' );
1578 global $wgRequest;
1579 return $wgRequest->getSession()->getToken( '', 'createaccount' )->toString();
1580 }
1581
1582 /**
1583 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1584 */
1585 public static function setCreateaccountToken() {
1586 wfDeprecated( __METHOD__, '1.27' );
1587 }
1588
1589 /**
1590 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1591 */
1592 public static function clearCreateaccountToken() {
1593 wfDeprecated( __METHOD__, '1.27' );
1594 global $wgRequest;
1595 $wgRequest->getSession()->resetToken( 'createaccount' );
1596 }
1597 }