Debian Codegraph @

vendor/wikimedia/parsoid/src/Config/Api/DataAccess.php

raw
1 <?php
2
3 declare( strict_types = 1 );
4
5 namespace Wikimedia\Parsoid\Config\Api;
6
7 use Wikimedia\Parsoid\Config\Api\SiteConfig as ApiSiteConfig;
8 use Wikimedia\Parsoid\Config\DataAccess as IDataAccess;
9 use Wikimedia\Parsoid\Config\PageConfig;
10 use Wikimedia\Parsoid\Config\PageContent;
11 use Wikimedia\Parsoid\Config\SiteConfig as ISiteConfig;
12 use Wikimedia\Parsoid\Core\ContentMetadataCollector;
13 use Wikimedia\Parsoid\Core\ContentMetadataCollectorStringSets as CMCSS;
14 use Wikimedia\Parsoid\Core\LinkTarget;
15 use Wikimedia\Parsoid\Mocks\MockPageContent;
16 use Wikimedia\Parsoid\Utils\PHPUtils;
17 use Wikimedia\Parsoid\Utils\Title;
18 use Wikimedia\Parsoid\Utils\TitleValue;
19
20 /**
21 * DataAccess via MediaWiki's Action API
22 *
23 * Note this is intended for testing, not performance.
24 */
25 class DataAccess extends IDataAccess {
26
27 /** @var ApiHelper */
28 private $api;
29
30 /**
31 * @var bool Should we strip the protocol from returned URLs?
32 * Generally this should be true, since the protocol of the API
33 * request doesn't necessarily match the protocol of article
34 * access; ie, we could be using https to access the API but emit
35 * article content which can be read with http. But for running
36 * parserTests, we need to include the protocol in order to match
37 * the parserTest configuration in core.
38 */
39 private $stripProto;
40
41 /**
42 * @name Caching
43 * @todo Someone should librarize MediaWiki core's MapCacheLRU so we can
44 * pull it in via composer and use it here.
45 * @{
46 */
47
48 private const MAX_CACHE_LEN = 100;
49
50 /**
51 * @var array
52 */
53 private $cache = [];
54
55 private ISiteConfig $siteConfig;
56
57 /**
58 * Get from cache
59 * @param string $key
60 * @return mixed
61 */
62 private function getCache( string $key ) {
63 if ( isset( $this->cache[$key] ) ) {
64 $ret = $this->cache[$key];
65 // The LRU cache uses position in the array to indicate recency, so
66 // move the accessed key to the end.
67 unset( $this->cache[$key] );
68 $this->cache[$key] = $ret;
69 return $ret;
70 }
71 return null;
72 }
73
74 /**
75 * Set a value into cache
76 * @param string $key
77 * @param mixed $value Not null.
78 */
79 private function setCache( string $key, $value ): void {
80 if ( isset( $this->cache[$key] ) ) {
81 // The LRU cache uses position in the array to indicate recency, so
82 // remove the old entry so the new version goes at the end.
83 unset( $this->cache[$key] );
84 } elseif ( count( $this->cache ) >= self::MAX_CACHE_LEN ) {
85 reset( $this->cache );
86 $evictKey = key( $this->cache );
87 unset( $this->cache[$evictKey] );
88 }
89 $this->cache[$key] = $value;
90 }
91
92 /** @} */
93
94 /**
95 * @param ApiHelper $api
96 * @param ISiteConfig $siteConfig
97 * @param array $opts
98 */
99 public function __construct( ApiHelper $api, ISiteConfig $siteConfig, array $opts ) {
100 $this->api = $api;
101 $this->siteConfig = $siteConfig;
102 $this->stripProto = $opts['stripProto'] ?? true;
103 }
104
105 /** @inheritDoc */
106 public function getPageInfo( $pageConfigOrTitle, array $titles ): array {
107 $contextTitle = $pageConfigOrTitle instanceof PageConfig ?
108 $pageConfigOrTitle->getLinkTarget() : $pageConfigOrTitle;
109
110 if ( !$titles ) {
111 return [];
112 }
113
114 $ret = [];
115 $pageConfigTitle = $this->toPrefixedText( $contextTitle );
116 foreach ( array_chunk( $titles, 50 ) as $batch ) {
117 $data = $this->api->makeRequest( [
118 'action' => 'query',
119 'prop' => 'info',
120 'inprop' => 'linkclasses',
121 'inlinkcontext' => $pageConfigTitle,
122 'titles' => implode( '|', $batch ),
123 ] )['query'];
124 $norm = [];
125 if ( isset( $data['normalized'] ) ) {
126 foreach ( $data['normalized'] as $n ) {
127 $from = $n['from'];
128 if ( $n['fromencoded'] ) {
129 $from = rawurldecode( $from );
130 }
131 $norm[$from] = $n['to'];
132 }
133 }
134 $pages = [];
135 foreach ( $data['pages'] as $p ) {
136 $pages[$p['title']] = $p;
137 }
138 foreach ( $batch as $title ) {
139 $ttitle = $title;
140 while ( isset( $norm[$ttitle] ) ) {
141 $ttitle = $norm[$ttitle];
142 }
143 $page = $pages[$ttitle] ?? [];
144 $ret[$title] = [
145 'pageId' => $page['pageid'] ?? null,
146 'revId' => $page['lastrevid'] ?? null,
147 'missing' => $page['missing'] ?? false,
148 'known' => ( $page['known'] ?? false ),
149 'redirect' => $page['redirect'] ?? false,
150 'linkclasses' => $page['linkclasses'] ?? [],
151 'invalid' => $page['invalid'] ?? false,
152 ];
153 if ( !( $ret[$title]['missing'] || $ret[$title]['invalid'] ) ) {
154 $ret[$title]['known'] = true;
155 }
156 }
157 }
158
159 return $ret;
160 }
161
162 /** @inheritDoc */
163 public function getFileInfo( PageConfig $pageConfig, array $files ): array {
164 $pageConfigTitle = $this->toPrefixedText( $pageConfig->getLinkTarget() );
165 $sc = $this->siteConfig;
166 if ( $sc instanceof ApiSiteConfig && $sc->hasVideoInfo() ) {
167 $prefix = "vi";
168 $propName = "videoinfo";
169 } else {
170 $prefix = "ii";
171 $propName = "imageinfo";
172 }
173 $apiArgs2 = [
174 'action' => 'query',
175 'format' => 'json',
176 'formatversion' => 2,
177 'rawcontinue' => 1,
178 'prop' => $propName,
179 "{$prefix}badfilecontexttitle" => $pageConfigTitle,
180 "{$prefix}prop" => implode( '|', [
181 'mediatype', 'mime', 'size', 'url', 'badfile', 'sha1', 'timestamp'
182 ] )
183 ];
184 if ( $prefix === 'vi' ) {
185 $apiArgs2["viprop"] .= '|derivatives|timedtext';
186 }
187 $ret = [];
188 foreach ( $files as $file ) {
189 $apiArgs = $apiArgs2; // Copy since we modify it
190 $name = $file[0];
191 $dims = $file[1];
192
193 $imgNS = $sc->namespaceName( $sc->canonicalNamespaceId( 'file' ) );
194 $apiArgs['titles'] = "$imgNS:$name";
195 $needsWidth = isset( $dims['page'] ) || isset( $dims['lang'] );
196 if ( isset( $dims['width'] ) ) {
197 $apiArgs["{$prefix}urlwidth"] = $dims['width'];
198 if ( $needsWidth ) {
199 if ( isset( $dims['page'] ) ) { // PDF
200 $apiArgs["{$prefix}urlparam"] = "page{$dims['page']}-{$dims['width']}px";
201 } elseif ( isset( $dims['lang'] ) ) { // SVG
202 $apiArgs["{$prefix}urlparam"] = "lang{$dims['lang']}-{$dims['width']}px";
203 }
204 $needsWidth = false;
205 }
206 }
207 if ( isset( $dims['height'] ) ) {
208 $apiArgs["{$prefix}urlheight"] = $dims['height'];
209 }
210 if ( isset( $dims['seek'] ) ) {
211 $apiArgs["{$prefix}urlparam"] = "seek={$dims['seek']}";
212 }
213
214 do {
215 $data = $this->api->makeRequest( $apiArgs );
216 // Expect exactly 1 row
217 $fileinfo = $data['query']['pages'][0][$propName][0];
218 // Corner case: if page is set, the core ImageInfo API doesn't
219 // respect it *unless* width is set as well. So repeat the
220 // request if necessary.
221 if ( isset( $fileinfo['pagecount'] ) && !isset( $dims['page'] ) ) {
222 $dims['page'] = 1; # also ensures we won't get here again
223 $needsWidth = true;
224 }
225 if ( $needsWidth && !isset( $fileinfo['filemissing'] ) ) {
226 $needsWidth = false; # ensure we won't get here again
227 $width = $fileinfo['width'];
228 $apiArgs["{$prefix}urlwidth"] = $width;
229 if ( isset( $dims['page'] ) ) { // PDF
230 $apiArgs["{$prefix}urlparam"] = "page{$dims['page']}-{$width}px";
231 } elseif ( isset( $dims['lang'] ) ) { // SVG
232 $apiArgs["{$prefix}urlparam"] = "lang{$dims['lang']}-{$width}px";
233 }
234 continue;
235 }
236 break;
237 } while ( true );
238
239 if ( isset( $fileinfo['filemissing'] ) ) {
240 $fileinfo = null;
241 } else {
242 $fileinfo['badFile'] = $data['query']['pages'][0]['badfile'];
243 $this->stripProto( $fileinfo, 'url' );
244 $this->stripProto( $fileinfo, 'thumburl' );
245 $this->stripProto( $fileinfo, 'descriptionurl' );
246 $this->stripProto( $fileinfo, 'descriptionshorturl' );
247 foreach ( $fileinfo['responsiveUrls'] ?? [] as $density => $url ) {
248 $this->stripProto( $fileinfo['responsiveUrls'], (string)$density );
249 }
250 if ( $prefix === 'vi' ) {
251 foreach ( $fileinfo['thumbdata']['derivatives'] ?? [] as $j => $d ) {
252 $this->stripProto( $fileinfo['thumbdata']['derivatives'][$j], 'src' );
253 }
254 foreach ( $fileinfo['thumbdata']['timedtext'] ?? [] as $j => $d ) {
255 $this->stripProto( $fileinfo['thumbdata']['timedtext'][$j], 'src' );
256 }
257 }
258 }
259 $ret[] = $fileinfo;
260 }
261 return $ret;
262 }
263
264 /**
265 * Convert the given URL into protocol-relative form.
266 *
267 * @param ?array &$obj
268 * @param string $key
269 */
270 private function stripProto( ?array &$obj, string $key ): void {
271 if ( $obj !== null && !empty( $obj[$key] ) && $this->stripProto ) {
272 $obj[$key] = preg_replace( '#^https?://#', '//', $obj[$key] );
273 }
274 }
275
276 /** @inheritDoc */
277 public function doPst( PageConfig $pageConfig, string $wikitext ): string {
278 $pageConfigTitle = $this->toPrefixedText( $pageConfig->getLinkTarget() );
279 $key = implode( ':', [ 'pst', md5( $pageConfigTitle ), md5( $wikitext ) ] );
280 $ret = $this->getCache( $key );
281 if ( $ret === null ) {
282 $data = $this->api->makeRequest( [
283 'action' => 'parse',
284 'title' => $pageConfigTitle,
285 'text' => $wikitext,
286 'contentmodel' => 'wikitext',
287 'onlypst' => 1,
288 ] );
289 $ret = $data['parse']['text'];
290 $this->setCache( $key, $ret );
291 }
292 return $ret;
293 }
294
295 /**
296 * Transfer the metadata returned in an API result into our
297 * ContentMetadataCollector.
298 * @param array $data
299 * @param ContentMetadataCollector $metadata
300 */
301 private function mergeMetadata( array $data, ContentMetadataCollector $metadata ): void {
302 foreach ( ( $data['categories'] ?? [] ) as $c ) {
303 $tv = TitleValue::tryNew(
304 14, // NS_CATEGORY,
305 $c['category']
306 );
307 $metadata->addCategory( $tv, $c['sortkey'] );
308 }
309 $metadata->appendOutputStrings( CMCSS::MODULE, $data['modules'] ?? [] );
310 $metadata->appendOutputStrings( CMCSS::MODULE_STYLE, $data['modulestyles'] ?? [] );
311 foreach ( ( $data['jsconfigvars'] ?? [] ) as $key => $value ) {
312 $strategy = 'write-once';
313 if ( is_array( $value ) ) {
314 // Strategy value will be exposed by change
315 // I974d9ecfb4ca8b22361d25c4c70fc5e55c39d5ed in core.
316 $strategy = $value['_mw-strategy'] ?? 'write-once';
317 unset( $value['_mw-strategy'] );
318 }
319 if ( $strategy === 'union' ) {
320 foreach ( $value as $item => $ignore ) {
321 $metadata->appendJsConfigVar( $key, $item );
322 }
323 } else {
324 $metadata->setJsConfigVar( $key, $value );
325 }
326 }
327 foreach ( ( $data['externallinks'] ?? [] ) as $url ) {
328 $metadata->addExternalLink( $url );
329 }
330 foreach ( ( $data['properties'] ?? [] ) as $name => $value ) {
331 if ( is_string( $value ) ) {
332 $metadata->setUnsortedPageProperty( $name, $value );
333 } elseif ( is_numeric( $value ) ) {
334 $metadata->setNumericPageProperty( $name, $value );
335 } elseif ( is_bool( $value ) ) {
336 // Deprecated back-compat
337 $metadata->setNumericPageProperty( $name, (int)$value );
338 } else {
339 // Non-scalar values deprecatedin 1.42; drop them.
340 }
341 }
342 }
343
344 /** @inheritDoc */
345 public function parseWikitext(
346 PageConfig $pageConfig,
347 ContentMetadataCollector $metadata,
348 string $wikitext
349 ): string {
350 $revid = $pageConfig->getRevisionId();
351 $pageConfigTitle = $this->toPrefixedText( $pageConfig->getLinkTarget() );
352 $key = implode( ':', [ 'parse', md5( $pageConfigTitle ), md5( $wikitext ), $revid ] );
353 $data = $this->getCache( $key );
354 if ( $data === null ) {
355 $params = [
356 'action' => 'parse',
357 'title' => $pageConfigTitle,
358 'text' => $wikitext,
359 'contentmodel' => 'wikitext',
360 'prop' => 'text|modules|jsconfigvars|categories|properties|externallinks',
361 'disablelimitreport' => 1,
362 'wrapoutputclass' => '',
363 'showstrategykeys' => 1,
364 ];
365 if ( $revid !== null ) {
366 $params['revid'] = $revid;
367 }
368 $data = $this->api->makeRequest( $params )['parse'];
369 $this->setCache( $key, $data );
370 }
371 $this->mergeMetadata( $data, $metadata );
372 return $data['text']; # HTML
373 }
374
375 /** @inheritDoc */
376 public function preprocessWikitext(
377 PageConfig $pageConfig,
378 ContentMetadataCollector $metadata,
379 string $wikitext
380 ): string {
381 $revid = $pageConfig->getRevisionId();
382 $pageConfigTitle = $this->toPrefixedText( $pageConfig->getLinkTarget() );
383 $key = implode( ':', [ 'preprocess', md5( $pageConfigTitle ), md5( $wikitext ), $revid ] );
384 $data = $this->getCache( $key );
385 if ( $data === null ) {
386 $params = [
387 'action' => 'expandtemplates',
388 'title' => $pageConfigTitle,
389 'text' => $wikitext,
390 'prop' => 'wikitext|modules|jsconfigvars|categories|properties',
391 'showstrategykeys' => 1,
392 ];
393 if ( $revid !== null ) {
394 $params['revid'] = $revid;
395 }
396 $data = $this->api->makeRequest( $params )['expandtemplates'];
397 $this->setCache( $key, $data );
398 }
399
400 $this->mergeMetadata( $data, $metadata );
401
402 return $data['wikitext'];
403 }
404
405 /** @inheritDoc */
406 public function fetchTemplateSource(
407 PageConfig $pageConfig, LinkTarget $title
408 ): ?PageContent {
409 $title = $this->toPrefixedText( $title );
410 $key = implode( ':', [ 'content', md5( $title ) ] );
411 $ret = $this->getCache( $key );
412 if ( $ret === null ) {
413 $params = [
414 'action' => 'query',
415 'prop' => 'revisions',
416 'rvprop' => 'content',
417 'rvslots' => '*',
418 'titles' => $title,
419 'rvlimit' => 1,
420 ];
421
422 $data = $this->api->makeRequest( $params );
423 $pageData = $data['query']['pages'][0];
424 if ( isset( $pageData['missing'] ) ) {
425 return null;
426 } else {
427 $ret = $pageData['revisions'][0]['slots'];
428 // PORT-FIXME set the redirect field if needed
429 $this->setCache( $key, $ret );
430 }
431 }
432 return new MockPageContent( $ret );
433 }
434
435 /** @inheritDoc */
436 public function fetchTemplateData( PageConfig $pageConfig, LinkTarget $title ): ?array {
437 $title = $this->toPrefixedText( $title );
438 $key = implode( ':', [ 'templatedata', md5( $title ) ] );
439 $ret = $this->getCache( $key );
440 if ( $ret === null ) {
441 $data = $this->api->makeRequest( [
442 'action' => 'templatedata',
443 'includeMissingTitles' => 1,
444 'titles' => $title,
445 'redirects' => 1,
446 ] )['pages'];
447 $ret = reset( $data );
448 $this->setCache( $key, $ret );
449 }
450 return $ret;
451 }
452
453 /** @inheritDoc */
454 public function logLinterData( PageConfig $pageConfig, array $lints ): void {
455 foreach ( $lints as $l ) {
456 error_log( PHPUtils::jsonEncode( $l ) );
457 }
458 }
459
460 /**
461 * Helper to turn a LinkTarget object into the "prefixed text" title form
462 * expected by the MediaWiki action API.
463 * @param LinkTarget $linkTarget
464 * @return string The title, as prefixed text
465 */
466 private function toPrefixedText( LinkTarget $linkTarget ): string {
467 return Title::newFromLinkTarget(
468 $linkTarget, $this->siteConfig
469 )->getPrefixedText();
470 }
471
472 /** @inheritDoc */
473 public function addTrackingCategory(
474 PageConfig $pageConfig,
475 ContentMetadataCollector $metadata,
476 string $key
477 ): void {
478 $pageConfigTitle = $this->toPrefixedText( $pageConfig->getLinkTarget() );
479 $cacheKey = implode( ':', [ 'allmessages', md5( $pageConfigTitle ), md5( $key ) ] );
480 $data = $this->getCache( $cacheKey );
481 if ( $data === null ) {
482 $params = [
483 'action' => 'query',
484 'meta' => 'allmessages',
485 'amtitle' => $pageConfigTitle,
486 'ammessages' => $key,
487 'amenableparser' => 1,
488 ];
489 $data = $this->api->makeRequest( $params )['query']['allmessages'][0];
490 $this->setCache( $cacheKey, $data );
491 }
492 if ( isset( $data['missing'] ) ) {
493 return;
494 }
495 $tv = TitleValue::tryNew(
496 14, // NS_CATEGORY,
497 $data['content']
498 );
499 $metadata->addCategory( $tv );
500 }
501 }