Declare dynamic properties
[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\Logger\LoggerFactory;
28 use MediaWiki\MediaWikiServices;
29 use MediaWiki\Session\SessionManager;
30 use Wikimedia\ScopedCallback;
31
32 /**
33 * Holds shared logic for login and account creation pages.
34 *
35 * @ingroup SpecialPage
36 */
37 abstract class LoginSignupSpecialPage extends AuthManagerSpecialPage {
38 protected $mReturnTo;
39 protected $mPosted;
40 protected $mAction;
41 protected $mLanguage;
42 protected $mReturnToQuery;
43 protected $mToken;
44 protected $mStickHTTPS;
45 protected $mFromHTTP;
46 protected $mEntryError = '';
47 protected $mEntryErrorType = 'error';
48
49 protected $mLoaded = false;
50 protected $mLoadedRequest = false;
51 protected $mSecureLoginUrl;
52
53 /** @var string */
54 protected $securityLevel;
55
56 /** @var bool True if the user if creating an account for someone else. Flag used for internal
57 * communication, only set at the very end.
58 */
59 protected $proxyAccountCreation;
60 /** @var User FIXME another flag for passing data. */
61 protected $targetUser;
62
63 /** @var HTMLForm */
64 protected $authForm;
65
66 abstract protected function isSignup();
67
68 /**
69 * @param bool $direct True if the action was successful just now; false if that happened
70 * pre-redirection (so this handler was called already)
71 * @param StatusValue|null $extraMessages
72 * @return void
73 */
74 abstract protected function successfulAction( $direct = false, $extraMessages = null );
75
76 /**
77 * Logs to the authmanager-stats channel.
78 * @param bool $success
79 * @param string|null $status Error message key
80 */
81 abstract protected function logAuthResult( $success, $status = null );
82
83 public function __construct( $name ) {
84 global $wgUseMediaWikiUIEverywhere;
85 parent::__construct( $name );
86
87 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
88 $wgUseMediaWikiUIEverywhere = true;
89 }
90
91 protected function setRequest( array $data, $wasPosted = null ) {
92 parent::setRequest( $data, $wasPosted );
93 $this->mLoadedRequest = false;
94 }
95
96 /**
97 * Load basic request parameters for this Special page.
98 */
99 private function loadRequestParameters() {
100 if ( $this->mLoadedRequest ) {
101 return;
102 }
103 $this->mLoadedRequest = true;
104 $request = $this->getRequest();
105
106 $this->mPosted = $request->wasPosted();
107 $this->mAction = $request->getVal( 'action' );
108 $this->mFromHTTP = $request->getBool( 'fromhttp', false )
109 || $request->getBool( 'wpFromhttp', false );
110 $this->mStickHTTPS = ( !$this->mFromHTTP && $request->getProtocol() === 'https' )
111 || $request->getBool( 'wpForceHttps', false );
112 $this->mLanguage = $request->getText( 'uselang' );
113 $this->mReturnTo = $request->getVal( 'returnto', '' );
114 $this->mReturnToQuery = $request->getVal( 'returntoquery', '' );
115 }
116
117 /**
118 * Load data from request.
119 * @private
120 * @param string $subPage Subpage of Special:Userlogin
121 */
122 protected function load( $subPage ) {
123 global $wgSecureLogin;
124
125 $this->loadRequestParameters();
126 if ( $this->mLoaded ) {
127 return;
128 }
129 $this->mLoaded = true;
130 $request = $this->getRequest();
131
132 $securityLevel = $this->getRequest()->getText( 'force' );
133 if (
134 $securityLevel && AuthManager::singleton()->securitySensitiveOperationStatus(
135 $securityLevel ) === AuthManager::SEC_REAUTH
136 ) {
137 $this->securityLevel = $securityLevel;
138 }
139
140 $this->loadAuth( $subPage );
141
142 $this->mToken = $request->getVal( $this->getTokenName() );
143
144 // Show an error or warning passed on from a previous page
145 $entryError = $this->msg( $request->getVal( 'error', '' ) );
146 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
147 // bc: provide login link as a parameter for messages where the translation
148 // was not updated
149 $loginreqlink = $this->getLinkRenderer()->makeKnownLink(
150 $this->getPageTitle(),
151 $this->msg( 'loginreqlink' )->text(),
152 [],
153 [
154 'returnto' => $this->mReturnTo,
155 'returntoquery' => $this->mReturnToQuery,
156 'uselang' => $this->mLanguage ?: null,
157 'fromhttp' => $wgSecureLogin && $this->mFromHTTP ? '1' : null,
158 ]
159 );
160
161 // Only show valid error or warning messages.
162 if ( $entryError->exists()
163 && in_array( $entryError->getKey(), LoginHelper::getValidErrorMessages(), true )
164 ) {
165 $this->mEntryErrorType = 'error';
166 $this->mEntryError = $entryError->rawParams( $loginreqlink )->parse();
167
168 } elseif ( $entryWarning->exists()
169 && in_array( $entryWarning->getKey(), LoginHelper::getValidErrorMessages(), true )
170 ) {
171 $this->mEntryErrorType = 'warning';
172 $this->mEntryError = $entryWarning->rawParams( $loginreqlink )->parse();
173 }
174
175 # 1. When switching accounts, it sucks to get automatically logged out
176 # 2. Do not return to PasswordReset after a successful password change
177 # but goto Wiki start page (Main_Page) instead ( T35997 )
178 $returnToTitle = Title::newFromText( $this->mReturnTo );
179 if ( is_object( $returnToTitle )
180 && ( $returnToTitle->isSpecial( 'Userlogout' )
181 || $returnToTitle->isSpecial( 'PasswordReset' ) )
182 ) {
183 $this->mReturnTo = '';
184 $this->mReturnToQuery = '';
185 }
186 }
187
188 protected function getPreservedParams( $withToken = false ) {
189 global $wgSecureLogin;
190
191 $params = parent::getPreservedParams( $withToken );
192 $params += [
193 'returnto' => $this->mReturnTo ?: null,
194 'returntoquery' => $this->mReturnToQuery ?: null,
195 ];
196 if ( $wgSecureLogin && !$this->isSignup() ) {
197 $params['fromhttp'] = $this->mFromHTTP ? '1' : null;
198 }
199 return $params;
200 }
201
202 protected function beforeExecute( $subPage ) {
203 // finish initializing the class before processing the request - T135924
204 $this->loadRequestParameters();
205 return parent::beforeExecute( $subPage );
206 }
207
208 /**
209 * @param string|null $subPage
210 * @suppress PhanTypeObjectUnsetDeclaredProperty
211 */
212 public function execute( $subPage ) {
213 if ( $this->mPosted ) {
214 $time = microtime( true );
215 $profilingScope = new ScopedCallback( function () use ( $time ) {
216 $time = microtime( true ) - $time;
217 $statsd = MediaWikiServices::getInstance()->getStatsdDataFactory();
218 $statsd->timing( "timing.login.ui.{$this->authAction}", $time * 1000 );
219 } );
220 }
221
222 $authManager = AuthManager::singleton();
223 $session = SessionManager::getGlobalSession();
224
225 // Session data is used for various things in the authentication process, so we must make
226 // sure a session cookie or some equivalent mechanism is set.
227 $session->persist();
228
229 $this->load( $subPage );
230 $this->setHeaders();
231 $this->checkPermissions();
232
233 // Make sure the system configuration allows log in / sign up
234 if ( !$this->isSignup() && !$authManager->canAuthenticateNow() ) {
235 if ( !$session->canSetUser() ) {
236 throw new ErrorPageError( 'cannotloginnow-title', 'cannotloginnow-text', [
237 $session->getProvider()->describe( RequestContext::getMain()->getLanguage() )
238 ] );
239 }
240 throw new ErrorPageError( 'cannotlogin-title', 'cannotlogin-text' );
241 } elseif ( $this->isSignup() && !$authManager->canCreateAccounts() ) {
242 throw new ErrorPageError( 'cannotcreateaccount-title', 'cannotcreateaccount-text' );
243 }
244
245 /*
246 * In the case where the user is already logged in, and was redirected to
247 * the login form from a page that requires login, do not show the login
248 * page. The use case scenario for this is when a user opens a large number
249 * of tabs, is redirected to the login page on all of them, and then logs
250 * in on one, expecting all the others to work properly.
251 *
252 * However, do show the form if it was visited intentionally (no 'returnto'
253 * is present). People who often switch between several accounts have grown
254 * accustomed to this behavior.
255 *
256 * Also make an exception when force=<level> is set in the URL, which means the user must
257 * reauthenticate for security reasons.
258 */
259 if ( !$this->isSignup() && !$this->mPosted && !$this->securityLevel &&
260 ( $this->mReturnTo !== '' || $this->mReturnToQuery !== '' ) &&
261 $this->getUser()->isLoggedIn()
262 ) {
263 $this->successfulAction();
264 return;
265 }
266
267 // If logging in and not on HTTPS, either redirect to it or offer a link.
268 global $wgSecureLogin;
269 if ( $this->getRequest()->getProtocol() !== 'https' ) {
270 $title = $this->getFullTitle();
271 $query = $this->getPreservedParams( false ) + [
272 'title' => null,
273 ( $this->mEntryErrorType === 'error' ? 'error'
274 : 'warning' ) => $this->mEntryError,
275 ] + $this->getRequest()->getQueryValues();
276 $url = $title->getFullURL( $query, false, PROTO_HTTPS );
277 if ( $wgSecureLogin && !$this->mFromHTTP &&
278 wfCanIPUseHTTPS( $this->getRequest()->getIP() )
279 ) {
280 // Avoid infinite redirect
281 $url = wfAppendQuery( $url, 'fromhttp=1' );
282 $this->getOutput()->redirect( $url );
283 // Since we only do this redir to change proto, always vary
284 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
285
286 return;
287 } else {
288 // A wiki without HTTPS login support should set $wgServer to
289 // http://somehost, in which case the secure URL generated
290 // above won't actually start with https://
291 if ( substr( $url, 0, 8 ) === 'https://' ) {
292 $this->mSecureLoginUrl = $url;
293 }
294 }
295 }
296
297 if ( !$this->isActionAllowed( $this->authAction ) ) {
298 // FIXME how do we explain this to the user? can we handle session loss better?
299 // messages used: authpage-cannot-login, authpage-cannot-login-continue,
300 // authpage-cannot-create, authpage-cannot-create-continue
301 $this->mainLoginForm( [], 'authpage-cannot-' . $this->authAction );
302 return;
303 }
304
305 if ( $this->canBypassForm( $button_name ) ) {
306 $this->setRequest( [], true );
307 $this->getRequest()->setVal( $this->getTokenName(), $this->getToken() );
308 if ( $button_name ) {
309 $this->getRequest()->setVal( $button_name, true );
310 }
311 }
312
313 $status = $this->trySubmit();
314
315 if ( !$status || !$status->isGood() ) {
316 $this->mainLoginForm( $this->authRequests, $status ? $status->getMessage() : '', 'error' );
317 return;
318 }
319
320 /** @var AuthenticationResponse $response */
321 $response = $status->getValue();
322
323 $returnToUrl = $this->getPageTitle( 'return' )
324 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS );
325 switch ( $response->status ) {
326 case AuthenticationResponse::PASS:
327 $this->logAuthResult( true );
328 $this->proxyAccountCreation = $this->isSignup() && !$this->getUser()->isAnon();
329 $this->targetUser = User::newFromName( $response->username );
330
331 if (
332 !$this->proxyAccountCreation
333 && $response->loginRequest
334 && $authManager->canAuthenticateNow()
335 ) {
336 // successful registration; log the user in instantly
337 $response2 = $authManager->beginAuthentication( [ $response->loginRequest ],
338 $returnToUrl );
339 if ( $response2->status !== AuthenticationResponse::PASS ) {
340 LoggerFactory::getInstance( 'login' )
341 ->error( 'Could not log in after account creation' );
342 $this->successfulAction( true, Status::newFatal( 'createacct-loginerror' ) );
343 break;
344 }
345 }
346
347 if ( !$this->proxyAccountCreation ) {
348 // Ensure that the context user is the same as the session user.
349 $this->setSessionUserForCurrentRequest();
350 }
351
352 $this->successfulAction( true );
353 break;
354 case AuthenticationResponse::FAIL:
355 // fall through
356 case AuthenticationResponse::RESTART:
357 unset( $this->authForm );
358 if ( $response->status === AuthenticationResponse::FAIL ) {
359 $action = $this->getDefaultAction( $subPage );
360 $messageType = 'error';
361 } else {
362 $action = $this->getContinueAction( $this->authAction );
363 $messageType = 'warning';
364 }
365 $this->logAuthResult( false, $response->message ? $response->message->getKey() : '-' );
366 $this->loadAuth( $subPage, $action, true );
367 $this->mainLoginForm( $this->authRequests, $response->message, $messageType );
368 break;
369 case AuthenticationResponse::REDIRECT:
370 unset( $this->authForm );
371 $this->getOutput()->redirect( $response->redirectTarget );
372 break;
373 case AuthenticationResponse::UI:
374 unset( $this->authForm );
375 $this->authAction = $this->isSignup() ? AuthManager::ACTION_CREATE_CONTINUE
376 : AuthManager::ACTION_LOGIN_CONTINUE;
377 $this->authRequests = $response->neededRequests;
378 $this->mainLoginForm( $response->neededRequests, $response->message, $response->messageType );
379 break;
380 default:
381 throw new LogicException( 'invalid AuthenticationResponse' );
382 }
383 }
384
385 /**
386 * Determine if the login form can be bypassed. This will be the case when no more than one
387 * button is present and no other user input fields that are not marked as 'skippable' are
388 * present. If the login form were not bypassed, the user would be presented with a
389 * superfluous page on which they must press the single button to proceed with login.
390 * Not only does this cause an additional mouse click and page load, it confuses users,
391 * especially since there are a help link and forgotten password link that are
392 * provided on the login page that do not apply to this situation.
393 *
394 * @param string|null &$button_name if the form has a single button, returns
395 * the name of the button; otherwise, returns null
396 * @return bool
397 */
398 private function canBypassForm( &$button_name ) {
399 $button_name = null;
400 if ( $this->isContinued() ) {
401 return false;
402 }
403 $fields = AuthenticationRequest::mergeFieldInfo( $this->authRequests );
404 foreach ( $fields as $fieldname => $field ) {
405 if ( !isset( $field['type'] ) ) {
406 return false;
407 }
408 if ( !empty( $field['skippable'] ) ) {
409 continue;
410 }
411 if ( $field['type'] === 'button' ) {
412 if ( $button_name !== null ) {
413 $button_name = null;
414 return false;
415 } else {
416 $button_name = $fieldname;
417 }
418 } elseif ( $field['type'] !== 'null' ) {
419 return false;
420 }
421 }
422 return true;
423 }
424
425 /**
426 * Show the success page.
427 *
428 * @param string $type Condition of return to; see `executeReturnTo`
429 * @param string|Message $title Page's title
430 * @param string $msgname
431 * @param string $injected_html
432 * @param StatusValue|null $extraMessages
433 */
434 protected function showSuccessPage(
435 $type, $title, $msgname, $injected_html, $extraMessages
436 ) {
437 $out = $this->getOutput();
438 $out->setPageTitle( $title );
439 if ( $msgname ) {
440 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
441 }
442 if ( $extraMessages ) {
443 $extraMessages = Status::wrap( $extraMessages );
444 $out->addWikiTextAsInterface( $extraMessages->getWikiText() );
445 }
446
447 $out->addHTML( $injected_html );
448
449 $helper = new LoginHelper( $this->getContext() );
450 $helper->showReturnToPage( $type, $this->mReturnTo, $this->mReturnToQuery, $this->mStickHTTPS );
451 }
452
453 /**
454 * Add a "return to" link or redirect to it.
455 * Extensions can use this to reuse the "return to" logic after
456 * inject steps (such as redirection) into the login process.
457 *
458 * @param string $type One of the following:
459 * - error: display a return to link ignoring $wgRedirectOnLogin
460 * - signup: display a return to link using $wgRedirectOnLogin if needed
461 * - success: display a return to link using $wgRedirectOnLogin if needed
462 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
463 * @param string $returnTo
464 * @param array|string $returnToQuery
465 * @param bool $stickHTTPS Keep redirect link on HTTPS
466 * @since 1.22
467 */
468 public function showReturnToPage(
469 $type, $returnTo = '', $returnToQuery = '', $stickHTTPS = false
470 ) {
471 $helper = new LoginHelper( $this->getContext() );
472 $helper->showReturnToPage( $type, $returnTo, $returnToQuery, $stickHTTPS );
473 }
474
475 /**
476 * Replace some globals to make sure the fact that the user has just been logged in is
477 * reflected in the current request.
478 */
479 protected function setSessionUserForCurrentRequest() {
480 global $wgUser, $wgLang;
481
482 $context = RequestContext::getMain();
483 $localContext = $this->getContext();
484 if ( $context !== $localContext ) {
485 // remove AuthManagerSpecialPage context hack
486 $this->setContext( $context );
487 }
488
489 $user = $context->getRequest()->getSession()->getUser();
490
491 $wgUser = $user;
492 $context->setUser( $user );
493
494 $wgLang = $context->getLanguage();
495 }
496
497 /**
498 * @param AuthenticationRequest[] $requests A list of AuthorizationRequest objects,
499 * used to generate the form fields. An empty array means a fatal error
500 * (authentication cannot continue).
501 * @param string|Message $msg
502 * @param string $msgtype
503 * @throws ErrorPageError
504 * @throws Exception
505 * @throws FatalError
506 * @throws MWException
507 * @throws PermissionsError
508 * @throws ReadOnlyError
509 * @private
510 */
511 protected function mainLoginForm( array $requests, $msg = '', $msgtype = 'error' ) {
512 $user = $this->getUser();
513 $out = $this->getOutput();
514
515 // FIXME how to handle empty $requests - restart, or no form, just an error message?
516 // no form would be better for no session type errors, restart is better when can* fails.
517 if ( !$requests ) {
518 $this->authAction = $this->getDefaultAction( $this->subPage );
519 $this->authForm = null;
520 $requests = AuthManager::singleton()->getAuthenticationRequests( $this->authAction, $user );
521 }
522
523 // Generic styles and scripts for both login and signup form
524 $out->addModuleStyles( [
525 'mediawiki.ui',
526 'mediawiki.ui.button',
527 'mediawiki.ui.checkbox',
528 'mediawiki.ui.input',
529 'mediawiki.special.userlogin.common.styles'
530 ] );
531 if ( $this->isSignup() ) {
532 // XXX hack pending RL or JS parse() support for complex content messages T27349
533 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
534 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
535
536 // Additional styles and scripts for signup form
537 $out->addModules( [
538 'mediawiki.special.userlogin.signup.js'
539 ] );
540 $out->addModuleStyles( [
541 'mediawiki.special.userlogin.signup.styles'
542 ] );
543 } else {
544 // Additional styles for login form
545 $out->addModuleStyles( [
546 'mediawiki.special.userlogin.login.styles'
547 ] );
548 }
549 $out->disallowUserJs(); // just in case...
550
551 $form = $this->getAuthForm( $requests, $this->authAction, $msg, $msgtype );
552 $form->prepareForm();
553
554 $submitStatus = Status::newGood();
555 if ( $msg && $msgtype === 'warning' ) {
556 $submitStatus->warning( $msg );
557 } elseif ( $msg && $msgtype === 'error' ) {
558 $submitStatus->fatal( $msg );
559 }
560
561 // warning header for non-standard workflows (e.g. security reauthentication)
562 if (
563 !$this->isSignup() &&
564 $this->getUser()->isLoggedIn() &&
565 $this->authAction !== AuthManager::ACTION_LOGIN_CONTINUE
566 ) {
567 $reauthMessage = $this->securityLevel ? 'userlogin-reauth' : 'userlogin-loggedin';
568 $submitStatus->warning( $reauthMessage, $this->getUser()->getName() );
569 }
570
571 $formHtml = $form->getHTML( $submitStatus );
572
573 $out->addHTML( $this->getPageHtml( $formHtml ) );
574 }
575
576 /**
577 * Add page elements which are outside the form.
578 * FIXME this should probably be a template, but use a sane language (handlebars?)
579 * @param string $formHtml
580 * @return string
581 */
582 protected function getPageHtml( $formHtml ) {
583 global $wgLoginLanguageSelector;
584
585 $loginPrompt = $this->isSignup() ? '' : Html::rawElement( 'div',
586 [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
587 $languageLinks = $wgLoginLanguageSelector ? $this->makeLanguageSelector() : '';
588 $signupStartMsg = $this->msg( 'signupstart' );
589 $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
590 ? Html::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
591 if ( $languageLinks ) {
592 $languageLinks = Html::rawElement( 'div', [ 'id' => 'languagelinks' ],
593 Html::rawElement( 'p', [], $languageLinks )
594 );
595 }
596
597 $benefitsContainer = '';
598 if ( $this->isSignup() && $this->showExtraInformation() ) {
599 // messages used:
600 // createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-body1
601 // createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-body2
602 // createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-body3
603 $benefitCount = 3;
604 $benefitList = '';
605 for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++ ) {
606 $headUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
607 $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->text();
608 $benefitList .= Html::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
609 Html::rawElement( 'h3', [],
610 $this->msg( "createacct-benefit-head$benefitIdx" )->escaped()
611 )
612 . Html::rawElement( 'p', [],
613 $this->msg( "createacct-benefit-body$benefitIdx" )->params( $headUnescaped )->escaped()
614 )
615 );
616 }
617 $benefitsContainer = Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
618 Html::rawElement( 'h2', [], $this->msg( 'createacct-benefit-heading' )->escaped() )
619 . Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ],
620 $benefitList
621 )
622 );
623 }
624
625 $html = Html::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
626 $loginPrompt
627 . $languageLinks
628 . $signupStart
629 . Html::rawElement( 'div', [ 'id' => 'userloginForm' ],
630 $formHtml
631 )
632 . $benefitsContainer
633 );
634
635 return $html;
636 }
637
638 /**
639 * Generates a form from the given request.
640 * @param AuthenticationRequest[] $requests
641 * @param string $action AuthManager action name
642 * @param string|Message $msg
643 * @param string $msgType
644 * @return HTMLForm
645 */
646 protected function getAuthForm( array $requests, $action, $msg = '', $msgType = 'error' ) {
647 global $wgSecureLogin;
648 // FIXME merge this with parent
649
650 if ( isset( $this->authForm ) ) {
651 return $this->authForm;
652 }
653
654 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
655
656 // get basic form description from the auth logic
657 $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
658 // this will call onAuthChangeFormFields()
659 $formDescriptor = static::fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction );
660 $this->postProcessFormDescriptor( $formDescriptor, $requests );
661
662 $context = $this->getContext();
663 if ( $context->getRequest() !== $this->getRequest() ) {
664 // We have overridden the request, need to make sure the form uses that too.
665 $context = new DerivativeContext( $this->getContext() );
666 $context->setRequest( $this->getRequest() );
667 }
668 $form = HTMLForm::factory( 'vform', $formDescriptor, $context );
669
670 $form->addHiddenField( 'authAction', $this->authAction );
671 if ( $this->mLanguage ) {
672 $form->addHiddenField( 'uselang', $this->mLanguage );
673 }
674 $form->addHiddenField( 'force', $this->securityLevel );
675 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
676 if ( $wgSecureLogin ) {
677 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
678 if ( !$this->isSignup() ) {
679 $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS );
680 $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
681 }
682 }
683
684 // set properties of the form itself
685 $form->setAction( $this->getPageTitle()->getLocalURL( $this->getReturnToQueryStringFragment() ) );
686 $form->setName( 'userlogin' . ( $this->isSignup() ? '2' : '' ) );
687 if ( $this->isSignup() ) {
688 $form->setId( 'userlogin2' );
689 }
690
691 $form->suppressDefaultSubmit();
692
693 $this->authForm = $form;
694
695 return $form;
696 }
697
698 public function onAuthChangeFormFields(
699 array $requests, array $fieldInfo, array &$formDescriptor, $action
700 ) {
701 $coreFieldDescriptors = $this->getFieldDefinitions();
702
703 // keep the ordering from getCoreFieldDescriptors() where there is no explicit weight
704 foreach ( $coreFieldDescriptors as $fieldName => $coreField ) {
705 $requestField = $formDescriptor[$fieldName] ?? [];
706
707 // remove everything that is not in the fieldinfo, is not marked as a supplemental field
708 // to something in the fieldinfo, and is not an info field or a submit button
709 if (
710 !isset( $fieldInfo[$fieldName] )
711 && (
712 !isset( $coreField['baseField'] )
713 || !isset( $fieldInfo[$coreField['baseField']] )
714 )
715 && (
716 !isset( $coreField['type'] )
717 || !in_array( $coreField['type'], [ 'submit', 'info' ], true )
718 )
719 ) {
720 $coreFieldDescriptors[$fieldName] = null;
721 continue;
722 }
723
724 // core message labels should always take priority
725 if (
726 isset( $coreField['label'] )
727 || isset( $coreField['label-message'] )
728 || isset( $coreField['label-raw'] )
729 ) {
730 unset( $requestField['label'], $requestField['label-message'], $coreField['label-raw'] );
731 }
732
733 $coreFieldDescriptors[$fieldName] += $requestField;
734 }
735
736 $formDescriptor = array_filter( $coreFieldDescriptors + $formDescriptor );
737 return true;
738 }
739
740 /**
741 * Show extra information such as password recovery information, link from login to signup,
742 * CTA etc? Such information should only be shown on the "landing page", ie. when the user
743 * is at the first step of the authentication process.
744 * @return bool
745 */
746 protected function showExtraInformation() {
747 return $this->authAction !== $this->getContinueAction( $this->authAction )
748 && !$this->securityLevel;
749 }
750
751 /**
752 * Create a HTMLForm descriptor for the core login fields.
753 * @return array
754 */
755 protected function getFieldDefinitions() {
756 global $wgEmailConfirmToEdit;
757
758 $isLoggedIn = $this->getUser()->isLoggedIn();
759 $continuePart = $this->isContinued() ? 'continue-' : '';
760 $anotherPart = $isLoggedIn ? 'another-' : '';
761 // @phan-suppress-next-line PhanUndeclaredMethod
762 $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
763 $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
764 $secureLoginLink = '';
765 if ( $this->mSecureLoginUrl ) {
766 $secureLoginLink = Html::element( 'a', [
767 'href' => $this->mSecureLoginUrl,
768 'class' => 'mw-ui-flush-right mw-secure',
769 ], $this->msg( 'userlogin-signwithsecure' )->text() );
770 }
771 $usernameHelpLink = '';
772 if ( !$this->msg( 'createacct-helpusername' )->isDisabled() ) {
773 $usernameHelpLink = Html::rawElement( 'span', [
774 'class' => 'mw-ui-flush-right',
775 ], $this->msg( 'createacct-helpusername' )->parse() );
776 }
777
778 if ( $this->isSignup() ) {
779 $fieldDefinitions = [
780 'statusarea' => [
781 // used by the mediawiki.special.userlogin.signup.js module for error display
782 // FIXME merge this with HTMLForm's normal status (error) area
783 'type' => 'info',
784 'raw' => true,
785 'default' => Html::element( 'div', [ 'id' => 'mw-createacct-status-area' ] ),
786 'weight' => -105,
787 ],
788 'username' => [
789 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $usernameHelpLink,
790 'id' => 'wpName2',
791 'placeholder-message' => $isLoggedIn ? 'createacct-another-username-ph'
792 : 'userlogin-yourname-ph',
793 ],
794 'mailpassword' => [
795 // create account without providing password, a temporary one will be mailed
796 'type' => 'check',
797 'label-message' => 'createaccountmail',
798 'name' => 'wpCreateaccountMail',
799 'id' => 'wpCreateaccountMail',
800 ],
801 'password' => [
802 'id' => 'wpPassword2',
803 'placeholder-message' => 'createacct-yourpassword-ph',
804 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
805 ],
806 'domain' => [],
807 'retype' => [
808 'baseField' => 'password',
809 'type' => 'password',
810 'label-message' => 'createacct-yourpasswordagain',
811 'id' => 'wpRetype',
812 'cssclass' => 'loginPassword',
813 'size' => 20,
814 'validation-callback' => function ( $value, $alldata ) {
815 if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
816 if ( !$value ) {
817 return $this->msg( 'htmlform-required' );
818 } elseif ( $value !== $alldata['password'] ) {
819 return $this->msg( 'badretype' );
820 }
821 }
822 return true;
823 },
824 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
825 'placeholder-message' => 'createacct-yourpasswordagain-ph',
826 ],
827 'email' => [
828 'type' => 'email',
829 'label-message' => $wgEmailConfirmToEdit ? 'createacct-emailrequired'
830 : 'createacct-emailoptional',
831 'id' => 'wpEmail',
832 'cssclass' => 'loginText',
833 'size' => '20',
834 // FIXME will break non-standard providers
835 'required' => $wgEmailConfirmToEdit,
836 'validation-callback' => function ( $value, $alldata ) {
837 global $wgEmailConfirmToEdit;
838
839 // AuthManager will check most of these, but that will make the auth
840 // session fail and this won't, so nicer to do it this way
841 if ( !$value && $wgEmailConfirmToEdit ) {
842 // no point in allowing registration without email when email is
843 // required to edit
844 return $this->msg( 'noemailtitle' );
845 } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
846 // cannot send password via email when there is no email address
847 return $this->msg( 'noemailcreate' );
848 } elseif ( $value && !Sanitizer::validateEmail( $value ) ) {
849 return $this->msg( 'invalidemailaddress' );
850 }
851 return true;
852 },
853 'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
854 ],
855 'realname' => [
856 'type' => 'text',
857 'help-message' => $isLoggedIn ? 'createacct-another-realname-tip'
858 : 'prefs-help-realname',
859 'label-message' => 'createacct-realname',
860 'cssclass' => 'loginText',
861 'size' => 20,
862 'id' => 'wpRealName',
863 ],
864 'reason' => [
865 // comment for the user creation log
866 'type' => 'text',
867 'label-message' => 'createacct-reason',
868 'cssclass' => 'loginText',
869 'id' => 'wpReason',
870 'size' => '20',
871 'placeholder-message' => 'createacct-reason-ph',
872 ],
873 'createaccount' => [
874 // submit button
875 'type' => 'submit',
876 'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
877 'submit' )->text(),
878 'name' => 'wpCreateaccount',
879 'id' => 'wpCreateaccount',
880 'weight' => 100,
881 ],
882 ];
883 } else {
884 $fieldDefinitions = [
885 'username' => [
886 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
887 'id' => 'wpName1',
888 'placeholder-message' => 'userlogin-yourname-ph',
889 ],
890 'password' => [
891 'id' => 'wpPassword1',
892 'placeholder-message' => 'userlogin-yourpassword-ph',
893 ],
894 'domain' => [],
895 'rememberMe' => [
896 // option for saving the user token to a cookie
897 'type' => 'check',
898 'name' => 'wpRemember',
899 'label-message' => $this->msg( 'userlogin-remembermypassword' )
900 ->numParams( $expirationDays ),
901 'id' => 'wpRemember',
902 ],
903 'loginattempt' => [
904 // submit button
905 'type' => 'submit',
906 'default' => $this->msg( 'pt-login-' . $continuePart . 'button' )->text(),
907 'id' => 'wpLoginAttempt',
908 'weight' => 100,
909 ],
910 'linkcontainer' => [
911 // help link
912 'type' => 'info',
913 'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
914 // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
915 'raw' => true,
916 'default' => Html::element( 'a', [
917 'href' => Skin::makeInternalOrExternalUrl( $this->msg( 'helplogin-url' )
918 ->inContentLanguage()
919 ->text() ),
920 ], $this->msg( 'userlogin-helplink2' )->text() ),
921 'weight' => 200,
922 ],
923 // button for ResetPasswordSecondaryAuthenticationProvider
924 'skipReset' => [
925 'weight' => 110,
926 'flags' => [],
927 ],
928 ];
929 }
930
931 $fieldDefinitions['username'] += [
932 'type' => 'text',
933 'name' => 'wpName',
934 'cssclass' => 'loginText',
935 'size' => 20,
936 // 'required' => true,
937 ];
938 $fieldDefinitions['password'] += [
939 'type' => 'password',
940 // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
941 'name' => 'wpPassword',
942 'cssclass' => 'loginPassword',
943 'size' => 20,
944 // 'required' => true,
945 ];
946
947 if ( $this->mEntryError ) {
948 $fieldDefinitions['entryError'] = [
949 'type' => 'info',
950 'default' => Html::rawElement( 'div', [ 'class' => $this->mEntryErrorType . 'box', ],
951 $this->mEntryError ),
952 'raw' => true,
953 'rawrow' => true,
954 'weight' => -100,
955 ];
956 }
957 if ( !$this->showExtraInformation() ) {
958 unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
959 }
960 if ( $this->isSignup() && $this->showExtraInformation() ) {
961 // blank signup footer for site customization
962 // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
963 $signupendMsg = $this->msg( 'signupend' );
964 $signupendHttpsMsg = $this->msg( 'signupend-https' );
965 if ( !$signupendMsg->isDisabled() ) {
966 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
967 $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
968 ? $signupendHttpsMsg->parse() : $signupendMsg->parse();
969 $fieldDefinitions['signupend'] = [
970 'type' => 'info',
971 'raw' => true,
972 'default' => Html::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
973 'weight' => 225,
974 ];
975 }
976 }
977 if ( !$this->isSignup() && $this->showExtraInformation() ) {
978 $passwordReset = new PasswordReset( $this->getConfig(), AuthManager::singleton() );
979 if ( $passwordReset->isAllowed( $this->getUser() )->isGood() ) {
980 $fieldDefinitions['passwordReset'] = [
981 'type' => 'info',
982 'raw' => true,
983 'cssclass' => 'mw-form-related-link-container',
984 'default' => $this->getLinkRenderer()->makeLink(
985 SpecialPage::getTitleFor( 'PasswordReset' ),
986 $this->msg( 'userlogin-resetpassword-link' )->text()
987 ),
988 'weight' => 230,
989 ];
990 }
991
992 // Don't show a "create account" link if the user can't.
993 if ( $this->showCreateAccountLink() ) {
994 // link to the other action
995 $linkTitle = $this->getTitleFor( $this->isSignup() ? 'Userlogin' : 'CreateAccount' );
996 $linkq = $this->getReturnToQueryStringFragment();
997 // Pass any language selection on to the mode switch link
998 if ( $this->mLanguage ) {
999 $linkq .= '&uselang=' . urlencode( $this->mLanguage );
1000 }
1001 $loggedIn = $this->getUser()->isLoggedIn();
1002
1003 $fieldDefinitions['createOrLogin'] = [
1004 'type' => 'info',
1005 'raw' => true,
1006 'linkQuery' => $linkq,
1007 'default' => function ( $params ) use ( $loggedIn, $linkTitle ) {
1008 return Html::rawElement( 'div',
1009 [ 'id' => 'mw-createaccount' . ( !$loggedIn ? '-cta' : '' ),
1010 'class' => ( $loggedIn ? 'mw-form-related-link-container' : 'mw-ui-vform-field' ) ],
1011 ( $loggedIn ? '' : $this->msg( 'userlogin-noaccount' )->escaped() )
1012 . Html::element( 'a',
1013 [
1014 'id' => 'mw-createaccount-join' . ( $loggedIn ? '-loggedin' : '' ),
1015 'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1016 'class' => ( $loggedIn ? '' : 'mw-ui-button' ),
1017 'tabindex' => 100,
1018 ],
1019 $this->msg(
1020 $loggedIn ? 'userlogin-createanother' : 'userlogin-joinproject'
1021 )->text()
1022 )
1023 );
1024 },
1025 'weight' => 235,
1026 ];
1027 }
1028 }
1029
1030 return $fieldDefinitions;
1031 }
1032
1033 /**
1034 * Check if a session cookie is present.
1035 *
1036 * This will not pick up a cookie set during _this_ request, but is meant
1037 * to ensure that the client is returning the cookie which was set on a
1038 * previous pass through the system.
1039 *
1040 * @return bool
1041 */
1042 protected function hasSessionCookie() {
1043 global $wgDisableCookieCheck, $wgInitialSessionId;
1044
1045 return $wgDisableCookieCheck || (
1046 $wgInitialSessionId &&
1047 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1048 );
1049 }
1050
1051 /**
1052 * Returns a string that can be appended to the URL (without encoding) to preserve the
1053 * return target. Does not include leading '?'/'&'.
1054 * @return string
1055 */
1056 protected function getReturnToQueryStringFragment() {
1057 $returnto = '';
1058 if ( $this->mReturnTo !== '' ) {
1059 $returnto = 'returnto=' . wfUrlencode( $this->mReturnTo );
1060 if ( $this->mReturnToQuery !== '' ) {
1061 $returnto .= '&returntoquery=' . wfUrlencode( $this->mReturnToQuery );
1062 }
1063 }
1064 return $returnto;
1065 }
1066
1067 /**
1068 * Whether the login/create account form should display a link to the
1069 * other form (in addition to whatever the skin provides).
1070 * @return bool
1071 */
1072 private function showCreateAccountLink() {
1073 if ( $this->isSignup() ) {
1074 return true;
1075 } elseif ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1076 return true;
1077 } else {
1078 return false;
1079 }
1080 }
1081
1082 protected function getTokenName() {
1083 return $this->isSignup() ? 'wpCreateaccountToken' : 'wpLoginToken';
1084 }
1085
1086 /**
1087 * Produce a bar of links which allow the user to select another language
1088 * during login/registration but retain "returnto"
1089 *
1090 * @return string
1091 */
1092 protected function makeLanguageSelector() {
1093 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1094 if ( $msg->isBlank() ) {
1095 return '';
1096 }
1097 $langs = explode( "\n", $msg->text() );
1098 $links = [];
1099 foreach ( $langs as $lang ) {
1100 $lang = trim( $lang, '* ' );
1101 $parts = explode( '|', $lang );
1102 if ( count( $parts ) >= 2 ) {
1103 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1104 }
1105 }
1106
1107 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1108 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1109 }
1110
1111 /**
1112 * Create a language selector link for a particular language
1113 * Links back to this page preserving type and returnto
1114 *
1115 * @param string $text Link text
1116 * @param string $lang Language code
1117 * @return string
1118 */
1119 protected function makeLanguageSelectorLink( $text, $lang ) {
1120 if ( $this->getLanguage()->getCode() == $lang ) {
1121 // no link for currently used language
1122 return htmlspecialchars( $text );
1123 }
1124 $query = [ 'uselang' => $lang ];
1125 if ( $this->mReturnTo !== '' ) {
1126 $query['returnto'] = $this->mReturnTo;
1127 $query['returntoquery'] = $this->mReturnToQuery;
1128 }
1129
1130 $attr = [];
1131 $targetLanguage = Language::factory( $lang );
1132 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1133
1134 return $this->getLinkRenderer()->makeKnownLink(
1135 $this->getPageTitle(),
1136 $text,
1137 $attr,
1138 $query
1139 );
1140 }
1141
1142 protected function getGroupName() {
1143 return 'login';
1144 }
1145
1146 /**
1147 * @param array &$formDescriptor
1148 * @param array $requests
1149 */
1150 protected function postProcessFormDescriptor( &$formDescriptor, $requests ) {
1151 // Pre-fill username (if not creating an account, T46775).
1152 if (
1153 isset( $formDescriptor['username'] ) &&
1154 !isset( $formDescriptor['username']['default'] ) &&
1155 !$this->isSignup()
1156 ) {
1157 $user = $this->getUser();
1158 if ( $user->isLoggedIn() ) {
1159 $formDescriptor['username']['default'] = $user->getName();
1160 } else {
1161 $formDescriptor['username']['default'] =
1162 $this->getRequest()->getSession()->suggestLoginUsername();
1163 }
1164 }
1165
1166 // don't show a submit button if there is nothing to submit (i.e. the only form content
1167 // is other submit buttons, for redirect flows)
1168 if ( !$this->needsSubmitButton( $requests ) ) {
1169 unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1170 }
1171
1172 if ( !$this->isSignup() ) {
1173 // FIXME HACK don't focus on non-empty field
1174 // maybe there should be an autofocus-if similar to hide-if?
1175 if (
1176 isset( $formDescriptor['username'] )
1177 && empty( $formDescriptor['username']['default'] )
1178 && !$this->getRequest()->getCheck( 'wpName' )
1179 ) {
1180 $formDescriptor['username']['autofocus'] = true;
1181 } elseif ( isset( $formDescriptor['password'] ) ) {
1182 $formDescriptor['password']['autofocus'] = true;
1183 }
1184 }
1185
1186 $this->addTabIndex( $formDescriptor );
1187 }
1188 }