Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
64.04% covered (warning)
64.04%
244 / 381
43.40% covered (danger)
43.40%
23 / 53
CRAP
0.00% covered (danger)
0.00%
0 / 1
ContentHandler
64.21% covered (warning)
64.21%
244 / 380
43.40% covered (danger)
43.40%
23 / 53
917.70
0.00% covered (danger)
0.00%
0 / 1
 makeContent
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
 getLocalizedName
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 serializeContent
n/a
0 / 0
n/a
0 / 0
0
 serializeContentToJsonArray
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 exportTransform
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 unserializeContent
n/a
0 / 0
n/a
0 / 0
0
 deserializeContentFromJsonArray
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 importTransform
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 makeEmptyContent
n/a
0 / 0
n/a
0 / 0
0
 makeRedirectContent
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getModelID
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 checkModelID
25.00% covered (danger)
25.00%
1 / 4
0.00% covered (danger)
0.00%
0 / 1
3.69
 getSupportedFormats
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getDefaultFormat
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getJsonFormat
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isSupportedFormat
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 checkFormat
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 getActionOverrides
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 createDifferenceEngine
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 getSlotDiffRenderer
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
3
 getSlotDiffRendererInternal
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getSlotDiffRendererWithOptions
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 createTextSlotDiffRenderer
84.62% covered (warning)
84.62%
22 / 26
0.00% covered (danger)
0.00%
0 / 1
5.09
 getPageLanguage
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
3.01
 getPageViewLanguage
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 canBeUsedOn
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getDiffEngineClass
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 merge3
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getLanguageConverter
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getChangeType
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
21
 getAutosummary
56.86% covered (warning)
56.86%
29 / 51
0.00% covered (danger)
0.00%
0 / 1
18.03
 getChangeTag
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 getAutoDeleteReason
0.00% covered (danger)
0.00%
0 / 50
0.00% covered (danger)
0.00%
0 / 1
306
 getUndoContent
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 isParserCacheSupported
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 supportsSections
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 supportsCategories
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 supportsRedirects
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 supportsDirectEditing
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 supportsPreloadContent
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 generateHTMLOnEdit
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 supportsDirectApiEditing
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getFieldsForSearchIndex
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
1
 addSearchField
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getDataForSearchIndex
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
3
 getParserOutputForIndexing
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 latestRevision
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 getSecondaryDataUpdates
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getDeletionUpdates
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 preSaveTransform
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 preloadTransform
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 validateSave
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getParserOutput
81.58% covered (warning)
81.58%
31 / 38
0.00% covered (danger)
0.00%
0 / 1
5.16
 fillParserOutputInternal
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 fillParserOutput
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\Content;
8
9use InvalidArgumentException;
10use JsonException;
11use LogicException;
12use MediaWiki\Actions\Action;
13use MediaWiki\CommentStore\CommentStore;
14use MediaWiki\Content\Renderer\ContentParseParams;
15use MediaWiki\Content\Transform\PreloadTransformParams;
16use MediaWiki\Content\Transform\PreSaveTransformParams;
17use MediaWiki\Context\IContextSource;
18use MediaWiki\Context\RequestContext;
19use MediaWiki\Deferred\DeferrableUpdate;
20use MediaWiki\Diff\DifferenceEngine;
21use MediaWiki\Diff\DifferenceEngineSlotDiffRenderer;
22use MediaWiki\Diff\SlotDiffRenderer;
23use MediaWiki\Diff\TextDiffer\ManifoldTextDiffer;
24use MediaWiki\Diff\TextSlotDiffRenderer;
25use MediaWiki\HookContainer\HookRunner;
26use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
27use MediaWiki\Language\ILanguageConverter;
28use MediaWiki\Language\Language;
29use MediaWiki\Logger\LoggerFactory;
30use MediaWiki\MainConfigNames;
31use MediaWiki\MediaWikiServices;
32use MediaWiki\Page\ParserOutputAccess;
33use MediaWiki\Page\WikiPage;
34use MediaWiki\Parser\ParserCache;
35use MediaWiki\Parser\ParserOutput;
36use MediaWiki\Revision\RevisionRecord;
37use MediaWiki\Revision\SlotRecord;
38use MediaWiki\Revision\SlotRenderingProvider;
39use MediaWiki\Search\ParserOutputSearchDataExtractor;
40use MediaWiki\Search\SearchEngine;
41use MediaWiki\Search\SearchIndexField;
42use MediaWiki\Title\Title;
43use RuntimeException;
44use StatusValue;
45use UnexpectedValueException;
46use Wikimedia\Assert\Assert;
47use Wikimedia\Rdbms\IDBAccessObject;
48use Wikimedia\ScopedCallback;
49
50/**
51 * Base class for content handling.
52 *
53 * A content handler knows how do deal with a specific type of content on a wiki
54 * page. Content is stored in the database in a serialized form (using a
55 * serialization format a.k.a. MIME type) and is unserialized into its native
56 * PHP representation (the content model), which is wrapped in an instance of
57 * the appropriate subclass of Content.
58 *
59 * ContentHandler instances are stateless singletons that serve, among other
60 * things, as a factory for Content objects. Generally, there is one subclass
61 * of ContentHandler and one subclass of Content for every type of content model.
62 *
63 * Some content types have a flat model, that is, their native representation
64 * is the same as their serialized form. Examples would be JavaScript and CSS
65 * code. As of now, this also applies to wikitext (MediaWiki's default content
66 * type), but wikitext content may be represented by a DOM or AST structure in
67 * the future.
68 *
69 * @stable to extend
70 * @since 1.21
71 * @ingroup Content
72 * @author Daniel Kinzler
73 */
74abstract class ContentHandler {
75    use ProtectedHookAccessorTrait;
76
77    /**
78     * Convenience function for creating a Content object from a given textual
79     * representation.
80     *
81     * $text will be deserialized into a Content object of the model specified
82     * by $modelId (or, if that is not given, $title->getContentModel()) using
83     * the given format.
84     *
85     * @since 1.21
86     *
87     * @param string $text The textual representation, will be
88     *    unserialized to create the Content object
89     * @param Title|null $title The title of the page this text belongs to.
90     *    Required if $modelId is not provided.
91     * @param string|null $modelId The model to deserialize to. If not provided,
92     *    $title->getContentModel() is used.
93     * @param string|null $format The format to use for deserialization. If not
94     *    given, the model's default format is used.
95     *
96     * @throws ContentSerializationException
97     * @throws UnknownContentModelException
98     * @return Content A Content object representing the text.
99     */
100    public static function makeContent( $text, ?Title $title = null,
101        $modelId = null, $format = null ) {
102        if ( !$title && !$modelId ) {
103            throw new InvalidArgumentException( "Must provide a Title object or a content model ID." );
104        }
105
106        return MediaWikiServices::getInstance()
107            ->getContentHandlerFactory()
108            ->getContentHandler( $modelId ?? $title->getContentModel() )
109            ->unserializeContent( $text, $format );
110    }
111
112    /**
113     * Returns the localized name for a given content model.
114     *
115     * Model names are localized using system messages. Message keys
116     * have the form content-model-$name, where $name is getContentModelName( $id ).
117     *
118     * @param string $name The content model ID, as given by a CONTENT_MODEL_XXX
119     *    constant or returned by Content::getModel() or SlotRecord::getModel().
120     * @param Language|null $lang The language to parse the message in (since 1.26)
121     *
122     * @return string The content model's localized name.
123     */
124    public static function getLocalizedName( $name, ?Language $lang = null ) {
125        // Messages: content-model-wikitext, content-model-text,
126        // content-model-javascript, content-model-css
127        // Lowercase the name as message keys need to be in lowercase, T358341
128        $key = "content-model-" . strtolower( $name ?? '' );
129
130        $msg = wfMessage( $key );
131        if ( $lang ) {
132            $msg->inLanguage( $lang );
133        }
134
135        return $msg->exists() ? $msg->plain() : $name;
136    }
137
138    // ------------------------------------------------------------------------
139
140    /**
141     * @var string
142     */
143    protected $mModelID;
144
145    /**
146     * @var string[]
147     */
148    protected $mSupportedFormats;
149
150    /**
151     * Constructor, initializing the ContentHandler instance with its model ID
152     * and a list of supported formats. Values for the parameters are typically
153     * provided as literals by subclass's constructors.
154     *
155     * @stable to call
156     *
157     * @param string $modelId (use CONTENT_MODEL_XXX constants).
158     * @param string[] $formats List for supported serialization formats
159     *    (typically as MIME types)
160     */
161    public function __construct( $modelId, $formats ) {
162        $this->mModelID = $modelId;
163        $this->mSupportedFormats = $formats;
164    }
165
166    /**
167     * Serializes a Content object of the type supported by this ContentHandler.
168     *
169     * @stable to override
170     *
171     * @since 1.21
172     *
173     * @param Content $content The Content object to serialize
174     * @param string|null $format The desired serialization format
175     *
176     * @return string Serialized form of the content
177     */
178    abstract public function serializeContent( Content $content, $format = null );
179
180    /**
181     * Serializes a Content object of the type supported by this
182     * ContentHandler to an array which is JsonCodecable.
183     *
184     * @since 1.45
185     *
186     * @param Content $content The Content object to serialize
187     *
188     * @return array An array of JsonCodecable content
189     */
190    public function serializeContentToJsonArray( Content $content ): array {
191        $format = $this->getJsonFormat();
192        $blob = $this->serializeContent( $content, $format );
193        return [
194            'format' => $format,
195            'blob' => $blob,
196        ];
197    }
198
199    /**
200     * Applies transformations on export (returns the blob unchanged by default).
201     * Subclasses may override this to perform transformations such as conversion
202     * of legacy formats or filtering of internal meta-data.
203     *
204     * @stable to override
205     *
206     * @param string $blob The blob to be exported
207     * @param string|null $format The blob's serialization format
208     *
209     * @return string
210     */
211    public function exportTransform( $blob, $format = null ) {
212        return $blob;
213    }
214
215    /**
216     * Unserializes a Content object of the type supported by this ContentHandler.
217     *
218     * @stable to override
219     * @since 1.21
220     *
221     * @param string $blob Serialized form of the content
222     * @param string|null $format The format used for serialization
223     *
224     * @return Content The Content object created by deserializing $blob
225     * @throws ContentSerializationException
226     * @see ContentJsonCodec
227     */
228    abstract public function unserializeContent( $blob, $format = null );
229
230    /**
231     * Deserializes a Content object of the type supported by this
232     * ContentHandler from a JsonCodecable array.
233     *
234     * @since 1.45
235     *
236     * @param array $json Serialized form of the content
237     *
238     * @return Content The Content object created by deserializing $blob
239     * @throws JsonException
240     * @see ContentJsonCodec
241     */
242    public function deserializeContentFromJsonArray( array $json ): Content {
243        try {
244            return $this->unserializeContent( $json['blob'], $json['format'] );
245        } catch ( ContentSerializationException $e ) {
246            throw new JsonException( $e->getMessage() );
247        }
248    }
249
250    /**
251     * Apply import transformation (by default, returns $blob unchanged).
252     * This gives subclasses an opportunity to transform data blobs on import.
253     *
254     * @stable to override
255     * @since 1.24
256     *
257     * @param string $blob
258     * @param string|null $format
259     *
260     * @return string
261     */
262    public function importTransform( $blob, $format = null ) {
263        return $blob;
264    }
265
266    /**
267     * Creates an empty Content object of the type supported by this
268     * ContentHandler.
269     *
270     * @stable to override
271     * @since 1.21
272     * @return Content
273     */
274    abstract public function makeEmptyContent();
275
276    /**
277     * Creates a new Content object that acts as a redirect to the given page,
278     * or null if redirects are not supported by this content model.
279     *
280     * This default implementation always returns null. Subclasses supporting redirects
281     * must override this method.
282     *
283     * Note that subclasses that override this method to return a Content object
284     * should also override supportsRedirects() to return true.
285     *
286     * @stable to override
287     * @since 1.21
288     *
289     * @param Title $destination The page to redirect to.
290     * @param string $text Text to include in the redirect, if possible.
291     *
292     * @return Content|null Always null.
293     */
294    public function makeRedirectContent( Title $destination, $text = '' ) {
295        return null;
296    }
297
298    /**
299     * Returns the model id that identifies the content model this
300     * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
301     *
302     * @since 1.21
303     * @return string The model ID
304     */
305    public function getModelID() {
306        return $this->mModelID;
307    }
308
309    /**
310     * @since 1.21
311     * @param string $model_id The model to check
312     * @throws UnexpectedContentModelException If the provided model ID differs from this ContentHandler
313     */
314    protected function checkModelID( $model_id ) {
315        if ( $model_id !== $this->mModelID ) {
316            throw new UnexpectedContentModelException( "Bad content model: " .
317                "expected {$this->mModelID} " .
318                "but got $model_id." );
319        }
320    }
321
322    /**
323     * Returns a list of serialization formats supported by the
324     * serializeContent() and unserializeContent() methods of this
325     * ContentHandler.
326     *
327     * @stable to override
328     * @since 1.21
329     * @return string[] List of serialization formats as MIME type like strings
330     */
331    public function getSupportedFormats() {
332        return $this->mSupportedFormats;
333    }
334
335    /**
336     * The format used for serialization/deserialization by default by this
337     * ContentHandler.
338     *
339     * This default implementation will return the first element of the array
340     * of formats that was passed to the constructor.
341     *
342     * @stable to override
343     * @since 1.21
344     * @return string The name of the default serialization format as a MIME type
345     */
346    public function getDefaultFormat() {
347        return $this->mSupportedFormats[0];
348    }
349
350    /**
351     * Allow ContentHandler to chose a non-default format for JSON
352     * serialization.
353     *
354     * In most cases will return the same as `::getDefaultFormat()`.
355     */
356    public function getJsonFormat(): string {
357        return $this->getDefaultFormat();
358    }
359
360    /**
361     * Returns true if $format is a serialization format supported by this
362     * ContentHandler, and false otherwise.
363     *
364     * Note that if $format is null, this method always returns true, because
365     * null means "use the default format".
366     *
367     * @stable to override
368     * @since 1.21
369     *
370     * @param string $format The serialization format to check
371     *
372     * @return bool
373     */
374    public function isSupportedFormat( $format ) {
375        if ( !$format ) {
376            return true; // this means "use the default"
377        }
378
379        return in_array( $format, $this->mSupportedFormats );
380    }
381
382    /**
383     * Convenient for checking whether a format provided as a parameter is actually supported.
384     *
385     * @param string $format The serialization format to check
386     *
387     * @throws UnsupportedContentFormatException If the format is not supported by this content handler.
388     */
389    protected function checkFormat( $format ) {
390        if ( !$this->isSupportedFormat( $format ) ) {
391            throw new UnsupportedContentFormatException(
392                "Format $format is not supported for content model "
393                . $this->getModelID()
394            );
395        }
396    }
397
398    /**
399     * Returns overrides for action handlers.
400     * Classes listed here will be used instead of the default one when
401     * (and only when) $wgActions[$action] === true. This allows subclasses
402     * to override the default action handlers.
403     *
404     * @stable to override
405     * @since 1.21
406     *
407     * @return array<string,class-string|callable|false|Action|array> An array mapping action names
408     *  (typically "view", "edit", "history" etc.) to a specification according to
409     *  {@see ActionFactory::getActionSpec}. Can be the full qualified class name of an Action
410     *  class, a callable taking ( Article $article, IContextSource $context ) as parameters and
411     *  returning an Action object, false to disable an action, an actual Action object,
412     *  or an ObjectFactory specification array (can have 'class', 'services', etc.).
413     *  An empty array in this default implementation.
414     *
415     * @see Action::factory
416     */
417    public function getActionOverrides() {
418        return [];
419    }
420
421    /**
422     * Factory for creating an appropriate DifferenceEngine for this content model.
423     * Since 1.32, this is only used for page-level diffs; to diff two content objects,
424     * use getSlotDiffRenderer.
425     *
426     * The DifferenceEngine subclass to use is selected in getDiffEngineClass(). The
427     * GetDifferenceEngine hook will receive the DifferenceEngine object and can replace or
428     * wrap it.
429     * (Note that in older versions of MediaWiki the hook documentation instructed extensions
430     * to return false from the hook; you should not rely on always being able to decorate
431     * the DifferenceEngine instance from the hook. If the owner of the content type wants to
432     * decorate the instance, overriding this method is a safer approach.)
433     *
434     * @todo This is page-level functionality so it should not belong to ContentHandler.
435     *   Move it to a better place once one exists (e.g. PageTypeHandler).
436     *
437     * @since 1.21
438     *
439     * @param IContextSource $context Context to use, anything else will be ignored.
440     * @param int $old Revision ID we want to show and diff with.
441     * @param int|string $new Either a revision ID or one of the strings 'cur', 'prev' or 'next'.
442     * @param int $rcid FIXME: Deprecated, no longer used. Defaults to 0.
443     * @param bool $refreshCache If set, refreshes the diff cache. Defaults to false.
444     * @param bool $unhide If set, allow viewing deleted revs. Defaults to false.
445     *
446     * @return DifferenceEngine
447     */
448    public function createDifferenceEngine( IContextSource $context, $old = 0, $new = 0,
449        $rcid = 0, // FIXME: Deprecated, no longer used
450        $refreshCache = false, $unhide = false
451    ) {
452        $diffEngineClass = $this->getDiffEngineClass();
453        $differenceEngine = new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
454        $this->getHookRunner()->onGetDifferenceEngine(
455            $context, $old, $new, $refreshCache, $unhide, $differenceEngine );
456        return $differenceEngine;
457    }
458
459    /**
460     * Get an appropriate SlotDiffRenderer for this content model.
461     *
462     * @stable to override
463     * @since 1.32
464     *
465     * @param IContextSource $context
466     * @param array $options An associative array of options passed to the SlotDiffRenderer:
467     *   - diff-type: (string) The text diff format
468     *   - contentLanguage: (string) The language code of the content language,
469     *     to be passed to the TextDiffer constructor. This is ignored if a
470     *     TextDiffer object is provided.
471     *   - textDiffer: (TextDiffer) A TextDiffer object to use for text
472     *     comparison.
473     * @return SlotDiffRenderer
474     */
475    final public function getSlotDiffRenderer( IContextSource $context, array $options = [] ) {
476        $slotDiffRenderer = $this->getSlotDiffRendererWithOptions( $context, $options );
477        if ( get_class( $slotDiffRenderer ) === TextSlotDiffRenderer::class ) {
478            // To keep B/C, when SlotDiffRenderer is not overridden for a given content type
479            // but DifferenceEngine is, use that instead.
480            $differenceEngine = $this->createDifferenceEngine( $context );
481            if ( get_class( $differenceEngine ) !== DifferenceEngine::class ) {
482                // TODO turn this into a deprecation warning in a later release
483                LoggerFactory::getInstance( 'diff' )->info(
484                    'Falling back to DifferenceEngineSlotDiffRenderer', [
485                        'modelID' => $this->getModelID(),
486                        'DifferenceEngine' => get_class( $differenceEngine ),
487                    ] );
488                $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
489            }
490        }
491        $this->getHookRunner()->onGetSlotDiffRenderer( $this, $slotDiffRenderer, $context );
492        return $slotDiffRenderer;
493    }
494
495    /**
496     * Return the SlotDiffRenderer appropriate for this content handler.
497     * @deprecated since 1.35; use getSlotDiffRendererWithOptions instead
498     *   Emitting deprecation warnings since 1.41.
499     * @param IContextSource $context
500     * @return SlotDiffRenderer|null
501     */
502    protected function getSlotDiffRendererInternal( IContextSource $context ) {
503        return null;
504    }
505
506    /**
507     * Return the SlotDiffRenderer appropriate for this content handler.
508     * @stable to override
509     *
510     * @param IContextSource $context
511     * @param array $options See getSlotDiffRenderer()
512     *
513     * @return SlotDiffRenderer
514     */
515    protected function getSlotDiffRendererWithOptions( IContextSource $context, $options = [] ) {
516        $internalRenderer = $this->getSlotDiffRendererInternal( $context );
517        // `getSlotDiffRendererInternal` has been overridden by a class using the deprecated method.
518        // Options will not work so exit early!
519        if ( $internalRenderer !== null ) {
520            wfDeprecated( 'ContentHandler::getSlotDiffRendererInternal', '1.35' );
521            return $internalRenderer;
522        }
523        return $this->createTextSlotDiffRenderer( $options );
524    }
525
526    /**
527     * Create a TextSlotDiffRenderer and inject dependencies
528     *
529     * @since 1.41
530     * @param array $options See getSlotDiffRenderer()
531     * @return TextSlotDiffRenderer
532     */
533    final protected function createTextSlotDiffRenderer( array $options = [] ): TextSlotDiffRenderer {
534        $slotDiffRenderer = new TextSlotDiffRenderer();
535
536        $services = MediaWikiServices::getInstance();
537        $slotDiffRenderer->setStatsFactory( $services->getStatsFactory() );
538        $slotDiffRenderer->setHookContainer( $services->getHookContainer() );
539        $slotDiffRenderer->setContentModel( $this->getModelID() );
540
541        if ( isset( $options['textDiffer'] ) ) {
542            $textDiffer = $options['textDiffer'];
543        } else {
544            if ( isset( $options['contentLanguage'] ) ) {
545                $language = $services->getLanguageFactory()->getLanguage( $options['contentLanguage'] );
546            } else {
547                $language = $services->getContentLanguage();
548            }
549            $config = $services->getMainConfig();
550            $textDiffer = new ManifoldTextDiffer(
551                RequestContext::getMain(),
552                $language,
553                $config->get( MainConfigNames::DiffEngine ),
554                $config->get( MainConfigNames::ExternalDiffEngine ),
555                $config->get( MainConfigNames::Wikidiff2Options )
556            );
557        }
558        $format = $options['diff-type'] ?? 'table';
559        if ( !$textDiffer->hasFormat( $format ) ) {
560            // Maybe it would be better to throw an exception here, but at
561            // present, the value comes straight from user input without
562            // validation, so we have to fall back.
563            $format = 'table';
564        }
565        $slotDiffRenderer->setFormat( $format );
566        $slotDiffRenderer->setTextDiffer( $textDiffer );
567        if ( $options['inline-toggle'] ?? false ) {
568            $slotDiffRenderer->setInlineToggleEnabled();
569        }
570
571        return $slotDiffRenderer;
572    }
573
574    /**
575     * Get the language in which the content of the given page is written.
576     *
577     * This default implementation just returns the content language (except for pages
578     * in the MediaWiki namespace)
579     *
580     * Note that the page's language is not cacheable, since it may in some
581     * cases depend on user settings.
582     *
583     * Also note that the page language may or may not depend on the actual content of the page,
584     * that is, this method may load the content in order to determine the language.
585     *
586     * @stable to override
587     * @since 1.21
588     *
589     * @param Title $title The page to determine the language for.
590     * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
591     *
592     * @return Language
593     */
594    public function getPageLanguage( Title $title, ?Content $content = null ) {
595        $services = MediaWikiServices::getInstance();
596        $pageLang = $services->getContentLanguage();
597
598        if ( $title->inNamespace( NS_MEDIAWIKI ) ) {
599            // Parse mediawiki messages with correct target language
600            [ /* $unused */, $lang ] = $services->getMessageCache()->figureMessage( $title->getText() );
601            $pageLang = $services->getLanguageFactory()->getLanguage( $lang );
602        }
603
604        // Unused, T299369
605        $userLang = null;
606        $this->getHookRunner()->onPageContentLanguage( $title, $pageLang, $userLang );
607
608        if ( !$pageLang instanceof Language ) {
609            throw new UnexpectedValueException( 'onPageContentLanguage() hook provided an invalid $pageLang object.' );
610        }
611
612        return $pageLang;
613    }
614
615    /**
616     * Get the language in which the content of this page is written when
617     * viewed by user. Defaults to $this->getPageLanguage(), but if the user
618     * specified a preferred variant, the variant will be used.
619     *
620     * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
621     * the user specified a preferred variant.
622     *
623     * Note that the pages view language is not cacheable, since it depends on user settings.
624     *
625     * Also note that the page language may or may not depend on the actual content of the page,
626     * that is, this method may load the content in order to determine the language.
627     *
628     * @stable to override
629     * @deprecated since 1.42 Use ParserOutput::getLanguage instead. See also OutputPage::getContLangForJS.
630     * @since 1.21
631     * @param Title $title The page to determine the language for.
632     * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
633     * @return Language The page's language for viewing
634     */
635    public function getPageViewLanguage( Title $title, ?Content $content = null ) {
636        $pageLang = $this->getPageLanguage( $title, $content );
637
638        if ( $title->getNamespace() !== NS_MEDIAWIKI ) {
639            // If the user chooses a variant, the content is actually
640            // in a language whose code is the variant code.
641            $variant = $this->getLanguageConverter( $pageLang )->getPreferredVariant();
642            if ( $pageLang->getCode() !== $variant ) {
643                $pageLang = MediaWikiServices::getInstance()->getLanguageFactory()
644                    ->getLanguage( $variant );
645            }
646        }
647
648        return $pageLang;
649    }
650
651    /**
652     * Determines whether the content type handled by this ContentHandler
653     * can be used for the main slot of the given page.
654     *
655     * This default implementation always returns true.
656     * Subclasses may override this to restrict the use of this content model to specific locations,
657     * typically based on the namespace or some other aspect of the title, such as a special suffix
658     * (e.g. ".svg" for SVG content).
659     *
660     * @note this calls the ContentHandlerCanBeUsedOn hook which may be used to override which
661     * content model can be used where.
662     *
663     * @stable to override
664     *
665     * @see SlotRoleHandler::isAllowedModel
666     *
667     * @param Title $title The page's title.
668     *
669     * @return bool True if content of this kind can be used on the given page, false otherwise.
670     */
671    public function canBeUsedOn( Title $title ) {
672        $ok = true;
673
674        $this->getHookRunner()->onContentModelCanBeUsedOn( $this->getModelID(), $title, $ok );
675
676        return $ok;
677    }
678
679    /**
680     * Returns the name of the diff engine to use.
681     *
682     * @stable to override
683     * @since 1.21
684     *
685     * @return class-string<DifferenceEngine>
686     */
687    protected function getDiffEngineClass() {
688        return DifferenceEngine::class;
689    }
690
691    /**
692     * Attempts to merge differences between three versions. Returns a new
693     * Content object for a clean merge and false for failure or a conflict.
694     *
695     * This default implementation always returns false.
696     *
697     * @stable to override
698     * @since 1.21
699     *
700     * @param Content $oldContent The page's previous content.
701     * @param Content $myContent One of the page's conflicting contents.
702     * @param Content $yourContent One of the page's conflicting contents.
703     *
704     * @return Content|false Always false.
705     */
706    public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
707        return false;
708    }
709
710    /**
711     * Shorthand for getting a Language Converter for specific language
712     * @param Language $language Language of converter
713     * @return ILanguageConverter
714     */
715    private function getLanguageConverter( $language ): ILanguageConverter {
716        return MediaWikiServices::getInstance()->getLanguageConverterFactory()
717            ->getLanguageConverter( $language );
718    }
719
720    /**
721     * Return type of change if one exists for the given edit.
722     *
723     * @stable to override
724     * @since 1.31
725     *
726     * @param Content|null $oldContent The previous text of the page.
727     * @param Content|null $newContent The submitted text of the page.
728     * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
729     *
730     * @return string|null String key representing type of change, or null.
731     */
732    private function getChangeType(
733        ?Content $oldContent = null,
734        ?Content $newContent = null,
735        $flags = 0
736    ) {
737        $oldTarget = $oldContent !== null ? $oldContent->getRedirectTarget() : null;
738        $newTarget = $newContent !== null ? $newContent->getRedirectTarget() : null;
739
740        // We check for the type of change in the given edit, and return string key accordingly
741
742        // Blanking of a page
743        if ( $oldContent && $oldContent->getSize() > 0 &&
744            $newContent && $newContent->getSize() === 0
745        ) {
746            return 'blank';
747        }
748
749        // Redirects
750        if ( $newTarget ) {
751            if ( !$oldTarget ) {
752                // New redirect page (by creating new page or by changing content page)
753                return 'new-redirect';
754            } elseif ( !$newTarget->equals( $oldTarget ) ||
755                $oldTarget->getFragment() !== $newTarget->getFragment()
756            ) {
757                // Redirect target changed
758                return 'changed-redirect-target';
759            }
760        } elseif ( $oldTarget ) {
761            // Changing an existing redirect into a non-redirect
762            return 'removed-redirect';
763        }
764
765        // New page created
766        if ( $flags & EDIT_NEW && $newContent ) {
767            if ( $newContent->getSize() === 0 ) {
768                // New blank page
769                return 'newblank';
770            } else {
771                return 'newpage';
772            }
773        }
774
775        // Removing more than 90% of the page
776        if ( $oldContent && $newContent && $oldContent->getSize() > 10 * $newContent->getSize() ) {
777            return 'replace';
778        }
779
780        // Content model changed
781        if ( $oldContent && $newContent && $oldContent->getModel() !== $newContent->getModel() ) {
782            return 'contentmodelchange';
783        }
784
785        return null;
786    }
787
788    /**
789     * Return an applicable auto-summary if one exists for the given edit.
790     *
791     * @stable to override
792     * @since 1.21
793     *
794     * @param Content|null $oldContent The previous text of the page.
795     * @param Content|null $newContent The submitted text of the page.
796     * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
797     *
798     * @return string An appropriate auto-summary, or an empty string.
799     */
800    public function getAutosummary(
801        ?Content $oldContent = null,
802        ?Content $newContent = null,
803        $flags = 0
804    ) {
805        $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
806
807        // There's no applicable auto-summary for our case, so our auto-summary is empty.
808        if ( !$changeType ) {
809            return '';
810        }
811
812        // Set the maximum auto-summary length to the general maximum summary length
813        // T221617
814        $summaryLimit = CommentStore::COMMENT_CHARACTER_LIMIT;
815
816        // Decide what kind of auto-summary is needed.
817        switch ( $changeType ) {
818            case 'new-redirect':
819                $newTarget = $newContent->getRedirectTarget();
820                $truncatedtext = $newContent->getTextForSummary(
821                    $summaryLimit
822                    - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
823                    - strlen( $newTarget->getFullText() )
824                );
825
826                return wfMessage( 'autoredircomment', $newTarget->getFullText() )
827                    ->plaintextParams( $truncatedtext )->inContentLanguage()->text();
828            case 'changed-redirect-target':
829                $oldTarget = $oldContent->getRedirectTarget();
830                $newTarget = $newContent->getRedirectTarget();
831
832                $truncatedtext = $newContent->getTextForSummary(
833                    $summaryLimit
834                    - strlen( wfMessage( 'autosumm-changed-redirect-target' )
835                        ->inContentLanguage()->text() )
836                    - strlen( $oldTarget->getFullText() )
837                    - strlen( $newTarget->getFullText() )
838                );
839
840                return wfMessage( 'autosumm-changed-redirect-target',
841                        $oldTarget->getFullText(),
842                        $newTarget->getFullText() )
843                    ->rawParams( $truncatedtext )->inContentLanguage()->text();
844            case 'removed-redirect':
845                $oldTarget = $oldContent->getRedirectTarget();
846                $truncatedtext = $newContent->getTextForSummary(
847                    $summaryLimit
848                    - strlen( wfMessage( 'autosumm-removed-redirect' )
849                        ->inContentLanguage()->text() )
850                    - strlen( $oldTarget->getFullText() ) );
851
852                return wfMessage( 'autosumm-removed-redirect', $oldTarget->getFullText() )
853                    ->rawParams( $truncatedtext )->inContentLanguage()->text();
854            case 'newpage':
855                // If they're making a new article, give its text, truncated, in the summary.
856                $truncatedtext = $newContent->getTextForSummary(
857                    $summaryLimit - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
858
859                return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
860                    ->inContentLanguage()->text();
861            case 'blank':
862                return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
863            case 'replace':
864                $truncatedtext = $newContent->getTextForSummary(
865                    $summaryLimit - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
866
867                return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
868                    ->inContentLanguage()->text();
869            case 'newblank':
870                return wfMessage( 'autosumm-newblank' )->inContentLanguage()->text();
871            default:
872                return '';
873        }
874    }
875
876    /**
877     * Return an applicable tag if one exists for the given edit or return null.
878     *
879     * @stable to override
880     * @since 1.31
881     *
882     * @param Content|null $oldContent The previous text of the page.
883     * @param Content|null $newContent The submitted text of the page.
884     * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
885     *
886     * @return string|null An appropriate tag, or null.
887     */
888    public function getChangeTag(
889        ?Content $oldContent = null,
890        ?Content $newContent = null,
891        $flags = 0
892    ) {
893        $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
894
895        // There's no applicable tag for this change.
896        if ( !$changeType ) {
897            return null;
898        }
899
900        // Core tags use the same keys as ones returned from $this->getChangeType()
901        // but prefixed with pseudo namespace 'mw-', so we add the prefix before checking
902        // if this type of change should be tagged. List of tags for grep:
903        // mw-blank, mw-new-redirect, mw-changed-redirect-target, mw-removed-redirect,
904        // mw-replace, mw-contentmodelchange
905        $tag = 'mw-' . $changeType;
906
907        // Not all change types are tagged, so we check against the list of defined tags.
908        if ( in_array( $tag, MediaWikiServices::getInstance()->getChangeTagsStore()->getSoftwareTags() ) ) {
909            return $tag;
910        }
911
912        return null;
913    }
914
915    /**
916     * Auto-generates a deletion reason
917     *
918     * @stable to override
919     * @since 1.21
920     *
921     * @param Title $title The page's title
922     *
923     * @return string|false String containing deletion reason or empty string, or
924     *    boolean false if no revision occurred
925     */
926    public function getAutoDeleteReason( Title $title ) {
927        $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
928        $revStore = MediaWikiServices::getInstance()->getRevisionStore();
929
930        // Get the last revision
931        $revRecord = $revStore->getRevisionByTitle( $title );
932
933        if ( $revRecord === null ) {
934            return false;
935        }
936
937        // Get the article's contents
938        $content = $revRecord->getContent( SlotRecord::MAIN );
939        $blank = false;
940
941        // If the page is blank, use the text from the previous revision,
942        if ( !$content || $content->isEmpty() ) {
943            $prev = $revStore->getPreviousRevision( $revRecord );
944
945            if ( $prev ) {
946                $prevContent = $prev->getContent( SlotRecord::MAIN );
947                if ( $prevContent && !$prevContent->isEmpty() ) {
948                    $revRecord = $prev;
949                    $content = $prevContent;
950                    $blank = true;
951                }
952                // Else since the previous revision is also blank or revdelled
953                // (the blank case only happen due to a move/import/protect dummy revision)
954                // skip the "before blanking" logic and fall back to just `content was ""`
955            }
956        }
957
958        $this->checkModelID( $revRecord->getSlot( SlotRecord::MAIN )->getModel() );
959
960        // Find out if there was only one contributor
961        // Only scan the last 20 revisions
962        $queryBuilder = $revStore->newSelectQueryBuilder( $dbr )
963            ->where( [
964                'rev_page' => $title->getArticleID(),
965                $dbr->bitAnd( 'rev_deleted', RevisionRecord::DELETED_USER ) . ' = 0'
966            ] )
967            ->limit( 20 );
968        $res = $queryBuilder->caller( __METHOD__ )->fetchResultSet();
969
970        if ( !$res->numRows() ) {
971            // This page has no revisions, which is very weird
972            return false;
973        }
974
975        $row = $res->fetchObject();
976
977        if ( $row ) { // $row is false if the only contributor is hidden
978            $onlyAuthor = $row->rev_user_text;
979            // Try to find a second contributor
980            foreach ( $res as $row ) {
981                if ( $row->rev_user_text != $onlyAuthor ) { // T24999
982                    $onlyAuthor = false;
983                    break;
984                }
985            }
986        } else {
987            $onlyAuthor = false;
988        }
989
990        // Generate the summary with a '$1' placeholder
991        if ( $blank ) {
992            $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
993        } else {
994            if ( $onlyAuthor ) {
995                $reason = wfMessage(
996                    'excontentauthor',
997                    '$1',
998                    $onlyAuthor
999                )->inContentLanguage()->text();
1000            } else {
1001                $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
1002            }
1003        }
1004
1005        if ( $reason == '-' ) {
1006            // Allow these UI messages to be blanked out cleanly
1007            return '';
1008        }
1009
1010        // Max content length = max comment length - length of the comment (excl. $1)
1011        $maxLength = CommentStore::COMMENT_CHARACTER_LIMIT - ( strlen( $reason ) - 2 );
1012        $text = $content ? $content->getTextForSummary( $maxLength ) : '';
1013        if ( $blank && !$text ) {
1014            // Don't display "content before blanking was ''" as misleading
1015            // This can happen if the content before blanking was two unclosed square brackets, for example
1016            // Do display `content was ""` if the page was always blank, though
1017            return false;
1018        }
1019
1020        // Now replace the '$1' placeholder
1021        $reason = str_replace( '$1', $text, $reason );
1022
1023        return $reason;
1024    }
1025
1026    /**
1027     * Get the Content object that needs to be saved in order to undo all changes
1028     * between $undo and $undoafter.
1029     *
1030     * @stable to override
1031     * @since 1.21
1032     * @since 1.32 accepts Content objects for all parameters instead of Revision objects.
1033     *  Passing Revision objects is deprecated.
1034     * @since 1.37 only accepts Content objects
1035     *
1036     * @param Content $currentContent The current text
1037     * @param Content $undoContent The content of the revision to undo
1038     * @param Content $undoAfterContent Must be from an earlier revision than $undo
1039     * @param bool $undoIsLatest Set true if $undo is from the latest revision (since 1.32)
1040     *
1041     * @return Content|false Content on success, false on failure
1042     */
1043    public function getUndoContent(
1044        Content $currentContent,
1045        Content $undoContent,
1046        Content $undoAfterContent,
1047        $undoIsLatest = false
1048    ) {
1049        try {
1050            $this->checkModelID( $currentContent->getModel() );
1051            $this->checkModelID( $undoContent->getModel() );
1052            if ( !$undoIsLatest ) {
1053                // If we are undoing the most recent revision,
1054                // its ok to revert content model changes. However
1055                // if we are undoing a revision in the middle, then
1056                // doing that will be confusing.
1057                $this->checkModelID( $undoAfterContent->getModel() );
1058            }
1059        } catch ( UnexpectedContentModelException ) {
1060            // If the revisions have different content models
1061            // just return false
1062            return false;
1063        }
1064
1065        if ( $currentContent->equals( $undoContent ) ) {
1066            // No use doing a merge if it's just a straight revert.
1067            return $undoAfterContent;
1068        }
1069
1070        $undone_content = $this->merge3( $undoContent, $undoAfterContent, $currentContent );
1071
1072        return $undone_content;
1073    }
1074
1075    /**
1076     * Returns true for content models that support caching using the
1077     * ParserCache mechanism. See WikiPage::shouldCheckParserCache().
1078     *
1079     * @stable to override
1080     * @since 1.21
1081     *
1082     * @return bool Always false.
1083     */
1084    public function isParserCacheSupported() {
1085        return false;
1086    }
1087
1088    /**
1089     * Returns true if this content model supports sections.
1090     * This default implementation returns false.
1091     *
1092     * Content models that return true here should also implement
1093     * Content::getSection, Content::replaceSection, etc. to handle sections.
1094     *
1095     * @stable to override
1096     *
1097     * @return bool Always false.
1098     */
1099    public function supportsSections() {
1100        return false;
1101    }
1102
1103    /**
1104     * Returns true if this content model supports categories.
1105     * The default implementation returns true.
1106     *
1107     * @stable to override
1108     *
1109     * @return bool Always true.
1110     */
1111    public function supportsCategories() {
1112        return true;
1113    }
1114
1115    /**
1116     * Returns true if this content model supports redirects.
1117     * This default implementation returns false.
1118     *
1119     * Content models that return true here should also implement
1120     * ContentHandler::makeRedirectContent to return a Content object.
1121     *
1122     * @stable to override
1123     *
1124     * @return bool Always false.
1125     */
1126    public function supportsRedirects() {
1127        return false;
1128    }
1129
1130    /**
1131     * Return true if this content model supports direct editing, such as via EditPage.
1132     * This should return true for TextContent and its derivatives, and return false
1133     * for structured data content.
1134     *
1135     * @stable to override
1136     *
1137     * @return bool Default is false.
1138     */
1139    public function supportsDirectEditing() {
1140        return false;
1141    }
1142
1143    /**
1144     * If a non-existing page can be created with the contents from another (arbitrary) page being
1145     * preloaded in the editor, see {@see EditPage::getContentObject}. Only makes sense together
1146     * with {@see supportsDirectEditing}.
1147     *
1148     * @stable to override
1149     * @since 1.39
1150     *
1151     * @return bool
1152     */
1153    public function supportsPreloadContent(): bool {
1154        return false;
1155    }
1156
1157    /**
1158     * Whether an edit on the content should trigger an HTML render and ParserCache entry.
1159     *
1160     * @stable to override
1161     * @since 1.37
1162     *
1163     * @return bool true if edit should trigger an HTML render false otherwise
1164     */
1165    public function generateHTMLOnEdit(): bool {
1166        return true;
1167    }
1168
1169    /**
1170     * Whether or not this content model supports direct editing via ApiEditPage
1171     *
1172     * @stable to override
1173     *
1174     * @return bool Default is false, and true for TextContent and derivatives.
1175     */
1176    public function supportsDirectApiEditing() {
1177        return $this->supportsDirectEditing();
1178    }
1179
1180    /**
1181     * Get fields definition for search index
1182     *
1183     * @todo Expose title, redirect, namespace, text, source_text, text_bytes
1184     *       field mappings here. (see T142670 and T143409)
1185     *
1186     * @stable to override
1187     *
1188     * @param SearchEngine $engine
1189     * @return SearchIndexField[] List of fields this content handler can provide.
1190     * @since 1.28
1191     */
1192    public function getFieldsForSearchIndex( SearchEngine $engine ) {
1193        $fields = [];
1194        $fields['category'] = $engine->makeSearchFieldMapping(
1195            'category',
1196            SearchIndexField::INDEX_TYPE_TEXT
1197        );
1198        $fields['category']->setFlag( SearchIndexField::FLAG_CASEFOLD );
1199
1200        $fields['external_link'] = $engine->makeSearchFieldMapping(
1201            'external_link',
1202            SearchIndexField::INDEX_TYPE_KEYWORD
1203        );
1204
1205        $fields['outgoing_link'] = $engine->makeSearchFieldMapping(
1206            'outgoing_link',
1207            SearchIndexField::INDEX_TYPE_KEYWORD
1208        );
1209
1210        $fields['template'] = $engine->makeSearchFieldMapping(
1211            'template',
1212            SearchIndexField::INDEX_TYPE_KEYWORD
1213        );
1214        $fields['template']->setFlag( SearchIndexField::FLAG_CASEFOLD );
1215
1216        $fields['content_model'] = $engine->makeSearchFieldMapping(
1217            'content_model',
1218            SearchIndexField::INDEX_TYPE_KEYWORD
1219        );
1220
1221        return $fields;
1222    }
1223
1224    /**
1225     * Add new field definition to array.
1226     * @param SearchIndexField[] &$fields
1227     * @param SearchEngine $engine
1228     * @param string $name
1229     * @param string $type
1230     * @return SearchIndexField[] new field defs
1231     * @since 1.28
1232     */
1233    protected function addSearchField( &$fields, SearchEngine $engine, $name, $type ) {
1234        $fields[$name] = $engine->makeSearchFieldMapping( $name, $type );
1235        return $fields;
1236    }
1237
1238    /**
1239     * Return fields to be indexed by search engine
1240     * as representation of this document.
1241     * Overriding class should call parent function or take care of calling
1242     * the SearchDataForIndex hook.
1243     *
1244     * The $output must be the result of a call to {@link getParserOutputForIndexing()}
1245     * on the same content handler. That method may return ParserOutput
1246     * {@link ParserOutput::hasText() without HTML}; this base implementation
1247     * does not rely on the HTML being present, so it is safe to call
1248     * even by subclasses that override {@link getParserOutputForIndexing()}
1249     * to skip HTML generation. On the other hand,
1250     * since the default implementation of {@link getParserOutputForIndexing()}
1251     * does generate HTML, subclasses are free to rely on the HTML here
1252     * if they do not override {@link getParserOutputForIndexing()}.
1253     *
1254     * @stable to override
1255     * @param WikiPage $page Page to index
1256     * @param ParserOutput $output
1257     * @param SearchEngine $engine Search engine for which we are indexing
1258     * @param RevisionRecord|null $revision Revision content to fetch if provided or use the latest revision
1259     *                                      from WikiPage::getRevisionRecord() if not
1260     * @return array Map of name=>value for fields, an empty array is returned if the latest
1261     *               revision cannot be retrieved.
1262     * @since 1.28
1263     */
1264    public function getDataForSearchIndex(
1265        WikiPage $page,
1266        ParserOutput $output,
1267        SearchEngine $engine,
1268        ?RevisionRecord $revision = null
1269    ) {
1270        $revision ??= $page->getRevisionRecord();
1271        if ( $revision === null ) {
1272            LoggerFactory::getInstance( 'search' )->warning(
1273                "Called getDataForSearchIndex on the page {page_id} for which the " .
1274                "latest revision cannot be loaded.",
1275                [ "page_id" => $page->getId() ]
1276            );
1277            return [];
1278        }
1279        Assert::invariant( $revision->getPageId() === $page->getId(),
1280            '$revision and $page must target the same page_id' );
1281
1282        $fieldData = [];
1283        $content = $revision->getContent( SlotRecord::MAIN );
1284
1285        if ( $content ) {
1286            $searchDataExtractor = new ParserOutputSearchDataExtractor();
1287
1288            $fieldData['category'] = $searchDataExtractor->getCategories( $output );
1289            $fieldData['external_link'] = $searchDataExtractor->getExternalLinks( $output );
1290            $fieldData['outgoing_link'] = $searchDataExtractor->getOutgoingLinks( $output );
1291            $fieldData['template'] = $searchDataExtractor->getTemplates( $output );
1292
1293            $text = $content->getTextForSearchIndex();
1294
1295            $fieldData['text'] = $text;
1296            $fieldData['source_text'] = $text;
1297            $fieldData['text_bytes'] = $content->getSize();
1298            $fieldData['content_model'] = $content->getModel();
1299        }
1300
1301        $this->getHookRunner()->onSearchDataForIndex( $fieldData, $this, $page, $output, $engine );
1302        $this->getHookRunner()->onSearchDataForIndex2( $fieldData, $this, $page, $output, $engine, $revision );
1303
1304        return $fieldData;
1305    }
1306
1307    /**
1308     * Produce page output suitable for indexing.
1309     * Typically used with {@link getDataForSearchIndex()}.
1310     *
1311     * Specific content handlers may override it if they need different content handling.
1312     *
1313     * The default implementation returns output {@link ParserOutput::hasText() with HTML},
1314     * but callers should not rely on this, and subclasses may override this method
1315     * and skip HTML generation if it is not needed for indexing.
1316     * (In that case, they should not attempt to store the output in the $cache.)
1317     *
1318     * @stable to override
1319     *
1320     * @param WikiPage $page
1321     * @param ParserCache|null $cache deprecated since 1.38 and won't have any effect
1322     * @param RevisionRecord|null $revision
1323     * @return ParserOutput|null null when the ParserOutput cannot be obtained
1324     * @see ParserOutputAccess::getParserOutput() for failure modes
1325     */
1326    public function getParserOutputForIndexing(
1327        WikiPage $page,
1328        ?ParserCache $cache = null,
1329        ?RevisionRecord $revision = null
1330    ) {
1331        // TODO: MCR: ContentHandler should be called per slot, not for the whole page.
1332        // See T190066.
1333        $parserOptions = $page->makeParserOptions( 'canonical' );
1334        $parserOptions->setRenderReason( 'ParserOutputForIndexing' );
1335        $parserOutputAccess = MediaWikiServices::getInstance()->getParserOutputAccess();
1336        return $parserOutputAccess->getParserOutput(
1337            $page,
1338            $parserOptions,
1339            $revision,
1340            [ ParserOutputAccess::OPT_NO_UPDATE_CACHE => true ],
1341        )->getValue();
1342    }
1343
1344    /**
1345     * Get the latest revision of the given $page,
1346     * fetching it from the primary if necessary.
1347     *
1348     * @param WikiPage $page
1349     * @return RevisionRecord
1350     * @since 1.36 (previously private)
1351     */
1352    protected function latestRevision( WikiPage $page ): RevisionRecord {
1353        $revRecord = $page->getRevisionRecord();
1354        if ( $revRecord == null ) {
1355            // If the content represents a brand new page it's possible
1356            // we need to fetch it from the primary.
1357            $page->loadPageData( IDBAccessObject::READ_LATEST );
1358            $revRecord = $page->getRevisionRecord();
1359            if ( $revRecord == null ) {
1360                $text = $page->getTitle()->getPrefixedText();
1361                throw new RuntimeException(
1362                    "No revision could be loaded for page: $text" );
1363            }
1364        }
1365
1366        return $revRecord;
1367    }
1368
1369    /**
1370     * Returns a list of DeferrableUpdate objects for recording information about the
1371     * given Content in some secondary data store.
1372     *
1373     * Application logic should not call this method directly. Instead, it should call
1374     * DerivedPageDataUpdater::getSecondaryDataUpdates().
1375     *
1376     * @note Implementations must not return a LinksUpdate instance. Instead, a LinksUpdate
1377     * is created by the calling code in DerivedPageDataUpdater, on the combined ParserOutput
1378     * of all slots, not for each slot individually. This is in contrast to the old
1379     * getSecondaryDataUpdates method defined by AbstractContent, which returned a LinksUpdate.
1380     *
1381     * @note Implementations should not call $content->getParserOutput, they should call
1382     * $slotOutput->getSlotRendering( $role, false ) instead if they need to access a ParserOutput
1383     * of $content. This allows existing ParserOutput objects to be re-used, while avoiding
1384     * creating a ParserOutput when none is needed.
1385     *
1386     * @stable to override
1387     *
1388     * @param Title $title The title of the page to supply the updates for
1389     * @param Content $content The content to generate data updates for.
1390     * @param string $role The role (slot) in which the content is being used. Which updates
1391     *        are performed should generally not depend on the role the content has, but the
1392     *        DeferrableUpdates themselves may need to know the role, to track to which slot the
1393     *        data refers, and to avoid overwriting data of the same kind from another slot.
1394     * @param SlotRenderingProvider $slotOutput A provider that can be used to gain access to
1395     *        a ParserOutput of $content by calling $slotOutput->getSlotParserOutput( $role, false ).
1396     * @return DeferrableUpdate[] A list of DeferrableUpdate objects for putting information
1397     *        about this content object somewhere. The default implementation returns an empty
1398     *        array.
1399     * @since 1.32
1400     */
1401    public function getSecondaryDataUpdates(
1402        Title $title,
1403        Content $content,
1404        $role,
1405        SlotRenderingProvider $slotOutput
1406    ) {
1407        return [];
1408    }
1409
1410    /**
1411     * Returns a list of DeferrableUpdate objects for removing information about content
1412     * in some secondary data store. This is used when a page is deleted, and also when
1413     * a slot is removed from a page.
1414     *
1415     * Application logic should not call this method directly. Instead, it should call
1416     * WikiPage::getSecondaryDataUpdates().
1417     *
1418     * @note Implementations must not return a LinksDeletionUpdate instance. Instead, a
1419     * LinksDeletionUpdate is created by the calling code in WikiPage.
1420     * This is in contrast to the old getDeletionUpdates method defined by AbstractContent,
1421     * which returned a LinksUpdate.
1422     *
1423     * @note Implementations should not rely on the page's current content, but rather the current
1424     * state of the secondary data store.
1425     *
1426     * @stable to override
1427     *
1428     * @param Title $title The title of the page to supply the updates for
1429     * @param string $role The role (slot) in which the content is being used. Which updates
1430     *        are performed should generally not depend on the role the content has, but the
1431     *        DeferrableUpdates themselves may need to know the role, to track to which slot the
1432     *        data refers, and to avoid overwriting data of the same kind from another slot.
1433     *
1434     * @return DeferrableUpdate[] A list of DeferrableUpdate objects for putting information
1435     *        about this content object somewhere. The default implementation returns an empty
1436     *        array.
1437     *
1438     * @since 1.32
1439     */
1440    public function getDeletionUpdates( Title $title, $role ) {
1441        return [];
1442    }
1443
1444    /**
1445     * Returns a $content object with pre-save transformations applied (or the same
1446     * object if no transformations apply).
1447     *
1448     * @note Not stable to call other then from ContentHandler hierarchy.
1449     * Callers need to use ContentTransformer::preSaveTransform.
1450     * @stable to override
1451     * @since 1.37
1452     *
1453     * @param Content $content
1454     * @param PreSaveTransformParams $pstParams
1455     *
1456     * @return Content
1457     */
1458    public function preSaveTransform(
1459        Content $content,
1460        PreSaveTransformParams $pstParams
1461    ): Content {
1462        return $content;
1463    }
1464
1465    /**
1466     * Returns a $content object with preload transformations applied (or the same
1467     * object if no transformations apply).
1468     *
1469     * @note Not stable to call other then from ContentHandler hierarchy.
1470     * Callers need to use ContentTransformer::preLoadTransform.
1471     * @stable to override
1472     * @since 1.37
1473     *
1474     * @param Content $content
1475     * @param PreloadTransformParams $pltParams
1476     *
1477     * @return Content
1478     */
1479    public function preloadTransform(
1480        Content $content,
1481        PreloadTransformParams $pltParams
1482    ): Content {
1483        return $content;
1484    }
1485
1486    /**
1487     * Validate content for saving it.
1488     *
1489     * This may be used to check the content's consistency with global state. This function should
1490     * NOT write any information to the database.
1491     *
1492     * Note that this method will usually be called inside the same transaction
1493     * bracket that will be used to save the new revision, so the revision passed
1494     * in is probably unsaved (has no id) and might belong to unsaved page.
1495     *
1496     * @since 1.38
1497     * @stable to override
1498     *
1499     * @param Content $content
1500     * @param ValidationParams $validationParams
1501     *
1502     * @return StatusValue A status object indicating if content can be saved in the given revision.
1503     */
1504    public function validateSave(
1505        Content $content,
1506        ValidationParams $validationParams
1507    ) {
1508        if ( $content->isValid() ) {
1509            return StatusValue::newGood();
1510        } else {
1511            return StatusValue::newFatal( "invalid-content-data" );
1512        }
1513    }
1514
1515    /**
1516     * Returns a ParserOutput object containing information derived from this content.
1517     * Most importantly, unless $cpoParams->getGenerateHtml was false, the return value contains an
1518     * HTML representation of the content.
1519     *
1520     * Subclasses that want to control the parser output may override
1521     * fillParserOutput() instead.
1522     *
1523     *
1524     *
1525     * @since 1.38
1526     *
1527     * @param Content $content
1528     * @param ContentParseParams $cpoParams
1529     * @return ParserOutput Containing information derived from this content.
1530     */
1531    public function getParserOutput(
1532        Content $content,
1533        ContentParseParams $cpoParams
1534    ) {
1535        $services = MediaWikiServices::getInstance();
1536        $title = $services->getTitleFactory()->newFromPageReference( $cpoParams->getPage() );
1537        $parserOptions = $cpoParams->getParserOptions();
1538
1539        if ( $parserOptions->getIsPreview() ) {
1540            $scopedCallback = $parserOptions->setupFakeRevision(
1541                $title,
1542                $content,
1543                $parserOptions->getUserIdentity(),
1544                $cpoParams->getRevId() ?: 0
1545            );
1546        }
1547
1548        $hookRunner = new HookRunner( $services->getHookContainer() );
1549
1550        $po = new ParserOutput();
1551
1552        // Initialize to the page language
1553        $po->setLanguage( $title->getPageLanguage() );
1554
1555        // Necessary use of a reference, because the fillParserOutput() call below also uses
1556        // pass-by-reference and may reassign $po (5c9322ae06384a8845962ba7e3c499731110e7f0).
1557        $parserOptions->registerWatcher( [ &$po, 'recordOption' ] );
1558        if ( $hookRunner->onContentGetParserOutput(
1559            // FIXME $cpoParams->getRevId() may be null here?
1560            // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
1561            $content, $title, $cpoParams->getRevId(), $parserOptions, $cpoParams->getGenerateHtml(), $po )
1562        ) {
1563            // Save and restore the old value, just in case something is reusing
1564            // the ParserOptions object in some weird way.
1565            $oldRedir = $parserOptions->getRedirectTarget();
1566            $parserOptions->setRedirectTarget( $content->getRedirectTarget() );
1567
1568            $po->resetParseStartTime();
1569            $this->fillParserOutput(
1570                $content,
1571                $cpoParams,
1572                $po
1573            );
1574            $po->recordTimeProfile();
1575
1576            MediaWikiServices::getInstance()->get( '_ParserObserver' )->notifyParse(
1577                $title,
1578                $cpoParams->getRevId(),
1579                $parserOptions,
1580                $content,
1581                $po
1582            );
1583            $parserOptions->setRedirectTarget( $oldRedir );
1584        }
1585
1586        $hookRunner->onContentAlterParserOutput( $content, $title, $po );
1587        $parserOptions->registerWatcher( null );
1588        if ( isset( $scopedCallback ) ) {
1589            ScopedCallback::consume( $scopedCallback );
1590        }
1591
1592        return $po;
1593    }
1594
1595    /**
1596     * A temporary layer to move AbstractContent::fillParserOutput to ContentHandler::fillParserOutput
1597     *
1598     * @internal only core AbstractContent::fillParserOutput implementations need to call this.
1599     * @since 1.38
1600     * @param Content $content
1601     * @param ContentParseParams $cpoParams
1602     * @param ParserOutput &$output The output object to fill (reference).
1603     */
1604    public function fillParserOutputInternal(
1605        Content $content,
1606        ContentParseParams $cpoParams,
1607        ParserOutput &$output
1608    ) {
1609        $this->fillParserOutput( $content, $cpoParams, $output );
1610    }
1611
1612    /**
1613     * Fills the provided ParserOutput with information derived from the content.
1614     * Unless $cpoParams->getGenerateHtml() was false,
1615     * this includes an HTML representation of the content.
1616     *
1617     * If $cpoParams->getGenerateHtml() is false, and you chose not to generate
1618     * html, the ParserOutput must have a text of null. If the
1619     * text of the ParserOutput object is anything other than null (even if ''),
1620     * it is assumed that you don't support not generating html, and that it is
1621     * safe to reuse the parser output for calls expecting that html was generated.
1622     *
1623     * Subclasses are expected to override this method.
1624     *
1625     * This placeholder implementation always throws an exception.
1626     *
1627     * @stable to override
1628     *
1629     * @since 1.38
1630     * @param Content $content
1631     * @param ContentParseParams $cpoParams
1632     * @param ParserOutput &$output The output object to fill (reference).
1633     * Most implementations should modify the output object passed in here;
1634     * if you choose to replace it with a fresh object instead,
1635     * make sure you call {@link ParserOutput::resetParseStartTime()} on it.
1636     */
1637    protected function fillParserOutput(
1638        Content $content,
1639        ContentParseParams $cpoParams,
1640        ParserOutput &$output
1641    ) {
1642        // Subclasses must override fillParserOutput() to directly don't fail.
1643        throw new LogicException( 'Subclasses of ContentHandler must override fillParserOutput!' );
1644    }
1645
1646}
1647
1648/** @deprecated class alias since 1.43 */
1649class_alias( ContentHandler::class, 'ContentHandler' );