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