Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / content / ContentHandler.php
blob5862bf11563c4ff3401be650670c4c1416594c8b
1 <?php
3 use MediaWiki\Search\ParserOutputSearchDataExtractor;
5 /**
6 * Base class for content handling.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @since 1.21
25 * @file
26 * @ingroup Content
28 * @author Daniel Kinzler
30 /**
31 * A content handler knows how do deal with a specific type of content on a wiki
32 * page. Content is stored in the database in a serialized form (using a
33 * serialization format a.k.a. MIME type) and is unserialized into its native
34 * PHP representation (the content model), which is wrapped in an instance of
35 * the appropriate subclass of Content.
37 * ContentHandler instances are stateless singletons that serve, among other
38 * things, as a factory for Content objects. Generally, there is one subclass
39 * of ContentHandler and one subclass of Content for every type of content model.
41 * Some content types have a flat model, that is, their native representation
42 * is the same as their serialized form. Examples would be JavaScript and CSS
43 * code. As of now, this also applies to wikitext (MediaWiki's default content
44 * type), but wikitext content may be represented by a DOM or AST structure in
45 * the future.
47 * @ingroup Content
49 abstract class ContentHandler {
50 /**
51 * Convenience function for getting flat text from a Content object. This
52 * should only be used in the context of backwards compatibility with code
53 * that is not yet able to handle Content objects!
55 * If $content is null, this method returns the empty string.
57 * If $content is an instance of TextContent, this method returns the flat
58 * text as returned by $content->getNativeData().
60 * If $content is not a TextContent object, the behavior of this method
61 * depends on the global $wgContentHandlerTextFallback:
62 * - If $wgContentHandlerTextFallback is 'fail' and $content is not a
63 * TextContent object, an MWException is thrown.
64 * - If $wgContentHandlerTextFallback is 'serialize' and $content is not a
65 * TextContent object, $content->serialize() is called to get a string
66 * form of the content.
67 * - If $wgContentHandlerTextFallback is 'ignore' and $content is not a
68 * TextContent object, this method returns null.
69 * - otherwise, the behavior is undefined.
71 * @since 1.21
73 * @param Content $content
75 * @throws MWException If the content is not an instance of TextContent and
76 * wgContentHandlerTextFallback was set to 'fail'.
77 * @return string|null Textual form of the content, if available.
79 public static function getContentText( Content $content = null ) {
80 global $wgContentHandlerTextFallback;
82 if ( is_null( $content ) ) {
83 return '';
86 if ( $content instanceof TextContent ) {
87 return $content->getNativeData();
90 wfDebugLog( 'ContentHandler', 'Accessing ' . $content->getModel() . ' content as text!' );
92 if ( $wgContentHandlerTextFallback == 'fail' ) {
93 throw new MWException(
94 "Attempt to get text from Content with model " .
95 $content->getModel()
99 if ( $wgContentHandlerTextFallback == 'serialize' ) {
100 return $content->serialize();
103 return null;
107 * Convenience function for creating a Content object from a given textual
108 * representation.
110 * $text will be deserialized into a Content object of the model specified
111 * by $modelId (or, if that is not given, $title->getContentModel()) using
112 * the given format.
114 * @since 1.21
116 * @param string $text The textual representation, will be
117 * unserialized to create the Content object
118 * @param Title $title The title of the page this text belongs to.
119 * Required if $modelId is not provided.
120 * @param string $modelId The model to deserialize to. If not provided,
121 * $title->getContentModel() is used.
122 * @param string $format The format to use for deserialization. If not
123 * given, the model's default format is used.
125 * @throws MWException If model ID or format is not supported or if the text can not be
126 * unserialized using the format.
127 * @return Content A Content object representing the text.
129 public static function makeContent( $text, Title $title = null,
130 $modelId = null, $format = null ) {
131 if ( is_null( $modelId ) ) {
132 if ( is_null( $title ) ) {
133 throw new MWException( "Must provide a Title object or a content model ID." );
136 $modelId = $title->getContentModel();
139 $handler = ContentHandler::getForModelID( $modelId );
141 return $handler->unserializeContent( $text, $format );
145 * Returns the name of the default content model to be used for the page
146 * with the given title.
148 * Note: There should rarely be need to call this method directly.
149 * To determine the actual content model for a given page, use
150 * Title::getContentModel().
152 * Which model is to be used by default for the page is determined based
153 * on several factors:
154 * - The global setting $wgNamespaceContentModels specifies a content model
155 * per namespace.
156 * - The hook ContentHandlerDefaultModelFor may be used to override the page's default
157 * model.
158 * - Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript
159 * model if they end in .js or .css, respectively.
160 * - Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
161 * - The hook TitleIsCssOrJsPage may be used to force a page to use the CSS
162 * or JavaScript model. This is a compatibility feature. The ContentHandlerDefaultModelFor
163 * hook should be used instead if possible.
164 * - The hook TitleIsWikitextPage may be used to force a page to use the
165 * wikitext model. This is a compatibility feature. The ContentHandlerDefaultModelFor
166 * hook should be used instead if possible.
168 * If none of the above applies, the wikitext model is used.
170 * Note: this is used by, and may thus not use, Title::getContentModel()
172 * @since 1.21
174 * @param Title $title
176 * @return string Default model name for the page given by $title
178 public static function getDefaultModelFor( Title $title ) {
179 // NOTE: this method must not rely on $title->getContentModel() directly or indirectly,
180 // because it is used to initialize the mContentModel member.
182 $ns = $title->getNamespace();
184 $ext = false;
185 $m = null;
186 $model = MWNamespace::getNamespaceContentModel( $ns );
188 // Hook can determine default model
189 if ( !Hooks::run( 'ContentHandlerDefaultModelFor', [ $title, &$model ] ) ) {
190 if ( !is_null( $model ) ) {
191 return $model;
195 // Could this page contain code based on the title?
196 $isCodePage = NS_MEDIAWIKI == $ns && preg_match( '!\.(css|js|json)$!u', $title->getText(), $m );
197 if ( $isCodePage ) {
198 $ext = $m[1];
201 // Is this a user subpage containing code?
202 $isCodeSubpage = NS_USER == $ns
203 && !$isCodePage
204 && preg_match( "/\\/.*\\.(js|css|json)$/", $title->getText(), $m );
205 if ( $isCodeSubpage ) {
206 $ext = $m[1];
209 // Is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
210 $isWikitext = is_null( $model ) || $model == CONTENT_MODEL_WIKITEXT;
211 $isWikitext = $isWikitext && !$isCodePage && !$isCodeSubpage;
213 if ( !$isWikitext ) {
214 switch ( $ext ) {
215 case 'js':
216 return CONTENT_MODEL_JAVASCRIPT;
217 case 'css':
218 return CONTENT_MODEL_CSS;
219 case 'json':
220 return CONTENT_MODEL_JSON;
221 default:
222 return is_null( $model ) ? CONTENT_MODEL_TEXT : $model;
226 // We established that it must be wikitext
228 return CONTENT_MODEL_WIKITEXT;
232 * Returns the appropriate ContentHandler singleton for the given title.
234 * @since 1.21
236 * @param Title $title
238 * @return ContentHandler
240 public static function getForTitle( Title $title ) {
241 $modelId = $title->getContentModel();
243 return ContentHandler::getForModelID( $modelId );
247 * Returns the appropriate ContentHandler singleton for the given Content
248 * object.
250 * @since 1.21
252 * @param Content $content
254 * @return ContentHandler
256 public static function getForContent( Content $content ) {
257 $modelId = $content->getModel();
259 return ContentHandler::getForModelID( $modelId );
263 * @var array A Cache of ContentHandler instances by model id
265 protected static $handlers;
268 * Returns the ContentHandler singleton for the given model ID. Use the
269 * CONTENT_MODEL_XXX constants to identify the desired content model.
271 * ContentHandler singletons are taken from the global $wgContentHandlers
272 * array. Keys in that array are model names, the values are either
273 * ContentHandler singleton objects, or strings specifying the appropriate
274 * subclass of ContentHandler.
276 * If a class name is encountered when looking up the singleton for a given
277 * model name, the class is instantiated and the class name is replaced by
278 * the resulting singleton in $wgContentHandlers.
280 * If no ContentHandler is defined for the desired $modelId, the
281 * ContentHandler may be provided by the ContentHandlerForModelID hook.
282 * If no ContentHandler can be determined, an MWException is raised.
284 * @since 1.21
286 * @param string $modelId The ID of the content model for which to get a
287 * handler. Use CONTENT_MODEL_XXX constants.
289 * @throws MWException For internal errors and problems in the configuration.
290 * @throws MWUnknownContentModelException If no handler is known for the model ID.
291 * @return ContentHandler The ContentHandler singleton for handling the model given by the ID.
293 public static function getForModelID( $modelId ) {
294 global $wgContentHandlers;
296 if ( isset( ContentHandler::$handlers[$modelId] ) ) {
297 return ContentHandler::$handlers[$modelId];
300 if ( empty( $wgContentHandlers[$modelId] ) ) {
301 $handler = null;
303 Hooks::run( 'ContentHandlerForModelID', [ $modelId, &$handler ] );
305 if ( $handler === null ) {
306 throw new MWUnknownContentModelException( $modelId );
309 if ( !( $handler instanceof ContentHandler ) ) {
310 throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
312 } else {
313 $classOrCallback = $wgContentHandlers[$modelId];
315 if ( is_callable( $classOrCallback ) ) {
316 $handler = call_user_func( $classOrCallback, $modelId );
317 } else {
318 $handler = new $classOrCallback( $modelId );
321 if ( !( $handler instanceof ContentHandler ) ) {
322 throw new MWException( "$classOrCallback from \$wgContentHandlers is not " .
323 "compatible with ContentHandler" );
327 wfDebugLog( 'ContentHandler', 'Created handler for ' . $modelId
328 . ': ' . get_class( $handler ) );
330 ContentHandler::$handlers[$modelId] = $handler;
332 return ContentHandler::$handlers[$modelId];
336 * Returns the localized name for a given content model.
338 * Model names are localized using system messages. Message keys
339 * have the form content-model-$name, where $name is getContentModelName( $id ).
341 * @param string $name The content model ID, as given by a CONTENT_MODEL_XXX
342 * constant or returned by Revision::getContentModel().
343 * @param Language|null $lang The language to parse the message in (since 1.26)
345 * @throws MWException If the model ID isn't known.
346 * @return string The content model's localized name.
348 public static function getLocalizedName( $name, Language $lang = null ) {
349 // Messages: content-model-wikitext, content-model-text,
350 // content-model-javascript, content-model-css
351 $key = "content-model-$name";
353 $msg = wfMessage( $key );
354 if ( $lang ) {
355 $msg->inLanguage( $lang );
358 return $msg->exists() ? $msg->plain() : $name;
361 public static function getContentModels() {
362 global $wgContentHandlers;
364 return array_keys( $wgContentHandlers );
367 public static function getAllContentFormats() {
368 global $wgContentHandlers;
370 $formats = [];
372 foreach ( $wgContentHandlers as $model => $class ) {
373 $handler = ContentHandler::getForModelID( $model );
374 $formats = array_merge( $formats, $handler->getSupportedFormats() );
377 $formats = array_unique( $formats );
379 return $formats;
382 // ------------------------------------------------------------------------
385 * @var string
387 protected $mModelID;
390 * @var string[]
392 protected $mSupportedFormats;
395 * Constructor, initializing the ContentHandler instance with its model ID
396 * and a list of supported formats. Values for the parameters are typically
397 * provided as literals by subclass's constructors.
399 * @param string $modelId (use CONTENT_MODEL_XXX constants).
400 * @param string[] $formats List for supported serialization formats
401 * (typically as MIME types)
403 public function __construct( $modelId, $formats ) {
404 $this->mModelID = $modelId;
405 $this->mSupportedFormats = $formats;
409 * Serializes a Content object of the type supported by this ContentHandler.
411 * @since 1.21
413 * @param Content $content The Content object to serialize
414 * @param string $format The desired serialization format
416 * @return string Serialized form of the content
418 abstract public function serializeContent( Content $content, $format = null );
421 * Applies transformations on export (returns the blob unchanged per default).
422 * Subclasses may override this to perform transformations such as conversion
423 * of legacy formats or filtering of internal meta-data.
425 * @param string $blob The blob to be exported
426 * @param string|null $format The blob's serialization format
428 * @return string
430 public function exportTransform( $blob, $format = null ) {
431 return $blob;
435 * Unserializes a Content object of the type supported by this ContentHandler.
437 * @since 1.21
439 * @param string $blob Serialized form of the content
440 * @param string $format The format used for serialization
442 * @return Content The Content object created by deserializing $blob
444 abstract public function unserializeContent( $blob, $format = null );
447 * Apply import transformation (per default, returns $blob unchanged).
448 * This gives subclasses an opportunity to transform data blobs on import.
450 * @since 1.24
452 * @param string $blob
453 * @param string|null $format
455 * @return string
457 public function importTransform( $blob, $format = null ) {
458 return $blob;
462 * Creates an empty Content object of the type supported by this
463 * ContentHandler.
465 * @since 1.21
467 * @return Content
469 abstract public function makeEmptyContent();
472 * Creates a new Content object that acts as a redirect to the given page,
473 * or null if redirects are not supported by this content model.
475 * This default implementation always returns null. Subclasses supporting redirects
476 * must override this method.
478 * Note that subclasses that override this method to return a Content object
479 * should also override supportsRedirects() to return true.
481 * @since 1.21
483 * @param Title $destination The page to redirect to.
484 * @param string $text Text to include in the redirect, if possible.
486 * @return Content Always null.
488 public function makeRedirectContent( Title $destination, $text = '' ) {
489 return null;
493 * Returns the model id that identifies the content model this
494 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
496 * @since 1.21
498 * @return string The model ID
500 public function getModelID() {
501 return $this->mModelID;
505 * @since 1.21
507 * @param string $model_id The model to check
509 * @throws MWException If the model ID is not the ID of the content model supported by this
510 * ContentHandler.
512 protected function checkModelID( $model_id ) {
513 if ( $model_id !== $this->mModelID ) {
514 throw new MWException( "Bad content model: " .
515 "expected {$this->mModelID} " .
516 "but got $model_id." );
521 * Returns a list of serialization formats supported by the
522 * serializeContent() and unserializeContent() methods of this
523 * ContentHandler.
525 * @since 1.21
527 * @return string[] List of serialization formats as MIME type like strings
529 public function getSupportedFormats() {
530 return $this->mSupportedFormats;
534 * The format used for serialization/deserialization by default by this
535 * ContentHandler.
537 * This default implementation will return the first element of the array
538 * of formats that was passed to the constructor.
540 * @since 1.21
542 * @return string The name of the default serialization format as a MIME type
544 public function getDefaultFormat() {
545 return $this->mSupportedFormats[0];
549 * Returns true if $format is a serialization format supported by this
550 * ContentHandler, and false otherwise.
552 * Note that if $format is null, this method always returns true, because
553 * null means "use the default format".
555 * @since 1.21
557 * @param string $format The serialization format to check
559 * @return bool
561 public function isSupportedFormat( $format ) {
562 if ( !$format ) {
563 return true; // this means "use the default"
566 return in_array( $format, $this->mSupportedFormats );
570 * Convenient for checking whether a format provided as a parameter is actually supported.
572 * @param string $format The serialization format to check
574 * @throws MWException If the format is not supported by this content handler.
576 protected function checkFormat( $format ) {
577 if ( !$this->isSupportedFormat( $format ) ) {
578 throw new MWException(
579 "Format $format is not supported for content model "
580 . $this->getModelID()
586 * Returns overrides for action handlers.
587 * Classes listed here will be used instead of the default one when
588 * (and only when) $wgActions[$action] === true. This allows subclasses
589 * to override the default action handlers.
591 * @since 1.21
593 * @return array An array mapping action names (typically "view", "edit", "history" etc.) to
594 * either the full qualified class name of an Action class, a callable taking ( Page $page,
595 * IContextSource $context = null ) as parameters and returning an Action object, or an actual
596 * Action object. An empty array in this default implementation.
598 * @see Action::factory
600 public function getActionOverrides() {
601 return [];
605 * Factory for creating an appropriate DifferenceEngine for this content model.
607 * @since 1.21
609 * @param IContextSource $context Context to use, anything else will be ignored.
610 * @param int $old Revision ID we want to show and diff with.
611 * @param int|string $new Either a revision ID or one of the strings 'cur', 'prev' or 'next'.
612 * @param int $rcid FIXME: Deprecated, no longer used. Defaults to 0.
613 * @param bool $refreshCache If set, refreshes the diff cache. Defaults to false.
614 * @param bool $unhide If set, allow viewing deleted revs. Defaults to false.
616 * @return DifferenceEngine
618 public function createDifferenceEngine( IContextSource $context, $old = 0, $new = 0,
619 $rcid = 0, // FIXME: Deprecated, no longer used
620 $refreshCache = false, $unhide = false ) {
622 // hook: get difference engine
623 $differenceEngine = null;
624 if ( !Hooks::run( 'GetDifferenceEngine',
625 [ $context, $old, $new, $refreshCache, $unhide, &$differenceEngine ]
626 ) ) {
627 return $differenceEngine;
629 $diffEngineClass = $this->getDiffEngineClass();
630 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
634 * Get the language in which the content of the given page is written.
636 * This default implementation just returns $wgContLang (except for pages
637 * in the MediaWiki namespace)
639 * Note that the pages language is not cacheable, since it may in some
640 * cases depend on user settings.
642 * Also note that the page language may or may not depend on the actual content of the page,
643 * that is, this method may load the content in order to determine the language.
645 * @since 1.21
647 * @param Title $title The page to determine the language for.
648 * @param Content $content The page's content, if you have it handy, to avoid reloading it.
650 * @return Language The page's language
652 public function getPageLanguage( Title $title, Content $content = null ) {
653 global $wgContLang, $wgLang;
654 $pageLang = $wgContLang;
656 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
657 // Parse mediawiki messages with correct target language
658 list( /* $unused */, $lang ) = MessageCache::singleton()->figureMessage( $title->getText() );
659 $pageLang = Language::factory( $lang );
662 Hooks::run( 'PageContentLanguage', [ $title, &$pageLang, $wgLang ] );
664 return wfGetLangObj( $pageLang );
668 * Get the language in which the content of this page is written when
669 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
670 * specified a preferred variant, the variant will be used.
672 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
673 * the user specified a preferred variant.
675 * Note that the pages view language is not cacheable, since it depends on user settings.
677 * Also note that the page language may or may not depend on the actual content of the page,
678 * that is, this method may load the content in order to determine the language.
680 * @since 1.21
682 * @param Title $title The page to determine the language for.
683 * @param Content $content The page's content, if you have it handy, to avoid reloading it.
685 * @return Language The page's language for viewing
687 public function getPageViewLanguage( Title $title, Content $content = null ) {
688 $pageLang = $this->getPageLanguage( $title, $content );
690 if ( $title->getNamespace() !== NS_MEDIAWIKI ) {
691 // If the user chooses a variant, the content is actually
692 // in a language whose code is the variant code.
693 $variant = $pageLang->getPreferredVariant();
694 if ( $pageLang->getCode() !== $variant ) {
695 $pageLang = Language::factory( $variant );
699 return $pageLang;
703 * Determines whether the content type handled by this ContentHandler
704 * can be used on the given page.
706 * This default implementation always returns true.
707 * Subclasses may override this to restrict the use of this content model to specific locations,
708 * typically based on the namespace or some other aspect of the title, such as a special suffix
709 * (e.g. ".svg" for SVG content).
711 * @note this calls the ContentHandlerCanBeUsedOn hook which may be used to override which
712 * content model can be used where.
714 * @param Title $title The page's title.
716 * @return bool True if content of this kind can be used on the given page, false otherwise.
718 public function canBeUsedOn( Title $title ) {
719 $ok = true;
721 Hooks::run( 'ContentModelCanBeUsedOn', [ $this->getModelID(), $title, &$ok ] );
723 return $ok;
727 * Returns the name of the diff engine to use.
729 * @since 1.21
731 * @return string
733 protected function getDiffEngineClass() {
734 return DifferenceEngine::class;
738 * Attempts to merge differences between three versions. Returns a new
739 * Content object for a clean merge and false for failure or a conflict.
741 * This default implementation always returns false.
743 * @since 1.21
745 * @param Content $oldContent The page's previous content.
746 * @param Content $myContent One of the page's conflicting contents.
747 * @param Content $yourContent One of the page's conflicting contents.
749 * @return Content|bool Always false.
751 public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
752 return false;
756 * Return an applicable auto-summary if one exists for the given edit.
758 * @since 1.21
760 * @param Content $oldContent The previous text of the page.
761 * @param Content $newContent The submitted text of the page.
762 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
764 * @return string An appropriate auto-summary, or an empty string.
766 public function getAutosummary( Content $oldContent = null, Content $newContent = null,
767 $flags ) {
768 // Decide what kind of auto-summary is needed.
770 // Redirect auto-summaries
773 * @var $ot Title
774 * @var $rt Title
777 $ot = !is_null( $oldContent ) ? $oldContent->getRedirectTarget() : null;
778 $rt = !is_null( $newContent ) ? $newContent->getRedirectTarget() : null;
780 if ( is_object( $rt ) ) {
781 if ( !is_object( $ot )
782 || !$rt->equals( $ot )
783 || $ot->getFragment() != $rt->getFragment()
785 $truncatedtext = $newContent->getTextForSummary(
787 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
788 - strlen( $rt->getFullText() ) );
790 return wfMessage( 'autoredircomment', $rt->getFullText() )
791 ->rawParams( $truncatedtext )->inContentLanguage()->text();
795 // New page auto-summaries
796 if ( $flags & EDIT_NEW && $newContent->getSize() > 0 ) {
797 // If they're making a new article, give its text, truncated, in
798 // the summary.
800 $truncatedtext = $newContent->getTextForSummary(
801 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
803 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
804 ->inContentLanguage()->text();
807 // Blanking auto-summaries
808 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
809 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
810 } elseif ( !empty( $oldContent )
811 && $oldContent->getSize() > 10 * $newContent->getSize()
812 && $newContent->getSize() < 500
814 // Removing more than 90% of the article
816 $truncatedtext = $newContent->getTextForSummary(
817 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
819 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
820 ->inContentLanguage()->text();
823 // New blank article auto-summary
824 if ( $flags & EDIT_NEW && $newContent->isEmpty() ) {
825 return wfMessage( 'autosumm-newblank' )->inContentLanguage()->text();
828 // If we reach this point, there's no applicable auto-summary for our
829 // case, so our auto-summary is empty.
830 return '';
834 * Auto-generates a deletion reason
836 * @since 1.21
838 * @param Title $title The page's title
839 * @param bool &$hasHistory Whether the page has a history
841 * @return mixed String containing deletion reason or empty string, or
842 * boolean false if no revision occurred
844 * @todo &$hasHistory is extremely ugly, it's here because
845 * WikiPage::getAutoDeleteReason() and Article::generateReason()
846 * have it / want it.
848 public function getAutoDeleteReason( Title $title, &$hasHistory ) {
849 $dbr = wfGetDB( DB_REPLICA );
851 // Get the last revision
852 $rev = Revision::newFromTitle( $title );
854 if ( is_null( $rev ) ) {
855 return false;
858 // Get the article's contents
859 $content = $rev->getContent();
860 $blank = false;
862 // If the page is blank, use the text from the previous revision,
863 // which can only be blank if there's a move/import/protect dummy
864 // revision involved
865 if ( !$content || $content->isEmpty() ) {
866 $prev = $rev->getPrevious();
868 if ( $prev ) {
869 $rev = $prev;
870 $content = $rev->getContent();
871 $blank = true;
875 $this->checkModelID( $rev->getContentModel() );
877 // Find out if there was only one contributor
878 // Only scan the last 20 revisions
879 $res = $dbr->select( 'revision', 'rev_user_text',
881 'rev_page' => $title->getArticleID(),
882 $dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0'
884 __METHOD__,
885 [ 'LIMIT' => 20 ]
888 if ( $res === false ) {
889 // This page has no revisions, which is very weird
890 return false;
893 $hasHistory = ( $res->numRows() > 1 );
894 $row = $dbr->fetchObject( $res );
896 if ( $row ) { // $row is false if the only contributor is hidden
897 $onlyAuthor = $row->rev_user_text;
898 // Try to find a second contributor
899 foreach ( $res as $row ) {
900 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
901 $onlyAuthor = false;
902 break;
905 } else {
906 $onlyAuthor = false;
909 // Generate the summary with a '$1' placeholder
910 if ( $blank ) {
911 // The current revision is blank and the one before is also
912 // blank. It's just not our lucky day
913 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
914 } else {
915 if ( $onlyAuthor ) {
916 $reason = wfMessage(
917 'excontentauthor',
918 '$1',
919 $onlyAuthor
920 )->inContentLanguage()->text();
921 } else {
922 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
926 if ( $reason == '-' ) {
927 // Allow these UI messages to be blanked out cleanly
928 return '';
931 // Max content length = max comment length - length of the comment (excl. $1)
932 $text = $content ? $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) : '';
934 // Now replace the '$1' placeholder
935 $reason = str_replace( '$1', $text, $reason );
937 return $reason;
941 * Get the Content object that needs to be saved in order to undo all revisions
942 * between $undo and $undoafter. Revisions must belong to the same page,
943 * must exist and must not be deleted.
945 * @since 1.21
947 * @param Revision $current The current text
948 * @param Revision $undo The revision to undo
949 * @param Revision $undoafter Must be an earlier revision than $undo
951 * @return mixed String on success, false on failure
953 public function getUndoContent( Revision $current, Revision $undo, Revision $undoafter ) {
954 $cur_content = $current->getContent();
956 if ( empty( $cur_content ) ) {
957 return false; // no page
960 $undo_content = $undo->getContent();
961 $undoafter_content = $undoafter->getContent();
963 if ( !$undo_content || !$undoafter_content ) {
964 return false; // no content to undo
967 try {
968 $this->checkModelID( $cur_content->getModel() );
969 $this->checkModelID( $undo_content->getModel() );
970 if ( $current->getId() !== $undo->getId() ) {
971 // If we are undoing the most recent revision,
972 // its ok to revert content model changes. However
973 // if we are undoing a revision in the middle, then
974 // doing that will be confusing.
975 $this->checkModelID( $undoafter_content->getModel() );
977 } catch ( MWException $e ) {
978 // If the revisions have different content models
979 // just return false
980 return false;
983 if ( $cur_content->equals( $undo_content ) ) {
984 // No use doing a merge if it's just a straight revert.
985 return $undoafter_content;
988 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
990 return $undone_content;
994 * Get parser options suitable for rendering and caching the article
996 * @param IContextSource|User|string $context One of the following:
997 * - IContextSource: Use the User and the Language of the provided
998 * context
999 * - User: Use the provided User object and $wgLang for the language,
1000 * so use an IContextSource object if possible.
1001 * - 'canonical': Canonical options (anonymous user with default
1002 * preferences and content language).
1004 * @throws MWException
1005 * @return ParserOptions
1007 public function makeParserOptions( $context ) {
1008 global $wgContLang, $wgEnableParserLimitReporting;
1010 if ( $context instanceof IContextSource ) {
1011 $options = ParserOptions::newFromContext( $context );
1012 } elseif ( $context instanceof User ) { // settings per user (even anons)
1013 $options = ParserOptions::newFromUser( $context );
1014 } elseif ( $context === 'canonical' ) { // canonical settings
1015 $options = ParserOptions::newFromUserAndLang( new User, $wgContLang );
1016 } else {
1017 throw new MWException( "Bad context for parser options: $context" );
1020 $options->enableLimitReport( $wgEnableParserLimitReporting ); // show inclusion/loop reports
1021 $options->setTidy( true ); // fix bad HTML
1023 return $options;
1027 * Returns true for content models that support caching using the
1028 * ParserCache mechanism. See WikiPage::shouldCheckParserCache().
1030 * @since 1.21
1032 * @return bool Always false.
1034 public function isParserCacheSupported() {
1035 return false;
1039 * Returns true if this content model supports sections.
1040 * This default implementation returns false.
1042 * Content models that return true here should also implement
1043 * Content::getSection, Content::replaceSection, etc. to handle sections..
1045 * @return bool Always false.
1047 public function supportsSections() {
1048 return false;
1052 * Returns true if this content model supports categories.
1053 * The default implementation returns true.
1055 * @return bool Always true.
1057 public function supportsCategories() {
1058 return true;
1062 * Returns true if this content model supports redirects.
1063 * This default implementation returns false.
1065 * Content models that return true here should also implement
1066 * ContentHandler::makeRedirectContent to return a Content object.
1068 * @return bool Always false.
1070 public function supportsRedirects() {
1071 return false;
1075 * Return true if this content model supports direct editing, such as via EditPage.
1077 * @return bool Default is false, and true for TextContent and it's derivatives.
1079 public function supportsDirectEditing() {
1080 return false;
1084 * Whether or not this content model supports direct editing via ApiEditPage
1086 * @return bool Default is false, and true for TextContent and derivatives.
1088 public function supportsDirectApiEditing() {
1089 return $this->supportsDirectEditing();
1093 * Get fields definition for search index
1095 * @todo Expose title, redirect, namespace, text, source_text, text_bytes
1096 * field mappings here. (see T142670 and T143409)
1098 * @param SearchEngine $engine
1099 * @return SearchIndexField[] List of fields this content handler can provide.
1100 * @since 1.28
1102 public function getFieldsForSearchIndex( SearchEngine $engine ) {
1103 $fields['category'] = $engine->makeSearchFieldMapping(
1104 'category',
1105 SearchIndexField::INDEX_TYPE_TEXT
1108 $fields['category']->setFlag( SearchIndexField::FLAG_CASEFOLD );
1110 $fields['external_link'] = $engine->makeSearchFieldMapping(
1111 'external_link',
1112 SearchIndexField::INDEX_TYPE_KEYWORD
1115 $fields['outgoing_link'] = $engine->makeSearchFieldMapping(
1116 'outgoing_link',
1117 SearchIndexField::INDEX_TYPE_KEYWORD
1120 $fields['template'] = $engine->makeSearchFieldMapping(
1121 'template',
1122 SearchIndexField::INDEX_TYPE_KEYWORD
1125 $fields['template']->setFlag( SearchIndexField::FLAG_CASEFOLD );
1127 return $fields;
1131 * Add new field definition to array.
1132 * @param SearchIndexField[] $fields
1133 * @param SearchEngine $engine
1134 * @param string $name
1135 * @param int $type
1136 * @return SearchIndexField[] new field defs
1137 * @since 1.28
1139 protected function addSearchField( &$fields, SearchEngine $engine, $name, $type ) {
1140 $fields[$name] = $engine->makeSearchFieldMapping( $name, $type );
1141 return $fields;
1145 * Return fields to be indexed by search engine
1146 * as representation of this document.
1147 * Overriding class should call parent function or take care of calling
1148 * the SearchDataForIndex hook.
1149 * @param WikiPage $page Page to index
1150 * @param ParserOutput $output
1151 * @param SearchEngine $engine Search engine for which we are indexing
1152 * @return array Map of name=>value for fields
1153 * @since 1.28
1155 public function getDataForSearchIndex( WikiPage $page, ParserOutput $output,
1156 SearchEngine $engine ) {
1157 $fieldData = [];
1158 $content = $page->getContent();
1160 if ( $content ) {
1161 $searchDataExtractor = new ParserOutputSearchDataExtractor();
1163 $fieldData['category'] = $searchDataExtractor->getCategories( $output );
1164 $fieldData['external_link'] = $searchDataExtractor->getExternalLinks( $output );
1165 $fieldData['outgoing_link'] = $searchDataExtractor->getOutgoingLinks( $output );
1166 $fieldData['template'] = $searchDataExtractor->getTemplates( $output );
1168 $text = $content->getTextForSearchIndex();
1170 $fieldData['text'] = $text;
1171 $fieldData['source_text'] = $text;
1172 $fieldData['text_bytes'] = $content->getSize();
1175 Hooks::run( 'SearchDataForIndex', [ &$fieldData, $this, $page, $output, $engine ] );
1176 return $fieldData;
1180 * Produce page output suitable for indexing.
1182 * Specific content handlers may override it if they need different content handling.
1184 * @param WikiPage $page
1185 * @param ParserCache $cache
1186 * @return ParserOutput
1188 public function getParserOutputForIndexing( WikiPage $page, ParserCache $cache = null ) {
1189 $parserOptions = $page->makeParserOptions( 'canonical' );
1190 $revId = $page->getRevision()->getId();
1191 if ( $cache ) {
1192 $parserOutput = $cache->get( $page, $parserOptions );
1194 if ( empty( $parserOutput ) ) {
1195 $parserOutput =
1196 $page->getContent()->getParserOutput( $page->getTitle(), $revId, $parserOptions );
1197 if ( $cache ) {
1198 $cache->save( $parserOutput, $page, $parserOptions );
1201 return $parserOutput;