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->getText().
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->getText();
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()
177 * @deprecated since 1.33, use SlotRoleHandler::getDefaultModel() together with
178 * SlotRoleRegistry::getRoleHandler().
180 * @param Title $title
182 * @return string Default model name for the page given by $title
184 public static function getDefaultModelFor( Title
$title ) {
185 $slotRoleregistry = MediaWikiServices
::getInstance()->getSlotRoleRegistry();
186 $mainSlotHandler = $slotRoleregistry->getRoleHandler( 'main' );
187 return $mainSlotHandler->getDefaultModel( $title );
191 * Returns the appropriate ContentHandler singleton for the given title.
195 * @param Title $title
197 * @return ContentHandler
199 public static function getForTitle( Title
$title ) {
200 $modelId = $title->getContentModel();
202 return self
::getForModelID( $modelId );
206 * Returns the appropriate ContentHandler singleton for the given Content
211 * @param Content $content
213 * @return ContentHandler
215 public static function getForContent( Content
$content ) {
216 $modelId = $content->getModel();
218 return self
::getForModelID( $modelId );
222 * @var array A Cache of ContentHandler instances by model id
224 protected static $handlers;
227 * Returns the ContentHandler singleton for the given model ID. Use the
228 * CONTENT_MODEL_XXX constants to identify the desired content model.
230 * ContentHandler singletons are taken from the global $wgContentHandlers
231 * array. Keys in that array are model names, the values are either
232 * ContentHandler singleton objects, or strings specifying the appropriate
233 * subclass of ContentHandler.
235 * If a class name is encountered when looking up the singleton for a given
236 * model name, the class is instantiated and the class name is replaced by
237 * the resulting singleton in $wgContentHandlers.
239 * If no ContentHandler is defined for the desired $modelId, the
240 * ContentHandler may be provided by the ContentHandlerForModelID hook.
241 * If no ContentHandler can be determined, an MWException is raised.
245 * @param string $modelId The ID of the content model for which to get a
246 * handler. Use CONTENT_MODEL_XXX constants.
248 * @throws MWException For internal errors and problems in the configuration.
249 * @throws MWUnknownContentModelException If no handler is known for the model ID.
250 * @return ContentHandler The ContentHandler singleton for handling the model given by the ID.
252 public static function getForModelID( $modelId ) {
253 global $wgContentHandlers;
255 if ( isset( self
::$handlers[$modelId] ) ) {
256 return self
::$handlers[$modelId];
259 if ( empty( $wgContentHandlers[$modelId] ) ) {
262 Hooks
::run( 'ContentHandlerForModelID', [ $modelId, &$handler ] );
264 if ( $handler === null ) {
265 throw new MWUnknownContentModelException( $modelId );
268 if ( !( $handler instanceof ContentHandler
) ) {
269 throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
272 $classOrCallback = $wgContentHandlers[$modelId];
274 if ( is_callable( $classOrCallback ) ) {
275 $handler = call_user_func( $classOrCallback, $modelId );
277 $handler = new $classOrCallback( $modelId );
280 if ( !( $handler instanceof ContentHandler
) ) {
281 throw new MWException( "$classOrCallback from \$wgContentHandlers is not " .
282 "compatible with ContentHandler" );
286 wfDebugLog( 'ContentHandler', 'Created handler for ' . $modelId
287 . ': ' . get_class( $handler ) );
289 self
::$handlers[$modelId] = $handler;
291 return self
::$handlers[$modelId];
295 * Clean up handlers cache.
297 public static function cleanupHandlersCache() {
298 self
::$handlers = [];
302 * Returns the localized name for a given content model.
304 * Model names are localized using system messages. Message keys
305 * have the form content-model-$name, where $name is getContentModelName( $id ).
307 * @param string $name The content model ID, as given by a CONTENT_MODEL_XXX
308 * constant or returned by Revision::getContentModel().
309 * @param Language|null $lang The language to parse the message in (since 1.26)
311 * @throws MWException If the model ID isn't known.
312 * @return string The content model's localized name.
314 public static function getLocalizedName( $name, Language
$lang = null ) {
315 // Messages: content-model-wikitext, content-model-text,
316 // content-model-javascript, content-model-css
317 $key = "content-model-$name";
319 $msg = wfMessage( $key );
321 $msg->inLanguage( $lang );
324 return $msg->exists() ?
$msg->plain() : $name;
327 public static function getContentModels() {
328 global $wgContentHandlers;
330 $models = array_keys( $wgContentHandlers );
331 Hooks
::run( 'GetContentModels', [ &$models ] );
335 public static function getAllContentFormats() {
336 global $wgContentHandlers;
340 foreach ( $wgContentHandlers as $model => $class ) {
341 $handler = self
::getForModelID( $model );
342 $formats = array_merge( $formats, $handler->getSupportedFormats() );
345 $formats = array_unique( $formats );
350 // ------------------------------------------------------------------------
360 protected $mSupportedFormats;
363 * Constructor, initializing the ContentHandler instance with its model ID
364 * and a list of supported formats. Values for the parameters are typically
365 * provided as literals by subclass's constructors.
367 * @param string $modelId (use CONTENT_MODEL_XXX constants).
368 * @param string[] $formats List for supported serialization formats
369 * (typically as MIME types)
371 public function __construct( $modelId, $formats ) {
372 $this->mModelID
= $modelId;
373 $this->mSupportedFormats
= $formats;
377 * Serializes a Content object of the type supported by this ContentHandler.
381 * @param Content $content The Content object to serialize
382 * @param string|null $format The desired serialization format
384 * @return string Serialized form of the content
386 abstract public function serializeContent( Content
$content, $format = null );
389 * Applies transformations on export (returns the blob unchanged per default).
390 * Subclasses may override this to perform transformations such as conversion
391 * of legacy formats or filtering of internal meta-data.
393 * @param string $blob The blob to be exported
394 * @param string|null $format The blob's serialization format
398 public function exportTransform( $blob, $format = null ) {
403 * Unserializes a Content object of the type supported by this ContentHandler.
407 * @param string $blob Serialized form of the content
408 * @param string|null $format The format used for serialization
410 * @return Content The Content object created by deserializing $blob
412 abstract public function unserializeContent( $blob, $format = null );
415 * Apply import transformation (per default, returns $blob unchanged).
416 * This gives subclasses an opportunity to transform data blobs on import.
420 * @param string $blob
421 * @param string|null $format
425 public function importTransform( $blob, $format = null ) {
430 * Creates an empty Content object of the type supported by this
437 abstract public function makeEmptyContent();
440 * Creates a new Content object that acts as a redirect to the given page,
441 * or null if redirects are not supported by this content model.
443 * This default implementation always returns null. Subclasses supporting redirects
444 * must override this method.
446 * Note that subclasses that override this method to return a Content object
447 * should also override supportsRedirects() to return true.
451 * @param Title $destination The page to redirect to.
452 * @param string $text Text to include in the redirect, if possible.
454 * @return Content Always null.
456 public function makeRedirectContent( Title
$destination, $text = '' ) {
461 * Returns the model id that identifies the content model this
462 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
466 * @return string The model ID
468 public function getModelID() {
469 return $this->mModelID
;
475 * @param string $model_id The model to check
477 * @throws MWException If the model ID is not the ID of the content model supported by this
480 protected function checkModelID( $model_id ) {
481 if ( $model_id !== $this->mModelID
) {
482 throw new MWException( "Bad content model: " .
483 "expected {$this->mModelID} " .
484 "but got $model_id." );
489 * Returns a list of serialization formats supported by the
490 * serializeContent() and unserializeContent() methods of this
495 * @return string[] List of serialization formats as MIME type like strings
497 public function getSupportedFormats() {
498 return $this->mSupportedFormats
;
502 * The format used for serialization/deserialization by default by this
505 * This default implementation will return the first element of the array
506 * of formats that was passed to the constructor.
510 * @return string The name of the default serialization format as a MIME type
512 public function getDefaultFormat() {
513 return $this->mSupportedFormats
[0];
517 * Returns true if $format is a serialization format supported by this
518 * ContentHandler, and false otherwise.
520 * Note that if $format is null, this method always returns true, because
521 * null means "use the default format".
525 * @param string $format The serialization format to check
529 public function isSupportedFormat( $format ) {
531 return true; // this means "use the default"
534 return in_array( $format, $this->mSupportedFormats
);
538 * Convenient for checking whether a format provided as a parameter is actually supported.
540 * @param string $format The serialization format to check
542 * @throws MWException If the format is not supported by this content handler.
544 protected function checkFormat( $format ) {
545 if ( !$this->isSupportedFormat( $format ) ) {
546 throw new MWException(
547 "Format $format is not supported for content model "
548 . $this->getModelID()
554 * Returns overrides for action handlers.
555 * Classes listed here will be used instead of the default one when
556 * (and only when) $wgActions[$action] === true. This allows subclasses
557 * to override the default action handlers.
561 * @return array An array mapping action names (typically "view", "edit", "history" etc.) to
562 * either the full qualified class name of an Action class, a callable taking ( Page $page,
563 * IContextSource $context = null ) as parameters and returning an Action object, or an actual
564 * Action object. An empty array in this default implementation.
566 * @see Action::factory
568 public function getActionOverrides() {
573 * Factory for creating an appropriate DifferenceEngine for this content model.
574 * Since 1.32, this is only used for page-level diffs; to diff two content objects,
575 * use getSlotDiffRenderer.
577 * The DifferenceEngine subclass to use is selected in getDiffEngineClass(). The
578 * GetDifferenceEngine hook will receive the DifferenceEngine object and can replace or
580 * (Note that in older versions of MediaWiki the hook documentation instructed extensions
581 * to return false from the hook; you should not rely on always being able to decorate
582 * the DifferenceEngine instance from the hook. If the owner of the content type wants to
583 * decorare the instance, overriding this method is a safer approach.)
585 * @todo This is page-level functionality so it should not belong to ContentHandler.
586 * Move it to a better place once one exists (e.g. PageTypeHandler).
590 * @param IContextSource $context Context to use, anything else will be ignored.
591 * @param int $old Revision ID we want to show and diff with.
592 * @param int|string $new Either a revision ID or one of the strings 'cur', 'prev' or 'next'.
593 * @param int $rcid FIXME: Deprecated, no longer used. Defaults to 0.
594 * @param bool $refreshCache If set, refreshes the diff cache. Defaults to false.
595 * @param bool $unhide If set, allow viewing deleted revs. Defaults to false.
597 * @return DifferenceEngine
599 public function createDifferenceEngine( IContextSource
$context, $old = 0, $new = 0,
600 $rcid = 0, // FIXME: Deprecated, no longer used
601 $refreshCache = false, $unhide = false
603 $diffEngineClass = $this->getDiffEngineClass();
604 $differenceEngine = new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
605 Hooks
::run( 'GetDifferenceEngine', [ $context, $old, $new, $refreshCache, $unhide,
606 &$differenceEngine ] );
607 return $differenceEngine;
611 * Get an appropriate SlotDiffRenderer for this content model.
613 * @param IContextSource $context
614 * @return SlotDiffRenderer
616 final public function getSlotDiffRenderer( IContextSource
$context ) {
617 $slotDiffRenderer = $this->getSlotDiffRendererInternal( $context );
618 if ( get_class( $slotDiffRenderer ) === TextSlotDiffRenderer
::class ) {
619 // To keep B/C, when SlotDiffRenderer is not overridden for a given content type
620 // but DifferenceEngine is, use that instead.
621 $differenceEngine = $this->createDifferenceEngine( $context );
622 if ( get_class( $differenceEngine ) !== DifferenceEngine
::class ) {
623 // TODO turn this into a deprecation warning in a later release
624 LoggerFactory
::getInstance( 'diff' )->info(
625 'Falling back to DifferenceEngineSlotDiffRenderer', [
626 'modelID' => $this->getModelID(),
627 'DifferenceEngine' => get_class( $differenceEngine ),
629 $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
632 Hooks
::run( 'GetSlotDiffRenderer', [ $this, &$slotDiffRenderer, $context ] );
633 return $slotDiffRenderer;
637 * Return the SlotDiffRenderer appropriate for this content handler.
638 * @param IContextSource $context
639 * @return SlotDiffRenderer
641 protected function getSlotDiffRendererInternal( IContextSource
$context ) {
642 $contentLanguage = MediaWikiServices
::getInstance()->getContentLanguage();
643 $statsdDataFactory = MediaWikiServices
::getInstance()->getStatsdDataFactory();
644 $slotDiffRenderer = new TextSlotDiffRenderer();
645 $slotDiffRenderer->setStatsdDataFactory( $statsdDataFactory );
646 // XXX using the page language would be better, but it's unclear how that should be injected
647 $slotDiffRenderer->setLanguage( $contentLanguage );
648 $slotDiffRenderer->setWikiDiff2MovedParagraphDetectionCutoff(
649 $context->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
652 $engine = DifferenceEngine
::getEngine();
653 if ( $engine === false ) {
654 $slotDiffRenderer->setEngine( TextSlotDiffRenderer
::ENGINE_PHP
);
655 } elseif ( $engine === 'wikidiff2' ) {
656 $slotDiffRenderer->setEngine( TextSlotDiffRenderer
::ENGINE_WIKIDIFF2
);
658 $slotDiffRenderer->setEngine( TextSlotDiffRenderer
::ENGINE_EXTERNAL
, $engine );
661 return $slotDiffRenderer;
665 * Get the language in which the content of the given page is written.
667 * This default implementation just returns the content language (except for pages
668 * in the MediaWiki namespace)
670 * Note that the page's language is not cacheable, since it may in some
671 * cases depend on user settings.
673 * Also note that the page language may or may not depend on the actual content of the page,
674 * that is, this method may load the content in order to determine the language.
678 * @param Title $title The page to determine the language for.
679 * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
681 * @return Language The page's language
683 public function getPageLanguage( Title
$title, Content
$content = null ) {
685 $pageLang = MediaWikiServices
::getInstance()->getContentLanguage();
687 if ( $title->inNamespace( NS_MEDIAWIKI
) ) {
688 // Parse mediawiki messages with correct target language
689 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $title->getText() );
690 $pageLang = Language
::factory( $lang );
693 Hooks
::run( 'PageContentLanguage', [ $title, &$pageLang, $wgLang ] );
695 return wfGetLangObj( $pageLang );
699 * Get the language in which the content of this page is written when
700 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
701 * specified a preferred variant, the variant will be used.
703 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
704 * the user specified a preferred variant.
706 * Note that the pages view language is not cacheable, since it depends on user settings.
708 * Also note that the page language may or may not depend on the actual content of the page,
709 * that is, this method may load the content in order to determine the language.
713 * @param Title $title The page to determine the language for.
714 * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
716 * @return Language The page's language for viewing
718 public function getPageViewLanguage( Title
$title, Content
$content = null ) {
719 $pageLang = $this->getPageLanguage( $title, $content );
721 if ( $title->getNamespace() !== NS_MEDIAWIKI
) {
722 // If the user chooses a variant, the content is actually
723 // in a language whose code is the variant code.
724 $variant = $pageLang->getPreferredVariant();
725 if ( $pageLang->getCode() !== $variant ) {
726 $pageLang = Language
::factory( $variant );
734 * Determines whether the content type handled by this ContentHandler
735 * can be used for the main slot of the given page.
737 * This default implementation always returns true.
738 * Subclasses may override this to restrict the use of this content model to specific locations,
739 * typically based on the namespace or some other aspect of the title, such as a special suffix
740 * (e.g. ".svg" for SVG content).
742 * @note this calls the ContentHandlerCanBeUsedOn hook which may be used to override which
743 * content model can be used where.
745 * @see SlotRoleHandler::isAllowedModel
747 * @param Title $title The page's title.
749 * @return bool True if content of this kind can be used on the given page, false otherwise.
751 public function canBeUsedOn( Title
$title ) {
754 Hooks
::run( 'ContentModelCanBeUsedOn', [ $this->getModelID(), $title, &$ok ] );
760 * Returns the name of the diff engine to use.
766 protected function getDiffEngineClass() {
767 return DifferenceEngine
::class;
771 * Attempts to merge differences between three versions. Returns a new
772 * Content object for a clean merge and false for failure or a conflict.
774 * This default implementation always returns false.
778 * @param Content $oldContent The page's previous content.
779 * @param Content $myContent One of the page's conflicting contents.
780 * @param Content $yourContent One of the page's conflicting contents.
782 * @return Content|bool Always false.
784 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
789 * Return type of change if one exists for the given edit.
793 * @param Content|null $oldContent The previous text of the page.
794 * @param Content|null $newContent The submitted text of the page.
795 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
797 * @return string|null String key representing type of change, or null.
799 private function getChangeType(
800 Content
$oldContent = null,
801 Content
$newContent = null,
804 $oldTarget = $oldContent !== null ?
$oldContent->getRedirectTarget() : null;
805 $newTarget = $newContent !== null ?
$newContent->getRedirectTarget() : null;
807 // We check for the type of change in the given edit, and return string key accordingly
809 // Blanking of a page
810 if ( $oldContent && $oldContent->getSize() > 0 &&
811 $newContent && $newContent->getSize() === 0
819 // New redirect page (by creating new page or by changing content page)
820 return 'new-redirect';
821 } elseif ( !$newTarget->equals( $oldTarget ) ||
822 $oldTarget->getFragment() !== $newTarget->getFragment()
824 // Redirect target changed
825 return 'changed-redirect-target';
827 } elseif ( $oldTarget ) {
828 // Changing an existing redirect into a non-redirect
829 return 'removed-redirect';
833 if ( $flags & EDIT_NEW
&& $newContent ) {
834 if ( $newContent->getSize() === 0 ) {
842 // Removing more than 90% of the page
843 if ( $oldContent && $newContent && $oldContent->getSize() > 10 * $newContent->getSize() ) {
847 // Content model changed
848 if ( $oldContent && $newContent && $oldContent->getModel() !== $newContent->getModel() ) {
849 return 'contentmodelchange';
856 * Return an applicable auto-summary if one exists for the given edit.
860 * @param Content|null $oldContent The previous text of the page.
861 * @param Content|null $newContent The submitted text of the page.
862 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
864 * @return string An appropriate auto-summary, or an empty string.
866 public function getAutosummary(
867 Content
$oldContent = null,
868 Content
$newContent = null,
871 $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
873 // There's no applicable auto-summary for our case, so our auto-summary is empty.
874 if ( !$changeType ) {
878 // Decide what kind of auto-summary is needed.
879 switch ( $changeType ) {
881 $newTarget = $newContent->getRedirectTarget();
882 $truncatedtext = $newContent->getTextForSummary(
884 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
885 - strlen( $newTarget->getFullText() )
888 return wfMessage( 'autoredircomment', $newTarget->getFullText() )
889 ->plaintextParams( $truncatedtext )->inContentLanguage()->text();
890 case 'changed-redirect-target':
891 $oldTarget = $oldContent->getRedirectTarget();
892 $newTarget = $newContent->getRedirectTarget();
894 $truncatedtext = $newContent->getTextForSummary(
896 - strlen( wfMessage( 'autosumm-changed-redirect-target' )
897 ->inContentLanguage()->text() )
898 - strlen( $oldTarget->getFullText() )
899 - strlen( $newTarget->getFullText() )
902 return wfMessage( 'autosumm-changed-redirect-target',
903 $oldTarget->getFullText(),
904 $newTarget->getFullText() )
905 ->rawParams( $truncatedtext )->inContentLanguage()->text();
906 case 'removed-redirect':
907 $oldTarget = $oldContent->getRedirectTarget();
908 $truncatedtext = $newContent->getTextForSummary(
910 - strlen( wfMessage( 'autosumm-removed-redirect' )
911 ->inContentLanguage()->text() )
912 - strlen( $oldTarget->getFullText() ) );
914 return wfMessage( 'autosumm-removed-redirect', $oldTarget->getFullText() )
915 ->rawParams( $truncatedtext )->inContentLanguage()->text();
917 // If they're making a new article, give its text, truncated, in the summary.
918 $truncatedtext = $newContent->getTextForSummary(
919 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
921 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
922 ->inContentLanguage()->text();
924 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
926 $truncatedtext = $newContent->getTextForSummary(
927 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
929 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
930 ->inContentLanguage()->text();
932 return wfMessage( 'autosumm-newblank' )->inContentLanguage()->text();
939 * Return an applicable tag if one exists for the given edit or return null.
943 * @param Content|null $oldContent The previous text of the page.
944 * @param Content|null $newContent The submitted text of the page.
945 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
947 * @return string|null An appropriate tag, or null.
949 public function getChangeTag(
950 Content
$oldContent = null,
951 Content
$newContent = null,
954 $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
956 // There's no applicable tag for this change.
957 if ( !$changeType ) {
961 // Core tags use the same keys as ones returned from $this->getChangeType()
962 // but prefixed with pseudo namespace 'mw-', so we add the prefix before checking
963 // if this type of change should be tagged
964 $tag = 'mw-' . $changeType;
966 // Not all change types are tagged, so we check against the list of defined tags.
967 if ( in_array( $tag, ChangeTags
::getSoftwareTags() ) ) {
975 * Auto-generates a deletion reason
979 * @param Title $title The page's title
980 * @param bool &$hasHistory Whether the page has a history
982 * @return mixed String containing deletion reason or empty string, or
983 * boolean false if no revision occurred
985 * @todo &$hasHistory is extremely ugly, it's here because
986 * WikiPage::getAutoDeleteReason() and Article::generateReason()
989 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
990 $dbr = wfGetDB( DB_REPLICA
);
992 // Get the last revision
993 $rev = Revision
::newFromTitle( $title );
995 if ( is_null( $rev ) ) {
999 // Get the article's contents
1000 $content = $rev->getContent();
1003 // If the page is blank, use the text from the previous revision,
1004 // which can only be blank if there's a move/import/protect dummy
1005 // revision involved
1006 if ( !$content ||
$content->isEmpty() ) {
1007 $prev = $rev->getPrevious();
1011 $content = $rev->getContent();
1016 $this->checkModelID( $rev->getContentModel() );
1018 // Find out if there was only one contributor
1019 // Only scan the last 20 revisions
1020 $revQuery = Revision
::getQueryInfo();
1021 $res = $dbr->select(
1022 $revQuery['tables'],
1023 [ 'rev_user_text' => $revQuery['fields']['rev_user_text'] ],
1025 'rev_page' => $title->getArticleID(),
1026 $dbr->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0'
1033 if ( $res === false ) {
1034 // This page has no revisions, which is very weird
1038 $hasHistory = ( $res->numRows() > 1 );
1039 $row = $dbr->fetchObject( $res );
1041 if ( $row ) { // $row is false if the only contributor is hidden
1042 $onlyAuthor = $row->rev_user_text
;
1043 // Try to find a second contributor
1044 foreach ( $res as $row ) {
1045 if ( $row->rev_user_text
!= $onlyAuthor ) { // T24999
1046 $onlyAuthor = false;
1051 $onlyAuthor = false;
1054 // Generate the summary with a '$1' placeholder
1056 // The current revision is blank and the one before is also
1057 // blank. It's just not our lucky day
1058 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
1060 if ( $onlyAuthor ) {
1061 $reason = wfMessage(
1065 )->inContentLanguage()->text();
1067 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
1071 if ( $reason == '-' ) {
1072 // Allow these UI messages to be blanked out cleanly
1076 // Max content length = max comment length - length of the comment (excl. $1)
1077 $text = $content ?
$content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) : '';
1079 // Now replace the '$1' placeholder
1080 $reason = str_replace( '$1', $text, $reason );
1086 * Get the Content object that needs to be saved in order to undo all revisions
1087 * between $undo and $undoafter. Revisions must belong to the same page,
1088 * must exist and must not be deleted.
1091 * @since 1.32 accepts Content objects for all parameters instead of Revision objects.
1092 * Passing Revision objects is deprecated.
1094 * @param Revision|Content $current The current text
1095 * @param Revision|Content $undo The content of the revision to undo
1096 * @param Revision|Content $undoafter Must be from an earlier revision than $undo
1097 * @param bool $undoIsLatest Set true if $undo is from the current revision (since 1.32)
1099 * @return mixed Content on success, false on failure
1101 public function getUndoContent( $current, $undo, $undoafter, $undoIsLatest = false ) {
1102 Assert
::parameterType( Revision
::class . '|' . Content
::class, $current, '$current' );
1103 if ( $current instanceof Content
) {
1104 Assert
::parameter( $undo instanceof Content
, '$undo',
1105 'Must be Content when $current is Content' );
1106 Assert
::parameter( $undoafter instanceof Content
, '$undoafter',
1107 'Must be Content when $current is Content' );
1108 $cur_content = $current;
1109 $undo_content = $undo;
1110 $undoafter_content = $undoafter;
1112 Assert
::parameter( $undo instanceof Revision
, '$undo',
1113 'Must be Revision when $current is Revision' );
1114 Assert
::parameter( $undoafter instanceof Revision
, '$undoafter',
1115 'Must be Revision when $current is Revision' );
1117 $cur_content = $current->getContent();
1119 if ( empty( $cur_content ) ) {
1120 return false; // no page
1123 $undo_content = $undo->getContent();
1124 $undoafter_content = $undoafter->getContent();
1126 if ( !$undo_content ||
!$undoafter_content ) {
1127 return false; // no content to undo
1130 $undoIsLatest = $current->getId() === $undo->getId();
1134 $this->checkModelID( $cur_content->getModel() );
1135 $this->checkModelID( $undo_content->getModel() );
1136 if ( !$undoIsLatest ) {
1137 // If we are undoing the most recent revision,
1138 // its ok to revert content model changes. However
1139 // if we are undoing a revision in the middle, then
1140 // doing that will be confusing.
1141 $this->checkModelID( $undoafter_content->getModel() );
1143 } catch ( MWException
$e ) {
1144 // If the revisions have different content models
1145 // just return false
1149 if ( $cur_content->equals( $undo_content ) ) {
1150 // No use doing a merge if it's just a straight revert.
1151 return $undoafter_content;
1154 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
1156 return $undone_content;
1160 * Get parser options suitable for rendering and caching the article
1162 * @deprecated since 1.32, use WikiPage::makeParserOptions() or
1163 * ParserOptions::newCanonical() instead.
1164 * @param IContextSource|User|string $context One of the following:
1165 * - IContextSource: Use the User and the Language of the provided
1167 * - User: Use the provided User object and $wgLang for the language,
1168 * so use an IContextSource object if possible.
1169 * - 'canonical': Canonical options (anonymous user with default
1170 * preferences and content language).
1172 * @throws MWException
1173 * @return ParserOptions
1175 public function makeParserOptions( $context ) {
1176 wfDeprecated( __METHOD__
, '1.32' );
1177 return ParserOptions
::newCanonical( $context );
1181 * Returns true for content models that support caching using the
1182 * ParserCache mechanism. See WikiPage::shouldCheckParserCache().
1186 * @return bool Always false.
1188 public function isParserCacheSupported() {
1193 * Returns true if this content model supports sections.
1194 * This default implementation returns false.
1196 * Content models that return true here should also implement
1197 * Content::getSection, Content::replaceSection, etc. to handle sections..
1199 * @return bool Always false.
1201 public function supportsSections() {
1206 * Returns true if this content model supports categories.
1207 * The default implementation returns true.
1209 * @return bool Always true.
1211 public function supportsCategories() {
1216 * Returns true if this content model supports redirects.
1217 * This default implementation returns false.
1219 * Content models that return true here should also implement
1220 * ContentHandler::makeRedirectContent to return a Content object.
1222 * @return bool Always false.
1224 public function supportsRedirects() {
1229 * Return true if this content model supports direct editing, such as via EditPage.
1231 * @return bool Default is false, and true for TextContent and it's derivatives.
1233 public function supportsDirectEditing() {
1238 * Whether or not this content model supports direct editing via ApiEditPage
1240 * @return bool Default is false, and true for TextContent and derivatives.
1242 public function supportsDirectApiEditing() {
1243 return $this->supportsDirectEditing();
1247 * Get fields definition for search index
1249 * @todo Expose title, redirect, namespace, text, source_text, text_bytes
1250 * field mappings here. (see T142670 and T143409)
1252 * @param SearchEngine $engine
1253 * @return SearchIndexField[] List of fields this content handler can provide.
1256 public function getFieldsForSearchIndex( SearchEngine
$engine ) {
1257 $fields['category'] = $engine->makeSearchFieldMapping(
1259 SearchIndexField
::INDEX_TYPE_TEXT
1261 $fields['category']->setFlag( SearchIndexField
::FLAG_CASEFOLD
);
1263 $fields['external_link'] = $engine->makeSearchFieldMapping(
1265 SearchIndexField
::INDEX_TYPE_KEYWORD
1268 $fields['outgoing_link'] = $engine->makeSearchFieldMapping(
1270 SearchIndexField
::INDEX_TYPE_KEYWORD
1273 $fields['template'] = $engine->makeSearchFieldMapping(
1275 SearchIndexField
::INDEX_TYPE_KEYWORD
1277 $fields['template']->setFlag( SearchIndexField
::FLAG_CASEFOLD
);
1279 $fields['content_model'] = $engine->makeSearchFieldMapping(
1281 SearchIndexField
::INDEX_TYPE_KEYWORD
1288 * Add new field definition to array.
1289 * @param SearchIndexField[] &$fields
1290 * @param SearchEngine $engine
1291 * @param string $name
1293 * @return SearchIndexField[] new field defs
1296 protected function addSearchField( &$fields, SearchEngine
$engine, $name, $type ) {
1297 $fields[$name] = $engine->makeSearchFieldMapping( $name, $type );
1302 * Return fields to be indexed by search engine
1303 * as representation of this document.
1304 * Overriding class should call parent function or take care of calling
1305 * the SearchDataForIndex hook.
1306 * @param WikiPage $page Page to index
1307 * @param ParserOutput $output
1308 * @param SearchEngine $engine Search engine for which we are indexing
1309 * @return array Map of name=>value for fields
1312 public function getDataForSearchIndex(
1314 ParserOutput
$output,
1315 SearchEngine
$engine
1318 $content = $page->getContent();
1321 $searchDataExtractor = new ParserOutputSearchDataExtractor();
1323 $fieldData['category'] = $searchDataExtractor->getCategories( $output );
1324 $fieldData['external_link'] = $searchDataExtractor->getExternalLinks( $output );
1325 $fieldData['outgoing_link'] = $searchDataExtractor->getOutgoingLinks( $output );
1326 $fieldData['template'] = $searchDataExtractor->getTemplates( $output );
1328 $text = $content->getTextForSearchIndex();
1330 $fieldData['text'] = $text;
1331 $fieldData['source_text'] = $text;
1332 $fieldData['text_bytes'] = $content->getSize();
1333 $fieldData['content_model'] = $content->getModel();
1336 Hooks
::run( 'SearchDataForIndex', [ &$fieldData, $this, $page, $output, $engine ] );
1341 * Produce page output suitable for indexing.
1343 * Specific content handlers may override it if they need different content handling.
1345 * @param WikiPage $page
1346 * @param ParserCache|null $cache
1347 * @return ParserOutput
1349 public function getParserOutputForIndexing( WikiPage
$page, ParserCache
$cache = null ) {
1350 // TODO: MCR: ContentHandler should be called per slot, not for the whole page.
1352 $parserOptions = $page->makeParserOptions( 'canonical' );
1354 $parserOutput = $cache->get( $page, $parserOptions );
1357 if ( empty( $parserOutput ) ) {
1358 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
1360 $renderer->getRenderedRevision(
1361 $page->getRevision()->getRevisionRecord(),
1363 )->getRevisionParserOutput();
1365 $cache->save( $parserOutput, $page, $parserOptions );
1368 return $parserOutput;
1372 * Returns a list of DeferrableUpdate objects for recording information about the
1373 * given Content in some secondary data store.
1375 * Application logic should not call this method directly. Instead, it should call
1376 * DerivedPageDataUpdater::getSecondaryDataUpdates().
1378 * @note Implementations must not return a LinksUpdate instance. Instead, a LinksUpdate
1379 * is created by the calling code in DerivedPageDataUpdater, on the combined ParserOutput
1380 * of all slots, not for each slot individually. This is in contrast to the old
1381 * getSecondaryDataUpdates method defined by AbstractContent, which returned a LinksUpdate.
1383 * @note Implementations should not call $content->getParserOutput, they should call
1384 * $slotOutput->getSlotRendering( $role, false ) instead if they need to access a ParserOutput
1385 * of $content. This allows existing ParserOutput objects to be re-used, while avoiding
1386 * creating a ParserOutput when none is needed.
1388 * @param Title $title The title of the page to supply the updates for
1389 * @param Content $content The content to generate data updates for.
1390 * @param string $role The role (slot) in which the content is being used. Which updates
1391 * are performed should generally not depend on the role the content has, but the
1392 * DeferrableUpdates themselves may need to know the role, to track to which slot the
1393 * data refers, and to avoid overwriting data of the same kind from another slot.
1394 * @param SlotRenderingProvider $slotOutput A provider that can be used to gain access to
1395 * a ParserOutput of $content by calling $slotOutput->getSlotParserOutput( $role, false ).
1396 * @return DeferrableUpdate[] A list of DeferrableUpdate objects for putting information
1397 * about this content object somewhere. The default implementation returns an empty
1401 public function getSecondaryDataUpdates(
1405 SlotRenderingProvider
$slotOutput
1411 * Returns a list of DeferrableUpdate objects for removing information about content
1412 * in some secondary data store. This is used when a page is deleted, and also when
1413 * a slot is removed from a page.
1415 * Application logic should not call this method directly. Instead, it should call
1416 * WikiPage::getSecondaryDataUpdates().
1418 * @note Implementations must not return a LinksDeletionUpdate instance. Instead, a
1419 * LinksDeletionUpdate is created by the calling code in WikiPage.
1420 * This is in contrast to the old getDeletionUpdates method defined by AbstractContent,
1421 * which returned a LinksUpdate.
1423 * @note Implementations should not rely on the page's current content, but rather the current
1424 * state of the secondary data store.
1426 * @param Title $title The title of the page to supply the updates for
1427 * @param string $role The role (slot) in which the content is being used. Which updates
1428 * are performed should generally not depend on the role the content has, but the
1429 * DeferrableUpdates themselves may need to know the role, to track to which slot the
1430 * data refers, and to avoid overwriting data of the same kind from another slot.
1432 * @return DeferrableUpdate[] A list of DeferrableUpdate objects for putting information
1433 * about this content object somewhere. The default implementation returns an empty
1438 public function getDeletionUpdates( Title
$title, $role ) {