Debian Codegraph @

vendor/wikimedia/parsoid/src/Config/SiteConfig.php

raw
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Wikimedia\Parsoid\Config;
5
6 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
7 use Monolog\Formatter\LineFormatter;
8 use Monolog\Handler\ErrorLogHandler;
9 use Monolog\Handler\StreamHandler;
10 use Monolog\Logger;
11 use Psr\Container\ContainerInterface;
12 use Psr\Container\NotFoundExceptionInterface;
13 use Psr\Log\LoggerInterface;
14 use Psr\Log\LogLevel;
15 use Psr\Log\NullLogger;
16 use Wikimedia\Assert\Assert;
17 use Wikimedia\Bcp47Code\Bcp47Code;
18 use Wikimedia\ObjectFactory\ObjectFactory;
19 use Wikimedia\Parsoid\Core\ContentMetadataCollector;
20 use Wikimedia\Parsoid\Core\ContentModelHandler;
21 use Wikimedia\Parsoid\Core\LinkTarget;
22 use Wikimedia\Parsoid\DOM\Document;
23 use Wikimedia\Parsoid\Ext\AnnotationStripper;
24 use Wikimedia\Parsoid\Ext\ExtensionModule;
25 use Wikimedia\Parsoid\Ext\ExtensionTagHandler;
26 use Wikimedia\Parsoid\Ext\Gallery\Gallery;
27 use Wikimedia\Parsoid\Ext\Indicator\Indicator;
28 use Wikimedia\Parsoid\Ext\JSON\JSON;
29 use Wikimedia\Parsoid\Ext\LST\LST;
30 use Wikimedia\Parsoid\Ext\Nowiki\Nowiki;
31 use Wikimedia\Parsoid\Ext\Pre\Pre;
32 use Wikimedia\Parsoid\Utils\DOMUtils;
33 use Wikimedia\Parsoid\Utils\PHPUtils;
34 use Wikimedia\Parsoid\Utils\Utils;
35 use Wikimedia\Parsoid\Wikitext\Consts;
36
37 /**
38 * Site-level configuration interface for Parsoid
39 *
40 * This includes both global configuration and wiki-level configuration.
41 */
42 abstract class SiteConfig {
43 /**
44 * FIXME: not private so that ParserTests can reset these variables
45 * since they reuse site config and other objects between tests for
46 * efficiency reasons.
47 *
48 * @var array|null
49 */
50 protected $mwAliases;
51
52 /** @var array|null */
53 private $behaviorSwitches;
54
55 /** @var array|null */
56 private $variables;
57
58 /** @var array|null */
59 private $mediaOptions;
60
61 /** @var array|null */
62 protected $functionSynonyms;
63
64 /** @var string[] */
65 private $protocolsRegexes = [];
66
67 /**
68 * FIXME: not private so that ParserTests can reset these variables
69 * since they reuse site config and other objects between tests for
70 * efficiency reasons.
71 * @var array|null
72 */
73 protected $interwikiMapNoNamespaces;
74
75 /**
76 * FIXME: not private so that ParserTests can reset these variables
77 * since they reuse site config and other objects between tests for
78 * efficiency reasons.
79 * @var string|null|bool
80 */
81 protected $linkTrailRegex = false;
82
83 /**
84 * These extension modules provide "core" functionality
85 * and their implementations live in the Parsoid repo.
86 *
87 * @var class-string<ExtensionModule>[]
88 */
89 private static $coreExtModules = [
90 // content modules
91 JSON::class,
92 // extension tags
93 Nowiki::class,
94 Pre::class,
95 Gallery::class,
96 Indicator::class,
97 // The following implementations will move to their own repositories
98 // soon, but for now are implemented in the Parsoid repo.
99 LST::class
100 ];
101
102 /**
103 * Array specifying fully qualified class name for Parsoid-compatible extensions
104 * @var ?array<int,ExtensionModule>
105 */
106 private $extModules = null;
107 /**
108 * Private counter to assign IDs to $extModules
109 * @var int
110 */
111 private $extModuleNextId = 0;
112
113 // phpcs:disable Generic.Files.LineLength.TooLong
114
115 /**
116 * Register a Parsoid extension module.
117 * @param string|array{name:string}|array{factory:callable}|array{class:class-string<ExtensionModule>} $configOrSpec
118 * Either an object factory specification for an ExtensionModule object,
119 * or else the configuration array which ExtensionModule::getConfig()
120 * would return. (The latter is preferred, but our internal extensions
121 * use the former.)
122 * @return int An integer identifier that can be passed to
123 * ::unregisterExtensionModule to remove this extension (
124 */
125 final public function registerExtensionModule( $configOrSpec ): int {
126 $this->getExtensionModules(); // ensure it's initialized w/ core modules
127 if ( is_string( $configOrSpec ) || isset( $configOrSpec['class'] ) || isset( $configOrSpec['factory'] ) ) {
128 // Treat this as an object factory spec for an ExtensionModule
129 // ObjectFactory::createObject accepts an array, not just a callable (phan bug)
130 // @phan-suppress-next-line PhanTypeInvalidCallableArraySize
131 $module = $this->getObjectFactory()->createObject( $configOrSpec, [
132 'allowClassName' => true,
133 'assertClass' => ExtensionModule::class,
134 ] );
135 } else {
136 // Treat this as a configuration array, create a new anonymous
137 // ExtensionModule object for it.
138 $module = new class( $configOrSpec ) implements ExtensionModule {
139 private $config;
140
141 /** @param array $config */
142 public function __construct( $config ) {
143 $this->config = $config;
144 }
145
146 /** @inheritDoc */
147 public function getConfig(): array {
148 return $this->config;
149 }
150 };
151 }
152 $extId = $this->extModuleNextId++;
153 $this->extModules[$extId] = $module;
154 // remove cached extConfig to ensure this registration is picked up
155 $this->extConfig = null;
156 return $extId;
157 }
158
159 // phpcs:enable Generic.Files.LineLength.TooLong
160
161 /**
162 * Unregister a Parsoid extension module. This is typically used
163 * only for testing purposes in order to reset a shared SiteConfig
164 * to its original configuration.
165 * @param int $extId The value returned by the call to
166 * ::registerExtensionModule()
167 */
168 final public function unregisterExtensionModule( int $extId ): void {
169 unset( $this->extModules[$extId] );
170 $this->extConfig = null; // remove cached extConfig
171 }
172
173 /**
174 * Return the set of Parsoid extension modules associated with this
175 * SiteConfig.
176 *
177 * @return ExtensionModule[]
178 */
179 final public function getExtensionModules() {
180 if ( $this->extModules === null ) {
181 $this->extModules = [];
182 foreach ( self::$coreExtModules as $m ) {
183 $this->extModules[$this->extModuleNextId++] = new $m();
184 }
185 }
186 return array_values( $this->extModules );
187 }
188
189 /** @var LoggerInterface|null */
190 protected $logger = null;
191
192 /** @var int */
193 protected $iwMatcherBatchSize = 4096;
194
195 /** @var array|null */
196 protected $iwMatcher = null;
197
198 /** @var bool */
199 protected $addHTMLTemplateParameters = false;
200
201 /** @var bool */
202 protected $scrubBidiChars = false;
203
204 /** @var bool */
205 protected $linterEnabled = false;
206
207 /** @var ?array */
208 protected $extConfig = null;
209
210 /**
211 * Tag handlers for some extensions currently explicit call unstripNowiki
212 * first thing in their handlers. They do this to strip <nowiki>..</nowiki>
213 * wrappers around args when encountered in the {{#tag:...}} parser function.
214 * However, this strategy won't work for Parsoid which calls the preprocessor
215 * to get expanded wikitext. In this mode, <nowiki> wrappers won't be stripped
216 * and this leads to functional differences in parsing and output.
217 *
218 * See T203293 and T299103 for more details.
219 *
220 * To get around this, T299103 proposes that extensions that require this support
221 * set a config flag in their Parsoid extension config. On the Parsoid end, we
222 * then let the legacy parser know of these tags. When such extension tags are
223 * encountered in the {{#tag:...}} parser function handler (see tagObj function
224 * in CoreParserFunctions.php), that handler can than automatically strip these
225 * nowiki wrappers on behalf of the extension.
226 *
227 * This serves two purposes. For one, it lets Parsoid support these extensions
228 * in this nowiki use edge case. For another, extensions that register handlers
229 * with Parsoid can get rid of explicit calls to unstripNowiki() in the
230 * tag handlers for the legacy parser.
231 *
232 * This property maintains an array of tags that need this support.
233 *
234 * @var array an associative array of tag names
235 */
236 private $t299103Tags = [];
237
238 /**
239 * Base constructor.
240 *
241 * This constructor is public because it is used to create mock objects
242 * in our test suite.
243 */
244 public function __construct() {
245 }
246
247 /************************************************************************//**
248 * @name Global config
249 * @{
250 */
251
252 /**
253 * General log channel
254 * @return LoggerInterface
255 */
256 public function getLogger(): LoggerInterface {
257 if ( $this->logger === null ) {
258 $this->logger = new NullLogger;
259 }
260 return $this->logger;
261 }
262
263 /**
264 * Set the log channel, for debugging
265 * @param ?LoggerInterface $logger
266 */
267 public function setLogger( ?LoggerInterface $logger ): void {
268 $this->logger = $logger;
269 }
270
271 /**
272 * Default gallery options for this wiki.
273 * @return array<string,string|int|bool>
274 */
275 public function galleryOptions(): array {
276 return [
277 'imagesPerRow' => 0,
278 'imageWidth' => 120,
279 'imageHeight' => 120,
280 'captionLength' => true,
281 'showBytes' => true,
282 'showDimensions' => true,
283 'mode' => 'traditional',
284 ];
285 }
286
287 /**
288 * When processing template parameters, parse them to HTML and add it to the
289 * template parameters data.
290 * @return bool
291 */
292 public function addHTMLTemplateParameters(): bool {
293 return $this->addHTMLTemplateParameters;
294 }
295
296 /**
297 * Statistics aggregator, for counting and timing.
298 *
299 * @return StatsdDataFactoryInterface|null
300 */
301 public function metrics(): ?StatsdDataFactoryInterface {
302 return null;
303 }
304
305 /**
306 * Increment a counter metric
307 * @param string $name
308 * @param array $labels
309 * @param float $amount
310 * @return void
311 */
312 abstract public function incrementCounter( string $name, array $labels, float $amount = 1 );
313
314 /**
315 * Record a timing metric.
316 *
317 * Note that the value should be provided in *milliseconds* even though
318 * the name of the metric may end (by convention) in `_seconds`. The
319 * metrics infrastructure will make the appropriate conversion.
320 *
321 * @param string $name
322 * @param float $value A timing value *in milliseconds*
323 * @param array $labels
324 * @return void
325 */
326 abstract public function observeTiming( string $name, float $value, array $labels );
327
328 /**
329 * If enabled, bidi chars adjacent to category links will be stripped
330 * in the html -> wt serialization pass.
331 * @return bool
332 */
333 public function scrubBidiChars(): bool {
334 return $this->scrubBidiChars;
335 }
336
337 /** @} */
338
339 /************************************************************************//**
340 * @name Wiki config
341 * @{
342 */
343
344 /**
345 * Allowed external image URL prefixes.
346 *
347 * @return string[] The empty array matches no URLs. The empty string matches
348 * all URLs.
349 */
350 abstract public function allowedExternalImagePrefixes(): array;
351
352 /**
353 * Site base URI
354 *
355 * This would be the URI found in `<base href="..." />`.
356 *
357 * @return string
358 */
359 abstract public function baseURI(): string;
360
361 /**
362 * Prefix for relative links
363 *
364 * Prefix to prepend to a page title to link to that page.
365 * Intended to be relative to the URI returned by baseURI().
366 *
367 * If possible, keep the default "./" so clients need not know this value
368 * to extract titles from link hrefs.
369 *
370 * @return string
371 */
372 public function relativeLinkPrefix(): string {
373 return './';
374 }
375
376 /**
377 * Regex matching all double-underscore magic words
378 * @return string
379 */
380 public function bswPagePropRegexp(): string {
381 static $bswPagePropRegexp = null;
382 if ( $bswPagePropRegexp === null ) {
383 $bswRegexp = $this->bswRegexp();
384 $bswPagePropRegexp =
385 '@(?:^|\\s)mw:PageProp/(?:' .
386 PHPUtils::reStrip( $bswRegexp, '@' ) .
387 ')(?=$|\\s)@uDS';
388 }
389 return $bswPagePropRegexp;
390 }
391
392 /**
393 * Map a canonical namespace name to its index
394 *
395 * @note This replaces canonicalNamespaces
396 * @param string $name all-lowercase and with underscores rather than spaces.
397 * @return int|null
398 */
399 abstract public function canonicalNamespaceId( string $name ): ?int;
400
401 /**
402 * Map a namespace name to its index
403 *
404 * @note This replaces canonicalNamespaces
405 * @param string $name all-lowercase and with underscores rather than spaces.
406 * @return int|null
407 */
408 abstract public function namespaceId( string $name ): ?int;
409
410 /**
411 * Map a namespace index to its preferred name
412 * (with spaces, not underscores).
413 *
414 * @note This replaces namespaceNames
415 * @param int $ns
416 * @return string|null
417 */
418 abstract public function namespaceName( int $ns ): ?string;
419
420 /**
421 * Test if a namespace has subpages
422 *
423 * @note This replaces namespacesWithSubpages
424 * @param int $ns
425 * @return bool
426 */
427 abstract public function namespaceHasSubpages( int $ns ): bool;
428
429 /**
430 * Return namespace case setting
431 * @param int $ns
432 * @return string 'first-letter' or 'case-sensitive'
433 */
434 abstract public function namespaceCase( int $ns ): string;
435
436 /**
437 * Test if a namespace is a talk namespace
438 *
439 * @note This replaces title.getNamespace().isATalkNamespace()
440 * @param int $ns
441 * @return bool
442 */
443 public function namespaceIsTalk( int $ns ): bool {
444 return $ns > 0 && $ns % 2;
445 }
446
447 /**
448 * Uppercasing method for titles
449 * @param string $str
450 * @return string
451 */
452 public function ucfirst( string $str ): string {
453 if ( $str === '' ) {
454 return '';
455 }
456 $o = ord( $str[0] );
457 if ( $o < 96 ) { // if already uppercase...
458 return $str;
459 } elseif ( $o < 128 ) {
460 if ( $str[0] === 'i' &&
461 in_array( $this->langBcp47()->toBcp47Code(), [ 'az', 'tr', 'kaa', 'kk' ], true )
462 ) {
463 return 'İ' . mb_substr( $str, 1 );
464 }
465 return ucfirst( $str ); // use PHP's ucfirst()
466 } else {
467 // fall back to more complex logic in case of multibyte strings
468 $char = mb_substr( $str, 0, 1 );
469 return mb_strtoupper( $char ) . mb_substr( $str, 1 );
470 }
471 }
472
473 /**
474 * Get the default local name for a special page
475 * @param string $alias Special page alias
476 * @return string|null
477 */
478 abstract public function specialPageLocalName( string $alias ): ?string;
479
480 /**
481 * Treat language links as magic connectors, not inline links
482 * @return bool
483 */
484 abstract public function interwikiMagic(): bool;
485
486 /**
487 * Return true if the specified magic link syntax is enabled on this
488 * wiki.
489 * @param string $which One of "ISBN", "PMID", or "RFC"
490 * @return true if the specified magic link type is enabled on this wiki
491 */
492 public function magicLinkEnabled( string $which ): bool {
493 // This should be an abstract method, but in order to provide
494 // graceful upgrades, start by defaulting to true for all link types
495 return true;
496 }
497
498 /**
499 * Interwiki link data.
500 *
501 * Note that the order of the keys in this array is significant: if more
502 * than one prefix matches a given URL during html2wt conversion, the
503 * *first* match is used. If you want `wikitech` to be used instead of
504 * `labsconsole`, for example, the `'wikitech'=>[....]` key needs to
505 * enumerate first.
506 *
507 * @return array<string,array> Keys are interwiki prefixes, values are arrays with the following keys:
508 * - prefix: (string) The interwiki prefix, same as the key.
509 * - url: (string) Target URL, containing a '$1' to be replaced by the interwiki target.
510 * - protorel: (bool, optional) Whether the url may be accessed by both http:// and https://.
511 * - local: (bool, optional) Whether the interwiki link is considered local (to the wikifarm).
512 * - localinterwiki: (bool, optional) Whether the interwiki link points to the current wiki.
513 * - language: (bool, optional) Whether the interwiki link is a language link.
514 * - extralanglink: (bool, optional) Whether the interwiki link is an "extra language link".
515 * - linktext: (string, optional) For "extra language links", the link text.
516 * (booleans marked "optional" must be omitted if false)
517 */
518 abstract public function interwikiMap(): array;
519
520 /**
521 * Interwiki link data, after removing items that conflict with namespace names.
522 * (In case of such conflict, namespace wins, interwiki is ignored.)
523 * @return array<string,array> See interwikiMap()
524 */
525 public function interwikiMapNoNamespaces(): array {
526 if ( $this->interwikiMapNoNamespaces === null ) {
527 $this->interwikiMapNoNamespaces = [];
528 foreach ( $this->interwikiMap() as $key => $value ) {
529 if ( $this->namespaceId( (string)$key ) === null ) {
530 $this->interwikiMapNoNamespaces[$key] = $value;
531 }
532 }
533 }
534 return $this->interwikiMapNoNamespaces;
535 }
536
537 /**
538 * Match interwiki URLs
539 * @param string $href Link to match against
540 * @return string[]|null Two values [ string $key, string $target ] on success, null on no match.
541 */
542 public function interwikiMatcher( string $href ): ?array {
543 if ( $this->iwMatcher === null ) {
544 $keys = [ [], [] ];
545 $patterns = [ [], [] ];
546 foreach ( $this->interwikiMapNoNamespaces() as $key => $iw ) {
547 $key = (string)$key;
548 $lang = (int)( !empty( $iw['language'] ) );
549
550 $url = $iw['url'];
551 $protocolRelative = substr( $url, 0, 2 ) === '//';
552 if ( !empty( $iw['protorel'] ) ) {
553 $url = preg_replace( '/^https?:/', '', $url );
554 $protocolRelative = true;
555 }
556
557 // full-url match pattern
558 $keys[$lang][] = $key;
559 $patterns[$lang][] =
560 // Support protocol-relative URLs
561 ( $protocolRelative ? '(?:https?:)?' : '' )
562 // Convert placeholder to group match
563 . strtr( preg_quote( $url, '/' ), [ '\\$1' => '(.*?)' ] );
564
565 if ( !empty( $iw['local'] ) ) {
566 // ./$interwikiPrefix:$title and
567 // $interwikiPrefix%3A$title shortcuts
568 // are recognized and the local wiki forwards
569 // these shortcuts to the remote wiki
570
571 $keys[$lang][] = $key;
572 $patterns[$lang][] = '^\\.\\/' . $iw['prefix'] . ':(.*?)';
573
574 $keys[$lang][] = $key;
575 $patterns[$lang][] = '^' . $iw['prefix'] . '%3A(.*?)';
576 }
577 }
578
579 // Prefer language matches over non-language matches
580 $numLangs = count( $keys[1] );
581 $keys = array_merge( $keys[1], $keys[0] );
582 $patterns = array_merge( $patterns[1], $patterns[0] );
583
584 // Chunk patterns into reasonably sized regexes
585 $this->iwMatcher = [];
586 $batchStart = 0;
587 $batchLen = 0;
588 foreach ( $patterns as $i => $pat ) {
589 $len = strlen( $pat );
590 if ( $i !== $batchStart && $batchLen + $len > $this->iwMatcherBatchSize ) {
591 $this->iwMatcher[] = [
592 array_slice( $keys, $batchStart, $i - $batchStart ),
593 '/^(?:' . implode( '|', array_slice( $patterns, $batchStart, $i - $batchStart ) ) . ')$/Di',
594 $numLangs - $batchStart,
595 ];
596 $batchStart = $i;
597 $batchLen = $len;
598 } else {
599 $batchLen += $len;
600 }
601 }
602 $i = count( $patterns );
603 if ( $i > $batchStart ) {
604 $this->iwMatcher[] = [
605 array_slice( $keys, $batchStart, $i - $batchStart ),
606 '/^(?:' . implode( '|', array_slice( $patterns, $batchStart, $i - $batchStart ) ) . ')$/Di',
607 $numLangs - $batchStart,
608 ];
609 }
610 }
611
612 foreach ( $this->iwMatcher as [ $keys, $regex, $numLangs ] ) {
613 if ( preg_match( $regex, $href, $m, PREG_UNMATCHED_AS_NULL ) ) {
614 foreach ( $keys as $i => $key ) {
615 if ( isset( $m[$i + 1] ) ) {
616 if ( $i < $numLangs ) {
617 // Escape language interwikis with a colon
618 $key = ':' . $key;
619 }
620 return [ $key, $m[$i + 1] ];
621 }
622 }
623 }
624 }
625 return null;
626 }
627
628 /**
629 * Wiki identifier, for cache keys.
630 * Should match a key in mwApiMap()?
631 * @return string
632 */
633 abstract public function iwp(): string;
634
635 /**
636 * Legal title characters
637 *
638 * Regex is intended to match bytes, not Unicode characters.
639 *
640 * @return string Regex character class (i.e. the bit that goes inside `[]`)
641 */
642 abstract public function legalTitleChars(): string;
643
644 /**
645 * Link prefix regular expression.
646 * @return string|null
647 */
648 abstract public function linkPrefixRegex(): ?string;
649
650 /**
651 * Return raw link trail regexp from config
652 * @return string
653 */
654 abstract protected function linkTrail(): string;
655
656 /**
657 * Link trail regular expression.
658 * @return string|null
659 */
660 public function linkTrailRegex(): ?string {
661 if ( $this->linkTrailRegex === false ) {
662 $trail = $this->linkTrail();
663 $trail = str_replace( '(.*)$', '', $trail );
664 if ( strpos( $trail, '()' ) !== false ) {
665 // Empty regex from zh-hans
666 $this->linkTrailRegex = null;
667 } else {
668 $this->linkTrailRegex = $trail;
669 }
670 }
671 return $this->linkTrailRegex;
672 }
673
674 /**
675 * Wiki language code.
676 * @return Bcp47Code BCP-47 language code
677 */
678 abstract public function langBcp47(): Bcp47Code;
679
680 /**
681 * Main page title, as LinkTarget
682 * @return LinkTarget
683 */
684 abstract public function mainPageLinkTarget(): LinkTarget;
685
686 /**
687 * Lookup config
688 * @param string $key
689 * @return mixed|null config value for $key, if present or null, if not.
690 * @deprecated This very broad interface is no longer needed.
691 */
692 abstract public function getMWConfigValue( string $key );
693
694 /**
695 * Whether the wiki language is right-to-left
696 * @return bool
697 */
698 abstract public function rtl(): bool;
699
700 /**
701 * Whether language converter is enabled for the specified language
702 * @param Bcp47Code $lang
703 * @return bool
704 */
705 abstract public function langConverterEnabledBcp47( Bcp47Code $lang ): bool;
706
707 /**
708 * The URL path to index.php.
709 * @return string
710 */
711 abstract public function script(): string;
712
713 /**
714 * FIXME: This is only used to compute the modules path below
715 * and maybe shouldn't be exposed.
716 *
717 * The base wiki path
718 * @return string
719 */
720 abstract public function scriptpath(): string;
721
722 /**
723 * The base URL of the server.
724 * @return string
725 */
726 abstract public function server(): string;
727
728 /**
729 * Export content metadata via meta tags (and via a stylesheet
730 * for now to aid some clients).
731 *
732 * @param Document $document
733 * @param ContentMetadataCollector $metadata
734 * @param string $defaultTitle The default title to display, as an
735 * unescaped string
736 * @param Bcp47Code $lang a BCP-47 language code
737 */
738 abstract public function exportMetadataToHeadBcp47(
739 Document $document,
740 ContentMetadataCollector $metadata,
741 string $defaultTitle,
742 Bcp47Code $lang
743 ): void;
744
745 /**
746 * Helper function to create <head> elements from metadata.
747 * @param Document $document
748 * @param string $modulesLoadURI
749 * @param string[] $modules
750 * @param string[] $moduleStyles
751 * @param array<string,mixed> $jsConfigVars
752 * @param string $htmlTitle The display title, as escaped HTML
753 * @param Bcp47Code $lang a Bcp47Code object
754 */
755 protected function exportMetadataHelper(
756 Document $document,
757 string $modulesLoadURI,
758 array $modules,
759 array $moduleStyles,
760 array $jsConfigVars,
761 string $htmlTitle,
762 Bcp47Code $lang
763 ): void {
764 // $htmlTitle contains the DISPLAYTITLE but it corresponds to the
765 // value of the ParserOutput *not* the ultimate value which would
766 // be used in the <h1> tag *nor* the plaintext value which would
767 // be used for the page <title>. OutputPage does additional
768 // validation/stripping on the displaytitle value before using it.
769 // As such we're going to just ignore $htmlTitle for now rather
770 // than report an incorrect value in the <head> (T324431).
771
772 // JsConfigVars
773 $content = null;
774 try {
775 if ( $jsConfigVars ) {
776 $content = PHPUtils::jsonEncode( $jsConfigVars );
777 }
778 } catch ( \Exception $e ) {
779 // Similar to ResourceLoader::makeConfigSetScript. See T289358
780 $this->getLogger()->log(
781 LogLevel::WARNING,
782 'JSON serialization of config data failed. ' .
783 'This usually means the config data is not valid UTF-8.'
784 );
785 }
786 if ( $content ) {
787 DOMUtils::appendToHead( $document, 'meta', [
788 'property' => 'mw:jsConfigVars',
789 'content' => $content,
790 ] );
791 }
792 // Styles from modules returned from preprocessor / parse requests
793 if ( $modules ) {
794 // mw:generalModules can be processed via JS (and async) and are usually (but
795 // not always) JS scripts.
796 DOMUtils::appendToHead( $document, 'meta', [
797 'property' => 'mw:generalModules',
798 'content' => implode( '|', array_unique( $modules ) )
799 ] );
800 }
801 // Styles from modules returned from preprocessor / parse requests
802 if ( $moduleStyles ) {
803 // mw:moduleStyles are CSS modules that are render-blocking.
804 DOMUtils::appendToHead( $document, 'meta', [
805 'property' => 'mw:moduleStyles',
806 'content' => implode( '|', array_unique( $moduleStyles ) )
807 ] );
808 }
809 /*
810 * While unnecessary for Wikimedia clients, a stylesheet url in
811 * the <head> is useful for clients like Kiwix and others who
812 * might not want to process the meta tags to construct the
813 * resourceloader url.
814 *
815 * Given that these clients will be consuming Parsoid HTML outside
816 * a MediaWiki skin, the clients are effectively responsible for
817 * their own "skin". But, once again, as a courtesy, we are
818 * hardcoding the vector skin modules for them. But, note that
819 * this may cause page elements to render differently than how
820 * they render on Wikimedia sites with the vector skin since this
821 * is probably missing a number of other modules.
822 *
823 * All that said, note that JS-generated parts of the page will
824 * still require them to have more intimate knowledge of how to
825 * process the JS modules. Except for <graph>s, page content
826 * doesn't require JS modules at this point. So, where these
827 * clients want to invest in the necessary logic to construct a
828 * better resourceloader url, they could simply delete / ignore
829 * this stylesheet.
830 */
831 $moreStyles = array_merge( $moduleStyles, [
832 'mediawiki.skinning.content.parsoid',
833 // Use the base styles that API output and fallback skin use.
834 'mediawiki.skinning.interface',
835 // Make sure to include contents of user generated styles
836 // e.g. MediaWiki:Common.css / MediaWiki:Mobile.css
837 'site.styles'
838 ] );
839 # need to use MW-internal language code for constructing resource
840 # loader path.
841 $langMw = Utils::bcp47ToMwCode( $lang );
842 $styleURI = $modulesLoadURI . '?lang=' . $langMw . '&modules=' .
843 PHPUtils::encodeURIComponent( implode( '|', array_unique( $moreStyles ) ) ) .
844 '&only=styles&skin=vector';
845 DOMUtils::appendToHead( $document, 'link', [ 'rel' => 'stylesheet', 'href' => $styleURI ] );
846 }
847
848 /**
849 * A regexp matching the localized 'REDIRECT' marker for this wiki.
850 * The regexp should be delimited, but should not have boundary anchors
851 * or capture groups.
852 * @return string
853 */
854 abstract public function redirectRegexp(): string;
855
856 /**
857 * A regexp matching the localized 'Category' prefix for this wiki.
858 * The regexp should be delimited, but should not have boundary anchors
859 * or capture groups.
860 * @return string
861 */
862 abstract public function categoryRegexp(): string;
863
864 /**
865 * A regexp matching localized behavior switches for this wiki.
866 * The regexp should be delimited, but should not have boundary anchors
867 * or capture groups.
868 * @return string
869 */
870 abstract public function bswRegexp(): string;
871
872 /**
873 * A regex matching a line containing just whitespace, comments, and
874 * sol transparent links and behavior switches.
875 * @return string
876 */
877 public function solTransparentWikitextRegexp(): string {
878 // cscott sadly says: Note that this depends on the precise
879 // localization of the magic words of this particular wiki.
880 static $solTransparentWikitextRegexp = null;
881 if ( $solTransparentWikitextRegexp === null ) {
882 $redirect = PHPUtils::reStrip( $this->redirectRegexp(), '@' );
883 $category = PHPUtils::reStrip( $this->categoryRegexp(), '@' );
884 $bswRegexp = PHPUtils::reStrip( $this->bswRegexp(), '@' );
885 $comment = PHPUtils::reStrip( Utils::COMMENT_REGEXP, '@' );
886 $solTransparentWikitextRegexp = '@' .
887 '^[ \t\n\r\0\x0b]*' .
888 '(?:' .
889 '(?:' . $redirect . ')' .
890 '[ \t\n\r\x0c]*(?::[ \t\n\r\x0c]*)?\[\[[^\]]+\]\]' .
891 ')?' .
892 '(?:' .
893 '\[\[' . $category . '\:[^\]]*?\]\]|' .
894 '__(?:' . $bswRegexp . ')__|' .
895 $comment . '|' .
896 '[ \t\n\r\0\x0b]' .
897 ')*$@';
898 }
899 return $solTransparentWikitextRegexp;
900 }
901
902 /**
903 * A regex matching a line containing just comments and
904 * sol transparent links and behavior switches.
905 *
906 * @param bool $addIncludes
907 * @return string
908 */
909 public function solTransparentWikitextNoWsRegexp(
910 bool $addIncludes = false
911 ): string {
912 // cscott sadly says: Note that this depends on the precise
913 // localization of the magic words of this particular wiki.
914 static $solTransparentWikitextNoWsRegexp = null;
915 if ( $solTransparentWikitextNoWsRegexp === null ) {
916 $redirect = PHPUtils::reStrip( $this->redirectRegexp(), '@' );
917 $category = PHPUtils::reStrip( $this->categoryRegexp(), '@' );
918 $bswRegexp = PHPUtils::reStrip( $this->bswRegexp(), '@' );
919 $comment = PHPUtils::reStrip( Utils::COMMENT_REGEXP, '@' );
920 $solTransparentWikitextNoWsRegexp = '@' .
921 '((?:' .
922 '(?:' . $redirect . ')' .
923 '[ \t\n\r\x0c]*(?::[ \t\n\r\x0c]*)?\[\[[^\]]+\]\]' .
924 ')?' .
925 '(?:' .
926 '\[\[' . $category . '\:[^\]]*?\]\]|' .
927 '__(?:' . $bswRegexp . ')__|' .
928 $comment .
929 // FIXME(SSS): What about onlyinclude and noinclude?
930 ( $addIncludes ? '|<includeonly>[\S\s]*?</includeonly>' : '' ) .
931 ')*)@';
932 }
933 return $solTransparentWikitextNoWsRegexp;
934 }
935
936 /**
937 * The wiki's time zone offset
938 * @return int Minutes east of UTC
939 */
940 abstract public function timezoneOffset(): int;
941
942 /**
943 * Language variant information for the given language (or null if
944 * unknown).
945 * @param Bcp47Code $lang The language for which you want variant information
946 * @return ?array{base:Bcp47Code,fallbacks:Bcp47Code[]} an array with
947 * two fields:
948 * - base: (Bcp47Code) Base BCP-47 language code (e.g. "zh")
949 * - fallbacks: (Bcp47Code[]) Fallback variants, as BCP-47 codes
950 */
951 abstract public function variantsFor( Bcp47Code $lang ): ?array;
952
953 /**
954 * Default thumbnail width
955 */
956 abstract public function widthOption(): int;
957
958 abstract protected function getVariableIDs(): array;
959
960 abstract protected function getMagicWords(): array;
961
962 /**
963 * Does the SiteConfig provide precomputed function synonyms?
964 * If no, the SiteConfig is expected to provide an implementation
965 * for updateFunctionSynonym.
966 */
967 protected function haveComputedFunctionSynonyms(): bool {
968 return true;
969 }
970
971 /**
972 * Get a list of precomputed function synonyms
973 */
974 protected function getFunctionSynonyms(): array {
975 return [];
976 }
977
978 protected function updateFunctionSynonym( string $func, string $magicword, bool $caseSensitive ): void {
979 throw new \RuntimeException( "Unexpected code path!" );
980 }
981
982 private function populateMagicWords() {
983 if ( !empty( $this->mwAliases ) ) {
984 return;
985 }
986
987 $this->mwAliases = $this->behaviorSwitches = $this->variables = $this->mediaOptions = [];
988 $variablesMap = PHPUtils::makeSet( $this->getVariableIDs() );
989 $this->functionSynonyms = $this->getFunctionSynonyms();
990 $haveSynonyms = $this->haveComputedFunctionSynonyms();
991 foreach ( $this->getMagicWords() as $magicword => $aliases ) {
992 $caseSensitive = array_shift( $aliases );
993 $isVariable = isset( $variablesMap[$magicword] );
994 $isMediaOption = preg_match( '/^(img|timedmedia)_/', $magicword );
995 foreach ( $aliases as $alias ) {
996 $this->mwAliases[$magicword][] = $alias;
997 if ( !$caseSensitive ) {
998 $alias = mb_strtolower( $alias );
999 $this->mwAliases[$magicword][] = $alias;
1000 }
1001 if ( substr( $alias, 0, 2 ) === '__' ) {
1002 $this->behaviorSwitches[$alias] = [ $caseSensitive, $magicword ];
1003 }
1004 if ( $isVariable ) {
1005 $this->variables[$alias] = $magicword;
1006 }
1007 if ( $isMediaOption ) {
1008 $this->mediaOptions[$alias] = [ $caseSensitive, $magicword ];
1009 }
1010 if ( !$haveSynonyms ) {
1011 $this->updateFunctionSynonym( $alias, $magicword, (bool)$caseSensitive );
1012 }
1013 }
1014 }
1015 }
1016
1017 /**
1018 * List all magic words by canonical name
1019 * @return string[][] Keys are canonical names, values are arrays of aliases.
1020 */
1021 public function mwAliases(): array {
1022 $this->populateMagicWords();
1023 return $this->mwAliases;
1024 }
1025
1026 /**
1027 * Return canonical magic word for a function hook
1028 * @param string $str
1029 * @return string|null
1030 */
1031 public function getMagicWordForFunctionHook( string $str ): ?string {
1032 $this->populateMagicWords();
1033 return $this->functionSynonyms[1][$str] ??
1034 # Case insensitive functions
1035 $this->functionSynonyms[0][mb_strtolower( $str )] ?? null;
1036 }
1037
1038 /**
1039 * Return canonical magic word for a variable
1040 * @param string $str
1041 * @return string|null
1042 */
1043 public function getMagicWordForVariable( string $str ): ?string {
1044 $this->populateMagicWords();
1045 return $this->variables[$str] ?? null;
1046 }
1047
1048 private static function getMagicWordCanonicalName( array $mws, string $word ): ?string {
1049 if ( isset( $mws[$word] ) ) {
1050 return $mws[$word][1];
1051 }
1052 $mw = $mws[mb_strtolower( $word )] ?? null;
1053 return ( $mw && !$mw[0] ) ? $mw[1] : null;
1054 }
1055
1056 /**
1057 * Return canonical magic word for a media option
1058 * @param string $word
1059 * @return string|null
1060 */
1061 public function getMagicWordForMediaOption( string $word ): ?string {
1062 $this->populateMagicWords();
1063 return self::getMagicWordCanonicalName( $this->mediaOptions, $word );
1064 }
1065
1066 /**
1067 * Return canonical magic word for a behavior switch
1068 * @param string $word
1069 * @return string|null
1070 */
1071 public function getMagicWordForBehaviorSwitch( string $word ): ?string {
1072 $this->populateMagicWords();
1073 return self::getMagicWordCanonicalName( $this->behaviorSwitches, $word );
1074 }
1075
1076 /**
1077 * Check if a string is a recognized behavior switch.
1078 *
1079 * @param string $word
1080 * @return bool
1081 */
1082 public function isBehaviorSwitch( string $word ): bool {
1083 return $this->getMagicWordForBehaviorSwitch( $word ) !== null;
1084 }
1085
1086 /**
1087 * Convert the internal canonical magic word name to the wikitext alias.
1088 * @param string $word Canonical magic word name
1089 * @param string $suggest Suggested alias (used as fallback and preferred choice)
1090 * @return string
1091 */
1092 public function getMagicWordWT( string $word, string $suggest ): string {
1093 $aliases = $this->mwAliases()[$word] ?? null;
1094 if ( !$aliases ) {
1095 return $suggest;
1096 }
1097 $ind = 0;
1098 if ( $suggest ) {
1099 $ind = array_search( $suggest, $aliases, true );
1100 }
1101 return $aliases[$ind ?: 0];
1102 }
1103
1104 /**
1105 * Get a regexp matching a localized magic word, given its id.
1106 *
1107 * FIXME: misleading function name
1108 *
1109 * @param string $id
1110 * @return string
1111 */
1112 abstract public function getMagicWordMatcher( string $id ): string;
1113
1114 /**
1115 * Get a matcher function for fetching values out of interpolated magic words,
1116 * ie those with `$1` in their aliases.
1117 *
1118 * The matcher takes a string and returns null if it doesn't match any of
1119 * the words, or an associative array if it did match:
1120 * - k: The magic word that matched
1121 * - v: The value of $1 that was matched
1122 * (the JS also returned 'a' with the specific alias that matched, but that
1123 * seems to be unused and so is omitted here)
1124 *
1125 * @param string[] $words Magic words to match
1126 * @return callable
1127 */
1128 abstract protected function getParameterizedAliasMatcher( array $words ): callable;
1129
1130 /**
1131 * Get a matcher function for fetching values out of interpolated magic words
1132 * which are media prefix options.
1133 *
1134 * The matcher takes a string and returns null if it doesn't match any of
1135 * the words, or an associative array if it did match:
1136 * - k: The magic word that matched
1137 * - v: The value of $1 that was matched
1138 * (the JS also returned 'a' with the specific alias that matched, but that
1139 * seems to be unused and so is omitted here)
1140 *
1141 * @return callable
1142 */
1143 final public function getMediaPrefixParameterizedAliasMatcher(): callable {
1144 // PORT-FIXME: this shouldn't be a constant, we should fetch these
1145 // from the SiteConfig. Further, we probably need a hook here so
1146 // Parsoid can handle media options defined in extensions... in
1147 // particular timedmedia_* magic words from Extension:TimedMediaHandler
1148 $mws = array_keys( Consts::$Media['PrefixOptions'] );
1149 return $this->getParameterizedAliasMatcher( $mws );
1150 }
1151
1152 /**
1153 * Get the maximum template depth
1154 *
1155 * @return int
1156 */
1157 abstract public function getMaxTemplateDepth(): int;
1158
1159 /**
1160 * Return name spaces aliases for the NS_SPECIAL namespace
1161 * @return array
1162 */
1163 abstract protected function getSpecialNSAliases(): array;
1164
1165 /**
1166 * Return Special Page aliases for a special page name
1167 * @param string $specialPage
1168 * @return array
1169 */
1170 abstract protected function getSpecialPageAliases( string $specialPage ): array;
1171
1172 /**
1173 * Quote a title regex
1174 *
1175 * Assumes '/' as the delimiter, and replaces spaces or underscores with
1176 * `[ _]` so either will be matched.
1177 *
1178 * @param string $s
1179 * @param string $delimiter Defaults to '/'
1180 * @return string
1181 */
1182 protected static function quoteTitleRe( string $s, string $delimiter = '/' ): string {
1183 $s = preg_quote( $s, $delimiter );
1184 $s = strtr( $s, [
1185 ' ' => '[ _]',
1186 '_' => '[ _]',
1187 ] );
1188 return $s;
1189 }
1190
1191 /**
1192 * Matcher for ISBN/RFC/PMID URL patterns, returning the type and number.
1193 *
1194 * The match method takes a string and returns false on no match or a tuple
1195 * like this on match: [ 'RFC', '12345' ]
1196 *
1197 * @return callable
1198 */
1199 public function getExtResourceURLPatternMatcher(): callable {
1200 $nsAliases = implode( '|', array_unique( $this->getSpecialNSAliases() ) );
1201 $pageAliases = implode( '|', array_map( [ $this, 'quoteTitleRe' ],
1202 $this->getSpecialPageAliases( 'Booksources' )
1203 ) );
1204
1205 $pats = [
1206 'ISBN' => '(?:\.\.?/)*(?i:' . $nsAliases . ')(?:%3[Aa]|:)'
1207 . '(?i:' . $pageAliases . ')(?:%2[Ff]|/)(?P<ISBN>\d+[Xx]?)',
1208 // Recently the target url for RFCs changed from
1209 // tools.ietf.org to datatracker.ietf.org/docs.
1210 // Given edit stash storage on Wikimedia wikis, we need to retain the
1211 // old mapping to ensure html->wt can handle that HTML properly
1212 // But, 3rd party wikis with Parsoid HTML in their caches will also
1213 // need this b/c support for much longer. Once the MW LTS release with
1214 // tools.ietf.org EOLs, we can remove the tools.ietf.org string here.
1215 // T382963 tracks the eventual removal of this b/c.
1216 'RFC' => '[^/]*//(?:datatracker\.ietf\.org/doc|tools\.ietf\.org)/html/rfc(?P<RFC>\w+)',
1217 'PMID' => '[^/]*//www\.ncbi\.nlm\.nih\.gov/pubmed/(?P<PMID>\w+)\?dopt=Abstract',
1218 ];
1219 // T145590: remove patterns for disabled magic links
1220 foreach ( array_keys( $pats ) as $v ) {
1221 if ( !$this->magicLinkEnabled( $v ) ) {
1222 unset( $pats[$v] );
1223 }
1224 }
1225 $regex = '!^(?:' . implode( '|', $pats ) . ')$!';
1226 return static function ( $text ) use ( $pats, $regex ) {
1227 if ( preg_match( $regex, $text, $m ) ) {
1228 foreach ( $pats as $k => $re ) {
1229 if ( isset( $m[$k] ) && $m[$k] !== '' ) {
1230 return [ $k, $m[$k] ];
1231 }
1232 }
1233 }
1234 return false;
1235 };
1236 }
1237
1238 /**
1239 * @return bool
1240 */
1241 public function linterEnabled(): bool {
1242 return $this->linterEnabled;
1243 }
1244
1245 /**
1246 * Return the desired linter configuration. These are heuristic values
1247 * which have hardcoded defaults but could be overridden on a per-wiki
1248 * basis.
1249 * @return array{enabled?:string[],disabled?:string[],maxTableColumnHeuristic?:int,maxTableRowsToCheck?:int}
1250 */
1251 public function getLinterSiteConfig(): array {
1252 return [
1253 // Allow list for specific lint types.
1254 // Takes precedence over block list.
1255 'enabled' => null,
1256 // Block list for specific lint types.
1257 // Not used if an allow list is set.
1258 'disabled' => null,
1259 // The maximum columns in a table before the table is considered
1260 // large
1261 'maxTableColumnHeuristic' => 5,
1262 // The maximum rows (header or data) to be checked for the large
1263 // table lint
1264 // - If we consider the first N rows to be representative of the
1265 // table, and the table is well-formed and uniform, it is
1266 // sufficent to check the first N rows to check if the table is
1267 // "large".
1268 // - This heuristic is used together with the
1269 // 'maxTableColumnHeuristic' to identify "large tables".
1270 'maxTableRowsToCheck' => 10,
1271 // Max length of content covered by 'white-space:nowrap' CSS
1272 // that we consider "safe" when Tidy is replaced. Beyond that,
1273 // wikitext will have to be fixed up to manually insert whitespace
1274 // at the right places. Length in bytes.
1275 'tidyWhitespaceBugMaxLength' => 100,
1276 ];
1277 }
1278
1279 /**
1280 * Serialize ISBN/RFC/PMID URL patterns
1281 *
1282 * @param string[] $match As returned by the getExtResourceURLPatternMatcher() matcher
1283 * @param string $href Fallback link target, if $match is invalid.
1284 * @param string $content Link text
1285 * @return string
1286 */
1287 public function makeExtResourceURL( array $match, string $href, string $content ): string {
1288 $normalized = preg_replace(
1289 '/[ \x{00A0}\x{1680}\x{2000}-\x{200A}\x{202F}\x{205F}\x{3000}]+/u', ' ',
1290 Utils::decodeWtEntities( $content )
1291 );
1292
1293 // TODO: T145590 ("Update Parsoid to be compatible with magic links being disabled")
1294 switch ( $match[0] ) {
1295 case 'ISBN':
1296 $normalized = strtoupper( preg_replace( '/[\- \t]/', '', $normalized ) );
1297 // validate ISBN length and format, so as not to produce magic links
1298 // which aren't actually magic
1299 $valid = preg_match( '/^ISBN(97[89])?\d{9}(\d|X)$/D', $normalized );
1300 if ( implode( '', $match ) === $normalized && $valid ) {
1301 return $content;
1302 }
1303 // strip "./" prefix. TODO: Use relativeLinkPrefix() instead?
1304 $href = PHPUtils::stripPrefix( $href, './' );
1305 return "[[$href|$content]]";
1306
1307 case 'RFC':
1308 case 'PMID':
1309 $normalized = preg_replace( '/[ \t]/', '', $normalized );
1310 return implode( '', $match ) === $normalized ? $content : "[$href $content]";
1311
1312 default:
1313 throw new \InvalidArgumentException( "Invalid match type '{$match[0]}'" );
1314 }
1315 }
1316
1317 /**
1318 * Get the list of valid protocols
1319 * @return array
1320 */
1321 abstract protected function getProtocols(): array;
1322
1323 /**
1324 * Get a regex fragment matching URL protocols, quoted for an exclamation
1325 * mark delimiter. The case-insensitive option should be used.
1326 *
1327 * @param bool $excludeProtRel Whether to exclude protocol-relative URLs
1328 * @return string
1329 */
1330 public function getProtocolsRegex( bool $excludeProtRel = false ) {
1331 $excludeProtRel = (int)$excludeProtRel;
1332 if ( !isset( $this->protocolsRegexes[$excludeProtRel] ) ) {
1333 $parts = [];
1334 foreach ( $this->getProtocols() as $protocol ) {
1335 if ( !$excludeProtRel || $protocol !== '//' ) {
1336 $parts[] = preg_quote( $protocol, '!' );
1337 }
1338 }
1339 $this->protocolsRegexes[$excludeProtRel] = implode( '|', $parts );
1340 }
1341 return $this->protocolsRegexes[$excludeProtRel];
1342 }
1343
1344 /**
1345 * Matcher for valid protocols, must be anchored at start of string.
1346 * @param string $potentialLink
1347 * @return bool Whether $potentialLink begins with a valid protocol
1348 */
1349 public function hasValidProtocol( string $potentialLink ): bool {
1350 $re = '!^(?:' . $this->getProtocolsRegex() . ')!i';
1351 return (bool)preg_match( $re, $potentialLink );
1352 }
1353
1354 /**
1355 * Matcher for valid protocols, may occur at any point within string.
1356 * @param string $potentialLink
1357 * @return bool Whether $potentialLink contains a valid protocol
1358 */
1359 public function findValidProtocol( string $potentialLink ): bool {
1360 $re = '!(?:\W|^)(?:' . $this->getProtocolsRegex() . ')!i';
1361 return (bool)preg_match( $re, $potentialLink );
1362 }
1363
1364 /** @} */
1365
1366 /**
1367 * Fake timestamp, for unit tests.
1368 * @return int|null Unix timestamp, or null to not fake it
1369 */
1370 public function fakeTimestamp(): ?int {
1371 return null;
1372 }
1373
1374 /**
1375 * Get an array of defined extension tags, with the lower case name in the
1376 * key, the value arbitrary. This is the set of extension tags that are
1377 * configured in M/W core. $coreExtModules may already be part of it,
1378 * but eventually this distinction will disappear since all extension tags
1379 * have to be defined against the Parsoid's extension API.
1380 *
1381 * @return array
1382 */
1383 abstract protected function getNonNativeExtensionTags(): array;
1384
1385 /**
1386 * Return an object factory to use when instantiating extensions.
1387 * (This is assumed to be plumbed up to an appropriate service container.)
1388 * @return ObjectFactory The object factory to use for extensions
1389 */
1390 public function getObjectFactory(): ObjectFactory {
1391 // Default implementation returns an object factory with an
1392 // empty service container.
1393 return new ObjectFactory( new class() implements ContainerInterface {
1394
1395 /**
1396 * @param string $id
1397 * @return never
1398 */
1399 public function get( $id ) {
1400 throw new class( "Empty service container" ) extends \Error
1401 implements NotFoundExceptionInterface {
1402 };
1403 }
1404
1405 /**
1406 * @param string $id
1407 * @return false
1408 */
1409 public function has( $id ): bool {
1410 return false;
1411 }
1412 } );
1413 }
1414
1415 /**
1416 * FIXME: might benefit from T250230 (caching) but see T270307 --
1417 * currently SiteConfig::unregisterExtensionModule() is called
1418 * during testing, which requires invalidating $this->extConfig.
1419 * (See also SiteConfig::fakeTimestamp() etc.) We'd probably need
1420 * to more fully separate/mock the "testing SiteConfig" as well
1421 * as provide a way for parser options to en/disable individual
1422 * registered modules before this class can be considered immutable
1423 * and cached.
1424 */
1425 private function constructExtConfig() {
1426 $this->extConfig = [
1427 'allTags' => [],
1428 'parsoidExtTags' => [],
1429 'annotationTags' => [],
1430 'domProcessors' => [],
1431 'annotationStrippers' => [],
1432 'contentModels' => [],
1433 ];
1434
1435 // There may be some tags defined by the parent wiki which have no
1436 // associated parsoid modules; for now we handle these by invoking
1437 // the legacy parser.
1438 $this->extConfig['allTags'] = $this->getNonNativeExtensionTags();
1439
1440 foreach ( $this->getExtensionModules() as $module ) {
1441 $this->processExtensionModule( $module );
1442 }
1443 }
1444
1445 /**
1446 * @param string $lowerTagName
1447 * @return bool
1448 */
1449 public function tagNeedsNowikiStrippedInTagPF( string $lowerTagName ): bool {
1450 return isset( $this->t299103Tags[$lowerTagName] );
1451 }
1452
1453 /**
1454 * Register a Parsoid-compatible extension
1455 * @param ExtensionModule $ext
1456 */
1457 protected function processExtensionModule( ExtensionModule $ext ): void {
1458 Assert::invariant( $this->extConfig !== null, "not yet inited!" );
1459 $extConfig = $ext->getConfig();
1460 Assert::invariant(
1461 isset( $extConfig['name'] ),
1462 "Every extension module must have a name."
1463 );
1464 $name = $extConfig['name'];
1465
1466 // These are extension tag handlers. They have
1467 // wt2html (sourceToDom), html2wt (domToWikitext), and
1468 // linter functionality.
1469 foreach ( $extConfig['tags'] ?? [] as $tagConfig ) {
1470 $lowerTagName = mb_strtolower( $tagConfig['name'] );
1471 $this->extConfig['allTags'][$lowerTagName] = true;
1472 $this->extConfig['parsoidExtTags'][$lowerTagName] = $tagConfig;
1473 // Deal with b/c nowiki stripping support needed by some extensions.
1474 // This register this tag with the legacy parser for
1475 // implicit nowiki stripping in {{#tag:..}} args for this tag.
1476 if ( isset( $tagConfig['options']['stripNowiki'] ) ) {
1477 $this->t299103Tags[$lowerTagName] = true;
1478 }
1479 }
1480
1481 if ( isset( $extConfig['annotations'] ) ) {
1482 $annotationConfig = $extConfig['annotations'];
1483 $annotationTags = $annotationConfig['tagNames'] ?? $annotationConfig;
1484 foreach ( $annotationTags ?? [] as $aTag ) {
1485 $lowerTagName = mb_strtolower( $aTag );
1486 $this->extConfig['allTags'][$lowerTagName] = true;
1487 $this->extConfig['annotationTags'][$lowerTagName] = true;
1488 }
1489 if ( isset( $annotationConfig['annotationStripper'] ) ) {
1490 $obj = $this->getObjectFactory()->createObject( $annotationConfig['annotationStripper'], [
1491 'allowClassName' => true,
1492 'assertClass' => AnnotationStripper::class,
1493 ] );
1494 $this->extConfig['annotationStrippers'][$name] = $obj;
1495 }
1496 }
1497
1498 // Extension modules may also register dom processors.
1499 // This is for wt2htmlPostProcessor and html2wtPreProcessor
1500 // functionality.
1501 if ( isset( $extConfig['domProcessors'] ) ) {
1502 $this->extConfig['domProcessors'][$name] = $extConfig['domProcessors'];
1503 }
1504
1505 foreach ( $extConfig['contentModels'] ?? [] as $cm => $spec ) {
1506 // For compatibility with mediawiki core, the first
1507 // registered extension wins.
1508 if ( isset( $this->extConfig['contentModels'][$cm] ) ) {
1509 continue;
1510 }
1511 $handler = $this->getObjectFactory()->createObject( $spec, [
1512 'allowClassName' => true,
1513 'assertClass' => ContentModelHandler::class,
1514 ] );
1515 $this->extConfig['contentModels'][$cm] = $handler;
1516 }
1517 }
1518
1519 protected function getExtConfig(): array {
1520 if ( !$this->extConfig ) {
1521 $this->constructExtConfig();
1522 }
1523 return $this->extConfig;
1524 }
1525
1526 /**
1527 * Return a ContentModelHandler for the specified $contentmodel, if one is registered.
1528 * If null is returned, will use the default wikitext content model handler.
1529 *
1530 * @param string $contentmodel
1531 * @return ContentModelHandler|null
1532 */
1533 public function getContentModelHandler( string $contentmodel ): ?ContentModelHandler {
1534 return ( $this->getExtConfig() )['contentModels'][$contentmodel] ?? null;
1535 }
1536
1537 /**
1538 * Returns all the annotationStrippers that are defined as annotation configuration
1539 * @return array<AnnotationStripper>
1540 */
1541 public function getAnnotationStrippers(): array {
1542 $res = $this->getExtConfig()['annotationStrippers'] ?? [];
1543 // ensures stability of the method list order
1544 ksort( $res );
1545 return array_values( $res );
1546 }
1547
1548 /**
1549 * Determine whether a given name, which must have already been converted
1550 * to lower case, is a valid extension tag name.
1551 *
1552 * @param string $name
1553 * @return bool
1554 */
1555 public function isExtensionTag( string $name ): bool {
1556 return isset( $this->getExtensionTagNameMap()[$name] );
1557 }
1558
1559 /**
1560 * @param string $tagName is $tagName an annotation tag?
1561 * @return bool
1562 */
1563 public function isAnnotationTag( string $tagName ): bool {
1564 return $this->getExtConfig()['annotationTags'][mb_strtolower( $tagName )] ?? false;
1565 }
1566
1567 /**
1568 * Get an array of defined annotation tags in lower case
1569 * @return array
1570 */
1571 public function getAnnotationTags(): array {
1572 $extConfig = $this->getExtConfig();
1573 return array_keys( $extConfig['annotationTags'] );
1574 }
1575
1576 /**
1577 * Get an array of defined extension tags, with the lower case name
1578 * in the key, and the value being arbitrary.
1579 *
1580 * @return array
1581 */
1582 public function getExtensionTagNameMap(): array {
1583 $extConfig = $this->getExtConfig();
1584 return $extConfig['allTags'];
1585 }
1586
1587 /**
1588 * @param string $tagName Extension tag name
1589 * @return array|null
1590 */
1591 public function getExtTagConfig( string $tagName ): ?array {
1592 $extConfig = $this->getExtConfig();
1593 return $extConfig['parsoidExtTags'][mb_strtolower( $tagName )] ?? null;
1594 }
1595
1596 private $tagHandlerCache = [];
1597
1598 /**
1599 * @param string $tagName Extension tag name
1600 * @return ExtensionTagHandler|null
1601 * Returns the implementation of the named extension, if there is one.
1602 */
1603 public function getExtTagImpl( string $tagName ): ?ExtensionTagHandler {
1604 if ( !array_key_exists( $tagName, $this->tagHandlerCache ) ) {
1605 $tagConfig = $this->getExtTagConfig( $tagName );
1606 $this->tagHandlerCache[$tagName] = isset( $tagConfig['handler'] ) ?
1607 $this->getObjectFactory()->createObject( $tagConfig['handler'], [
1608 'allowClassName' => true,
1609 'assertClass' => ExtensionTagHandler::class,
1610 ] ) : null;
1611 }
1612
1613 return $this->tagHandlerCache[$tagName];
1614 }
1615
1616 /**
1617 * Return an array mapping extension name to an array of object factory
1618 * specs for Ext\DOMProcessor objects
1619 * @return array
1620 */
1621 public function getExtDOMProcessors(): array {
1622 $extConfig = $this->getExtConfig();
1623 return $extConfig['domProcessors'];
1624 }
1625
1626 /** @var array<string,int> */
1627 protected $wt2htmlLimits = [
1628 // We won't handle pages beyond this size
1629 'wikitextSize' => 2048 * 1024, // ParserOptions::maxIncludeSize
1630
1631 // Max list items per page
1632 'listItem' => 30000,
1633
1634 // Max table cells per page
1635 'tableCell' => 30000,
1636
1637 // Max transclusions per page
1638 'transclusion' => 10000,
1639
1640 // DISABLED for now
1641 // Max images per page
1642 'image' => 1000,
1643
1644 // Max top-level token size
1645 'token' => 1000000, // 1M
1646 ];
1647
1648 /**
1649 * @return array<string,int>
1650 */
1651 public function getWt2HtmlLimits(): array {
1652 return $this->wt2htmlLimits;
1653 }
1654
1655 /** @var array<string,int> */
1656 protected $html2wtLimits = [
1657 // We refuse to serialize HTML strings bigger than this
1658 'htmlSize' => 10000000, // 10M
1659 ];
1660
1661 /**
1662 * @return array<string,int>
1663 */
1664 public function getHtml2WtLimits(): array {
1665 return $this->html2wtLimits;
1666 }
1667
1668 /**
1669 * @param ?string $filePath File to log to (if null, logs to console)
1670 * @return Logger
1671 */
1672 public static function createLogger( ?string $filePath = null ): Logger {
1673 // Use Monolog's PHP console handler
1674 $logger = new Logger( "Parsoid CLI" );
1675 $format = '%message%';
1676 if ( $filePath ) {
1677 $handler = new StreamHandler( $filePath );
1678 $format .= "\n";
1679 } else {
1680 $handler = new ErrorLogHandler();
1681 }
1682 // Don't suppress inline newlines
1683 $handler->setFormatter( new LineFormatter( $format, null, true ) );
1684 $logger->pushHandler( $handler );
1685
1686 if ( $filePath ) {
1687 // Separator between logs since StreamHandler appends
1688 $logger->log( Logger::INFO, "-------------- starting fresh log --------------" );
1689 }
1690
1691 return $logger;
1692 }
1693
1694 abstract public function getNoFollowConfig(): array;
1695
1696 /** @return string|false */
1697 abstract public function getExternalLinkTarget();
1698 }