Debian Codegraph @

includes/parser/Parsoid/Config/DataAccess.php

raw symbols SCIP
1 <?php
2 /**
3 * Copyright (C) 2011-2022 Wikimedia Foundation and others.
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 */
19
20 namespace MediaWiki\Parser\Parsoid\Config;
21
22 use File;
23 use MediaTransformError;
24 use MediaWiki\Cache\LinkBatchFactory;
25 use MediaWiki\Category\TrackingCategories;
26 use MediaWiki\Config\ServiceOptions;
27 use MediaWiki\Content\ContentHandler;
28 use MediaWiki\Content\Transform\ContentTransformer;
29 use MediaWiki\HookContainer\HookContainer;
30 use MediaWiki\HookContainer\HookRunner;
31 use MediaWiki\Language\LanguageCode;
32 use MediaWiki\Linker\Linker;
33 use MediaWiki\MainConfigNames;
34 use MediaWiki\Page\File\BadFileLookup;
35 use MediaWiki\Parser\Parser;
36 use MediaWiki\Parser\ParserFactory;
37 use MediaWiki\Parser\PPFrame;
38 use MediaWiki\Title\Title;
39 use RepoGroup;
40 use Wikimedia\Assert\UnreachableException;
41 use Wikimedia\Parsoid\Config\DataAccess as IDataAccess;
42 use Wikimedia\Parsoid\Config\PageConfig as IPageConfig;
43 use Wikimedia\Parsoid\Config\PageContent as IPageContent;
44 use Wikimedia\Parsoid\Core\ContentMetadataCollector;
45 use Wikimedia\Parsoid\Core\LinkTarget as ParsoidLinkTarget;
46 use Wikimedia\Rdbms\ReadOnlyMode;
47
48 /**
49 * Implement Parsoid's abstract class for data access.
50 *
51 * @since 1.39
52 * @internal
53 */
54 class DataAccess extends IDataAccess {
55 public const CONSTRUCTOR_OPTIONS = [
56 MainConfigNames::SVGMaxSize,
57 ];
58
59 private RepoGroup $repoGroup;
60 private BadFileLookup $badFileLookup;
61 private HookContainer $hookContainer;
62 private HookRunner $hookRunner;
63 private ContentTransformer $contentTransformer;
64 private TrackingCategories $trackingCategories;
65 private ParserFactory $parserFactory;
66 /** Lazy-created via self::prepareParser() */
67 private ?Parser $parser = null;
68 private PPFrame $ppFrame;
69 private ?PageConfig $previousPageConfig = null;
70 private ServiceOptions $config;
71 private ReadOnlyMode $readOnlyMode;
72 private LinkBatchFactory $linkBatchFactory;
73
74 /**
75 * @param ServiceOptions $config MediaWiki main configuration object
76 * @param RepoGroup $repoGroup
77 * @param BadFileLookup $badFileLookup
78 * @param HookContainer $hookContainer
79 * @param ContentTransformer $contentTransformer
80 * @param TrackingCategories $trackingCategories
81 * @param ReadOnlyMode $readOnlyMode used to disable linting when the
82 * database is read-only.
83 * @param ParserFactory $parserFactory A legacy parser factory,
84 * for PST/preprocessing/extension handling
85 * @param LinkBatchFactory $linkBatchFactory
86 */
87 public function __construct(
88 ServiceOptions $config,
89 RepoGroup $repoGroup,
90 BadFileLookup $badFileLookup,
91 HookContainer $hookContainer,
92 ContentTransformer $contentTransformer,
93 TrackingCategories $trackingCategories,
94 ReadOnlyMode $readOnlyMode,
95 ParserFactory $parserFactory,
96 LinkBatchFactory $linkBatchFactory
97 ) {
98 $config->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
99 $this->config = $config;
100 $this->repoGroup = $repoGroup;
101 $this->badFileLookup = $badFileLookup;
102 $this->hookContainer = $hookContainer;
103 $this->contentTransformer = $contentTransformer;
104 $this->trackingCategories = $trackingCategories;
105 $this->readOnlyMode = $readOnlyMode;
106 $this->linkBatchFactory = $linkBatchFactory;
107
108 $this->hookRunner = new HookRunner( $hookContainer );
109
110 $this->parserFactory = $parserFactory;
111 $this->previousPageConfig = null; // ensure we initialize parser options
112 }
113
114 /**
115 * @param IPageConfig $pageConfig
116 * @param File $file
117 * @param array $hp
118 * @return array
119 */
120 private function makeTransformOptions( IPageConfig $pageConfig, $file, array $hp ): array {
121 // Validate the input parameters like Parser::makeImage()
122 $handler = $file->getHandler();
123 if ( !$handler ) {
124 return []; // will get iconThumb()
125 }
126 foreach ( $hp as $name => $value ) {
127 if ( !$handler->validateParam( $name, $value ) ) {
128 unset( $hp[$name] );
129 }
130 }
131
132 // This part is similar to Linker::makeImageLink(). If there is no width,
133 // set one based on the source file size.
134 $page = $hp['page'] ?? 0;
135 if ( !isset( $hp['width'] ) ) {
136 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
137 // If it's a vector image, and user only specifies height
138 // we don't want it to be limited by its "normal" width.
139 $hp['width'] = $this->config->get( MainConfigNames::SVGMaxSize );
140 } else {
141 $hp['width'] = $file->getWidth( $page );
142 }
143
144 // We don't need to fill in a default thumbnail width here, since
145 // that is done by Parsoid. Parsoid always sets the width parameter
146 // for thumbnails.
147 }
148
149 // Parser::makeImage() always sets this
150 $hp['targetlang'] = LanguageCode::bcp47ToInternal(
151 $pageConfig->getPageLanguageBcp47()
152 );
153
154 return $hp;
155 }
156
157 /** @inheritDoc */
158 public function getPageInfo( $pageConfigOrTitle, array $titles ): array {
159 if ( $pageConfigOrTitle instanceof IPageConfig ) {
160 $context_title = Title::newFromLinkTarget(
161 $pageConfigOrTitle->getLinkTarget()
162 );
163 } elseif ( is_string( $pageConfigOrTitle ) ) {
164 // Temporary, deprecated.
165 $context_title = Title::newFromTextThrow( $pageConfigOrTitle );
166 } elseif ( $pageConfigOrTitle instanceof ParsoidLinkTarget ) {
167 $context_title = Title::newFromLinkTarget( $pageConfigOrTitle );
168 } else {
169 throw new UnreachableException( "Bad type for argument 1" );
170 }
171 $titleObjs = [];
172 $pagemap = [];
173 $classes = [];
174 $ret = [];
175 foreach ( $titles as $name ) {
176 $t = Title::newFromText( $name );
177 // Filter out invalid titles. Title::newFromText in core (not our bespoke
178 // version in src/Utils/Title.php) can return null for invalid titles.
179 if ( !$t ) {
180 // FIXME: This is a bandaid to patch up the fact that Env::makeTitle treats
181 // this as a valid title, but Title::newFromText treats it as invalid.
182 // T237535
183 // This matches what ApiQuery::outputGeneralPageInfo() would
184 // return for an invalid title.
185 $ret[$name] = [
186 'pageId' => -1,
187 'revId' => -1,
188 'invalid' => true,
189 'invalidreason' => 'The requested page title is invalid',
190 ];
191 } else {
192 $titleObjs[$name] = $t;
193 }
194 }
195 $linkBatch = $this->linkBatchFactory->newLinkBatch( $titleObjs );
196 $linkBatch->setCaller( __METHOD__ );
197 $linkBatch->execute();
198
199 foreach ( $titleObjs as $obj ) {
200 $pdbk = $obj->getPrefixedDBkey();
201 $pagemap[$obj->getArticleID()] = $pdbk;
202 $classes[$pdbk] = $obj->isRedirect() ? 'mw-redirect' : '';
203 }
204 $this->hookRunner->onGetLinkColours(
205 # $classes is passed by reference and mutated
206 $pagemap, $classes, $context_title
207 );
208
209 foreach ( $titleObjs as $name => $obj ) {
210 /** @var Title $obj */
211 $pdbk = $obj->getPrefixedDBkey();
212 $c = preg_split(
213 '/\s+/', $classes[$pdbk] ?? '', -1, PREG_SPLIT_NO_EMPTY
214 );
215 $ret[$name] = [
216 'pageId' => $obj->getArticleID(),
217 'revId' => $obj->getLatestRevID(),
218 'missing' => !$obj->exists(),
219 'known' => $obj->isKnown(),
220 'redirect' => $obj->isRedirect(),
221 'linkclasses' => $c, # See ApiQueryInfo::getLinkClasses() in core
222 ];
223 }
224 return $ret;
225 }
226
227 /** @inheritDoc */
228 public function getFileInfo( IPageConfig $pageConfig, array $files ): array {
229 $page = Title::newFromLinkTarget( $pageConfig->getLinkTarget() );
230
231 $keys = [];
232 foreach ( $files as $f ) {
233 $keys[] = $f[0];
234 }
235 $fileObjs = $this->repoGroup->findFiles( $keys );
236
237 $ret = [];
238 foreach ( $files as $f ) {
239 $filename = $f[0];
240 $dims = $f[1];
241
242 /** @var File $file */
243 $file = $fileObjs[$filename] ?? null;
244 if ( !$file ) {
245 $ret[] = null;
246 continue;
247 }
248
249 // See Linker::makeImageLink; 'page' is a key in $handlerParams
250 // core uses 'false' as the default then casts to (int) => 0
251 $pageNum = $dims['page'] ?? 0;
252
253 $result = [
254 'width' => $file->getWidth( $pageNum ),
255 'height' => $file->getHeight( $pageNum ),
256 'size' => $file->getSize(),
257 'mediatype' => $file->getMediaType(),
258 'mime' => $file->getMimeType(),
259 'url' => $file->getFullUrl(),
260 'mustRender' => $file->mustRender(),
261 'badFile' => $this->badFileLookup->isBadFile( $filename, $page ),
262 'timestamp' => $file->getTimestamp(),
263 'sha1' => $file->getSha1(),
264 ];
265
266 $length = $file->getLength();
267 if ( $length ) {
268 $result['duration'] = (float)$length;
269 }
270
271 if ( isset( $dims['seek'] ) ) {
272 $dims['thumbtime'] = $dims['seek'];
273 }
274
275 $txopts = $this->makeTransformOptions( $pageConfig, $file, $dims );
276 $mto = $file->transform( $txopts );
277 if ( $mto ) {
278 if ( $mto->isError() && $mto instanceof MediaTransformError ) {
279 $result['thumberror'] = $mto->toText();
280 } else {
281 if ( $txopts ) {
282 // Do srcset scaling
283 Linker::processResponsiveImages( $file, $mto, $txopts );
284 if ( count( $mto->responsiveUrls ) ) {
285 $result['responsiveUrls'] = [];
286 foreach ( $mto->responsiveUrls as $density => $url ) {
287 $result['responsiveUrls'][$density] = $url;
288 }
289 }
290 }
291
292 // Proposed MediaTransformOutput serialization method for T51896 etc.
293 // Note that getAPIData(['fullurl']) would return
294 // UrlUtils::expand(), which wouldn't respect the wiki's
295 // protocol preferences -- instead it would use the
296 // protocol used for the API request.
297 if ( is_callable( [ $mto, 'getAPIData' ] ) ) {
298 $result['thumbdata'] = $mto->getAPIData( [ 'withhash' ] );
299 }
300
301 $result['thumburl'] = $mto->getUrl();
302 $result['thumbwidth'] = $mto->getWidth();
303 $result['thumbheight'] = $mto->getHeight();
304 }
305 } else {
306 $result['thumberror'] = "Presumably, invalid parameters, despite validation.";
307 }
308
309 $ret[] = $result;
310 }
311
312 return $ret;
313 }
314
315 /**
316 * Prepare MediaWiki's parser for preprocessing or extension tag parsing,
317 * clearing its state if necessary.
318 *
319 * @param IPageConfig $pageConfig
320 * @param int $outputType
321 * @return Parser
322 */
323 private function prepareParser( IPageConfig $pageConfig, int $outputType ) {
324 '@phan-var PageConfig $pageConfig'; // @var PageConfig $pageConfig
325 // Clear the state only when the PageConfig changes, so that Parser's internal caches can
326 // be retained. This should also provide better compatibility with extension tags.
327 $clearState = $this->previousPageConfig !== $pageConfig;
328 $this->previousPageConfig = $pageConfig;
329 // Use the same legacy parser object for all calls to extension tag
330 // processing, for greater compatibility.
331 $this->parser ??= $this->parserFactory->create();
332 $this->parser->startExternalParse(
333 Title::newFromLinkTarget( $pageConfig->getLinkTarget() ),
334 $pageConfig->getParserOptions(),
335 $outputType, $clearState, $pageConfig->getRevisionId() );
336 $this->parser->resetOutput();
337
338 // Retain a PPFrame object between preprocess requests since it contains
339 // some useful caches.
340 if ( $clearState ) {
341 $this->ppFrame = $this->parser->getPreprocessor()->newFrame();
342 }
343 return $this->parser;
344 }
345
346 /** @inheritDoc */
347 public function doPst( IPageConfig $pageConfig, string $wikitext ): string {
348 '@phan-var PageConfig $pageConfig'; // @var PageConfig $pageConfig
349 // This could use prepareParser(), but it's only called once per page,
350 // so it's not essential.
351 $titleObj = Title::newFromLinkTarget( $pageConfig->getLinkTarget() );
352 $user = $pageConfig->getParserOptions()->getUserIdentity();
353 $content = ContentHandler::makeContent( $wikitext, $titleObj, CONTENT_MODEL_WIKITEXT );
354 return $this->contentTransformer->preSaveTransform(
355 $content,
356 $titleObj,
357 $user,
358 $pageConfig->getParserOptions()
359 )->serialize();
360 }
361
362 /** @inheritDoc */
363 public function parseWikitext(
364 IPageConfig $pageConfig,
365 ContentMetadataCollector $metadata,
366 string $wikitext
367 ): string {
368 $parser = $this->prepareParser( $pageConfig, Parser::OT_HTML );
369 $html = $parser->parseExtensionTagAsTopLevelDoc( $wikitext );
370 // XXX: Ideally we will eventually have the legacy parser use our
371 // ContentMetadataCollector instead of having a new ParserOutput
372 // created (implicitly in ::prepareParser()/Parser::resetOutput() )
373 // which we then have to manually merge.
374 $out = $parser->getOutput();
375 $out->setRawText( $html );
376 $out->collectMetadata( $metadata ); # merges $out into $metadata
377 return Parser::extractBody( $out->getRawText() );
378 }
379
380 /** @inheritDoc */
381 public function preprocessWikitext(
382 IPageConfig $pageConfig,
383 ContentMetadataCollector $metadata,
384 string $wikitext
385 ): string {
386 $parser = $this->prepareParser( $pageConfig, Parser::OT_PREPROCESS );
387 $this->hookRunner->onParserBeforePreprocess(
388 # $wikitext is passed by reference and mutated
389 $parser, $wikitext, $parser->getStripState()
390 );
391 $wikitext = $parser->replaceVariables( $wikitext, $this->ppFrame );
392 // FIXME (T289545): StripState markers protect content that need to be protected from further
393 // "wikitext processing". So, where the result has strip state markers, we actually
394 // need to tunnel this content through rather than unwrap and let it go through the
395 // rest of the parsoid pipeline. For example, some parser functions might return HTML
396 // not wikitext, and where the content might contain wikitext characters, we are now
397 // going to potentially mangle that output.
398 $wikitext = $parser->getStripState()->unstripBoth( $wikitext );
399
400 // XXX: Ideally we will eventually have the legacy parser use our
401 // ContentMetadataCollector instead of having a new ParserOutput
402 // created (implicitly in ::prepareParser()/Parser::resetOutput() )
403 // which we then have to manually merge.
404 $out = $parser->getOutput();
405 $out->collectMetadata( $metadata ); # merges $out into $metadata
406 return $wikitext;
407 }
408
409 /** @inheritDoc */
410 public function fetchTemplateSource(
411 IPageConfig $pageConfig, $title
412 ): ?IPageContent {
413 '@phan-var PageConfig $pageConfig'; // @var PageConfig $pageConfig
414 if ( is_string( $title ) ) {
415 $titleObj = Title::newFromTextThrow( $title );
416 } else {
417 $titleObj = Title::newFromLinkTarget( $title );
418 }
419
420 // Use the PageConfig to take advantage of custom template
421 // fetch hooks like FlaggedRevisions, etc.
422 $revRecord = $pageConfig->fetchRevisionRecordOfTemplate( $titleObj );
423
424 return $revRecord ? new PageContent( $revRecord ) : null;
425 }
426
427 /** @inheritDoc */
428 public function fetchTemplateData( IPageConfig $pageConfig, $title ): ?array {
429 $ret = [];
430 if ( !is_string( $title ) ) {
431 $titleObj = Title::newFromLinkTarget( $title );
432 $title = $titleObj->getPrefixedText();
433 }
434 // @todo: This hook needs some clean up: T304899
435 $this->hookRunner->onParserFetchTemplateData(
436 [ $title ],
437 $ret # value returned by reference
438 );
439
440 // Cast value to array since the hook returns this as a stdclass
441 $tplData = $ret[$title] ?? null;
442 if ( $tplData ) {
443 // Deep convert to associative array
444 $tplData = json_decode( json_encode( $tplData ), true );
445 }
446 return $tplData;
447 }
448
449 /**
450 * Add a tracking category with the given key to the metadata for the page.
451 * @param IPageConfig $pageConfig the page on which the tracking category
452 * is to be added
453 * @param ContentMetadataCollector $metadata The metadata for the page
454 * @param string $key Message key (not localized)
455 */
456 public function addTrackingCategory(
457 IPageConfig $pageConfig,
458 ContentMetadataCollector $metadata,
459 string $key
460 ): void {
461 $page = Title::newFromLinkTarget( $pageConfig->getLinkTarget() );
462 $this->trackingCategories->addTrackingCategory(
463 $metadata, $key, $page
464 );
465 }
466
467 /** @inheritDoc */
468 public function logLinterData( IPageConfig $pageConfig, array $lints ): void {
469 if ( $this->readOnlyMode->isReadOnly() ) {
470 return;
471 }
472
473 $revId = $pageConfig->getRevisionId();
474 $title = Title::newFromLinkTarget(
475 $pageConfig->getLinkTarget()
476 )->getPrefixedText();
477 $pageInfo = $this->getPageInfo( $pageConfig, [ $title ] );
478 $latest = $pageInfo[$title]['revId'];
479
480 // Only send the request if it the latest revision
481 if ( $revId !== null && $revId === $latest ) {
482 $this->hookRunner->onParserLogLinterData(
483 $title, $revId, $lints
484 );
485 }
486 }
487
488 }