Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
95.89% covered (success)
95.89%
70 / 73
70.00% covered (warning)
70.00%
7 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
PageHTMLHandler
95.89% covered (success)
95.89%
70 / 73
70.00% covered (warning)
70.00%
7 / 10
19
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getRedirectHelper
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 postValidationSetup
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
5
 run
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
2
 getETag
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 getLastModified
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 needsWriteAccess
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getParamSettings
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 getHeaderParamSettings
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 generateResponseSpec
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace MediaWiki\Rest\Handler;
4
5use MediaWiki\Parser\ParserOptions;
6use MediaWiki\Rest\Handler;
7use MediaWiki\Rest\Handler\Helper\HtmlOutputHelper;
8use MediaWiki\Rest\Handler\Helper\HtmlOutputRendererHelper;
9use MediaWiki\Rest\Handler\Helper\PageContentHelper;
10use MediaWiki\Rest\Handler\Helper\PageRedirectHelper;
11use MediaWiki\Rest\Handler\Helper\PageRestHelperFactory;
12use MediaWiki\Rest\LocalizedHttpException;
13use MediaWiki\Rest\Response;
14use MediaWiki\Rest\ResponseHeaders;
15use MediaWiki\Rest\SimpleHandler;
16use MediaWiki\Rest\StringStream;
17use Wikimedia\Assert\Assert;
18use Wikimedia\Message\MessageValue;
19use Wikimedia\ParamValidator\ParamValidator;
20
21/**
22 * A handler that returns Parsoid HTML for the following route:
23 * - /page/{title}/html
24 *
25 * (The /page/{title}/with_html route is served by PageHandler via prop=html.)
26 *
27 * @internal
28 */
29class PageHTMLHandler extends SimpleHandler {
30
31    private HtmlOutputHelper $htmlHelper;
32    private readonly PageContentHelper $contentHelper;
33
34    public function __construct(
35        private readonly PageRestHelperFactory $helperFactory,
36    ) {
37        $this->contentHelper = $helperFactory->newPageContentHelper();
38    }
39
40    private function getRedirectHelper(): PageRedirectHelper {
41        return $this->helperFactory->newPageRedirectHelper(
42            $this->getResponseFactory(),
43            $this->getRouter(),
44            $this->getRoutePath(),
45            $this->getRequest()
46        );
47    }
48
49    protected function postValidationSetup() {
50        $authority = $this->getAuthority();
51        $this->contentHelper->init( $authority, $this->getValidatedParams() );
52
53        $page = $this->contentHelper->getPageIdentity();
54        $isShadowPage = $this->contentHelper->useShadowContent();
55
56        if ( $page ) {
57            if ( $isShadowPage ) {
58                $this->htmlHelper = $this->helperFactory->newHtmlShadowOutputHelper(
59                    $page,
60                    ParserOptions::newFromAnon()
61                );
62            } else {
63                $revision = $this->contentHelper->getTargetRevision();
64                $this->htmlHelper = $this->helperFactory->newHtmlOutputRendererHelper(
65                    $page, $this->getValidatedParams(), $authority, $revision
66                );
67
68                $request = $this->getRequest();
69                $acceptLanguage = $request->getHeaderLine( 'Accept-Language' ) ?: null;
70                if ( $acceptLanguage ) {
71                    $this->htmlHelper->setVariantConversionLanguage(
72                        $acceptLanguage
73                    );
74                }
75            }
76        }
77    }
78
79    /**
80     * @return Response
81     * @throws LocalizedHttpException
82     */
83    public function run(): Response {
84        $this->contentHelper->checkAccessPermission();
85        $page = $this->contentHelper->getPageIdentity();
86
87        $followWikiRedirects = $this->contentHelper->getRedirectsAllowed();
88
89        // The call to $this->contentHelper->getPage() should not return null if
90        // $this->contentHelper->checkAccessPermission() did not throw.
91        Assert::invariant( $page !== null, 'Page should be known' );
92
93        $redirectHelper = $this->getRedirectHelper();
94        $redirectHelper->setFollowWikiRedirects( $followWikiRedirects );
95        // Should treat variant redirects a special case as wiki redirects
96        // if ?redirect=no language variant should do nothing and fall into the 404 path
97        $redirectResponse = $redirectHelper->createRedirectResponseIfNeeded(
98            $page,
99            $this->contentHelper->getTitleText()
100        );
101
102        if ( $redirectResponse !== null ) {
103            // XXX: Do we really want 60 second max-age for wiki redirects as well?
104            //      Shouldn't that use the same max-age as page content?
105            //      PageRedirectHelper already sets a longer max-age for normalization redirects.
106            $redirectResponse->setHeader( ResponseHeaders::CACHE_CONTROL, 'max-age=60' );
107            return $redirectResponse;
108        }
109
110        // We could have a missing page at this point, check and return 404 if that's the case
111        $this->contentHelper->checkHasContent();
112
113        $cacheExpiry = $this->htmlHelper->getHtml()->getCacheExpiry();
114
115        // This endpoint emits a full document from the page bundle
116        $parserOutputHtml = $this->htmlHelper->getPageBundle()->html;
117
118        $response = $this->getResponseFactory()->create();
119        $this->contentHelper->setCacheControl( $response, $cacheExpiry );
120        $response->setBody( new StringStream( $parserOutputHtml ) );
121
122        $this->htmlHelper->putHeaders( $response );
123        return $response;
124    }
125
126    /**
127     * Returns an ETag representing a page's source. The ETag assumes a page's source has changed
128     * if the latest revision of a page has been made private, un-readable for another reason,
129     * or a newer revision exists.
130     * @return string|null
131     */
132    protected function getETag(): ?string {
133        if ( !$this->contentHelper->isAccessible() || !$this->contentHelper->hasContent() ) {
134            return null;
135        }
136
137        return $this->htmlHelper->getETag();
138    }
139
140    protected function getLastModified(): ?string {
141        if ( !$this->contentHelper->isAccessible() || !$this->contentHelper->hasContent() ) {
142            return null;
143        }
144
145        return $this->htmlHelper->getLastModified();
146    }
147
148    public function needsWriteAccess(): bool {
149        return false;
150    }
151
152    public function getParamSettings(): array {
153        return array_merge(
154            $this->contentHelper->getParamSettings(),
155            // Note that postValidation we might end up using
156            // a HtmlShadowOutputHelper, but the param settings
157            // for that are a subset of those for HtmlOutputRendererHelper
158            HtmlOutputRendererHelper::getParamSettings()
159        );
160    }
161
162    public function getHeaderParamSettings(): array {
163        return [
164            'Accept-Language' => [
165                self::PARAM_SOURCE => 'header',
166                ParamValidator::PARAM_TYPE => 'string',
167                ParamValidator::PARAM_REQUIRED => false,
168                Handler::PARAM_DESCRIPTION => new MessageValue( 'rest-requestheader-desc-acceptlanguage' ),
169                Handler::PARAM_EXAMPLE => 'en',
170            ],
171        ];
172    }
173
174    protected function generateResponseSpec( string $method ): array {
175        $spec = parent::generateResponseSpec( $method );
176
177        // TODO: Consider if we prefer something like:
178        //    text/html; charset=utf-8; profile="https://www.mediawiki.org/wiki/Specs/HTML/2.8.0"
179        //  That would be more specific, but fragile when the profile version changes. It could
180        //  also be inaccurate if the page content was not in fact produced by Parsoid.
181        unset( $spec['200']['content']['application/json'] );
182        $spec['200']['content']['text/html']['schema']['type'] = 'string';
183        $spec['200']['content']['text/html']['example'] = '<h2 id="mwAA">Hello world</h2>';
184
185        return $spec;
186    }
187
188}