3 use MediaWiki\MediaWikiServices
;
4 use MediaWiki\Search\ParserOutputSearchDataExtractor
;
7 * Base class for content handling.
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * @author Daniel Kinzler
32 * A content handler knows how do deal with a specific type of content on a wiki
33 * page. Content is stored in the database in a serialized form (using a
34 * serialization format a.k.a. MIME type) and is unserialized into its native
35 * PHP representation (the content model), which is wrapped in an instance of
36 * the appropriate subclass of Content.
38 * ContentHandler instances are stateless singletons that serve, among other
39 * things, as a factory for Content objects. Generally, there is one subclass
40 * of ContentHandler and one subclass of Content for every type of content model.
42 * Some content types have a flat model, that is, their native representation
43 * is the same as their serialized form. Examples would be JavaScript and CSS
44 * code. As of now, this also applies to wikitext (MediaWiki's default content
45 * type), but wikitext content may be represented by a DOM or AST structure in
50 abstract class ContentHandler
{
52 * Convenience function for getting flat text from a Content object. This
53 * should only be used in the context of backwards compatibility with code
54 * that is not yet able to handle Content objects!
56 * If $content is null, this method returns the empty string.
58 * If $content is an instance of TextContent, this method returns the flat
59 * text as returned by $content->getNativeData().
61 * If $content is not a TextContent object, the behavior of this method
62 * depends on the global $wgContentHandlerTextFallback:
63 * - If $wgContentHandlerTextFallback is 'fail' and $content is not a
64 * TextContent object, an MWException is thrown.
65 * - If $wgContentHandlerTextFallback is 'serialize' and $content is not a
66 * TextContent object, $content->serialize() is called to get a string
67 * form of the content.
68 * - If $wgContentHandlerTextFallback is 'ignore' and $content is not a
69 * TextContent object, this method returns null.
70 * - otherwise, the behavior is undefined.
74 * @param Content|null $content
76 * @throws MWException If the content is not an instance of TextContent and
77 * wgContentHandlerTextFallback was set to 'fail'.
78 * @return string|null Textual form of the content, if available.
80 public static function getContentText( Content
$content = null ) {
81 global $wgContentHandlerTextFallback;
83 if ( is_null( $content ) ) {
87 if ( $content instanceof TextContent
) {
88 return $content->getNativeData();
91 wfDebugLog( 'ContentHandler', 'Accessing ' . $content->getModel() . ' content as text!' );
93 if ( $wgContentHandlerTextFallback == 'fail' ) {
94 throw new MWException(
95 "Attempt to get text from Content with model " .
100 if ( $wgContentHandlerTextFallback == 'serialize' ) {
101 return $content->serialize();
108 * Convenience function for creating a Content object from a given textual
111 * $text will be deserialized into a Content object of the model specified
112 * by $modelId (or, if that is not given, $title->getContentModel()) using
117 * @param string $text The textual representation, will be
118 * unserialized to create the Content object
119 * @param Title|null $title The title of the page this text belongs to.
120 * Required if $modelId is not provided.
121 * @param string|null $modelId The model to deserialize to. If not provided,
122 * $title->getContentModel() is used.
123 * @param string|null $format The format to use for deserialization. If not
124 * given, the model's default format is used.
126 * @throws MWException If model ID or format is not supported or if the text can not be
127 * unserialized using the format.
128 * @return Content A Content object representing the text.
130 public static function makeContent( $text, Title
$title = null,
131 $modelId = null, $format = null ) {
132 if ( is_null( $modelId ) ) {
133 if ( is_null( $title ) ) {
134 throw new MWException( "Must provide a Title object or a content model ID." );
137 $modelId = $title->getContentModel();
140 $handler = self
::getForModelID( $modelId );
142 return $handler->unserializeContent( $text, $format );
146 * Returns the name of the default content model to be used for the page
147 * with the given title.
149 * Note: There should rarely be need to call this method directly.
150 * To determine the actual content model for a given page, use
151 * Title::getContentModel().
153 * Which model is to be used by default for the page is determined based
154 * on several factors:
155 * - The global setting $wgNamespaceContentModels specifies a content model
157 * - The hook ContentHandlerDefaultModelFor may be used to override the page's default
159 * - Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript
160 * model if they end in .js or .css, respectively.
161 * - Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
162 * - The hook TitleIsCssOrJsPage may be used to force a page to use the CSS
163 * or JavaScript model. This is a compatibility feature. The ContentHandlerDefaultModelFor
164 * hook should be used instead if possible.
165 * - The hook TitleIsWikitextPage may be used to force a page to use the
166 * wikitext model. This is a compatibility feature. The ContentHandlerDefaultModelFor
167 * hook should be used instead if possible.
169 * If none of the above applies, the wikitext model is used.
171 * Note: this is used by, and may thus not use, Title::getContentModel()
175 * @param Title $title
177 * @return string Default model name for the page given by $title
179 public static function getDefaultModelFor( Title
$title ) {
180 // NOTE: this method must not rely on $title->getContentModel() directly or indirectly,
181 // because it is used to initialize the mContentModel member.
183 $ns = $title->getNamespace();
187 $model = MWNamespace
::getNamespaceContentModel( $ns );
189 // Hook can determine default model
190 if ( !Hooks
::run( 'ContentHandlerDefaultModelFor', [ $title, &$model ] ) ) {
191 if ( !is_null( $model ) ) {
196 // Could this page contain code based on the title?
197 $isCodePage = NS_MEDIAWIKI
== $ns && preg_match( '!\.(css|js|json)$!u', $title->getText(), $m );
202 // Is this a user subpage containing code?
203 $isCodeSubpage = NS_USER
== $ns
205 && preg_match( "/\\/.*\\.(js|css|json)$/", $title->getText(), $m );
206 if ( $isCodeSubpage ) {
210 // Is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
211 $isWikitext = is_null( $model ) ||
$model == CONTENT_MODEL_WIKITEXT
;
212 $isWikitext = $isWikitext && !$isCodePage && !$isCodeSubpage;
214 if ( !$isWikitext ) {
217 return CONTENT_MODEL_JAVASCRIPT
;
219 return CONTENT_MODEL_CSS
;
221 return CONTENT_MODEL_JSON
;
223 return is_null( $model ) ? CONTENT_MODEL_TEXT
: $model;
227 // We established that it must be wikitext
229 return CONTENT_MODEL_WIKITEXT
;
233 * Returns the appropriate ContentHandler singleton for the given title.
237 * @param Title $title
239 * @return ContentHandler
241 public static function getForTitle( Title
$title ) {
242 $modelId = $title->getContentModel();
244 return self
::getForModelID( $modelId );
248 * Returns the appropriate ContentHandler singleton for the given Content
253 * @param Content $content
255 * @return ContentHandler
257 public static function getForContent( Content
$content ) {
258 $modelId = $content->getModel();
260 return self
::getForModelID( $modelId );
264 * @var array A Cache of ContentHandler instances by model id
266 protected static $handlers;
269 * Returns the ContentHandler singleton for the given model ID. Use the
270 * CONTENT_MODEL_XXX constants to identify the desired content model.
272 * ContentHandler singletons are taken from the global $wgContentHandlers
273 * array. Keys in that array are model names, the values are either
274 * ContentHandler singleton objects, or strings specifying the appropriate
275 * subclass of ContentHandler.
277 * If a class name is encountered when looking up the singleton for a given
278 * model name, the class is instantiated and the class name is replaced by
279 * the resulting singleton in $wgContentHandlers.
281 * If no ContentHandler is defined for the desired $modelId, the
282 * ContentHandler may be provided by the ContentHandlerForModelID hook.
283 * If no ContentHandler can be determined, an MWException is raised.
287 * @param string $modelId The ID of the content model for which to get a
288 * handler. Use CONTENT_MODEL_XXX constants.
290 * @throws MWException For internal errors and problems in the configuration.
291 * @throws MWUnknownContentModelException If no handler is known for the model ID.
292 * @return ContentHandler The ContentHandler singleton for handling the model given by the ID.
294 public static function getForModelID( $modelId ) {
295 global $wgContentHandlers;
297 if ( isset( self
::$handlers[$modelId] ) ) {
298 return self
::$handlers[$modelId];
301 if ( empty( $wgContentHandlers[$modelId] ) ) {
304 Hooks
::run( 'ContentHandlerForModelID', [ $modelId, &$handler ] );
306 if ( $handler === null ) {
307 throw new MWUnknownContentModelException( $modelId );
310 if ( !( $handler instanceof ContentHandler
) ) {
311 throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
314 $classOrCallback = $wgContentHandlers[$modelId];
316 if ( is_callable( $classOrCallback ) ) {
317 $handler = call_user_func( $classOrCallback, $modelId );
319 $handler = new $classOrCallback( $modelId );
322 if ( !( $handler instanceof ContentHandler
) ) {
323 throw new MWException( "$classOrCallback from \$wgContentHandlers is not " .
324 "compatible with ContentHandler" );
328 wfDebugLog( 'ContentHandler', 'Created handler for ' . $modelId
329 . ': ' . get_class( $handler ) );
331 self
::$handlers[$modelId] = $handler;
333 return self
::$handlers[$modelId];
337 * Clean up handlers cache.
339 public static function cleanupHandlersCache() {
340 self
::$handlers = [];
344 * Returns the localized name for a given content model.
346 * Model names are localized using system messages. Message keys
347 * have the form content-model-$name, where $name is getContentModelName( $id ).
349 * @param string $name The content model ID, as given by a CONTENT_MODEL_XXX
350 * constant or returned by Revision::getContentModel().
351 * @param Language|null $lang The language to parse the message in (since 1.26)
353 * @throws MWException If the model ID isn't known.
354 * @return string The content model's localized name.
356 public static function getLocalizedName( $name, Language
$lang = null ) {
357 // Messages: content-model-wikitext, content-model-text,
358 // content-model-javascript, content-model-css
359 $key = "content-model-$name";
361 $msg = wfMessage( $key );
363 $msg->inLanguage( $lang );
366 return $msg->exists() ?
$msg->plain() : $name;
369 public static function getContentModels() {
370 global $wgContentHandlers;
372 $models = array_keys( $wgContentHandlers );
373 Hooks
::run( 'GetContentModels', [ &$models ] );
377 public static function getAllContentFormats() {
378 global $wgContentHandlers;
382 foreach ( $wgContentHandlers as $model => $class ) {
383 $handler = self
::getForModelID( $model );
384 $formats = array_merge( $formats, $handler->getSupportedFormats() );
387 $formats = array_unique( $formats );
392 // ------------------------------------------------------------------------
402 protected $mSupportedFormats;
405 * Constructor, initializing the ContentHandler instance with its model ID
406 * and a list of supported formats. Values for the parameters are typically
407 * provided as literals by subclass's constructors.
409 * @param string $modelId (use CONTENT_MODEL_XXX constants).
410 * @param string[] $formats List for supported serialization formats
411 * (typically as MIME types)
413 public function __construct( $modelId, $formats ) {
414 $this->mModelID
= $modelId;
415 $this->mSupportedFormats
= $formats;
419 * Serializes a Content object of the type supported by this ContentHandler.
423 * @param Content $content The Content object to serialize
424 * @param string|null $format The desired serialization format
426 * @return string Serialized form of the content
428 abstract public function serializeContent( Content
$content, $format = null );
431 * Applies transformations on export (returns the blob unchanged per default).
432 * Subclasses may override this to perform transformations such as conversion
433 * of legacy formats or filtering of internal meta-data.
435 * @param string $blob The blob to be exported
436 * @param string|null $format The blob's serialization format
440 public function exportTransform( $blob, $format = null ) {
445 * Unserializes a Content object of the type supported by this ContentHandler.
449 * @param string $blob Serialized form of the content
450 * @param string|null $format The format used for serialization
452 * @return Content The Content object created by deserializing $blob
454 abstract public function unserializeContent( $blob, $format = null );
457 * Apply import transformation (per default, returns $blob unchanged).
458 * This gives subclasses an opportunity to transform data blobs on import.
462 * @param string $blob
463 * @param string|null $format
467 public function importTransform( $blob, $format = null ) {
472 * Creates an empty Content object of the type supported by this
479 abstract public function makeEmptyContent();
482 * Creates a new Content object that acts as a redirect to the given page,
483 * or null if redirects are not supported by this content model.
485 * This default implementation always returns null. Subclasses supporting redirects
486 * must override this method.
488 * Note that subclasses that override this method to return a Content object
489 * should also override supportsRedirects() to return true.
493 * @param Title $destination The page to redirect to.
494 * @param string $text Text to include in the redirect, if possible.
496 * @return Content Always null.
498 public function makeRedirectContent( Title
$destination, $text = '' ) {
503 * Returns the model id that identifies the content model this
504 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
508 * @return string The model ID
510 public function getModelID() {
511 return $this->mModelID
;
517 * @param string $model_id The model to check
519 * @throws MWException If the model ID is not the ID of the content model supported by this
522 protected function checkModelID( $model_id ) {
523 if ( $model_id !== $this->mModelID
) {
524 throw new MWException( "Bad content model: " .
525 "expected {$this->mModelID} " .
526 "but got $model_id." );
531 * Returns a list of serialization formats supported by the
532 * serializeContent() and unserializeContent() methods of this
537 * @return string[] List of serialization formats as MIME type like strings
539 public function getSupportedFormats() {
540 return $this->mSupportedFormats
;
544 * The format used for serialization/deserialization by default by this
547 * This default implementation will return the first element of the array
548 * of formats that was passed to the constructor.
552 * @return string The name of the default serialization format as a MIME type
554 public function getDefaultFormat() {
555 return $this->mSupportedFormats
[0];
559 * Returns true if $format is a serialization format supported by this
560 * ContentHandler, and false otherwise.
562 * Note that if $format is null, this method always returns true, because
563 * null means "use the default format".
567 * @param string $format The serialization format to check
571 public function isSupportedFormat( $format ) {
573 return true; // this means "use the default"
576 return in_array( $format, $this->mSupportedFormats
);
580 * Convenient for checking whether a format provided as a parameter is actually supported.
582 * @param string $format The serialization format to check
584 * @throws MWException If the format is not supported by this content handler.
586 protected function checkFormat( $format ) {
587 if ( !$this->isSupportedFormat( $format ) ) {
588 throw new MWException(
589 "Format $format is not supported for content model "
590 . $this->getModelID()
596 * Returns overrides for action handlers.
597 * Classes listed here will be used instead of the default one when
598 * (and only when) $wgActions[$action] === true. This allows subclasses
599 * to override the default action handlers.
603 * @return array An array mapping action names (typically "view", "edit", "history" etc.) to
604 * either the full qualified class name of an Action class, a callable taking ( Page $page,
605 * IContextSource $context = null ) as parameters and returning an Action object, or an actual
606 * Action object. An empty array in this default implementation.
608 * @see Action::factory
610 public function getActionOverrides() {
615 * Factory for creating an appropriate DifferenceEngine for this content model.
619 * @param IContextSource $context Context to use, anything else will be ignored.
620 * @param int $old Revision ID we want to show and diff with.
621 * @param int|string $new Either a revision ID or one of the strings 'cur', 'prev' or 'next'.
622 * @param int $rcid FIXME: Deprecated, no longer used. Defaults to 0.
623 * @param bool $refreshCache If set, refreshes the diff cache. Defaults to false.
624 * @param bool $unhide If set, allow viewing deleted revs. Defaults to false.
626 * @return DifferenceEngine
628 public function createDifferenceEngine( IContextSource
$context, $old = 0, $new = 0,
629 $rcid = 0, // FIXME: Deprecated, no longer used
630 $refreshCache = false, $unhide = false
632 // hook: get difference engine
633 $differenceEngine = null;
634 if ( !Hooks
::run( 'GetDifferenceEngine',
635 [ $context, $old, $new, $refreshCache, $unhide, &$differenceEngine ]
637 return $differenceEngine;
639 $diffEngineClass = $this->getDiffEngineClass();
640 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
644 * Get the language in which the content of the given page is written.
646 * This default implementation just returns the content language (except for pages
647 * in the MediaWiki namespace)
649 * Note that the pages language is not cacheable, since it may in some
650 * cases depend on user settings.
652 * Also note that the page language may or may not depend on the actual content of the page,
653 * that is, this method may load the content in order to determine the language.
657 * @param Title $title The page to determine the language for.
658 * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
660 * @return Language The page's language
662 public function getPageLanguage( Title
$title, Content
$content = null ) {
664 $pageLang = MediaWikiServices
::getInstance()->getContentLanguage();
666 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
667 // Parse mediawiki messages with correct target language
668 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $title->getText() );
669 $pageLang = Language
::factory( $lang );
672 Hooks
::run( 'PageContentLanguage', [ $title, &$pageLang, $wgLang ] );
674 return wfGetLangObj( $pageLang );
678 * Get the language in which the content of this page is written when
679 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
680 * specified a preferred variant, the variant will be used.
682 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
683 * the user specified a preferred variant.
685 * Note that the pages view language is not cacheable, since it depends on user settings.
687 * Also note that the page language may or may not depend on the actual content of the page,
688 * that is, this method may load the content in order to determine the language.
692 * @param Title $title The page to determine the language for.
693 * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
695 * @return Language The page's language for viewing
697 public function getPageViewLanguage( Title
$title, Content
$content = null ) {
698 $pageLang = $this->getPageLanguage( $title, $content );
700 if ( $title->getNamespace() !== NS_MEDIAWIKI
) {
701 // If the user chooses a variant, the content is actually
702 // in a language whose code is the variant code.
703 $variant = $pageLang->getPreferredVariant();
704 if ( $pageLang->getCode() !== $variant ) {
705 $pageLang = Language
::factory( $variant );
713 * Determines whether the content type handled by this ContentHandler
714 * can be used on the given page.
716 * This default implementation always returns true.
717 * Subclasses may override this to restrict the use of this content model to specific locations,
718 * typically based on the namespace or some other aspect of the title, such as a special suffix
719 * (e.g. ".svg" for SVG content).
721 * @note this calls the ContentHandlerCanBeUsedOn hook which may be used to override which
722 * content model can be used where.
724 * @param Title $title The page's title.
726 * @return bool True if content of this kind can be used on the given page, false otherwise.
728 public function canBeUsedOn( Title
$title ) {
731 Hooks
::run( 'ContentModelCanBeUsedOn', [ $this->getModelID(), $title, &$ok ] );
737 * Returns the name of the diff engine to use.
743 protected function getDiffEngineClass() {
744 return DifferenceEngine
::class;
748 * Attempts to merge differences between three versions. Returns a new
749 * Content object for a clean merge and false for failure or a conflict.
751 * This default implementation always returns false.
755 * @param Content $oldContent The page's previous content.
756 * @param Content $myContent One of the page's conflicting contents.
757 * @param Content $yourContent One of the page's conflicting contents.
759 * @return Content|bool Always false.
761 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
766 * Return type of change if one exists for the given edit.
770 * @param Content|null $oldContent The previous text of the page.
771 * @param Content|null $newContent The submitted text of the page.
772 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
774 * @return string|null String key representing type of change, or null.
776 private function getChangeType(
777 Content
$oldContent = null,
778 Content
$newContent = null,
781 $oldTarget = $oldContent !== null ?
$oldContent->getRedirectTarget() : null;
782 $newTarget = $newContent !== null ?
$newContent->getRedirectTarget() : null;
784 // We check for the type of change in the given edit, and return string key accordingly
786 // Blanking of a page
787 if ( $oldContent && $oldContent->getSize() > 0 &&
788 $newContent && $newContent->getSize() === 0
796 // New redirect page (by creating new page or by changing content page)
797 return 'new-redirect';
798 } elseif ( !$newTarget->equals( $oldTarget ) ||
799 $oldTarget->getFragment() !== $newTarget->getFragment()
801 // Redirect target changed
802 return 'changed-redirect-target';
804 } elseif ( $oldTarget ) {
805 // Changing an existing redirect into a non-redirect
806 return 'removed-redirect';
810 if ( $flags & EDIT_NEW
&& $newContent ) {
811 if ( $newContent->getSize() === 0 ) {
819 // Removing more than 90% of the page
820 if ( $oldContent && $newContent && $oldContent->getSize() > 10 * $newContent->getSize() ) {
824 // Content model changed
825 if ( $oldContent && $newContent && $oldContent->getModel() !== $newContent->getModel() ) {
826 return 'contentmodelchange';
833 * Return an applicable auto-summary if one exists for the given edit.
837 * @param Content|null $oldContent The previous text of the page.
838 * @param Content|null $newContent The submitted text of the page.
839 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
841 * @return string An appropriate auto-summary, or an empty string.
843 public function getAutosummary(
844 Content
$oldContent = null,
845 Content
$newContent = null,
848 $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
850 // There's no applicable auto-summary for our case, so our auto-summary is empty.
851 if ( !$changeType ) {
855 // Decide what kind of auto-summary is needed.
856 switch ( $changeType ) {
858 $newTarget = $newContent->getRedirectTarget();
859 $truncatedtext = $newContent->getTextForSummary(
861 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
862 - strlen( $newTarget->getFullText() )
865 return wfMessage( 'autoredircomment', $newTarget->getFullText() )
866 ->plaintextParams( $truncatedtext )->inContentLanguage()->text();
867 case 'changed-redirect-target':
868 $oldTarget = $oldContent->getRedirectTarget();
869 $newTarget = $newContent->getRedirectTarget();
871 $truncatedtext = $newContent->getTextForSummary(
873 - strlen( wfMessage( 'autosumm-changed-redirect-target' )
874 ->inContentLanguage()->text() )
875 - strlen( $oldTarget->getFullText() )
876 - strlen( $newTarget->getFullText() )
879 return wfMessage( 'autosumm-changed-redirect-target',
880 $oldTarget->getFullText(),
881 $newTarget->getFullText() )
882 ->rawParams( $truncatedtext )->inContentLanguage()->text();
883 case 'removed-redirect':
884 $oldTarget = $oldContent->getRedirectTarget();
885 $truncatedtext = $newContent->getTextForSummary(
887 - strlen( wfMessage( 'autosumm-removed-redirect' )
888 ->inContentLanguage()->text() )
889 - strlen( $oldTarget->getFullText() ) );
891 return wfMessage( 'autosumm-removed-redirect', $oldTarget->getFullText() )
892 ->rawParams( $truncatedtext )->inContentLanguage()->text();
894 // If they're making a new article, give its text, truncated, in the summary.
895 $truncatedtext = $newContent->getTextForSummary(
896 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
898 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
899 ->inContentLanguage()->text();
901 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
903 $truncatedtext = $newContent->getTextForSummary(
904 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
906 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
907 ->inContentLanguage()->text();
909 return wfMessage( 'autosumm-newblank' )->inContentLanguage()->text();
916 * Return an applicable tag if one exists for the given edit or return null.
920 * @param Content|null $oldContent The previous text of the page.
921 * @param Content|null $newContent The submitted text of the page.
922 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
924 * @return string|null An appropriate tag, or null.
926 public function getChangeTag(
927 Content
$oldContent = null,
928 Content
$newContent = null,
931 $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
933 // There's no applicable tag for this change.
934 if ( !$changeType ) {
938 // Core tags use the same keys as ones returned from $this->getChangeType()
939 // but prefixed with pseudo namespace 'mw-', so we add the prefix before checking
940 // if this type of change should be tagged
941 $tag = 'mw-' . $changeType;
943 // Not all change types are tagged, so we check against the list of defined tags.
944 if ( in_array( $tag, ChangeTags
::getSoftwareTags() ) ) {
952 * Auto-generates a deletion reason
956 * @param Title $title The page's title
957 * @param bool &$hasHistory Whether the page has a history
959 * @return mixed String containing deletion reason or empty string, or
960 * boolean false if no revision occurred
962 * @todo &$hasHistory is extremely ugly, it's here because
963 * WikiPage::getAutoDeleteReason() and Article::generateReason()
966 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
967 $dbr = wfGetDB( DB_REPLICA
);
969 // Get the last revision
970 $rev = Revision
::newFromTitle( $title );
972 if ( is_null( $rev ) ) {
976 // Get the article's contents
977 $content = $rev->getContent();
980 // If the page is blank, use the text from the previous revision,
981 // which can only be blank if there's a move/import/protect dummy
983 if ( !$content ||
$content->isEmpty() ) {
984 $prev = $rev->getPrevious();
988 $content = $rev->getContent();
993 $this->checkModelID( $rev->getContentModel() );
995 // Find out if there was only one contributor
996 // Only scan the last 20 revisions
997 $revQuery = Revision
::getQueryInfo();
1000 [ 'rev_user_text' => $revQuery['fields']['rev_user_text'] ],
1002 'rev_page' => $title->getArticleID(),
1003 $dbr->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0'
1010 if ( $res === false ) {
1011 // This page has no revisions, which is very weird
1015 $hasHistory = ( $res->numRows() > 1 );
1016 $row = $dbr->fetchObject( $res );
1018 if ( $row ) { // $row is false if the only contributor is hidden
1019 $onlyAuthor = $row->rev_user_text
;
1020 // Try to find a second contributor
1021 foreach ( $res as $row ) {
1022 if ( $row->rev_user_text
!= $onlyAuthor ) { // T24999
1023 $onlyAuthor = false;
1028 $onlyAuthor = false;
1031 // Generate the summary with a '$1' placeholder
1033 // The current revision is blank and the one before is also
1034 // blank. It's just not our lucky day
1035 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
1037 if ( $onlyAuthor ) {
1038 $reason = wfMessage(
1042 )->inContentLanguage()->text();
1044 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
1048 if ( $reason == '-' ) {
1049 // Allow these UI messages to be blanked out cleanly
1053 // Max content length = max comment length - length of the comment (excl. $1)
1054 $text = $content ?
$content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) : '';
1056 // Now replace the '$1' placeholder
1057 $reason = str_replace( '$1', $text, $reason );
1063 * Get the Content object that needs to be saved in order to undo all revisions
1064 * between $undo and $undoafter. Revisions must belong to the same page,
1065 * must exist and must not be deleted.
1069 * @param Revision $current The current text
1070 * @param Revision $undo The revision to undo
1071 * @param Revision $undoafter Must be an earlier revision than $undo
1073 * @return mixed Content on success, false on failure
1075 public function getUndoContent( Revision
$current, Revision
$undo, Revision
$undoafter ) {
1076 $cur_content = $current->getContent();
1078 if ( empty( $cur_content ) ) {
1079 return false; // no page
1082 $undo_content = $undo->getContent();
1083 $undoafter_content = $undoafter->getContent();
1085 if ( !$undo_content ||
!$undoafter_content ) {
1086 return false; // no content to undo
1090 $this->checkModelID( $cur_content->getModel() );
1091 $this->checkModelID( $undo_content->getModel() );
1092 if ( $current->getId() !== $undo->getId() ) {
1093 // If we are undoing the most recent revision,
1094 // its ok to revert content model changes. However
1095 // if we are undoing a revision in the middle, then
1096 // doing that will be confusing.
1097 $this->checkModelID( $undoafter_content->getModel() );
1099 } catch ( MWException
$e ) {
1100 // If the revisions have different content models
1101 // just return false
1105 if ( $cur_content->equals( $undo_content ) ) {
1106 // No use doing a merge if it's just a straight revert.
1107 return $undoafter_content;
1110 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
1112 return $undone_content;
1116 * Get parser options suitable for rendering and caching the article
1118 * @deprecated since 1.32, use WikiPage::makeParserOptions() or
1119 * ParserOptions::newCanonical() instead.
1120 * @param IContextSource|User|string $context One of the following:
1121 * - IContextSource: Use the User and the Language of the provided
1123 * - User: Use the provided User object and $wgLang for the language,
1124 * so use an IContextSource object if possible.
1125 * - 'canonical': Canonical options (anonymous user with default
1126 * preferences and content language).
1128 * @throws MWException
1129 * @return ParserOptions
1131 public function makeParserOptions( $context ) {
1132 wfDeprecated( __METHOD__
, '1.32' );
1133 return ParserOptions
::newCanonical( $context );
1137 * Returns true for content models that support caching using the
1138 * ParserCache mechanism. See WikiPage::shouldCheckParserCache().
1142 * @return bool Always false.
1144 public function isParserCacheSupported() {
1149 * Returns true if this content model supports sections.
1150 * This default implementation returns false.
1152 * Content models that return true here should also implement
1153 * Content::getSection, Content::replaceSection, etc. to handle sections..
1155 * @return bool Always false.
1157 public function supportsSections() {
1162 * Returns true if this content model supports categories.
1163 * The default implementation returns true.
1165 * @return bool Always true.
1167 public function supportsCategories() {
1172 * Returns true if this content model supports redirects.
1173 * This default implementation returns false.
1175 * Content models that return true here should also implement
1176 * ContentHandler::makeRedirectContent to return a Content object.
1178 * @return bool Always false.
1180 public function supportsRedirects() {
1185 * Return true if this content model supports direct editing, such as via EditPage.
1187 * @return bool Default is false, and true for TextContent and it's derivatives.
1189 public function supportsDirectEditing() {
1194 * Whether or not this content model supports direct editing via ApiEditPage
1196 * @return bool Default is false, and true for TextContent and derivatives.
1198 public function supportsDirectApiEditing() {
1199 return $this->supportsDirectEditing();
1203 * Get fields definition for search index
1205 * @todo Expose title, redirect, namespace, text, source_text, text_bytes
1206 * field mappings here. (see T142670 and T143409)
1208 * @param SearchEngine $engine
1209 * @return SearchIndexField[] List of fields this content handler can provide.
1212 public function getFieldsForSearchIndex( SearchEngine
$engine ) {
1213 $fields['category'] = $engine->makeSearchFieldMapping(
1215 SearchIndexField
::INDEX_TYPE_TEXT
1217 $fields['category']->setFlag( SearchIndexField
::FLAG_CASEFOLD
);
1219 $fields['external_link'] = $engine->makeSearchFieldMapping(
1221 SearchIndexField
::INDEX_TYPE_KEYWORD
1224 $fields['outgoing_link'] = $engine->makeSearchFieldMapping(
1226 SearchIndexField
::INDEX_TYPE_KEYWORD
1229 $fields['template'] = $engine->makeSearchFieldMapping(
1231 SearchIndexField
::INDEX_TYPE_KEYWORD
1233 $fields['template']->setFlag( SearchIndexField
::FLAG_CASEFOLD
);
1235 $fields['content_model'] = $engine->makeSearchFieldMapping(
1237 SearchIndexField
::INDEX_TYPE_KEYWORD
1244 * Add new field definition to array.
1245 * @param SearchIndexField[] &$fields
1246 * @param SearchEngine $engine
1247 * @param string $name
1249 * @return SearchIndexField[] new field defs
1252 protected function addSearchField( &$fields, SearchEngine
$engine, $name, $type ) {
1253 $fields[$name] = $engine->makeSearchFieldMapping( $name, $type );
1258 * Return fields to be indexed by search engine
1259 * as representation of this document.
1260 * Overriding class should call parent function or take care of calling
1261 * the SearchDataForIndex hook.
1262 * @param WikiPage $page Page to index
1263 * @param ParserOutput $output
1264 * @param SearchEngine $engine Search engine for which we are indexing
1265 * @return array Map of name=>value for fields
1268 public function getDataForSearchIndex(
1270 ParserOutput
$output,
1271 SearchEngine
$engine
1274 $content = $page->getContent();
1277 $searchDataExtractor = new ParserOutputSearchDataExtractor();
1279 $fieldData['category'] = $searchDataExtractor->getCategories( $output );
1280 $fieldData['external_link'] = $searchDataExtractor->getExternalLinks( $output );
1281 $fieldData['outgoing_link'] = $searchDataExtractor->getOutgoingLinks( $output );
1282 $fieldData['template'] = $searchDataExtractor->getTemplates( $output );
1284 $text = $content->getTextForSearchIndex();
1286 $fieldData['text'] = $text;
1287 $fieldData['source_text'] = $text;
1288 $fieldData['text_bytes'] = $content->getSize();
1289 $fieldData['content_model'] = $content->getModel();
1292 Hooks
::run( 'SearchDataForIndex', [ &$fieldData, $this, $page, $output, $engine ] );
1297 * Produce page output suitable for indexing.
1299 * Specific content handlers may override it if they need different content handling.
1301 * @param WikiPage $page
1302 * @param ParserCache|null $cache
1303 * @return ParserOutput
1305 public function getParserOutputForIndexing( WikiPage
$page, ParserCache
$cache = null ) {
1306 $parserOptions = $page->makeParserOptions( 'canonical' );
1307 $revId = $page->getRevision()->getId();
1309 $parserOutput = $cache->get( $page, $parserOptions );
1311 if ( empty( $parserOutput ) ) {
1313 $page->getContent()->getParserOutput( $page->getTitle(), $revId, $parserOptions );
1315 $cache->save( $parserOutput, $page, $parserOptions );
1318 return $parserOutput;