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