3 * Base class for content handling.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @author Daniel Kinzler
28 use Wikimedia\Assert\Assert
;
29 use MediaWiki\Logger\LoggerFactory
;
30 use MediaWiki\MediaWikiServices
;
31 use MediaWiki\Revision\SlotRenderingProvider
;
32 use MediaWiki\Search\ParserOutputSearchDataExtractor
;
35 * A content handler knows how do deal with a specific type of content on a wiki
36 * page. Content is stored in the database in a serialized form (using a
37 * serialization format a.k.a. MIME type) and is unserialized into its native
38 * PHP representation (the content model), which is wrapped in an instance of
39 * the appropriate subclass of Content.
41 * ContentHandler instances are stateless singletons that serve, among other
42 * things, as a factory for Content objects. Generally, there is one subclass
43 * of ContentHandler and one subclass of Content for every type of content model.
45 * Some content types have a flat model, that is, their native representation
46 * is the same as their serialized form. Examples would be JavaScript and CSS
47 * code. As of now, this also applies to wikitext (MediaWiki's default content
48 * type), but wikitext content may be represented by a DOM or AST structure in
53 abstract class ContentHandler
{
55 * Convenience function for getting flat text from a Content object. This
56 * should only be used in the context of backwards compatibility with code
57 * that is not yet able to handle Content objects!
59 * If $content is null, this method returns the empty string.
61 * If $content is an instance of TextContent, this method returns the flat
62 * text as returned by $content->getNativeData().
64 * If $content is not a TextContent object, the behavior of this method
65 * depends on the global $wgContentHandlerTextFallback:
66 * - If $wgContentHandlerTextFallback is 'fail' and $content is not a
67 * TextContent object, an MWException is thrown.
68 * - If $wgContentHandlerTextFallback is 'serialize' and $content is not a
69 * TextContent object, $content->serialize() is called to get a string
70 * form of the content.
71 * - If $wgContentHandlerTextFallback is 'ignore' and $content is not a
72 * TextContent object, this method returns null.
73 * - otherwise, the behavior is undefined.
77 * @param Content|null $content
79 * @throws MWException If the content is not an instance of TextContent and
80 * wgContentHandlerTextFallback was set to 'fail'.
81 * @return string|null Textual form of the content, if available.
83 public static function getContentText( Content
$content = null ) {
84 global $wgContentHandlerTextFallback;
86 if ( is_null( $content ) ) {
90 if ( $content instanceof TextContent
) {
91 return $content->getNativeData();
94 wfDebugLog( 'ContentHandler', 'Accessing ' . $content->getModel() . ' content as text!' );
96 if ( $wgContentHandlerTextFallback == 'fail' ) {
97 throw new MWException(
98 "Attempt to get text from Content with model " .
103 if ( $wgContentHandlerTextFallback == 'serialize' ) {
104 return $content->serialize();
111 * Convenience function for creating a Content object from a given textual
114 * $text will be deserialized into a Content object of the model specified
115 * by $modelId (or, if that is not given, $title->getContentModel()) using
120 * @param string $text The textual representation, will be
121 * unserialized to create the Content object
122 * @param Title|null $title The title of the page this text belongs to.
123 * Required if $modelId is not provided.
124 * @param string|null $modelId The model to deserialize to. If not provided,
125 * $title->getContentModel() is used.
126 * @param string|null $format The format to use for deserialization. If not
127 * given, the model's default format is used.
129 * @throws MWException If model ID or format is not supported or if the text can not be
130 * unserialized using the format.
131 * @return Content A Content object representing the text.
133 public static function makeContent( $text, Title
$title = null,
134 $modelId = null, $format = null ) {
135 if ( is_null( $modelId ) ) {
136 if ( is_null( $title ) ) {
137 throw new MWException( "Must provide a Title object or a content model ID." );
140 $modelId = $title->getContentModel();
143 $handler = self
::getForModelID( $modelId );
145 return $handler->unserializeContent( $text, $format );
149 * Returns the name of the default content model to be used for the page
150 * with the given title.
152 * Note: There should rarely be need to call this method directly.
153 * To determine the actual content model for a given page, use
154 * Title::getContentModel().
156 * Which model is to be used by default for the page is determined based
157 * on several factors:
158 * - The global setting $wgNamespaceContentModels specifies a content model
160 * - The hook ContentHandlerDefaultModelFor may be used to override the page's default
162 * - Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript
163 * model if they end in .js or .css, respectively.
164 * - Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
165 * - The hook TitleIsCssOrJsPage may be used to force a page to use the CSS
166 * or JavaScript model. This is a compatibility feature. The ContentHandlerDefaultModelFor
167 * hook should be used instead if possible.
168 * - The hook TitleIsWikitextPage may be used to force a page to use the
169 * wikitext model. This is a compatibility feature. The ContentHandlerDefaultModelFor
170 * hook should be used instead if possible.
172 * If none of the above applies, the wikitext model is used.
174 * Note: this is used by, and may thus not use, Title::getContentModel()
178 * @param Title $title
180 * @return string Default model name for the page given by $title
182 public static function getDefaultModelFor( Title
$title ) {
183 // NOTE: this method must not rely on $title->getContentModel() directly or indirectly,
184 // because it is used to initialize the mContentModel member.
186 $ns = $title->getNamespace();
190 $model = MWNamespace
::getNamespaceContentModel( $ns );
192 // Hook can determine default model
193 if ( !Hooks
::run( 'ContentHandlerDefaultModelFor', [ $title, &$model ] ) ) {
194 if ( !is_null( $model ) ) {
199 // Could this page contain code based on the title?
200 $isCodePage = NS_MEDIAWIKI
== $ns && preg_match( '!\.(css|js|json)$!u', $title->getText(), $m );
205 // Is this a user subpage containing code?
206 $isCodeSubpage = NS_USER
== $ns
208 && preg_match( "/\\/.*\\.(js|css|json)$/", $title->getText(), $m );
209 if ( $isCodeSubpage ) {
213 // Is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
214 $isWikitext = is_null( $model ) ||
$model == CONTENT_MODEL_WIKITEXT
;
215 $isWikitext = $isWikitext && !$isCodePage && !$isCodeSubpage;
217 if ( !$isWikitext ) {
220 return CONTENT_MODEL_JAVASCRIPT
;
222 return CONTENT_MODEL_CSS
;
224 return CONTENT_MODEL_JSON
;
226 return is_null( $model ) ? CONTENT_MODEL_TEXT
: $model;
230 // We established that it must be wikitext
232 return CONTENT_MODEL_WIKITEXT
;
236 * Returns the appropriate ContentHandler singleton for the given title.
240 * @param Title $title
242 * @return ContentHandler
244 public static function getForTitle( Title
$title ) {
245 $modelId = $title->getContentModel();
247 return self
::getForModelID( $modelId );
251 * Returns the appropriate ContentHandler singleton for the given Content
256 * @param Content $content
258 * @return ContentHandler
260 public static function getForContent( Content
$content ) {
261 $modelId = $content->getModel();
263 return self
::getForModelID( $modelId );
267 * @var array A Cache of ContentHandler instances by model id
269 protected static $handlers;
272 * Returns the ContentHandler singleton for the given model ID. Use the
273 * CONTENT_MODEL_XXX constants to identify the desired content model.
275 * ContentHandler singletons are taken from the global $wgContentHandlers
276 * array. Keys in that array are model names, the values are either
277 * ContentHandler singleton objects, or strings specifying the appropriate
278 * subclass of ContentHandler.
280 * If a class name is encountered when looking up the singleton for a given
281 * model name, the class is instantiated and the class name is replaced by
282 * the resulting singleton in $wgContentHandlers.
284 * If no ContentHandler is defined for the desired $modelId, the
285 * ContentHandler may be provided by the ContentHandlerForModelID hook.
286 * If no ContentHandler can be determined, an MWException is raised.
290 * @param string $modelId The ID of the content model for which to get a
291 * handler. Use CONTENT_MODEL_XXX constants.
293 * @throws MWException For internal errors and problems in the configuration.
294 * @throws MWUnknownContentModelException If no handler is known for the model ID.
295 * @return ContentHandler The ContentHandler singleton for handling the model given by the ID.
297 public static function getForModelID( $modelId ) {
298 global $wgContentHandlers;
300 if ( isset( self
::$handlers[$modelId] ) ) {
301 return self
::$handlers[$modelId];
304 if ( empty( $wgContentHandlers[$modelId] ) ) {
307 Hooks
::run( 'ContentHandlerForModelID', [ $modelId, &$handler ] );
309 if ( $handler === null ) {
310 throw new MWUnknownContentModelException( $modelId );
313 if ( !( $handler instanceof ContentHandler
) ) {
314 throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
317 $classOrCallback = $wgContentHandlers[$modelId];
319 if ( is_callable( $classOrCallback ) ) {
320 $handler = call_user_func( $classOrCallback, $modelId );
322 $handler = new $classOrCallback( $modelId );
325 if ( !( $handler instanceof ContentHandler
) ) {
326 throw new MWException( "$classOrCallback from \$wgContentHandlers is not " .
327 "compatible with ContentHandler" );
331 wfDebugLog( 'ContentHandler', 'Created handler for ' . $modelId
332 . ': ' . get_class( $handler ) );
334 self
::$handlers[$modelId] = $handler;
336 return self
::$handlers[$modelId];
340 * Clean up handlers cache.
342 public static function cleanupHandlersCache() {
343 self
::$handlers = [];
347 * Returns the localized name for a given content model.
349 * Model names are localized using system messages. Message keys
350 * have the form content-model-$name, where $name is getContentModelName( $id ).
352 * @param string $name The content model ID, as given by a CONTENT_MODEL_XXX
353 * constant or returned by Revision::getContentModel().
354 * @param Language|null $lang The language to parse the message in (since 1.26)
356 * @throws MWException If the model ID isn't known.
357 * @return string The content model's localized name.
359 public static function getLocalizedName( $name, Language
$lang = null ) {
360 // Messages: content-model-wikitext, content-model-text,
361 // content-model-javascript, content-model-css
362 $key = "content-model-$name";
364 $msg = wfMessage( $key );
366 $msg->inLanguage( $lang );
369 return $msg->exists() ?
$msg->plain() : $name;
372 public static function getContentModels() {
373 global $wgContentHandlers;
375 $models = array_keys( $wgContentHandlers );
376 Hooks
::run( 'GetContentModels', [ &$models ] );
380 public static function getAllContentFormats() {
381 global $wgContentHandlers;
385 foreach ( $wgContentHandlers as $model => $class ) {
386 $handler = self
::getForModelID( $model );
387 $formats = array_merge( $formats, $handler->getSupportedFormats() );
390 $formats = array_unique( $formats );
395 // ------------------------------------------------------------------------
405 protected $mSupportedFormats;
408 * Constructor, initializing the ContentHandler instance with its model ID
409 * and a list of supported formats. Values for the parameters are typically
410 * provided as literals by subclass's constructors.
412 * @param string $modelId (use CONTENT_MODEL_XXX constants).
413 * @param string[] $formats List for supported serialization formats
414 * (typically as MIME types)
416 public function __construct( $modelId, $formats ) {
417 $this->mModelID
= $modelId;
418 $this->mSupportedFormats
= $formats;
422 * Serializes a Content object of the type supported by this ContentHandler.
426 * @param Content $content The Content object to serialize
427 * @param string|null $format The desired serialization format
429 * @return string Serialized form of the content
431 abstract public function serializeContent( Content
$content, $format = null );
434 * Applies transformations on export (returns the blob unchanged per default).
435 * Subclasses may override this to perform transformations such as conversion
436 * of legacy formats or filtering of internal meta-data.
438 * @param string $blob The blob to be exported
439 * @param string|null $format The blob's serialization format
443 public function exportTransform( $blob, $format = null ) {
448 * Unserializes a Content object of the type supported by this ContentHandler.
452 * @param string $blob Serialized form of the content
453 * @param string|null $format The format used for serialization
455 * @return Content The Content object created by deserializing $blob
457 abstract public function unserializeContent( $blob, $format = null );
460 * Apply import transformation (per default, returns $blob unchanged).
461 * This gives subclasses an opportunity to transform data blobs on import.
465 * @param string $blob
466 * @param string|null $format
470 public function importTransform( $blob, $format = null ) {
475 * Creates an empty Content object of the type supported by this
482 abstract public function makeEmptyContent();
485 * Creates a new Content object that acts as a redirect to the given page,
486 * or null if redirects are not supported by this content model.
488 * This default implementation always returns null. Subclasses supporting redirects
489 * must override this method.
491 * Note that subclasses that override this method to return a Content object
492 * should also override supportsRedirects() to return true.
496 * @param Title $destination The page to redirect to.
497 * @param string $text Text to include in the redirect, if possible.
499 * @return Content Always null.
501 public function makeRedirectContent( Title
$destination, $text = '' ) {
506 * Returns the model id that identifies the content model this
507 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
511 * @return string The model ID
513 public function getModelID() {
514 return $this->mModelID
;
520 * @param string $model_id The model to check
522 * @throws MWException If the model ID is not the ID of the content model supported by this
525 protected function checkModelID( $model_id ) {
526 if ( $model_id !== $this->mModelID
) {
527 throw new MWException( "Bad content model: " .
528 "expected {$this->mModelID} " .
529 "but got $model_id." );
534 * Returns a list of serialization formats supported by the
535 * serializeContent() and unserializeContent() methods of this
540 * @return string[] List of serialization formats as MIME type like strings
542 public function getSupportedFormats() {
543 return $this->mSupportedFormats
;
547 * The format used for serialization/deserialization by default by this
550 * This default implementation will return the first element of the array
551 * of formats that was passed to the constructor.
555 * @return string The name of the default serialization format as a MIME type
557 public function getDefaultFormat() {
558 return $this->mSupportedFormats
[0];
562 * Returns true if $format is a serialization format supported by this
563 * ContentHandler, and false otherwise.
565 * Note that if $format is null, this method always returns true, because
566 * null means "use the default format".
570 * @param string $format The serialization format to check
574 public function isSupportedFormat( $format ) {
576 return true; // this means "use the default"
579 return in_array( $format, $this->mSupportedFormats
);
583 * Convenient for checking whether a format provided as a parameter is actually supported.
585 * @param string $format The serialization format to check
587 * @throws MWException If the format is not supported by this content handler.
589 protected function checkFormat( $format ) {
590 if ( !$this->isSupportedFormat( $format ) ) {
591 throw new MWException(
592 "Format $format is not supported for content model "
593 . $this->getModelID()
599 * Returns overrides for action handlers.
600 * Classes listed here will be used instead of the default one when
601 * (and only when) $wgActions[$action] === true. This allows subclasses
602 * to override the default action handlers.
606 * @return array An array mapping action names (typically "view", "edit", "history" etc.) to
607 * either the full qualified class name of an Action class, a callable taking ( Page $page,
608 * IContextSource $context = null ) as parameters and returning an Action object, or an actual
609 * Action object. An empty array in this default implementation.
611 * @see Action::factory
613 public function getActionOverrides() {
618 * Factory for creating an appropriate DifferenceEngine for this content model.
619 * Since 1.32, this is only used for page-level diffs; to diff two content objects,
620 * use getSlotDiffRenderer.
622 * The DifferenceEngine subclass to use is selected in getDiffEngineClass(). The
623 * GetDifferenceEngine hook will receive the DifferenceEngine object and can replace or
625 * (Note that in older versions of MediaWiki the hook documentation instructed extensions
626 * to return false from the hook; you should not rely on always being able to decorate
627 * the DifferenceEngine instance from the hook. If the owner of the content type wants to
628 * decorare the instance, overriding this method is a safer approach.)
630 * @todo This is page-level functionality so it should not belong to ContentHandler.
631 * Move it to a better place once one exists (e.g. PageTypeHandler).
635 * @param IContextSource $context Context to use, anything else will be ignored.
636 * @param int $old Revision ID we want to show and diff with.
637 * @param int|string $new Either a revision ID or one of the strings 'cur', 'prev' or 'next'.
638 * @param int $rcid FIXME: Deprecated, no longer used. Defaults to 0.
639 * @param bool $refreshCache If set, refreshes the diff cache. Defaults to false.
640 * @param bool $unhide If set, allow viewing deleted revs. Defaults to false.
642 * @return DifferenceEngine
644 public function createDifferenceEngine( IContextSource
$context, $old = 0, $new = 0,
645 $rcid = 0, // FIXME: Deprecated, no longer used
646 $refreshCache = false, $unhide = false
648 $diffEngineClass = $this->getDiffEngineClass();
649 $differenceEngine = new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
650 Hooks
::run( 'GetDifferenceEngine', [ $context, $old, $new, $refreshCache, $unhide,
651 &$differenceEngine ] );
652 return $differenceEngine;
656 * Get an appropriate SlotDiffRenderer for this content model.
658 * @param IContextSource $context
659 * @return SlotDiffRenderer
661 final public function getSlotDiffRenderer( IContextSource
$context ) {
662 $slotDiffRenderer = $this->getSlotDiffRendererInternal( $context );
663 if ( get_class( $slotDiffRenderer ) === TextSlotDiffRenderer
::class ) {
664 // To keep B/C, when SlotDiffRenderer is not overridden for a given content type
665 // but DifferenceEngine is, use that instead.
666 $differenceEngine = $this->createDifferenceEngine( $context );
667 if ( get_class( $differenceEngine ) !== DifferenceEngine
::class ) {
668 // TODO turn this into a deprecation warning in a later release
669 LoggerFactory
::getInstance( 'diff' )->info(
670 'Falling back to DifferenceEngineSlotDiffRenderer', [
671 'modelID' => $this->getModelID(),
672 'DifferenceEngine' => get_class( $differenceEngine ),
674 $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
677 Hooks
::run( 'GetSlotDiffRenderer', [ $this, &$slotDiffRenderer, $context ] );
678 return $slotDiffRenderer;
682 * Return the SlotDiffRenderer appropriate for this content handler.
683 * @param IContextSource $context
684 * @return SlotDiffRenderer
686 protected function getSlotDiffRendererInternal( IContextSource
$context ) {
687 $contentLanguage = MediaWikiServices
::getInstance()->getContentLanguage();
688 $statsdDataFactory = MediaWikiServices
::getInstance()->getStatsdDataFactory();
689 $slotDiffRenderer = new TextSlotDiffRenderer();
690 $slotDiffRenderer->setStatsdDataFactory( $statsdDataFactory );
691 // XXX using the page language would be better, but it's unclear how that should be injected
692 $slotDiffRenderer->setLanguage( $contentLanguage );
693 $slotDiffRenderer->setWikiDiff2MovedParagraphDetectionCutoff(
694 $context->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
697 $engine = DifferenceEngine
::getEngine();
698 if ( $engine === false ) {
699 $slotDiffRenderer->setEngine( TextSlotDiffRenderer
::ENGINE_PHP
);
700 } elseif ( $engine === 'wikidiff2' ) {
701 $slotDiffRenderer->setEngine( TextSlotDiffRenderer
::ENGINE_WIKIDIFF2
);
703 $slotDiffRenderer->setEngine( TextSlotDiffRenderer
::ENGINE_EXTERNAL
, $engine );
706 return $slotDiffRenderer;
710 * Get the language in which the content of the given page is written.
712 * This default implementation just returns the content language (except for pages
713 * in the MediaWiki namespace)
715 * Note that the pages language is not cacheable, since it may in some
716 * cases depend on user settings.
718 * Also note that the page language may or may not depend on the actual content of the page,
719 * that is, this method may load the content in order to determine the language.
723 * @param Title $title The page to determine the language for.
724 * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
726 * @return Language The page's language
728 public function getPageLanguage( Title
$title, Content
$content = null ) {
730 $pageLang = MediaWikiServices
::getInstance()->getContentLanguage();
732 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
733 // Parse mediawiki messages with correct target language
734 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $title->getText() );
735 $pageLang = Language
::factory( $lang );
738 Hooks
::run( 'PageContentLanguage', [ $title, &$pageLang, $wgLang ] );
740 return wfGetLangObj( $pageLang );
744 * Get the language in which the content of this page is written when
745 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
746 * specified a preferred variant, the variant will be used.
748 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
749 * the user specified a preferred variant.
751 * Note that the pages view language is not cacheable, since it depends on user settings.
753 * Also note that the page language may or may not depend on the actual content of the page,
754 * that is, this method may load the content in order to determine the language.
758 * @param Title $title The page to determine the language for.
759 * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
761 * @return Language The page's language for viewing
763 public function getPageViewLanguage( Title
$title, Content
$content = null ) {
764 $pageLang = $this->getPageLanguage( $title, $content );
766 if ( $title->getNamespace() !== NS_MEDIAWIKI
) {
767 // If the user chooses a variant, the content is actually
768 // in a language whose code is the variant code.
769 $variant = $pageLang->getPreferredVariant();
770 if ( $pageLang->getCode() !== $variant ) {
771 $pageLang = Language
::factory( $variant );
779 * Determines whether the content type handled by this ContentHandler
780 * can be used on the given page.
782 * This default implementation always returns true.
783 * Subclasses may override this to restrict the use of this content model to specific locations,
784 * typically based on the namespace or some other aspect of the title, such as a special suffix
785 * (e.g. ".svg" for SVG content).
787 * @note this calls the ContentHandlerCanBeUsedOn hook which may be used to override which
788 * content model can be used where.
790 * @param Title $title The page's title.
792 * @return bool True if content of this kind can be used on the given page, false otherwise.
794 public function canBeUsedOn( Title
$title ) {
797 Hooks
::run( 'ContentModelCanBeUsedOn', [ $this->getModelID(), $title, &$ok ] );
803 * Returns the name of the diff engine to use.
809 protected function getDiffEngineClass() {
810 return DifferenceEngine
::class;
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.
817 * This default implementation always returns false.
821 * @param Content $oldContent The page's previous content.
822 * @param Content $myContent One of the page's conflicting contents.
823 * @param Content $yourContent One of the page's conflicting contents.
825 * @return Content|bool Always false.
827 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
832 * Return type of change if one exists for the given edit.
836 * @param Content|null $oldContent The previous text of the page.
837 * @param Content|null $newContent The submitted text of the page.
838 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
840 * @return string|null String key representing type of change, or null.
842 private function getChangeType(
843 Content
$oldContent = null,
844 Content
$newContent = null,
847 $oldTarget = $oldContent !== null ?
$oldContent->getRedirectTarget() : null;
848 $newTarget = $newContent !== null ?
$newContent->getRedirectTarget() : null;
850 // We check for the type of change in the given edit, and return string key accordingly
852 // Blanking of a page
853 if ( $oldContent && $oldContent->getSize() > 0 &&
854 $newContent && $newContent->getSize() === 0
862 // New redirect page (by creating new page or by changing content page)
863 return 'new-redirect';
864 } elseif ( !$newTarget->equals( $oldTarget ) ||
865 $oldTarget->getFragment() !== $newTarget->getFragment()
867 // Redirect target changed
868 return 'changed-redirect-target';
870 } elseif ( $oldTarget ) {
871 // Changing an existing redirect into a non-redirect
872 return 'removed-redirect';
876 if ( $flags & EDIT_NEW
&& $newContent ) {
877 if ( $newContent->getSize() === 0 ) {
885 // Removing more than 90% of the page
886 if ( $oldContent && $newContent && $oldContent->getSize() > 10 * $newContent->getSize() ) {
890 // Content model changed
891 if ( $oldContent && $newContent && $oldContent->getModel() !== $newContent->getModel() ) {
892 return 'contentmodelchange';
899 * Return an applicable auto-summary if one exists for the given edit.
903 * @param Content|null $oldContent The previous text of the page.
904 * @param Content|null $newContent The submitted text of the page.
905 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
907 * @return string An appropriate auto-summary, or an empty string.
909 public function getAutosummary(
910 Content
$oldContent = null,
911 Content
$newContent = null,
914 $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
916 // There's no applicable auto-summary for our case, so our auto-summary is empty.
917 if ( !$changeType ) {
921 // Decide what kind of auto-summary is needed.
922 switch ( $changeType ) {
924 $newTarget = $newContent->getRedirectTarget();
925 $truncatedtext = $newContent->getTextForSummary(
927 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
928 - strlen( $newTarget->getFullText() )
931 return wfMessage( 'autoredircomment', $newTarget->getFullText() )
932 ->plaintextParams( $truncatedtext )->inContentLanguage()->text();
933 case 'changed-redirect-target':
934 $oldTarget = $oldContent->getRedirectTarget();
935 $newTarget = $newContent->getRedirectTarget();
937 $truncatedtext = $newContent->getTextForSummary(
939 - strlen( wfMessage( 'autosumm-changed-redirect-target' )
940 ->inContentLanguage()->text() )
941 - strlen( $oldTarget->getFullText() )
942 - strlen( $newTarget->getFullText() )
945 return wfMessage( 'autosumm-changed-redirect-target',
946 $oldTarget->getFullText(),
947 $newTarget->getFullText() )
948 ->rawParams( $truncatedtext )->inContentLanguage()->text();
949 case 'removed-redirect':
950 $oldTarget = $oldContent->getRedirectTarget();
951 $truncatedtext = $newContent->getTextForSummary(
953 - strlen( wfMessage( 'autosumm-removed-redirect' )
954 ->inContentLanguage()->text() )
955 - strlen( $oldTarget->getFullText() ) );
957 return wfMessage( 'autosumm-removed-redirect', $oldTarget->getFullText() )
958 ->rawParams( $truncatedtext )->inContentLanguage()->text();
960 // If they're making a new article, give its text, truncated, in the summary.
961 $truncatedtext = $newContent->getTextForSummary(
962 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
964 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
965 ->inContentLanguage()->text();
967 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
969 $truncatedtext = $newContent->getTextForSummary(
970 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
972 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
973 ->inContentLanguage()->text();
975 return wfMessage( 'autosumm-newblank' )->inContentLanguage()->text();
982 * Return an applicable tag if one exists for the given edit or return null.
986 * @param Content|null $oldContent The previous text of the page.
987 * @param Content|null $newContent The submitted text of the page.
988 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
990 * @return string|null An appropriate tag, or null.
992 public function getChangeTag(
993 Content
$oldContent = null,
994 Content
$newContent = null,
997 $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
999 // There's no applicable tag for this change.
1000 if ( !$changeType ) {
1004 // Core tags use the same keys as ones returned from $this->getChangeType()
1005 // but prefixed with pseudo namespace 'mw-', so we add the prefix before checking
1006 // if this type of change should be tagged
1007 $tag = 'mw-' . $changeType;
1009 // Not all change types are tagged, so we check against the list of defined tags.
1010 if ( in_array( $tag, ChangeTags
::getSoftwareTags() ) ) {
1018 * Auto-generates a deletion reason
1022 * @param Title $title The page's title
1023 * @param bool &$hasHistory Whether the page has a history
1025 * @return mixed String containing deletion reason or empty string, or
1026 * boolean false if no revision occurred
1028 * @todo &$hasHistory is extremely ugly, it's here because
1029 * WikiPage::getAutoDeleteReason() and Article::generateReason()
1030 * have it / want it.
1032 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
1033 $dbr = wfGetDB( DB_REPLICA
);
1035 // Get the last revision
1036 $rev = Revision
::newFromTitle( $title );
1038 if ( is_null( $rev ) ) {
1042 // Get the article's contents
1043 $content = $rev->getContent();
1046 // If the page is blank, use the text from the previous revision,
1047 // which can only be blank if there's a move/import/protect dummy
1048 // revision involved
1049 if ( !$content ||
$content->isEmpty() ) {
1050 $prev = $rev->getPrevious();
1054 $content = $rev->getContent();
1059 $this->checkModelID( $rev->getContentModel() );
1061 // Find out if there was only one contributor
1062 // Only scan the last 20 revisions
1063 $revQuery = Revision
::getQueryInfo();
1064 $res = $dbr->select(
1065 $revQuery['tables'],
1066 [ 'rev_user_text' => $revQuery['fields']['rev_user_text'] ],
1068 'rev_page' => $title->getArticleID(),
1069 $dbr->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0'
1076 if ( $res === false ) {
1077 // This page has no revisions, which is very weird
1081 $hasHistory = ( $res->numRows() > 1 );
1082 $row = $dbr->fetchObject( $res );
1084 if ( $row ) { // $row is false if the only contributor is hidden
1085 $onlyAuthor = $row->rev_user_text
;
1086 // Try to find a second contributor
1087 foreach ( $res as $row ) {
1088 if ( $row->rev_user_text
!= $onlyAuthor ) { // T24999
1089 $onlyAuthor = false;
1094 $onlyAuthor = false;
1097 // Generate the summary with a '$1' placeholder
1099 // The current revision is blank and the one before is also
1100 // blank. It's just not our lucky day
1101 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
1103 if ( $onlyAuthor ) {
1104 $reason = wfMessage(
1108 )->inContentLanguage()->text();
1110 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
1114 if ( $reason == '-' ) {
1115 // Allow these UI messages to be blanked out cleanly
1119 // Max content length = max comment length - length of the comment (excl. $1)
1120 $text = $content ?
$content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) : '';
1122 // Now replace the '$1' placeholder
1123 $reason = str_replace( '$1', $text, $reason );
1129 * Get the Content object that needs to be saved in order to undo all revisions
1130 * between $undo and $undoafter. Revisions must belong to the same page,
1131 * must exist and must not be deleted.
1134 * @since 1.32 accepts Content objects for all parameters instead of Revision objects.
1135 * Passing Revision objects is deprecated.
1137 * @param Revision|Content $current The current text
1138 * @param Revision|Content $undo The content of the revision to undo
1139 * @param Revision|Content $undoafter Must be from an earlier revision than $undo
1140 * @param bool $undoIsLatest Set true if $undo is from the current revision (since 1.32)
1142 * @return mixed Content on success, false on failure
1144 public function getUndoContent( $current, $undo, $undoafter, $undoIsLatest = false ) {
1145 Assert
::parameterType( Revision
::class . '|' . Content
::class, $current, '$current' );
1146 if ( $current instanceof Content
) {
1147 Assert
::parameter( $undo instanceof Content
, '$undo',
1148 'Must be Content when $current is Content' );
1149 Assert
::parameter( $undoafter instanceof Content
, '$undoafter',
1150 'Must be Content when $current is Content' );
1151 $cur_content = $current;
1152 $undo_content = $undo;
1153 $undoafter_content = $undoafter;
1155 Assert
::parameter( $undo instanceof Revision
, '$undo',
1156 'Must be Revision when $current is Revision' );
1157 Assert
::parameter( $undoafter instanceof Revision
, '$undoafter',
1158 'Must be Revision when $current is Revision' );
1160 $cur_content = $current->getContent();
1162 if ( empty( $cur_content ) ) {
1163 return false; // no page
1166 $undo_content = $undo->getContent();
1167 $undoafter_content = $undoafter->getContent();
1169 if ( !$undo_content ||
!$undoafter_content ) {
1170 return false; // no content to undo
1173 $undoIsLatest = $current->getId() === $undo->getId();
1177 $this->checkModelID( $cur_content->getModel() );
1178 $this->checkModelID( $undo_content->getModel() );
1179 if ( !$undoIsLatest ) {
1180 // If we are undoing the most recent revision,
1181 // its ok to revert content model changes. However
1182 // if we are undoing a revision in the middle, then
1183 // doing that will be confusing.
1184 $this->checkModelID( $undoafter_content->getModel() );
1186 } catch ( MWException
$e ) {
1187 // If the revisions have different content models
1188 // just return false
1192 if ( $cur_content->equals( $undo_content ) ) {
1193 // No use doing a merge if it's just a straight revert.
1194 return $undoafter_content;
1197 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
1199 return $undone_content;
1203 * Get parser options suitable for rendering and caching the article
1205 * @deprecated since 1.32, use WikiPage::makeParserOptions() or
1206 * ParserOptions::newCanonical() instead.
1207 * @param IContextSource|User|string $context One of the following:
1208 * - IContextSource: Use the User and the Language of the provided
1210 * - User: Use the provided User object and $wgLang for the language,
1211 * so use an IContextSource object if possible.
1212 * - 'canonical': Canonical options (anonymous user with default
1213 * preferences and content language).
1215 * @throws MWException
1216 * @return ParserOptions
1218 public function makeParserOptions( $context ) {
1219 wfDeprecated( __METHOD__
, '1.32' );
1220 return ParserOptions
::newCanonical( $context );
1224 * Returns true for content models that support caching using the
1225 * ParserCache mechanism. See WikiPage::shouldCheckParserCache().
1229 * @return bool Always false.
1231 public function isParserCacheSupported() {
1236 * Returns true if this content model supports sections.
1237 * This default implementation returns false.
1239 * Content models that return true here should also implement
1240 * Content::getSection, Content::replaceSection, etc. to handle sections..
1242 * @return bool Always false.
1244 public function supportsSections() {
1249 * Returns true if this content model supports categories.
1250 * The default implementation returns true.
1252 * @return bool Always true.
1254 public function supportsCategories() {
1259 * Returns true if this content model supports redirects.
1260 * This default implementation returns false.
1262 * Content models that return true here should also implement
1263 * ContentHandler::makeRedirectContent to return a Content object.
1265 * @return bool Always false.
1267 public function supportsRedirects() {
1272 * Return true if this content model supports direct editing, such as via EditPage.
1274 * @return bool Default is false, and true for TextContent and it's derivatives.
1276 public function supportsDirectEditing() {
1281 * Whether or not this content model supports direct editing via ApiEditPage
1283 * @return bool Default is false, and true for TextContent and derivatives.
1285 public function supportsDirectApiEditing() {
1286 return $this->supportsDirectEditing();
1290 * Get fields definition for search index
1292 * @todo Expose title, redirect, namespace, text, source_text, text_bytes
1293 * field mappings here. (see T142670 and T143409)
1295 * @param SearchEngine $engine
1296 * @return SearchIndexField[] List of fields this content handler can provide.
1299 public function getFieldsForSearchIndex( SearchEngine
$engine ) {
1300 $fields['category'] = $engine->makeSearchFieldMapping(
1302 SearchIndexField
::INDEX_TYPE_TEXT
1304 $fields['category']->setFlag( SearchIndexField
::FLAG_CASEFOLD
);
1306 $fields['external_link'] = $engine->makeSearchFieldMapping(
1308 SearchIndexField
::INDEX_TYPE_KEYWORD
1311 $fields['outgoing_link'] = $engine->makeSearchFieldMapping(
1313 SearchIndexField
::INDEX_TYPE_KEYWORD
1316 $fields['template'] = $engine->makeSearchFieldMapping(
1318 SearchIndexField
::INDEX_TYPE_KEYWORD
1320 $fields['template']->setFlag( SearchIndexField
::FLAG_CASEFOLD
);
1322 $fields['content_model'] = $engine->makeSearchFieldMapping(
1324 SearchIndexField
::INDEX_TYPE_KEYWORD
1331 * Add new field definition to array.
1332 * @param SearchIndexField[] &$fields
1333 * @param SearchEngine $engine
1334 * @param string $name
1336 * @return SearchIndexField[] new field defs
1339 protected function addSearchField( &$fields, SearchEngine
$engine, $name, $type ) {
1340 $fields[$name] = $engine->makeSearchFieldMapping( $name, $type );
1345 * Return fields to be indexed by search engine
1346 * as representation of this document.
1347 * Overriding class should call parent function or take care of calling
1348 * the SearchDataForIndex hook.
1349 * @param WikiPage $page Page to index
1350 * @param ParserOutput $output
1351 * @param SearchEngine $engine Search engine for which we are indexing
1352 * @return array Map of name=>value for fields
1355 public function getDataForSearchIndex(
1357 ParserOutput
$output,
1358 SearchEngine
$engine
1361 $content = $page->getContent();
1364 $searchDataExtractor = new ParserOutputSearchDataExtractor();
1366 $fieldData['category'] = $searchDataExtractor->getCategories( $output );
1367 $fieldData['external_link'] = $searchDataExtractor->getExternalLinks( $output );
1368 $fieldData['outgoing_link'] = $searchDataExtractor->getOutgoingLinks( $output );
1369 $fieldData['template'] = $searchDataExtractor->getTemplates( $output );
1371 $text = $content->getTextForSearchIndex();
1373 $fieldData['text'] = $text;
1374 $fieldData['source_text'] = $text;
1375 $fieldData['text_bytes'] = $content->getSize();
1376 $fieldData['content_model'] = $content->getModel();
1379 Hooks
::run( 'SearchDataForIndex', [ &$fieldData, $this, $page, $output, $engine ] );
1384 * Produce page output suitable for indexing.
1386 * Specific content handlers may override it if they need different content handling.
1388 * @param WikiPage $page
1389 * @param ParserCache|null $cache
1390 * @return ParserOutput
1392 public function getParserOutputForIndexing( WikiPage
$page, ParserCache
$cache = null ) {
1393 // TODO: MCR: ContentHandler should be called per slot, not for the whole page.
1395 $parserOptions = $page->makeParserOptions( 'canonical' );
1397 $parserOutput = $cache->get( $page, $parserOptions );
1400 if ( empty( $parserOutput ) ) {
1401 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
1403 $renderer->getRenderedRevision(
1404 $page->getRevision()->getRevisionRecord(),
1406 )->getRevisionParserOutput();
1408 $cache->save( $parserOutput, $page, $parserOptions );
1411 return $parserOutput;
1415 * Returns a list of DeferrableUpdate objects for recording information about the
1416 * given Content in some secondary data store.
1418 * Application logic should not call this method directly. Instead, it should call
1419 * DerivedPageDataUpdater::getSecondaryDataUpdates().
1421 * @note Implementations must not return a LinksUpdate instance. Instead, a LinksUpdate
1422 * is created by the calling code in DerivedPageDataUpdater, on the combined ParserOutput
1423 * of all slots, not for each slot individually. This is in contrast to the old
1424 * getSecondaryDataUpdates method defined by AbstractContent, which returned a LinksUpdate.
1426 * @note Implementations should not call $content->getParserOutput, they should call
1427 * $slotOutput->getSlotRendering( $role, false ) instead if they need to access a ParserOutput
1428 * of $content. This allows existing ParserOutput objects to be re-used, while avoiding
1429 * creating a ParserOutput when none is needed.
1431 * @param Title $title The title of the page to supply the updates for
1432 * @param Content $content The content to generate data updates for.
1433 * @param string $role The role (slot) in which the content is being used. Which updates
1434 * are performed should generally not depend on the role the content has, but the
1435 * DeferrableUpdates themselves may need to know the role, to track to which slot the
1436 * data refers, and to avoid overwriting data of the same kind from another slot.
1437 * @param SlotRenderingProvider $slotOutput A provider that can be used to gain access to
1438 * a ParserOutput of $content by calling $slotOutput->getSlotParserOutput( $role, false ).
1439 * @return DeferrableUpdate[] A list of DeferrableUpdate objects for putting information
1440 * about this content object somewhere. The default implementation returns an empty
1444 public function getSecondaryDataUpdates(
1448 SlotRenderingProvider
$slotOutput
1454 * Returns a list of DeferrableUpdate objects for removing information about content
1455 * in some secondary data store. This is used when a page is deleted, and also when
1456 * a slot is removed from a page.
1458 * Application logic should not call this method directly. Instead, it should call
1459 * WikiPage::getSecondaryDataUpdates().
1461 * @note Implementations must not return a LinksDeletionUpdate instance. Instead, a
1462 * LinksDeletionUpdate is created by the calling code in WikiPage.
1463 * This is in contrast to the old getDeletionUpdates method defined by AbstractContent,
1464 * which returned a LinksUpdate.
1466 * @note Implementations should not rely on the page's current content, but rather the current
1467 * state of the secondary data store.
1469 * @param Title $title The title of the page to supply the updates for
1470 * @param string $role The role (slot) in which the content is being used. Which updates
1471 * are performed should generally not depend on the role the content has, but the
1472 * DeferrableUpdates themselves may need to know the role, to track to which slot the
1473 * data refers, and to avoid overwriting data of the same kind from another slot.
1475 * @return DeferrableUpdate[] A list of DeferrableUpdate objects for putting information
1476 * about this content object somewhere. The default implementation returns an empty
1481 public function getDeletionUpdates( Title
$title, $role ) {