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\Search\ParserOutputSearchDataExtractor
;
34 * A content handler knows how do deal with a specific type of content on a wiki
35 * page. Content is stored in the database in a serialized form (using a
36 * serialization format a.k.a. MIME type) and is unserialized into its native
37 * PHP representation (the content model), which is wrapped in an instance of
38 * the appropriate subclass of Content.
40 * ContentHandler instances are stateless singletons that serve, among other
41 * things, as a factory for Content objects. Generally, there is one subclass
42 * of ContentHandler and one subclass of Content for every type of content model.
44 * Some content types have a flat model, that is, their native representation
45 * is the same as their serialized form. Examples would be JavaScript and CSS
46 * code. As of now, this also applies to wikitext (MediaWiki's default content
47 * type), but wikitext content may be represented by a DOM or AST structure in
52 abstract class ContentHandler
{
54 * Convenience function for getting flat text from a Content object. This
55 * should only be used in the context of backwards compatibility with code
56 * that is not yet able to handle Content objects!
58 * If $content is null, this method returns the empty string.
60 * If $content is an instance of TextContent, this method returns the flat
61 * text as returned by $content->getNativeData().
63 * If $content is not a TextContent object, the behavior of this method
64 * depends on the global $wgContentHandlerTextFallback:
65 * - If $wgContentHandlerTextFallback is 'fail' and $content is not a
66 * TextContent object, an MWException is thrown.
67 * - If $wgContentHandlerTextFallback is 'serialize' and $content is not a
68 * TextContent object, $content->serialize() is called to get a string
69 * form of the content.
70 * - If $wgContentHandlerTextFallback is 'ignore' and $content is not a
71 * TextContent object, this method returns null.
72 * - otherwise, the behavior is undefined.
76 * @param Content|null $content
78 * @throws MWException If the content is not an instance of TextContent and
79 * wgContentHandlerTextFallback was set to 'fail'.
80 * @return string|null Textual form of the content, if available.
82 public static function getContentText( Content
$content = null ) {
83 global $wgContentHandlerTextFallback;
85 if ( is_null( $content ) ) {
89 if ( $content instanceof TextContent
) {
90 return $content->getNativeData();
93 wfDebugLog( 'ContentHandler', 'Accessing ' . $content->getModel() . ' content as text!' );
95 if ( $wgContentHandlerTextFallback == 'fail' ) {
96 throw new MWException(
97 "Attempt to get text from Content with model " .
102 if ( $wgContentHandlerTextFallback == 'serialize' ) {
103 return $content->serialize();
110 * Convenience function for creating a Content object from a given textual
113 * $text will be deserialized into a Content object of the model specified
114 * by $modelId (or, if that is not given, $title->getContentModel()) using
119 * @param string $text The textual representation, will be
120 * unserialized to create the Content object
121 * @param Title|null $title The title of the page this text belongs to.
122 * Required if $modelId is not provided.
123 * @param string|null $modelId The model to deserialize to. If not provided,
124 * $title->getContentModel() is used.
125 * @param string|null $format The format to use for deserialization. If not
126 * given, the model's default format is used.
128 * @throws MWException If model ID or format is not supported or if the text can not be
129 * unserialized using the format.
130 * @return Content A Content object representing the text.
132 public static function makeContent( $text, Title
$title = null,
133 $modelId = null, $format = null ) {
134 if ( is_null( $modelId ) ) {
135 if ( is_null( $title ) ) {
136 throw new MWException( "Must provide a Title object or a content model ID." );
139 $modelId = $title->getContentModel();
142 $handler = self
::getForModelID( $modelId );
144 return $handler->unserializeContent( $text, $format );
148 * Returns the name of the default content model to be used for the page
149 * with the given title.
151 * Note: There should rarely be need to call this method directly.
152 * To determine the actual content model for a given page, use
153 * Title::getContentModel().
155 * Which model is to be used by default for the page is determined based
156 * on several factors:
157 * - The global setting $wgNamespaceContentModels specifies a content model
159 * - The hook ContentHandlerDefaultModelFor may be used to override the page's default
161 * - Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript
162 * model if they end in .js or .css, respectively.
163 * - Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
164 * - The hook TitleIsCssOrJsPage may be used to force a page to use the CSS
165 * or JavaScript model. This is a compatibility feature. The ContentHandlerDefaultModelFor
166 * hook should be used instead if possible.
167 * - The hook TitleIsWikitextPage may be used to force a page to use the
168 * wikitext model. This is a compatibility feature. The ContentHandlerDefaultModelFor
169 * hook should be used instead if possible.
171 * If none of the above applies, the wikitext model is used.
173 * Note: this is used by, and may thus not use, Title::getContentModel()
177 * @param Title $title
179 * @return string Default model name for the page given by $title
181 public static function getDefaultModelFor( Title
$title ) {
182 // NOTE: this method must not rely on $title->getContentModel() directly or indirectly,
183 // because it is used to initialize the mContentModel member.
185 $ns = $title->getNamespace();
189 $model = MWNamespace
::getNamespaceContentModel( $ns );
191 // Hook can determine default model
192 if ( !Hooks
::run( 'ContentHandlerDefaultModelFor', [ $title, &$model ] ) ) {
193 if ( !is_null( $model ) ) {
198 // Could this page contain code based on the title?
199 $isCodePage = NS_MEDIAWIKI
== $ns && preg_match( '!\.(css|js|json)$!u', $title->getText(), $m );
204 // Is this a user subpage containing code?
205 $isCodeSubpage = NS_USER
== $ns
207 && preg_match( "/\\/.*\\.(js|css|json)$/", $title->getText(), $m );
208 if ( $isCodeSubpage ) {
212 // Is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
213 $isWikitext = is_null( $model ) ||
$model == CONTENT_MODEL_WIKITEXT
;
214 $isWikitext = $isWikitext && !$isCodePage && !$isCodeSubpage;
216 if ( !$isWikitext ) {
219 return CONTENT_MODEL_JAVASCRIPT
;
221 return CONTENT_MODEL_CSS
;
223 return CONTENT_MODEL_JSON
;
225 return is_null( $model ) ? CONTENT_MODEL_TEXT
: $model;
229 // We established that it must be wikitext
231 return CONTENT_MODEL_WIKITEXT
;
235 * Returns the appropriate ContentHandler singleton for the given title.
239 * @param Title $title
241 * @return ContentHandler
243 public static function getForTitle( Title
$title ) {
244 $modelId = $title->getContentModel();
246 return self
::getForModelID( $modelId );
250 * Returns the appropriate ContentHandler singleton for the given Content
255 * @param Content $content
257 * @return ContentHandler
259 public static function getForContent( Content
$content ) {
260 $modelId = $content->getModel();
262 return self
::getForModelID( $modelId );
266 * @var array A Cache of ContentHandler instances by model id
268 protected static $handlers;
271 * Returns the ContentHandler singleton for the given model ID. Use the
272 * CONTENT_MODEL_XXX constants to identify the desired content model.
274 * ContentHandler singletons are taken from the global $wgContentHandlers
275 * array. Keys in that array are model names, the values are either
276 * ContentHandler singleton objects, or strings specifying the appropriate
277 * subclass of ContentHandler.
279 * If a class name is encountered when looking up the singleton for a given
280 * model name, the class is instantiated and the class name is replaced by
281 * the resulting singleton in $wgContentHandlers.
283 * If no ContentHandler is defined for the desired $modelId, the
284 * ContentHandler may be provided by the ContentHandlerForModelID hook.
285 * If no ContentHandler can be determined, an MWException is raised.
289 * @param string $modelId The ID of the content model for which to get a
290 * handler. Use CONTENT_MODEL_XXX constants.
292 * @throws MWException For internal errors and problems in the configuration.
293 * @throws MWUnknownContentModelException If no handler is known for the model ID.
294 * @return ContentHandler The ContentHandler singleton for handling the model given by the ID.
296 public static function getForModelID( $modelId ) {
297 global $wgContentHandlers;
299 if ( isset( self
::$handlers[$modelId] ) ) {
300 return self
::$handlers[$modelId];
303 if ( empty( $wgContentHandlers[$modelId] ) ) {
306 Hooks
::run( 'ContentHandlerForModelID', [ $modelId, &$handler ] );
308 if ( $handler === null ) {
309 throw new MWUnknownContentModelException( $modelId );
312 if ( !( $handler instanceof ContentHandler
) ) {
313 throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
316 $classOrCallback = $wgContentHandlers[$modelId];
318 if ( is_callable( $classOrCallback ) ) {
319 $handler = call_user_func( $classOrCallback, $modelId );
321 $handler = new $classOrCallback( $modelId );
324 if ( !( $handler instanceof ContentHandler
) ) {
325 throw new MWException( "$classOrCallback from \$wgContentHandlers is not " .
326 "compatible with ContentHandler" );
330 wfDebugLog( 'ContentHandler', 'Created handler for ' . $modelId
331 . ': ' . get_class( $handler ) );
333 self
::$handlers[$modelId] = $handler;
335 return self
::$handlers[$modelId];
339 * Clean up handlers cache.
341 public static function cleanupHandlersCache() {
342 self
::$handlers = [];
346 * Returns the localized name for a given content model.
348 * Model names are localized using system messages. Message keys
349 * have the form content-model-$name, where $name is getContentModelName( $id ).
351 * @param string $name The content model ID, as given by a CONTENT_MODEL_XXX
352 * constant or returned by Revision::getContentModel().
353 * @param Language|null $lang The language to parse the message in (since 1.26)
355 * @throws MWException If the model ID isn't known.
356 * @return string The content model's localized name.
358 public static function getLocalizedName( $name, Language
$lang = null ) {
359 // Messages: content-model-wikitext, content-model-text,
360 // content-model-javascript, content-model-css
361 $key = "content-model-$name";
363 $msg = wfMessage( $key );
365 $msg->inLanguage( $lang );
368 return $msg->exists() ?
$msg->plain() : $name;
371 public static function getContentModels() {
372 global $wgContentHandlers;
374 $models = array_keys( $wgContentHandlers );
375 Hooks
::run( 'GetContentModels', [ &$models ] );
379 public static function getAllContentFormats() {
380 global $wgContentHandlers;
384 foreach ( $wgContentHandlers as $model => $class ) {
385 $handler = self
::getForModelID( $model );
386 $formats = array_merge( $formats, $handler->getSupportedFormats() );
389 $formats = array_unique( $formats );
394 // ------------------------------------------------------------------------
404 protected $mSupportedFormats;
407 * Constructor, initializing the ContentHandler instance with its model ID
408 * and a list of supported formats. Values for the parameters are typically
409 * provided as literals by subclass's constructors.
411 * @param string $modelId (use CONTENT_MODEL_XXX constants).
412 * @param string[] $formats List for supported serialization formats
413 * (typically as MIME types)
415 public function __construct( $modelId, $formats ) {
416 $this->mModelID
= $modelId;
417 $this->mSupportedFormats
= $formats;
421 * Serializes a Content object of the type supported by this ContentHandler.
425 * @param Content $content The Content object to serialize
426 * @param string|null $format The desired serialization format
428 * @return string Serialized form of the content
430 abstract public function serializeContent( Content
$content, $format = null );
433 * Applies transformations on export (returns the blob unchanged per default).
434 * Subclasses may override this to perform transformations such as conversion
435 * of legacy formats or filtering of internal meta-data.
437 * @param string $blob The blob to be exported
438 * @param string|null $format The blob's serialization format
442 public function exportTransform( $blob, $format = null ) {
447 * Unserializes a Content object of the type supported by this ContentHandler.
451 * @param string $blob Serialized form of the content
452 * @param string|null $format The format used for serialization
454 * @return Content The Content object created by deserializing $blob
456 abstract public function unserializeContent( $blob, $format = null );
459 * Apply import transformation (per default, returns $blob unchanged).
460 * This gives subclasses an opportunity to transform data blobs on import.
464 * @param string $blob
465 * @param string|null $format
469 public function importTransform( $blob, $format = null ) {
474 * Creates an empty Content object of the type supported by this
481 abstract public function makeEmptyContent();
484 * Creates a new Content object that acts as a redirect to the given page,
485 * or null if redirects are not supported by this content model.
487 * This default implementation always returns null. Subclasses supporting redirects
488 * must override this method.
490 * Note that subclasses that override this method to return a Content object
491 * should also override supportsRedirects() to return true.
495 * @param Title $destination The page to redirect to.
496 * @param string $text Text to include in the redirect, if possible.
498 * @return Content Always null.
500 public function makeRedirectContent( Title
$destination, $text = '' ) {
505 * Returns the model id that identifies the content model this
506 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
510 * @return string The model ID
512 public function getModelID() {
513 return $this->mModelID
;
519 * @param string $model_id The model to check
521 * @throws MWException If the model ID is not the ID of the content model supported by this
524 protected function checkModelID( $model_id ) {
525 if ( $model_id !== $this->mModelID
) {
526 throw new MWException( "Bad content model: " .
527 "expected {$this->mModelID} " .
528 "but got $model_id." );
533 * Returns a list of serialization formats supported by the
534 * serializeContent() and unserializeContent() methods of this
539 * @return string[] List of serialization formats as MIME type like strings
541 public function getSupportedFormats() {
542 return $this->mSupportedFormats
;
546 * The format used for serialization/deserialization by default by this
549 * This default implementation will return the first element of the array
550 * of formats that was passed to the constructor.
554 * @return string The name of the default serialization format as a MIME type
556 public function getDefaultFormat() {
557 return $this->mSupportedFormats
[0];
561 * Returns true if $format is a serialization format supported by this
562 * ContentHandler, and false otherwise.
564 * Note that if $format is null, this method always returns true, because
565 * null means "use the default format".
569 * @param string $format The serialization format to check
573 public function isSupportedFormat( $format ) {
575 return true; // this means "use the default"
578 return in_array( $format, $this->mSupportedFormats
);
582 * Convenient for checking whether a format provided as a parameter is actually supported.
584 * @param string $format The serialization format to check
586 * @throws MWException If the format is not supported by this content handler.
588 protected function checkFormat( $format ) {
589 if ( !$this->isSupportedFormat( $format ) ) {
590 throw new MWException(
591 "Format $format is not supported for content model "
592 . $this->getModelID()
598 * Returns overrides for action handlers.
599 * Classes listed here will be used instead of the default one when
600 * (and only when) $wgActions[$action] === true. This allows subclasses
601 * to override the default action handlers.
605 * @return array An array mapping action names (typically "view", "edit", "history" etc.) to
606 * either the full qualified class name of an Action class, a callable taking ( Page $page,
607 * IContextSource $context = null ) as parameters and returning an Action object, or an actual
608 * Action object. An empty array in this default implementation.
610 * @see Action::factory
612 public function getActionOverrides() {
617 * Factory for creating an appropriate DifferenceEngine for this content model.
618 * Since 1.32, this is only used for page-level diffs; to diff two content objects,
619 * use getSlotDiffRenderer.
621 * The DifferenceEngine subclass to use is selected in getDiffEngineClass(). The
622 * GetDifferenceEngine hook will receive the DifferenceEngine object and can replace or
624 * (Note that in older versions of MediaWiki the hook documentation instructed extensions
625 * to return false from the hook; you should not rely on always being able to decorate
626 * the DifferenceEngine instance from the hook. If the owner of the content type wants to
627 * decorare the instance, overriding this method is a safer approach.)
629 * @todo This is page-level functionality so it should not belong to ContentHandler.
630 * Move it to a better place once one exists (e.g. PageTypeHandler).
634 * @param IContextSource $context Context to use, anything else will be ignored.
635 * @param int $old Revision ID we want to show and diff with.
636 * @param int|string $new Either a revision ID or one of the strings 'cur', 'prev' or 'next'.
637 * @param int $rcid FIXME: Deprecated, no longer used. Defaults to 0.
638 * @param bool $refreshCache If set, refreshes the diff cache. Defaults to false.
639 * @param bool $unhide If set, allow viewing deleted revs. Defaults to false.
641 * @return DifferenceEngine
643 public function createDifferenceEngine( IContextSource
$context, $old = 0, $new = 0,
644 $rcid = 0, // FIXME: Deprecated, no longer used
645 $refreshCache = false, $unhide = false
647 $diffEngineClass = $this->getDiffEngineClass();
648 $differenceEngine = new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
649 Hooks
::run( 'GetDifferenceEngine', [ $context, $old, $new, $refreshCache, $unhide,
650 &$differenceEngine ] );
651 return $differenceEngine;
655 * Get an appropriate SlotDiffRenderer for this content model.
657 * @param IContextSource $context
658 * @return SlotDiffRenderer
660 final public function getSlotDiffRenderer( IContextSource
$context ) {
661 $slotDiffRenderer = $this->getSlotDiffRendererInternal( $context );
662 if ( get_class( $slotDiffRenderer ) === TextSlotDiffRenderer
::class ) {
663 // To keep B/C, when SlotDiffRenderer is not overridden for a given content type
664 // but DifferenceEngine is, use that instead.
665 $differenceEngine = $this->createDifferenceEngine( $context );
666 if ( get_class( $differenceEngine ) !== DifferenceEngine
::class ) {
667 // TODO turn this into a deprecation warning in a later release
668 LoggerFactory
::getInstance( 'diff' )->info(
669 'Falling back to DifferenceEngineSlotDiffRenderer', [
670 'modelID' => $this->getModelID(),
671 'DifferenceEngine' => get_class( $differenceEngine ),
673 $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
676 Hooks
::run( 'GetSlotDiffRenderer', [ $this, &$slotDiffRenderer, $context ] );
677 return $slotDiffRenderer;
681 * Return the SlotDiffRenderer appropriate for this content handler.
682 * @param IContextSource $context
683 * @return SlotDiffRenderer
685 protected function getSlotDiffRendererInternal( IContextSource
$context ) {
686 $contentLanguage = MediaWikiServices
::getInstance()->getContentLanguage();
687 $statsdDataFactory = MediaWikiServices
::getInstance()->getStatsdDataFactory();
688 $slotDiffRenderer = new TextSlotDiffRenderer();
689 $slotDiffRenderer->setStatsdDataFactory( $statsdDataFactory );
690 // XXX using the page language would be better, but it's unclear how that should be injected
691 $slotDiffRenderer->setLanguage( $contentLanguage );
692 $slotDiffRenderer->setWikiDiff2MovedParagraphDetectionCutoff(
693 $context->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
696 $engine = DifferenceEngine
::getEngine();
697 if ( $engine === false ) {
698 $slotDiffRenderer->setEngine( TextSlotDiffRenderer
::ENGINE_PHP
);
699 } elseif ( $engine === 'wikidiff2' ) {
700 $slotDiffRenderer->setEngine( TextSlotDiffRenderer
::ENGINE_WIKIDIFF2
);
702 $slotDiffRenderer->setEngine( TextSlotDiffRenderer
::ENGINE_EXTERNAL
, $engine );
705 return $slotDiffRenderer;
709 * Get the language in which the content of the given page is written.
711 * This default implementation just returns the content language (except for pages
712 * in the MediaWiki namespace)
714 * Note that the pages language is not cacheable, since it may in some
715 * cases depend on user settings.
717 * Also note that the page language may or may not depend on the actual content of the page,
718 * that is, this method may load the content in order to determine the language.
722 * @param Title $title The page to determine the language for.
723 * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
725 * @return Language The page's language
727 public function getPageLanguage( Title
$title, Content
$content = null ) {
729 $pageLang = MediaWikiServices
::getInstance()->getContentLanguage();
731 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
732 // Parse mediawiki messages with correct target language
733 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $title->getText() );
734 $pageLang = Language
::factory( $lang );
737 Hooks
::run( 'PageContentLanguage', [ $title, &$pageLang, $wgLang ] );
739 return wfGetLangObj( $pageLang );
743 * Get the language in which the content of this page is written when
744 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
745 * specified a preferred variant, the variant will be used.
747 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
748 * the user specified a preferred variant.
750 * Note that the pages view language is not cacheable, since it depends on user settings.
752 * Also note that the page language may or may not depend on the actual content of the page,
753 * that is, this method may load the content in order to determine the language.
757 * @param Title $title The page to determine the language for.
758 * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
760 * @return Language The page's language for viewing
762 public function getPageViewLanguage( Title
$title, Content
$content = null ) {
763 $pageLang = $this->getPageLanguage( $title, $content );
765 if ( $title->getNamespace() !== NS_MEDIAWIKI
) {
766 // If the user chooses a variant, the content is actually
767 // in a language whose code is the variant code.
768 $variant = $pageLang->getPreferredVariant();
769 if ( $pageLang->getCode() !== $variant ) {
770 $pageLang = Language
::factory( $variant );
778 * Determines whether the content type handled by this ContentHandler
779 * can be used on the given page.
781 * This default implementation always returns true.
782 * Subclasses may override this to restrict the use of this content model to specific locations,
783 * typically based on the namespace or some other aspect of the title, such as a special suffix
784 * (e.g. ".svg" for SVG content).
786 * @note this calls the ContentHandlerCanBeUsedOn hook which may be used to override which
787 * content model can be used where.
789 * @param Title $title The page's title.
791 * @return bool True if content of this kind can be used on the given page, false otherwise.
793 public function canBeUsedOn( Title
$title ) {
796 Hooks
::run( 'ContentModelCanBeUsedOn', [ $this->getModelID(), $title, &$ok ] );
802 * Returns the name of the diff engine to use.
808 protected function getDiffEngineClass() {
809 return DifferenceEngine
::class;
813 * Attempts to merge differences between three versions. Returns a new
814 * Content object for a clean merge and false for failure or a conflict.
816 * This default implementation always returns false.
820 * @param Content $oldContent The page's previous content.
821 * @param Content $myContent One of the page's conflicting contents.
822 * @param Content $yourContent One of the page's conflicting contents.
824 * @return Content|bool Always false.
826 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
831 * Return type of change if one exists for the given edit.
835 * @param Content|null $oldContent The previous text of the page.
836 * @param Content|null $newContent The submitted text of the page.
837 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
839 * @return string|null String key representing type of change, or null.
841 private function getChangeType(
842 Content
$oldContent = null,
843 Content
$newContent = null,
846 $oldTarget = $oldContent !== null ?
$oldContent->getRedirectTarget() : null;
847 $newTarget = $newContent !== null ?
$newContent->getRedirectTarget() : null;
849 // We check for the type of change in the given edit, and return string key accordingly
851 // Blanking of a page
852 if ( $oldContent && $oldContent->getSize() > 0 &&
853 $newContent && $newContent->getSize() === 0
861 // New redirect page (by creating new page or by changing content page)
862 return 'new-redirect';
863 } elseif ( !$newTarget->equals( $oldTarget ) ||
864 $oldTarget->getFragment() !== $newTarget->getFragment()
866 // Redirect target changed
867 return 'changed-redirect-target';
869 } elseif ( $oldTarget ) {
870 // Changing an existing redirect into a non-redirect
871 return 'removed-redirect';
875 if ( $flags & EDIT_NEW
&& $newContent ) {
876 if ( $newContent->getSize() === 0 ) {
884 // Removing more than 90% of the page
885 if ( $oldContent && $newContent && $oldContent->getSize() > 10 * $newContent->getSize() ) {
889 // Content model changed
890 if ( $oldContent && $newContent && $oldContent->getModel() !== $newContent->getModel() ) {
891 return 'contentmodelchange';
898 * Return an applicable auto-summary if one exists for the given edit.
902 * @param Content|null $oldContent The previous text of the page.
903 * @param Content|null $newContent The submitted text of the page.
904 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
906 * @return string An appropriate auto-summary, or an empty string.
908 public function getAutosummary(
909 Content
$oldContent = null,
910 Content
$newContent = null,
913 $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
915 // There's no applicable auto-summary for our case, so our auto-summary is empty.
916 if ( !$changeType ) {
920 // Decide what kind of auto-summary is needed.
921 switch ( $changeType ) {
923 $newTarget = $newContent->getRedirectTarget();
924 $truncatedtext = $newContent->getTextForSummary(
926 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
927 - strlen( $newTarget->getFullText() )
930 return wfMessage( 'autoredircomment', $newTarget->getFullText() )
931 ->plaintextParams( $truncatedtext )->inContentLanguage()->text();
932 case 'changed-redirect-target':
933 $oldTarget = $oldContent->getRedirectTarget();
934 $newTarget = $newContent->getRedirectTarget();
936 $truncatedtext = $newContent->getTextForSummary(
938 - strlen( wfMessage( 'autosumm-changed-redirect-target' )
939 ->inContentLanguage()->text() )
940 - strlen( $oldTarget->getFullText() )
941 - strlen( $newTarget->getFullText() )
944 return wfMessage( 'autosumm-changed-redirect-target',
945 $oldTarget->getFullText(),
946 $newTarget->getFullText() )
947 ->rawParams( $truncatedtext )->inContentLanguage()->text();
948 case 'removed-redirect':
949 $oldTarget = $oldContent->getRedirectTarget();
950 $truncatedtext = $newContent->getTextForSummary(
952 - strlen( wfMessage( 'autosumm-removed-redirect' )
953 ->inContentLanguage()->text() )
954 - strlen( $oldTarget->getFullText() ) );
956 return wfMessage( 'autosumm-removed-redirect', $oldTarget->getFullText() )
957 ->rawParams( $truncatedtext )->inContentLanguage()->text();
959 // If they're making a new article, give its text, truncated, in the summary.
960 $truncatedtext = $newContent->getTextForSummary(
961 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
963 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
964 ->inContentLanguage()->text();
966 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
968 $truncatedtext = $newContent->getTextForSummary(
969 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
971 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
972 ->inContentLanguage()->text();
974 return wfMessage( 'autosumm-newblank' )->inContentLanguage()->text();
981 * Return an applicable tag if one exists for the given edit or return null.
985 * @param Content|null $oldContent The previous text of the page.
986 * @param Content|null $newContent The submitted text of the page.
987 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
989 * @return string|null An appropriate tag, or null.
991 public function getChangeTag(
992 Content
$oldContent = null,
993 Content
$newContent = null,
996 $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
998 // There's no applicable tag for this change.
999 if ( !$changeType ) {
1003 // Core tags use the same keys as ones returned from $this->getChangeType()
1004 // but prefixed with pseudo namespace 'mw-', so we add the prefix before checking
1005 // if this type of change should be tagged
1006 $tag = 'mw-' . $changeType;
1008 // Not all change types are tagged, so we check against the list of defined tags.
1009 if ( in_array( $tag, ChangeTags
::getSoftwareTags() ) ) {
1017 * Auto-generates a deletion reason
1021 * @param Title $title The page's title
1022 * @param bool &$hasHistory Whether the page has a history
1024 * @return mixed String containing deletion reason or empty string, or
1025 * boolean false if no revision occurred
1027 * @todo &$hasHistory is extremely ugly, it's here because
1028 * WikiPage::getAutoDeleteReason() and Article::generateReason()
1029 * have it / want it.
1031 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
1032 $dbr = wfGetDB( DB_REPLICA
);
1034 // Get the last revision
1035 $rev = Revision
::newFromTitle( $title );
1037 if ( is_null( $rev ) ) {
1041 // Get the article's contents
1042 $content = $rev->getContent();
1045 // If the page is blank, use the text from the previous revision,
1046 // which can only be blank if there's a move/import/protect dummy
1047 // revision involved
1048 if ( !$content ||
$content->isEmpty() ) {
1049 $prev = $rev->getPrevious();
1053 $content = $rev->getContent();
1058 $this->checkModelID( $rev->getContentModel() );
1060 // Find out if there was only one contributor
1061 // Only scan the last 20 revisions
1062 $revQuery = Revision
::getQueryInfo();
1063 $res = $dbr->select(
1064 $revQuery['tables'],
1065 [ 'rev_user_text' => $revQuery['fields']['rev_user_text'] ],
1067 'rev_page' => $title->getArticleID(),
1068 $dbr->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0'
1075 if ( $res === false ) {
1076 // This page has no revisions, which is very weird
1080 $hasHistory = ( $res->numRows() > 1 );
1081 $row = $dbr->fetchObject( $res );
1083 if ( $row ) { // $row is false if the only contributor is hidden
1084 $onlyAuthor = $row->rev_user_text
;
1085 // Try to find a second contributor
1086 foreach ( $res as $row ) {
1087 if ( $row->rev_user_text
!= $onlyAuthor ) { // T24999
1088 $onlyAuthor = false;
1093 $onlyAuthor = false;
1096 // Generate the summary with a '$1' placeholder
1098 // The current revision is blank and the one before is also
1099 // blank. It's just not our lucky day
1100 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
1102 if ( $onlyAuthor ) {
1103 $reason = wfMessage(
1107 )->inContentLanguage()->text();
1109 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
1113 if ( $reason == '-' ) {
1114 // Allow these UI messages to be blanked out cleanly
1118 // Max content length = max comment length - length of the comment (excl. $1)
1119 $text = $content ?
$content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) : '';
1121 // Now replace the '$1' placeholder
1122 $reason = str_replace( '$1', $text, $reason );
1128 * Get the Content object that needs to be saved in order to undo all revisions
1129 * between $undo and $undoafter. Revisions must belong to the same page,
1130 * must exist and must not be deleted.
1133 * @since 1.32 accepts Content objects for all parameters instead of Revision objects.
1134 * Passing Revision objects is deprecated.
1136 * @param Revision|Content $current The current text
1137 * @param Revision|Content $undo The content of the revision to undo
1138 * @param Revision|Content $undoafter Must be from an earlier revision than $undo
1139 * @param bool $undoIsLatest Set true if $undo is from the current revision (since 1.32)
1141 * @return mixed Content on success, false on failure
1143 public function getUndoContent( $current, $undo, $undoafter, $undoIsLatest = false ) {
1144 Assert
::parameterType( Revision
::class . '|' . Content
::class, $current, '$current' );
1145 if ( $current instanceof Content
) {
1146 Assert
::parameter( $undo instanceof Content
, '$undo',
1147 'Must be Content when $current is Content' );
1148 Assert
::parameter( $undoafter instanceof Content
, '$undoafter',
1149 'Must be Content when $current is Content' );
1150 $cur_content = $current;
1151 $undo_content = $undo;
1152 $undoafter_content = $undoafter;
1154 Assert
::parameter( $undo instanceof Revision
, '$undo',
1155 'Must be Revision when $current is Revision' );
1156 Assert
::parameter( $undoafter instanceof Revision
, '$undoafter',
1157 'Must be Revision when $current is Revision' );
1159 $cur_content = $current->getContent();
1161 if ( empty( $cur_content ) ) {
1162 return false; // no page
1165 $undo_content = $undo->getContent();
1166 $undoafter_content = $undoafter->getContent();
1168 if ( !$undo_content ||
!$undoafter_content ) {
1169 return false; // no content to undo
1172 $undoIsLatest = $current->getId() === $undo->getId();
1176 $this->checkModelID( $cur_content->getModel() );
1177 $this->checkModelID( $undo_content->getModel() );
1178 if ( !$undoIsLatest ) {
1179 // If we are undoing the most recent revision,
1180 // its ok to revert content model changes. However
1181 // if we are undoing a revision in the middle, then
1182 // doing that will be confusing.
1183 $this->checkModelID( $undoafter_content->getModel() );
1185 } catch ( MWException
$e ) {
1186 // If the revisions have different content models
1187 // just return false
1191 if ( $cur_content->equals( $undo_content ) ) {
1192 // No use doing a merge if it's just a straight revert.
1193 return $undoafter_content;
1196 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
1198 return $undone_content;
1202 * Get parser options suitable for rendering and caching the article
1204 * @deprecated since 1.32, use WikiPage::makeParserOptions() or
1205 * ParserOptions::newCanonical() instead.
1206 * @param IContextSource|User|string $context One of the following:
1207 * - IContextSource: Use the User and the Language of the provided
1209 * - User: Use the provided User object and $wgLang for the language,
1210 * so use an IContextSource object if possible.
1211 * - 'canonical': Canonical options (anonymous user with default
1212 * preferences and content language).
1214 * @throws MWException
1215 * @return ParserOptions
1217 public function makeParserOptions( $context ) {
1218 wfDeprecated( __METHOD__
, '1.32' );
1219 return ParserOptions
::newCanonical( $context );
1223 * Returns true for content models that support caching using the
1224 * ParserCache mechanism. See WikiPage::shouldCheckParserCache().
1228 * @return bool Always false.
1230 public function isParserCacheSupported() {
1235 * Returns true if this content model supports sections.
1236 * This default implementation returns false.
1238 * Content models that return true here should also implement
1239 * Content::getSection, Content::replaceSection, etc. to handle sections..
1241 * @return bool Always false.
1243 public function supportsSections() {
1248 * Returns true if this content model supports categories.
1249 * The default implementation returns true.
1251 * @return bool Always true.
1253 public function supportsCategories() {
1258 * Returns true if this content model supports redirects.
1259 * This default implementation returns false.
1261 * Content models that return true here should also implement
1262 * ContentHandler::makeRedirectContent to return a Content object.
1264 * @return bool Always false.
1266 public function supportsRedirects() {
1271 * Return true if this content model supports direct editing, such as via EditPage.
1273 * @return bool Default is false, and true for TextContent and it's derivatives.
1275 public function supportsDirectEditing() {
1280 * Whether or not this content model supports direct editing via ApiEditPage
1282 * @return bool Default is false, and true for TextContent and derivatives.
1284 public function supportsDirectApiEditing() {
1285 return $this->supportsDirectEditing();
1289 * Get fields definition for search index
1291 * @todo Expose title, redirect, namespace, text, source_text, text_bytes
1292 * field mappings here. (see T142670 and T143409)
1294 * @param SearchEngine $engine
1295 * @return SearchIndexField[] List of fields this content handler can provide.
1298 public function getFieldsForSearchIndex( SearchEngine
$engine ) {
1299 $fields['category'] = $engine->makeSearchFieldMapping(
1301 SearchIndexField
::INDEX_TYPE_TEXT
1303 $fields['category']->setFlag( SearchIndexField
::FLAG_CASEFOLD
);
1305 $fields['external_link'] = $engine->makeSearchFieldMapping(
1307 SearchIndexField
::INDEX_TYPE_KEYWORD
1310 $fields['outgoing_link'] = $engine->makeSearchFieldMapping(
1312 SearchIndexField
::INDEX_TYPE_KEYWORD
1315 $fields['template'] = $engine->makeSearchFieldMapping(
1317 SearchIndexField
::INDEX_TYPE_KEYWORD
1319 $fields['template']->setFlag( SearchIndexField
::FLAG_CASEFOLD
);
1321 $fields['content_model'] = $engine->makeSearchFieldMapping(
1323 SearchIndexField
::INDEX_TYPE_KEYWORD
1330 * Add new field definition to array.
1331 * @param SearchIndexField[] &$fields
1332 * @param SearchEngine $engine
1333 * @param string $name
1335 * @return SearchIndexField[] new field defs
1338 protected function addSearchField( &$fields, SearchEngine
$engine, $name, $type ) {
1339 $fields[$name] = $engine->makeSearchFieldMapping( $name, $type );
1344 * Return fields to be indexed by search engine
1345 * as representation of this document.
1346 * Overriding class should call parent function or take care of calling
1347 * the SearchDataForIndex hook.
1348 * @param WikiPage $page Page to index
1349 * @param ParserOutput $output
1350 * @param SearchEngine $engine Search engine for which we are indexing
1351 * @return array Map of name=>value for fields
1354 public function getDataForSearchIndex(
1356 ParserOutput
$output,
1357 SearchEngine
$engine
1360 $content = $page->getContent();
1363 $searchDataExtractor = new ParserOutputSearchDataExtractor();
1365 $fieldData['category'] = $searchDataExtractor->getCategories( $output );
1366 $fieldData['external_link'] = $searchDataExtractor->getExternalLinks( $output );
1367 $fieldData['outgoing_link'] = $searchDataExtractor->getOutgoingLinks( $output );
1368 $fieldData['template'] = $searchDataExtractor->getTemplates( $output );
1370 $text = $content->getTextForSearchIndex();
1372 $fieldData['text'] = $text;
1373 $fieldData['source_text'] = $text;
1374 $fieldData['text_bytes'] = $content->getSize();
1375 $fieldData['content_model'] = $content->getModel();
1378 Hooks
::run( 'SearchDataForIndex', [ &$fieldData, $this, $page, $output, $engine ] );
1383 * Produce page output suitable for indexing.
1385 * Specific content handlers may override it if they need different content handling.
1387 * @param WikiPage $page
1388 * @param ParserCache|null $cache
1389 * @return ParserOutput
1391 public function getParserOutputForIndexing( WikiPage
$page, ParserCache
$cache = null ) {
1392 // TODO: MCR: ContentHandler should be called per slot, not for the whole page.
1394 $parserOptions = $page->makeParserOptions( 'canonical' );
1396 $parserOutput = $cache->get( $page, $parserOptions );
1399 if ( empty( $parserOutput ) ) {
1400 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
1402 $renderer->getRenderedRevision(
1403 $page->getRevision()->getRevisionRecord(),
1405 )->getRevisionParserOutput();
1407 $cache->save( $parserOutput, $page, $parserOptions );
1410 return $parserOutput;