wiki.techinc.nl/includes/Rest/Handler/PageHTMLHandler.php

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

204 lines
6.3 KiB
PHP
Raw Normal View History

<?php
namespace MediaWiki\Rest\Handler;
use LogicException;
use MediaWiki\Rest\Handler\Helper\HtmlOutputHelper;
use MediaWiki\Rest\Handler\Helper\HtmlOutputRendererHelper;
use MediaWiki\Rest\Handler\Helper\PageContentHelper;
use MediaWiki\Rest\Handler\Helper\PageRedirectHelper;
use MediaWiki\Rest\Handler\Helper\PageRestHelperFactory;
use MediaWiki\Rest\LocalizedHttpException;
use MediaWiki\Rest\Response;
use MediaWiki\Rest\SimpleHandler;
use MediaWiki\Rest\StringStream;
use Wikimedia\Assert\Assert;
/**
* A handler that returns Parsoid HTML for the following routes:
* - /page/{title}/html,
* - /page/{title}/with_html
*
* @package MediaWiki\Rest\Handler
*/
class PageHTMLHandler extends SimpleHandler {
private HtmlOutputHelper $htmlHelper;
private PageContentHelper $contentHelper;
private PageRestHelperFactory $helperFactory;
public function __construct(
PageRestHelperFactory $helperFactory
) {
$this->contentHelper = $helperFactory->newPageContentHelper();
$this->helperFactory = $helperFactory;
}
private function getRedirectHelper(): PageRedirectHelper {
return $this->helperFactory->newPageRedirectHelper(
$this->getResponseFactory(),
$this->getRouter(),
$this->getPath(),
$this->getRequest()
);
}
protected function postValidationSetup() {
$authority = $this->getAuthority();
$this->contentHelper->init( $authority, $this->getValidatedParams() );
$page = $this->contentHelper->getPageIdentity();
$isSystemMessage = $this->contentHelper->useDefaultSystemMessage();
if ( $page ) {
if ( $isSystemMessage ) {
$this->htmlHelper = $this->helperFactory->newHtmlMessageOutputHelper( $page );
} else {
$revision = $this->contentHelper->getTargetRevision();
$this->htmlHelper = $this->helperFactory->newHtmlOutputRendererHelper(
$page, $this->getValidatedParams(), $authority, $revision
);
$request = $this->getRequest();
$acceptLanguage = $request->getHeaderLine( 'Accept-Language' ) ?: null;
if ( $acceptLanguage ) {
Use Bcp47Code when interfacing with Parsoid It is very easy for developers and maintainers to mix up "internal MediaWiki language codes" and "BCP-47 language codes"; the latter are standards-compliant and used in web protocols like HTTP, HTML, and SVG; but much of WMF production is very dependent on historical codes used by MediaWiki which in some cases predate the IANA standardized name for the language in question. Phan and other static checking tools aren't much help distinguishing BCP-47 from internal codes when both are represented with the PHP string type, so the wikimedia/bcp-47-code package introduced a very lightweight wrapper type in order to uniquely identify BCP-47 codes. Language implements Bcp47Code, and LanguageFactory::getLanguage() is an easy way to convert (or downcast) between Bcp47Code and Language objects. This patch updates the Parsoid integration code and the associated REST handlers to use Bcp47Code in APIs so that the standalone Parsoid library does not need to know anything about MediaWiki-internal codes. The principle has been, first, to try to convert a string to a Bcp47Code as soon as possible and as close to the original input as possible, so it is easy to see *why* a given string is a BCP-47 code (usually, because it is coming from HTTP/HTML/etc) and we're not stuck deep inside some method trying to figure out where a string we're given is coming from and therefore what sort of string code it might be. Second, we've added explicit compatibility code to accept MediaWiki internal codes and convert them to Bcp47Code for backward compatibility with existing clients, using the @internal LanguageCode::normalizeNonstandardCodeAndWarn() method. The intention is to gradually remove these backward compatibility thunks and replace them with HTTP 400 errors or wfDeprecated messages in order to identify and repair callers who are incorrectly using non-standard-compliant language codes in web standards (HTTP/HTML/SVG/etc). Finally, maintaining a code as a Bcp47Code and not immediately converting to Language helps us delay or even avoid full loading of a Language object in some cases, which is another reason to occasionally push Bcp47Code (instead of Language) down the call stack. Bug: T327379 Depends-On: I830867d58f8962d6a57be16ce3735e8384f9ac1c Change-Id: I982e0df706a633b05dcc02b5220b737c19adc401
2022-11-04 17:29:23 +00:00
$this->htmlHelper->setVariantConversionLanguage(
$acceptLanguage
);
}
}
}
}
/**
* @return Response
* @throws LocalizedHttpException
*/
public function run(): Response {
$this->contentHelper->checkAccessPermission();
$page = $this->contentHelper->getPageIdentity();
$params = $this->getRequest()->getQueryParams();
if ( array_key_exists( 'redirect', $params ) ) {
$followWikiRedirects = $params['redirect'] !== 'no';
} else {
$followWikiRedirects = true;
}
// The call to $this->contentHelper->getPage() should not return null if
// $this->contentHelper->checkAccess() did not throw.
Assert::invariant( $page !== null, 'Page should be known' );
$redirectHelper = $this->getRedirectHelper();
$redirectHelper->setFollowWikiRedirects( $followWikiRedirects );
// Should treat variant redirects a special case as wiki redirects
// if ?redirect=no language variant should do nothing and fall into the 404 path
$redirectResponse = $redirectHelper->createRedirectResponseIfNeeded(
$page,
$this->contentHelper->getTitleText()
);
if ( $redirectResponse !== null ) {
return $redirectResponse;
}
// We could have a missing page at this point, check and return 404 if that's the case
$this->contentHelper->checkHasContent();
$parserOutput = $this->htmlHelper->getHtml();
Allow setting a ParserOption to generate Parsoid HTML This is an initial quick-and-dirty implementation. The ParsoidParser class will eventually inherit from \Parser, but this is an initial placeholder to unblock other Parsoid read views work. Currently Parsoid does not fully implement all the ParserOutput metadata set by the legacy parser, but we're working on it. This patch also addresses T300325 by ensuring the the Page HTML APIs use ParserOutput::getRawText(), which will return the entire Parsoid HTML document without post-processing. This is what the Parsoid team refers to as "edit mode" HTML. The ParserOutput::getText() method returns only the <body> contents of the HTML, and applies several transformations, including inserting Table of Contents and style deduplication; this is the "read views" flavor of the Parsoid HTML. We need to be careful of the interaction of the `useParsoid` flag with the ParserCacheMetadata. Effectively `useParsoid` should *always* be marked as "used" or else the ParserCache will assume its value doesn't matter and will serve legacy content for parsoid requests and vice-versa. T330677 is a follow up to address this more thoroughly by splitting the parser cache in ParserOutputAccess; the stop gap in this patch is fragile and, because it doesn't fork the ParserCacheMetadata cache, may corrupt the ParserCacheMetadata in the case when Parsoid and the legacy parser consult different sets of options to render a page. Bug: T300191 Bug: T330677 Bug: T300325 Change-Id: Ica09a4284c00d7917f8b6249e946232b2fb38011
2022-05-27 16:38:32 +00:00
$parserOutputHtml = $parserOutput->getRawText();
$outputMode = $this->getOutputMode();
switch ( $outputMode ) {
case 'html':
$response = $this->getResponseFactory()->create();
$this->contentHelper->setCacheControl( $response, $parserOutput->getCacheExpiry() );
$response->setBody( new StringStream( $parserOutputHtml ) );
break;
case 'with_html':
$body = $this->contentHelper->constructMetadata();
$body['html'] = $parserOutputHtml;
$redirectTargetUrl = $redirectHelper->getWikiRedirectTargetUrl( $page );
if ( $redirectTargetUrl ) {
$body['redirect_target'] = $redirectTargetUrl;
}
$response = $this->getResponseFactory()->createJson( $body );
$this->contentHelper->setCacheControl( $response, $parserOutput->getCacheExpiry() );
break;
default:
throw new LogicException( "Unknown HTML type $outputMode" );
}
$setContentLanguageHeader = ( $outputMode === 'html' );
$this->htmlHelper->putHeaders( $response, $setContentLanguageHeader );
return $response;
}
/**
* Returns an ETag representing a page's source. The ETag assumes a page's source has changed
* if the latest revision of a page has been made private, un-readable for another reason,
* or a newer revision exists.
* @return string|null
*/
protected function getETag(): ?string {
if ( !$this->contentHelper->isAccessible() || !$this->contentHelper->hasContent() ) {
return null;
}
// Vary eTag based on output mode
return $this->htmlHelper->getETag( $this->getOutputMode() );
}
/**
* @return string|null
*/
protected function getLastModified(): ?string {
if ( !$this->contentHelper->isAccessible() || !$this->contentHelper->hasContent() ) {
return null;
}
return $this->htmlHelper->getLastModified();
}
private function getOutputMode(): string {
return $this->getConfig()['format'];
}
public function needsWriteAccess(): bool {
return false;
}
public function getParamSettings(): array {
return array_merge(
$this->contentHelper->getParamSettings(),
// Note that postValidation we might end up using
// a HtmlMessageOutputHelper, but the param settings
// for that are a subset of those for HtmlOutputRendererHelper
HtmlOutputRendererHelper::getParamSettings()
);
}
protected function generateResponseSpec( string $method ): array {
$spec = parent::generateResponseSpec( $method );
// TODO: Consider if we prefer something like:
// text/html; charset=utf-8; profile="https://www.mediawiki.org/wiki/Specs/HTML/2.8.0"
// That would be more specific, but fragile when the profile version changes. It could
// also be inaccurate if the page content was not in fact produced by Parsoid.
if ( $this->getOutputMode() == 'html' ) {
unset( $spec['200']['content']['application/json'] );
$spec['200']['content']['text/html']['schema']['type'] = 'string';
}
return $spec;
}
public function getResponseBodySchemaFileName( string $method ): ?string {
return 'includes/Rest/Handler/Schema/ExistingPageHtml.json';
}
}