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