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