Debian Codegraph @

includes/parser/Parsoid/Config/SiteConfig.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 // NO_PRELOAD -- anonymous class in parent
21
22 namespace MediaWiki\Parser\Parsoid\Config;
23
24 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
25 use MediaWiki\Config\Config;
26 use MediaWiki\Config\MutableConfig;
27 use MediaWiki\Config\ServiceOptions;
28 use MediaWiki\Content\IContentHandlerFactory;
29 use MediaWiki\Interwiki\InterwikiLookup;
30 use MediaWiki\Language\Language;
31 use MediaWiki\Language\LanguageCode;
32 use MediaWiki\Language\LanguageConverter;
33 use MediaWiki\Languages\LanguageConverterFactory;
34 use MediaWiki\Languages\LanguageFactory;
35 use MediaWiki\Languages\LanguageNameUtils;
36 use MediaWiki\Logger\LoggerFactory;
37 use MediaWiki\MainConfigNames;
38 use MediaWiki\Parser\MagicWordArray;
39 use MediaWiki\Parser\MagicWordFactory;
40 use MediaWiki\Parser\ParserFactory;
41 use MediaWiki\Parser\ParserOutput;
42 use MediaWiki\SpecialPage\SpecialPageFactory;
43 use MediaWiki\Title\NamespaceInfo;
44 use MediaWiki\Title\Title;
45 use MediaWiki\User\Options\UserOptionsLookup;
46 use MediaWiki\Utils\UrlUtils;
47 use MediaWiki\WikiMap\WikiMap;
48 use MWUnknownContentModelException;
49 use Psr\Log\LoggerInterface;
50 use UnexpectedValueException;
51 use Wikimedia\Bcp47Code\Bcp47Code;
52 use Wikimedia\ObjectFactory\ObjectFactory;
53 use Wikimedia\Parsoid\Config\SiteConfig as ISiteConfig;
54 use Wikimedia\Parsoid\Core\ContentMetadataCollector;
55 use Wikimedia\Parsoid\DOM\Document;
56 use Wikimedia\Parsoid\Utils\Utils;
57 use Wikimedia\Stats\PrefixingStatsdDataFactoryProxy;
58 use Wikimedia\Stats\StatsFactory;
59
60 /**
61 * Site-level configuration for Parsoid
62 *
63 * This includes both global configuration and wiki-level configuration.
64 *
65 * @since 1.39
66 * @internal
67 */
68 class SiteConfig extends ISiteConfig {
69
70 /**
71 * Regular expression fragment for matching wikitext comments.
72 * Meant for inclusion in other regular expressions.
73 */
74 protected const COMMENT_REGEXP_FRAGMENT = '<!--(?>[\s\S]*?-->)';
75
76 public const CONSTRUCTOR_OPTIONS = [
77 MainConfigNames::GalleryOptions,
78 MainConfigNames::AllowExternalImages,
79 MainConfigNames::AllowExternalImagesFrom,
80 MainConfigNames::Server,
81 MainConfigNames::ArticlePath,
82 MainConfigNames::InterwikiMagic,
83 MainConfigNames::ExtraInterlanguageLinkPrefixes,
84 MainConfigNames::InterlanguageLinkCodeMap,
85 MainConfigNames::LocalInterwikis,
86 MainConfigNames::LanguageCode,
87 MainConfigNames::NamespaceAliases,
88 MainConfigNames::UrlProtocols,
89 MainConfigNames::Script,
90 MainConfigNames::ScriptPath,
91 MainConfigNames::LoadScript,
92 MainConfigNames::LocalTZoffset,
93 MainConfigNames::ThumbLimits,
94 MainConfigNames::MaxTemplateDepth,
95 MainConfigNames::NoFollowLinks,
96 MainConfigNames::NoFollowNsExceptions,
97 MainConfigNames::NoFollowDomainExceptions,
98 MainConfigNames::ExternalLinkTarget,
99 MainConfigNames::EnableMagicLinks,
100 ];
101
102 private ServiceOptions $config;
103 private Config $mwConfig;
104 /** Parsoid-specific options array from $config */
105 private array $parsoidSettings;
106 private Language $contLang;
107 private StatsdDataFactoryInterface $stats;
108 private StatsFactory $statsFactory;
109 private MagicWordFactory $magicWordFactory;
110 private NamespaceInfo $namespaceInfo;
111 private SpecialPageFactory $specialPageFactory;
112 private InterwikiLookup $interwikiLookup;
113 private ParserFactory $parserFactory;
114 private UserOptionsLookup $userOptionsLookup;
115 private ObjectFactory $objectFactory;
116 private LanguageFactory $languageFactory;
117 private LanguageConverterFactory $languageConverterFactory;
118 private LanguageNameUtils $languageNameUtils;
119 private UrlUtils $urlUtils;
120 private IContentHandlerFactory $contentHandlerFactory;
121 private ?string $baseUri = null;
122 private ?string $relativeLinkPrefix = null;
123 private ?array $interwikiMap = null;
124 private ?array $variants = null;
125 private ?array $extensionTags = null;
126 private bool $isTimedMediaHandlerLoaded;
127
128 /**
129 * @param ServiceOptions $config MediaWiki main configuration object
130 * @param array $parsoidSettings Parsoid-specific options array from main configuration.
131 * @param ObjectFactory $objectFactory
132 * @param Language $contentLanguage Content language.
133 * @param StatsdDataFactoryInterface $stats
134 * @param StatsFactory $statsFactory
135 * @param MagicWordFactory $magicWordFactory
136 * @param NamespaceInfo $namespaceInfo
137 * @param SpecialPageFactory $specialPageFactory
138 * @param InterwikiLookup $interwikiLookup
139 * @param UserOptionsLookup $userOptionsLookup
140 * @param LanguageFactory $languageFactory
141 * @param LanguageConverterFactory $languageConverterFactory
142 * @param LanguageNameUtils $languageNameUtils
143 * @param UrlUtils $urlUtils
144 * @param IContentHandlerFactory $contentHandlerFactory
145 * @param array $extensionParsoidModules
146 * @param ParserFactory $parserFactory
147 * @param Config $mwConfig
148 * @param bool $isTimedMediaHandlerLoaded
149 */
150 public function __construct(
151 ServiceOptions $config,
152 array $parsoidSettings,
153 ObjectFactory $objectFactory,
154 Language $contentLanguage,
155 StatsdDataFactoryInterface $stats,
156 StatsFactory $statsFactory,
157 MagicWordFactory $magicWordFactory,
158 NamespaceInfo $namespaceInfo,
159 SpecialPageFactory $specialPageFactory,
160 InterwikiLookup $interwikiLookup,
161 UserOptionsLookup $userOptionsLookup,
162 LanguageFactory $languageFactory,
163 LanguageConverterFactory $languageConverterFactory,
164 LanguageNameUtils $languageNameUtils,
165 UrlUtils $urlUtils,
166 IContentHandlerFactory $contentHandlerFactory,
167 array $extensionParsoidModules,
168 // $parserFactory is temporary and may be removed once a better solution is found.
169 ParserFactory $parserFactory, // T268776
170 Config $mwConfig,
171 bool $isTimedMediaHandlerLoaded
172 ) {
173 parent::__construct();
174
175 $config->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
176 $this->config = $config;
177 $this->mwConfig = $mwConfig;
178 $this->parsoidSettings = $parsoidSettings;
179
180 $this->objectFactory = $objectFactory;
181 $this->contLang = $contentLanguage;
182 $this->stats = $stats;
183 $this->statsFactory = $statsFactory;
184 $this->magicWordFactory = $magicWordFactory;
185 $this->namespaceInfo = $namespaceInfo;
186 $this->specialPageFactory = $specialPageFactory;
187 $this->interwikiLookup = $interwikiLookup;
188 $this->parserFactory = $parserFactory;
189 $this->userOptionsLookup = $userOptionsLookup;
190 $this->languageFactory = $languageFactory;
191 $this->languageConverterFactory = $languageConverterFactory;
192 $this->languageNameUtils = $languageNameUtils;
193 $this->urlUtils = $urlUtils;
194 $this->contentHandlerFactory = $contentHandlerFactory;
195
196 // Override parent default
197 if ( isset( $this->parsoidSettings['linting'] ) ) {
198 // @todo: Add this setting to MW's MainConfigSchema
199 $this->linterEnabled = $this->parsoidSettings['linting'];
200 }
201
202 if ( isset( $this->parsoidSettings['wt2htmlLimits'] ) ) {
203 $this->wt2htmlLimits = $this->parsoidSettings['wt2htmlLimits'] + $this->wt2htmlLimits;
204 }
205 if ( isset( $this->parsoidSettings['html2wtLimits'] ) ) {
206 $this->html2wtLimits = $this->parsoidSettings['html2wtLimits'] + $this->html2wtLimits;
207 }
208
209 // Register extension modules
210 foreach ( $extensionParsoidModules as $configOrSpec ) {
211 $this->registerExtensionModule( $configOrSpec );
212 }
213
214 $this->isTimedMediaHandlerLoaded = $isTimedMediaHandlerLoaded;
215 }
216
217 /** @inheritDoc */
218 public function getObjectFactory(): ObjectFactory {
219 return $this->objectFactory;
220 }
221
222 /** @inheritDoc */
223 public function getLogger(): LoggerInterface {
224 // TODO: inject
225 if ( $this->logger === null ) {
226 $this->logger = LoggerFactory::getInstance( 'Parsoid' );
227 }
228 return $this->logger;
229 }
230
231 /**
232 * Get stats prefix
233 * @param bool $trimmed Trim trailing dot on prefix name
234 * @return string
235 */
236 private function getStatsPrefix( bool $trimmed = false ): string {
237 $component = $this->parsoidSettings['metricsPrefix'] ?? 'Parsoid.';
238 if ( $trimmed ) {
239 $component = rtrim( $component, '.' );
240 }
241 return $component;
242 }
243
244 public function metrics(): ?StatsdDataFactoryInterface {
245 // TODO: inject
246 static $prefixedMetrics = null;
247 $prefixedMetrics ??= new PrefixingStatsdDataFactoryProxy(
248 // Our stats will also get prefixed with 'MediaWiki.'
249 $this->stats,
250 $this->getStatsPrefix()
251 );
252 return $prefixedMetrics;
253 }
254
255 /**
256 * Create a prefixed StatsFactory for parsoid stats
257 * @return StatsFactory
258 */
259 public function prefixedStatsFactory(): StatsFactory {
260 $component = $this->getStatsPrefix( true );
261 return $this->statsFactory->withComponent( $component );
262 }
263
264 /**
265 * Record a timing metric
266 * @param string $name
267 * @param float $value A time value in milliseconds
268 * @param array $labels
269 * @return void
270 */
271 public function observeTiming( string $name, float $value, array $labels ) {
272 $this->prefixedStatsFactory()->getTiming( $name )
273 ->setLabels( $labels )
274 ->observe( $value );
275 }
276
277 /**
278 * Increment a counter metric
279 * @param string $name
280 * @param array $labels
281 * @param float $amount
282 * @return void
283 */
284 public function incrementCounter( string $name, array $labels, float $amount = 1 ) {
285 $this->prefixedStatsFactory()->getCounter( $name )
286 ->setLabels( $labels )
287 ->incrementBy( $amount );
288 }
289
290 public function galleryOptions(): array {
291 return $this->config->get( MainConfigNames::GalleryOptions );
292 }
293
294 public function allowedExternalImagePrefixes(): array {
295 if ( $this->config->get( MainConfigNames::AllowExternalImages ) ) {
296 return [ '' ];
297 } else {
298 $allowFrom = $this->config->get( MainConfigNames::AllowExternalImagesFrom );
299 return $allowFrom ? (array)$allowFrom : [];
300 }
301 }
302
303 /**
304 * Determine the article base URI and relative prefix
305 *
306 * Populates `$this->baseUri` and `$this->relativeLinkPrefix` based on
307 * `$wgServer` and `$wgArticlePath`, by splitting it at the last '/' in the
308 * path portion.
309 */
310 private function determineArticlePath(): void {
311 $url = $this->config->get( MainConfigNames::Server ) .
312 $this->config->get( MainConfigNames::ArticlePath );
313
314 if ( substr( $url, -2 ) !== '$1' ) {
315 throw new UnexpectedValueException( "Article path '$url' does not have '$1' at the end" );
316 }
317 $url = substr( $url, 0, -2 );
318
319 $bits = $this->urlUtils->parse( $url );
320 if ( !$bits ) {
321 throw new UnexpectedValueException( "Failed to parse article path '$url'" );
322 }
323
324 if ( empty( $bits['path'] ) ) {
325 $path = '/';
326 } else {
327 $path = UrlUtils::removeDotSegments( $bits['path'] );
328 }
329
330 $relParts = [ 'query' => true, 'fragment' => true ];
331 $base = array_diff_key( $bits, $relParts );
332 $rel = array_intersect_key( $bits, $relParts );
333
334 $i = strrpos( $path, '/' );
335 $base['path'] = substr( $path, 0, $i + 1 );
336 $rel['path'] = '.' . substr( $path, $i );
337
338 $this->baseUri = UrlUtils::assemble( $base );
339 $this->relativeLinkPrefix = UrlUtils::assemble( $rel );
340 }
341
342 public function baseURI(): string {
343 if ( $this->baseUri === null ) {
344 $this->determineArticlePath();
345 }
346 return $this->baseUri;
347 }
348
349 public function relativeLinkPrefix(): string {
350 if ( $this->relativeLinkPrefix === null ) {
351 $this->determineArticlePath();
352 }
353 return $this->relativeLinkPrefix;
354 }
355
356 /**
357 * This is very similar to MagicWordArray::getBaseRegex() except we
358 * don't emit the named grouping constructs, which can cause havoc
359 * when embedded in other regexps with grouping constructs.
360 *
361 * @param MagicWordArray $magicWordArray
362 * @param string $delimiter
363 * @return string
364 */
365 private static function mwaToRegex(
366 MagicWordArray $magicWordArray,
367 string $delimiter = '/'
368 ): string {
369 return implode( '|', $magicWordArray->getBaseRegex( false, $delimiter ) );
370 }
371
372 public function redirectRegexp(): string {
373 $redirect = self::mwaToRegex( $this->magicWordFactory->newArray( [ 'redirect' ] ), '@' );
374 return "@$redirect@Su";
375 }
376
377 public function categoryRegexp(): string {
378 $canon = $this->namespaceInfo->getCanonicalName( NS_CATEGORY );
379 $result = [ $canon ];
380 foreach ( $this->contLang->getNamespaceAliases() as $alias => $ns ) {
381 if ( $ns === NS_CATEGORY && $alias !== $canon ) {
382 $result[] = $alias;
383 }
384 }
385 $category = implode( '|', array_map( function ( $v ) {
386 return $this->quoteTitleRe( $v, '@' );
387 }, $result ) );
388 return "@(?i:$category)@";
389 }
390
391 public function bswRegexp(): string {
392 $bsw = self::mwaToRegex( $this->magicWordFactory->getDoubleUnderscoreArray(), '@' );
393 // Aliases for double underscore mws include the underscores
394 // So, strip them since the base regexp will have included them
395 // and they aren't expected at the use sites of bswRegexp
396 $bsw = str_replace( '__', '', $bsw );
397 return "@$bsw@Su";
398 }
399
400 /** @inheritDoc */
401 public function canonicalNamespaceId( string $name ): ?int {
402 $ret = $this->namespaceInfo->getCanonicalIndex( $name );
403 return $ret === false ? null : $ret;
404 }
405
406 /** @inheritDoc */
407 public function namespaceId( string $name ): ?int {
408 $ret = $this->contLang->getNsIndex( $name );
409 return $ret === false ? null : $ret;
410 }
411
412 /** @inheritDoc */
413 public function namespaceName( int $ns ): ?string {
414 $ret = $this->contLang->getFormattedNsText( $ns );
415 return $ret === '' && $ns !== NS_MAIN ? null : $ret;
416 }
417
418 /** @inheritDoc */
419 public function namespaceHasSubpages( int $ns ): bool {
420 return $this->namespaceInfo->hasSubpages( $ns );
421 }
422
423 /** @inheritDoc */
424 public function namespaceCase( int $ns ): string {
425 return $this->namespaceInfo->isCapitalized( $ns ) ? 'first-letter' : 'case-sensitive';
426 }
427
428 /** @inheritDoc */
429 public function namespaceIsTalk( int $ns ): bool {
430 return $this->namespaceInfo->isTalk( $ns );
431 }
432
433 /** @inheritDoc */
434 public function ucfirst( string $str ): string {
435 return $this->contLang->ucfirst( $str );
436 }
437
438 /** @inheritDoc */
439 public function specialPageLocalName( string $alias ): ?string {
440 $aliases = $this->specialPageFactory->resolveAlias( $alias );
441 return $aliases[0] !== null ? $this->specialPageFactory->getLocalNameFor( ...$aliases ) : $alias;
442 }
443
444 public function interwikiMagic(): bool {
445 return $this->config->get( MainConfigNames::InterwikiMagic );
446 }
447
448 /** @inheritDoc */
449 public function magicLinkEnabled( string $which ): bool {
450 $m = $this->config->get( MainConfigNames::EnableMagicLinks );
451 return $m[$which] ?? true;
452 }
453
454 public function interwikiMap(): array {
455 // Unfortunate that this mostly duplicates \ApiQuerySiteinfo::appendInterwikiMap()
456 if ( $this->interwikiMap !== null ) {
457 return $this->interwikiMap;
458 }
459 $this->interwikiMap = [];
460
461 $getPrefixes = $this->interwikiLookup->getAllPrefixes();
462 $langNames = $this->languageNameUtils->getLanguageNames();
463 $extraLangPrefixes = $this->config->get( MainConfigNames::ExtraInterlanguageLinkPrefixes );
464 $extraLangCodeMap = $this->config->get( MainConfigNames::InterlanguageLinkCodeMap );
465 $localInterwikis = $this->config->get( MainConfigNames::LocalInterwikis );
466
467 foreach ( $getPrefixes as $row ) {
468 $prefix = $row['iw_prefix'];
469 $val = [];
470 $val['prefix'] = $prefix;
471 // ApiQuerySiteInfo::appendInterwikiMap uses PROTO_CURRENT here,
472 // but that's the 'current' protocol *of the API request*; use
473 // PROTO_CANONICAL instead.
474 $val['url'] = $this->urlUtils->expand( $row['iw_url'], PROTO_CANONICAL ) ?? false;
475
476 // Fix up broken interwiki hrefs that are missing a $1 placeholder
477 // Just append the placeholder at the end.
478 // This makes sure that the interwikiMatcher adds one match
479 // group per URI, and that interwiki links work as expected.
480 if ( !str_contains( $val['url'], '$1' ) ) {
481 $val['url'] .= '$1';
482 }
483
484 if ( str_starts_with( $row['iw_url'], '//' ) ) {
485 $val['protorel'] = true;
486 }
487 if ( isset( $row['iw_local'] ) && $row['iw_local'] == '1' ) {
488 $val['local'] = true;
489 }
490 if ( isset( $langNames[$prefix] ) ) {
491 $val['language'] = true;
492 $standard = LanguageCode::replaceDeprecatedCodes( $prefix );
493 if ( $standard !== $prefix ) {
494 # Note that even if this code is deprecated, it should
495 # only be remapped if extralanglink (set below) is false.
496 $val['deprecated'] = $standard;
497 }
498 $val['bcp47'] = LanguageCode::bcp47( $standard );
499 }
500 if ( in_array( $prefix, $localInterwikis, true ) ) {
501 $val['localinterwiki'] = true;
502 }
503 if ( in_array( $prefix, $extraLangPrefixes, true ) ) {
504 $val['extralanglink'] = true;
505 $val['code'] = $extraLangCodeMap[$prefix] ?? $prefix;
506 $val['bcp47'] = LanguageCode::bcp47( $val['code'] );
507 }
508
509 $this->interwikiMap[$prefix] = $val;
510 }
511 return $this->interwikiMap;
512 }
513
514 public function iwp(): string {
515 return WikiMap::getCurrentWikiId();
516 }
517
518 public function legalTitleChars(): string {
519 return Title::legalChars();
520 }
521
522 public function linkPrefixRegex(): ?string {
523 if ( !$this->contLang->linkPrefixExtension() ) {
524 return null;
525 }
526 return '/[' . $this->contLang->linkPrefixCharset() . ']+$/Du';
527 }
528
529 /** @inheritDoc */
530 protected function linkTrail(): string {
531 return $this->contLang->linkTrail();
532 }
533
534 public function langBcp47(): Bcp47Code {
535 return $this->contLang;
536 }
537
538 public function mainpage(): string {
539 // @todo Perhaps should inject TitleFactory here?
540 return Title::newMainPage()->getPrefixedText();
541 }
542
543 public function mainPageLinkTarget(): Title {
544 // @todo Perhaps should inject TitleFactory here?
545 return Title::newMainPage();
546 }
547
548 /**
549 * Lookup config
550 * @param string $key
551 * @return mixed config value for $key, if present or null, if not.
552 */
553 public function getMWConfigValue( string $key ) {
554 return $this->mwConfig->has( $key ) ? $this->mwConfig->get( $key ) : null;
555 }
556
557 public function rtl(): bool {
558 return $this->contLang->isRTL();
559 }
560
561 /**
562 * @param Bcp47Code $lang
563 * @return bool
564 */
565 public function langConverterEnabledBcp47( Bcp47Code $lang ): bool {
566 if ( $this->languageConverterFactory->isConversionDisabled() ) {
567 return false;
568 }
569
570 $langObject = $this->languageFactory->getLanguage( $lang );
571 if ( !in_array( $langObject->getCode(), LanguageConverter::$languagesWithVariants, true ) ) {
572 return false;
573 }
574 $converter = $this->languageConverterFactory->getLanguageConverter( $langObject );
575 return $converter->hasVariants();
576 }
577
578 public function script(): string {
579 return $this->config->get( MainConfigNames::Script );
580 }
581
582 public function scriptpath(): string {
583 return $this->config->get( MainConfigNames::ScriptPath );
584 }
585
586 public function server(): string {
587 return $this->config->get( MainConfigNames::Server );
588 }
589
590 /**
591 * @inheritDoc
592 * @param Document $document
593 * @param ContentMetadataCollector $metadata
594 * @param string $defaultTitle
595 * @param Bcp47Code $lang
596 */
597 public function exportMetadataToHeadBcp47(
598 Document $document,
599 ContentMetadataCollector $metadata,
600 string $defaultTitle,
601 Bcp47Code $lang
602 ): void {
603 '@phan-var ParserOutput $metadata'; // @var ParserOutput $metadata
604 // Look for a displaytitle.
605 $displayTitle = $metadata->getPageProperty( 'displaytitle' ) ?:
606 // Use the default title, properly escaped
607 Utils::escapeHtml( $defaultTitle );
608 $this->exportMetadataHelper(
609 $document,
610 $this->config->get( MainConfigNames::LoadScript ),
611 $metadata->getModules(),
612 $metadata->getModuleStyles(),
613 $metadata->getJsConfigVars(),
614 $displayTitle,
615 $lang
616 );
617 }
618
619 public function timezoneOffset(): int {
620 return $this->config->get( MainConfigNames::LocalTZoffset );
621 }
622
623 /**
624 * Language variant information
625 * @return array<string,array> Keys are MediaWiki-internal variant codes (e.g. "zh-cn"),
626 * values are arrays with two fields:
627 * - base: (string) Base language code (e.g. "zh") (MediaWiki-internal)
628 * - fallbacks: (string[]) Fallback variants (MediaWiki-internal codes)
629 * @deprecated since 1.43; use ::variantsFor() (T320662)
630 */
631 public function variants(): array {
632 // Deprecated for all external callers; to make private and remove this warning.
633 if ( wfGetCaller() !== __CLASS__ . '->variantsFor' ) {
634 wfDeprecated( __METHOD__, '1.43' );
635 }
636
637 if ( $this->variants !== null ) {
638 return $this->variants;
639 }
640 $this->variants = [];
641
642 $langNames = LanguageConverter::$languagesWithVariants;
643 if ( $this->languageConverterFactory->isConversionDisabled() ) {
644 // Ensure result is empty if language conversion is disabled.
645 $langNames = [];
646 }
647
648 foreach ( $langNames as $langCode ) {
649 $lang = $this->languageFactory->getLanguage( $langCode );
650 $converter = $this->languageConverterFactory->getLanguageConverter( $lang );
651 if ( !$converter->hasVariants() ) {
652 continue;
653 }
654
655 $variants = $converter->getVariants();
656 foreach ( $variants as $v ) {
657 $fallbacks = $converter->getVariantFallbacks( $v );
658 if ( !is_array( $fallbacks ) ) {
659 $fallbacks = [ $fallbacks ];
660 }
661 $this->variants[$v] = [
662 'base' => $langCode,
663 'fallbacks' => $fallbacks,
664 ];
665 }
666 }
667 return $this->variants;
668 }
669
670 /**
671 * Language variant information for the given language (or null if
672 * unknown).
673 * @param Bcp47Code $code The language for which you want variant information
674 * @return ?array{base:Bcp47Code,fallbacks:Bcp47Code[]} an array with
675 * two fields:
676 * - base: (Bcp47Code) Base BCP-47 language code (e.g. "zh")
677 * - fallbacks: (Bcp47Code[]) Fallback variants, as BCP-47 codes
678 */
679 public function variantsFor( Bcp47Code $code ): ?array {
680 $variants = $this->variants();
681 $lang = $this->languageFactory->getLanguage( $code );
682 $tuple = $variants[$lang->getCode()] ?? null;
683 if ( $tuple === null ) {
684 return null;
685 }
686 return [
687 'base' => $this->languageFactory->getLanguage( $tuple['base'] ),
688 'fallbacks' => array_map(
689 [ $this->languageFactory, 'getLanguage' ],
690 $tuple['fallbacks']
691 ),
692 ];
693 }
694
695 public function widthOption(): int {
696 // Even though this looks like Parsoid is supporting per-user thumbsize
697 // options, that is not the case, Parsoid doesn't receive user session state
698 $thumbsize = $this->userOptionsLookup->getDefaultOption( 'thumbsize' );
699 return $this->config->get( MainConfigNames::ThumbLimits )[$thumbsize];
700 }
701
702 /** @inheritDoc */
703 protected function getVariableIDs(): array {
704 return $this->magicWordFactory->getVariableIDs();
705 }
706
707 /** @inheritDoc */
708 protected function getFunctionSynonyms(): array {
709 return $this->parserFactory->getMainInstance()->getFunctionSynonyms();
710 }
711
712 /** @return array<string,array> $magicWord => [ int $caseSensitive, string ...$alias ] */
713 protected function getMagicWords(): array {
714 return $this->contLang->getMagicWords();
715 }
716
717 /** @inheritDoc */
718 public function getMagicWordMatcher( string $id ): string {
719 return $this->magicWordFactory->get( $id )->getRegexStartToEnd();
720 }
721
722 /** @inheritDoc */
723 public function getParameterizedAliasMatcher( array $words ): callable {
724 // PORT-FIXME: this should be combined with
725 // getMediaPrefixParameterizedAliasMatcher; see PORT-FIXME comment
726 // in that method.
727 // Filter out timedmedia-* unless that extension is loaded, so Parsoid
728 // doesn't have a hard dependency on an extension.
729 if ( !$this->isTimedMediaHandlerLoaded ) {
730 $words = preg_grep( '/^timedmedia_/', $words, PREG_GREP_INVERT );
731 }
732 $words = $this->magicWordFactory->newArray( $words );
733 return static function ( $text ) use ( $words ) {
734 $ret = $words->matchVariableStartToEnd( $text );
735 if ( $ret[0] === false || $ret[1] === false ) {
736 return null;
737 } else {
738 return [ 'k' => $ret[0], 'v' => $ret[1] ];
739 }
740 };
741 }
742
743 private function populateExtensionTags(): void {
744 $this->extensionTags = array_fill_keys( $this->parserFactory->getMainInstance()->getTags(), true );
745 }
746
747 /** @inheritDoc */
748 protected function getNonNativeExtensionTags(): array {
749 if ( $this->extensionTags === null ) {
750 $this->populateExtensionTags();
751 }
752 return $this->extensionTags;
753 }
754
755 /** @inheritDoc */
756 public function getMaxTemplateDepth(): int {
757 return (int)$this->config->get( MainConfigNames::MaxTemplateDepth );
758 }
759
760 /**
761 * Overrides the max template depth in the MediaWiki configuration.
762 * @param int $depth
763 */
764 public function setMaxTemplateDepth( int $depth ): void {
765 // Parsoid's command-line tools let you set the max template depth
766 // as a CLI argument. Since we currently invoke the legacy
767 // preprocessor in some situations, we can't just override
768 // ::getMaxTemplateDepth() above, we need to reset the Config
769 // service.
770 if ( $this->config instanceof MutableConfig ) {
771 $this->config->set( MainConfigNames::MaxTemplateDepth, $depth );
772 } else {
773 // Fall back on global variable (hopefully we're using
774 // a GlobalVarConfig and this will work)
775 $GLOBALS['wgMaxTemplateDepth'] = $depth;
776 }
777 }
778
779 /** @inheritDoc */
780 protected function getSpecialNSAliases(): array {
781 $nsAliases = [
782 'Special',
783 $this->quoteTitleRe( $this->contLang->getNsText( NS_SPECIAL ) )
784 ];
785 foreach (
786 $this->contLang->getNamespaceAliases() +
787 $this->config->get( MainConfigNames::NamespaceAliases )
788 as $name => $ns
789 ) {
790 if ( $ns === NS_SPECIAL ) {
791 $nsAliases[] = $this->quoteTitleRe( $name );
792 }
793 }
794
795 return $nsAliases;
796 }
797
798 /** @inheritDoc */
799 protected function getSpecialPageAliases( string $specialPage ): array {
800 return array_merge( [ $specialPage ],
801 $this->contLang->getSpecialPageAliases()[$specialPage] ?? []
802 );
803 }
804
805 /** @inheritDoc */
806 protected function getProtocols(): array {
807 return $this->config->get( MainConfigNames::UrlProtocols );
808 }
809
810 /** @return array */
811 public function getNoFollowConfig(): array {
812 return [
813 'nofollow' => $this->config->get( MainConfigNames::NoFollowLinks ),
814 'nsexceptions' => $this->config->get( MainConfigNames::NoFollowNsExceptions ),
815 'domainexceptions' => $this->config->get( MainConfigNames::NoFollowDomainExceptions )
816 ];
817 }
818
819 /** @return string|false */
820 public function getExternalLinkTarget() {
821 return $this->config->get( MainConfigNames::ExternalLinkTarget );
822 }
823
824 // MW-specific helper
825
826 /**
827 * Returns true iff Parsoid natively supports the given content model.
828 * @param string $model content model identifier
829 * @return bool
830 */
831 public function supportsContentModel( string $model ): bool {
832 if ( $model === CONTENT_MODEL_WIKITEXT ) {
833 return true;
834 }
835
836 // Check if the content model serializes to wikitext.
837 // NOTE: We could use isSupportedFormat( CONTENT_FORMAT_WIKITEXT ) if PageContent::getContent()
838 // would specify the format when calling serialize().
839 try {
840 $handler = $this->contentHandlerFactory->getContentHandler( $model );
841 if ( $handler->getDefaultFormat() === CONTENT_FORMAT_WIKITEXT ) {
842 return true;
843 }
844 } catch ( MWUnknownContentModelException $ex ) {
845 // If the content model is not known, it can't be supported.
846 return false;
847 }
848
849 return $this->getContentModelHandler( $model ) !== null;
850 }
851
852 }