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
29 * Exception representing a failure to serialize or unserialize a content object.
33 class MWContentSerializationException
extends MWException
{
37 * Exception thrown when an unregistered content model is requested. This error
38 * can be triggered by user input, so a separate exception class is provided so
39 * callers can substitute a context-specific, internationalised error message.
44 class MWUnknownContentModelException
extends MWException
{
45 /** @var string The name of the unknown content model */
48 /** @param string $modelId */
49 function __construct( $modelId ) {
50 parent
::__construct( "The content model '$modelId' is not registered on this wiki.\n" .
51 'See https://www.mediawiki.org/wiki/Content_handlers to find out which extensions ' .
52 'handle this content model.' );
53 $this->modelId
= $modelId;
57 public function getModelId() {
63 * A content handler knows how do deal with a specific type of content on a wiki
64 * page. Content is stored in the database in a serialized form (using a
65 * serialization format a.k.a. MIME type) and is unserialized into its native
66 * PHP representation (the content model), which is wrapped in an instance of
67 * the appropriate subclass of Content.
69 * ContentHandler instances are stateless singletons that serve, among other
70 * things, as a factory for Content objects. Generally, there is one subclass
71 * of ContentHandler and one subclass of Content for every type of content model.
73 * Some content types have a flat model, that is, their native representation
74 * is the same as their serialized form. Examples would be JavaScript and CSS
75 * code. As of now, this also applies to wikitext (MediaWiki's default content
76 * type), but wikitext content may be represented by a DOM or AST structure in
81 abstract class ContentHandler
{
83 * Switch for enabling deprecation warnings. Used by ContentHandler::deprecated()
84 * and ContentHandler::runLegacyHooks().
86 * Once the ContentHandler code has settled in a bit, this should be set to true to
87 * make extensions etc. show warnings when using deprecated functions and hooks.
89 protected static $enableDeprecationWarnings = false;
92 * Convenience function for getting flat text from a Content object. This
93 * should only be used in the context of backwards compatibility with code
94 * that is not yet able to handle Content objects!
96 * If $content is null, this method returns the empty string.
98 * If $content is an instance of TextContent, this method returns the flat
99 * text as returned by $content->getNativeData().
101 * If $content is not a TextContent object, the behavior of this method
102 * depends on the global $wgContentHandlerTextFallback:
103 * - If $wgContentHandlerTextFallback is 'fail' and $content is not a
104 * TextContent object, an MWException is thrown.
105 * - If $wgContentHandlerTextFallback is 'serialize' and $content is not a
106 * TextContent object, $content->serialize() is called to get a string
107 * form of the content.
108 * - If $wgContentHandlerTextFallback is 'ignore' and $content is not a
109 * TextContent object, this method returns null.
110 * - otherwise, the behavior is undefined.
114 * @param Content $content
116 * @throws MWException If the content is not an instance of TextContent and
117 * wgContentHandlerTextFallback was set to 'fail'.
118 * @return string|null Textual form of the content, if available.
120 public static function getContentText( Content
$content = null ) {
121 global $wgContentHandlerTextFallback;
123 if ( is_null( $content ) ) {
127 if ( $content instanceof TextContent
) {
128 return $content->getNativeData();
131 wfDebugLog( 'ContentHandler', 'Accessing ' . $content->getModel() . ' content as text!' );
133 if ( $wgContentHandlerTextFallback == 'fail' ) {
134 throw new MWException(
135 "Attempt to get text from Content with model " .
140 if ( $wgContentHandlerTextFallback == 'serialize' ) {
141 return $content->serialize();
148 * Convenience function for creating a Content object from a given textual
151 * $text will be deserialized into a Content object of the model specified
152 * by $modelId (or, if that is not given, $title->getContentModel()) using
157 * @param string $text The textual representation, will be
158 * unserialized to create the Content object
159 * @param Title $title The title of the page this text belongs to.
160 * Required if $modelId is not provided.
161 * @param string $modelId The model to deserialize to. If not provided,
162 * $title->getContentModel() is used.
163 * @param string $format The format to use for deserialization. If not
164 * given, the model's default format is used.
166 * @throws MWException If model ID or format is not supported or if the text can not be
167 * unserialized using the format.
168 * @return Content A Content object representing the text.
170 public static function makeContent( $text, Title
$title = null,
171 $modelId = null, $format = null ) {
172 if ( is_null( $modelId ) ) {
173 if ( is_null( $title ) ) {
174 throw new MWException( "Must provide a Title object or a content model ID." );
177 $modelId = $title->getContentModel();
180 $handler = ContentHandler
::getForModelID( $modelId );
182 return $handler->unserializeContent( $text, $format );
186 * Returns the name of the default content model to be used for the page
187 * with the given title.
189 * Note: There should rarely be need to call this method directly.
190 * To determine the actual content model for a given page, use
191 * Title::getContentModel().
193 * Which model is to be used by default for the page is determined based
194 * on several factors:
195 * - The global setting $wgNamespaceContentModels specifies a content model
197 * - The hook ContentHandlerDefaultModelFor may be used to override the page's default
199 * - Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript
200 * model if they end in .js or .css, respectively.
201 * - Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
202 * - The hook TitleIsCssOrJsPage may be used to force a page to use the CSS
203 * or JavaScript model. This is a compatibility feature. The ContentHandlerDefaultModelFor
204 * hook should be used instead if possible.
205 * - The hook TitleIsWikitextPage may be used to force a page to use the
206 * wikitext model. This is a compatibility feature. The ContentHandlerDefaultModelFor
207 * hook should be used instead if possible.
209 * If none of the above applies, the wikitext model is used.
211 * Note: this is used by, and may thus not use, Title::getContentModel()
215 * @param Title $title
217 * @return string Default model name for the page given by $title
219 public static function getDefaultModelFor( Title
$title ) {
220 // NOTE: this method must not rely on $title->getContentModel() directly or indirectly,
221 // because it is used to initialize the mContentModel member.
223 $ns = $title->getNamespace();
227 $model = MWNamespace
::getNamespaceContentModel( $ns );
229 // Hook can determine default model
230 if ( !Hooks
::run( 'ContentHandlerDefaultModelFor', array( $title, &$model ) ) ) {
231 if ( !is_null( $model ) ) {
236 // Could this page contain code based on the title?
237 $isCodePage = NS_MEDIAWIKI
== $ns && preg_match( '!\.(css|js|json)$!u', $title->getText(), $m );
242 // Hook can force JS/CSS
243 Hooks
::run( 'TitleIsCssOrJsPage', array( $title, &$isCodePage ), '1.25' );
245 // Is this a user subpage containing code?
246 $isCodeSubpage = NS_USER
== $ns
248 && preg_match( "/\\/.*\\.(js|css|json)$/", $title->getText(), $m );
249 if ( $isCodeSubpage ) {
253 // Is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
254 $isWikitext = is_null( $model ) ||
$model == CONTENT_MODEL_WIKITEXT
;
255 $isWikitext = $isWikitext && !$isCodePage && !$isCodeSubpage;
257 // Hook can override $isWikitext
258 Hooks
::run( 'TitleIsWikitextPage', array( $title, &$isWikitext ), '1.25' );
260 if ( !$isWikitext ) {
263 return CONTENT_MODEL_JAVASCRIPT
;
265 return CONTENT_MODEL_CSS
;
267 return CONTENT_MODEL_JSON
;
269 return is_null( $model ) ? CONTENT_MODEL_TEXT
: $model;
273 // We established that it must be wikitext
275 return CONTENT_MODEL_WIKITEXT
;
279 * Returns the appropriate ContentHandler singleton for the given title.
283 * @param Title $title
285 * @return ContentHandler
287 public static function getForTitle( Title
$title ) {
288 $modelId = $title->getContentModel();
290 return ContentHandler
::getForModelID( $modelId );
294 * Returns the appropriate ContentHandler singleton for the given Content
299 * @param Content $content
301 * @return ContentHandler
303 public static function getForContent( Content
$content ) {
304 $modelId = $content->getModel();
306 return ContentHandler
::getForModelID( $modelId );
310 * @var array A Cache of ContentHandler instances by model id
312 protected static $handlers;
315 * Returns the ContentHandler singleton for the given model ID. Use the
316 * CONTENT_MODEL_XXX constants to identify the desired content model.
318 * ContentHandler singletons are taken from the global $wgContentHandlers
319 * array. Keys in that array are model names, the values are either
320 * ContentHandler singleton objects, or strings specifying the appropriate
321 * subclass of ContentHandler.
323 * If a class name is encountered when looking up the singleton for a given
324 * model name, the class is instantiated and the class name is replaced by
325 * the resulting singleton in $wgContentHandlers.
327 * If no ContentHandler is defined for the desired $modelId, the
328 * ContentHandler may be provided by the ContentHandlerForModelID hook.
329 * If no ContentHandler can be determined, an MWException is raised.
333 * @param string $modelId The ID of the content model for which to get a
334 * handler. Use CONTENT_MODEL_XXX constants.
336 * @throws MWException For internal errors and problems in the configuration.
337 * @throws MWUnknownContentModelException If no handler is known for the model ID.
338 * @return ContentHandler The ContentHandler singleton for handling the model given by the ID.
340 public static function getForModelID( $modelId ) {
341 global $wgContentHandlers;
343 if ( isset( ContentHandler
::$handlers[$modelId] ) ) {
344 return ContentHandler
::$handlers[$modelId];
347 if ( empty( $wgContentHandlers[$modelId] ) ) {
350 Hooks
::run( 'ContentHandlerForModelID', array( $modelId, &$handler ) );
352 if ( $handler === null ) {
353 throw new MWUnknownContentModelException( $modelId );
356 if ( !( $handler instanceof ContentHandler
) ) {
357 throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
360 $class = $wgContentHandlers[$modelId];
361 $handler = new $class( $modelId );
363 if ( !( $handler instanceof ContentHandler
) ) {
364 throw new MWException( "$class from \$wgContentHandlers is not " .
365 "compatible with ContentHandler" );
369 wfDebugLog( 'ContentHandler', 'Created handler for ' . $modelId
370 . ': ' . get_class( $handler ) );
372 ContentHandler
::$handlers[$modelId] = $handler;
374 return ContentHandler
::$handlers[$modelId];
378 * Returns the localized name for a given content model.
380 * Model names are localized using system messages. Message keys
381 * have the form content-model-$name, where $name is getContentModelName( $id ).
383 * @param string $name The content model ID, as given by a CONTENT_MODEL_XXX
384 * constant or returned by Revision::getContentModel().
385 * @param Language|null $lang The language to parse the message in (since 1.26)
387 * @throws MWException If the model ID isn't known.
388 * @return string The content model's localized name.
390 public static function getLocalizedName( $name, Language
$lang = null ) {
391 // Messages: content-model-wikitext, content-model-text,
392 // content-model-javascript, content-model-css
393 $key = "content-model-$name";
395 $msg = wfMessage( $key );
397 $msg->inLanguage( $lang );
400 return $msg->exists() ?
$msg->plain() : $name;
403 public static function getContentModels() {
404 global $wgContentHandlers;
406 return array_keys( $wgContentHandlers );
409 public static function getAllContentFormats() {
410 global $wgContentHandlers;
414 foreach ( $wgContentHandlers as $model => $class ) {
415 $handler = ContentHandler
::getForModelID( $model );
416 $formats = array_merge( $formats, $handler->getSupportedFormats() );
419 $formats = array_unique( $formats );
424 // ------------------------------------------------------------------------
434 protected $mSupportedFormats;
437 * Constructor, initializing the ContentHandler instance with its model ID
438 * and a list of supported formats. Values for the parameters are typically
439 * provided as literals by subclass's constructors.
441 * @param string $modelId (use CONTENT_MODEL_XXX constants).
442 * @param string[] $formats List for supported serialization formats
443 * (typically as MIME types)
445 public function __construct( $modelId, $formats ) {
446 $this->mModelID
= $modelId;
447 $this->mSupportedFormats
= $formats;
449 $this->mModelName
= preg_replace( '/(Content)?Handler$/', '', get_class( $this ) );
450 $this->mModelName
= preg_replace( '/[_\\\\]/', '', $this->mModelName
);
451 $this->mModelName
= strtolower( $this->mModelName
);
455 * Serializes a Content object of the type supported by this ContentHandler.
459 * @param Content $content The Content object to serialize
460 * @param string $format The desired serialization format
462 * @return string Serialized form of the content
464 abstract public function serializeContent( Content
$content, $format = null );
467 * Applies transformations on export (returns the blob unchanged per default).
468 * Subclasses may override this to perform transformations such as conversion
469 * of legacy formats or filtering of internal meta-data.
471 * @param string $blob The blob to be exported
472 * @param string|null $format The blob's serialization format
476 public function exportTransform( $blob, $format = null ) {
481 * Unserializes a Content object of the type supported by this ContentHandler.
485 * @param string $blob Serialized form of the content
486 * @param string $format The format used for serialization
488 * @return Content The Content object created by deserializing $blob
490 abstract public function unserializeContent( $blob, $format = null );
493 * Apply import transformation (per default, returns $blob unchanged).
494 * This gives subclasses an opportunity to transform data blobs on import.
498 * @param string $blob
499 * @param string|null $format
503 public function importTransform( $blob, $format = null ) {
508 * Creates an empty Content object of the type supported by this
515 abstract public function makeEmptyContent();
518 * Creates a new Content object that acts as a redirect to the given page,
519 * or null if redirects are not supported by this content model.
521 * This default implementation always returns null. Subclasses supporting redirects
522 * must override this method.
524 * Note that subclasses that override this method to return a Content object
525 * should also override supportsRedirects() to return true.
529 * @param Title $destination The page to redirect to.
530 * @param string $text Text to include in the redirect, if possible.
532 * @return Content Always null.
534 public function makeRedirectContent( Title
$destination, $text = '' ) {
539 * Returns the model id that identifies the content model this
540 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
544 * @return string The model ID
546 public function getModelID() {
547 return $this->mModelID
;
553 * @param string $model_id The model to check
555 * @throws MWException If the model ID is not the ID of the content model supported by this
558 protected function checkModelID( $model_id ) {
559 if ( $model_id !== $this->mModelID
) {
560 throw new MWException( "Bad content model: " .
561 "expected {$this->mModelID} " .
562 "but got $model_id." );
567 * Returns a list of serialization formats supported by the
568 * serializeContent() and unserializeContent() methods of this
573 * @return string[] List of serialization formats as MIME type like strings
575 public function getSupportedFormats() {
576 return $this->mSupportedFormats
;
580 * The format used for serialization/deserialization by default by this
583 * This default implementation will return the first element of the array
584 * of formats that was passed to the constructor.
588 * @return string The name of the default serialization format as a MIME type
590 public function getDefaultFormat() {
591 return $this->mSupportedFormats
[0];
595 * Returns true if $format is a serialization format supported by this
596 * ContentHandler, and false otherwise.
598 * Note that if $format is null, this method always returns true, because
599 * null means "use the default format".
603 * @param string $format The serialization format to check
607 public function isSupportedFormat( $format ) {
609 return true; // this means "use the default"
612 return in_array( $format, $this->mSupportedFormats
);
616 * Convenient for checking whether a format provided as a parameter is actually supported.
618 * @param string $format The serialization format to check
620 * @throws MWException If the format is not supported by this content handler.
622 protected function checkFormat( $format ) {
623 if ( !$this->isSupportedFormat( $format ) ) {
624 throw new MWException(
625 "Format $format is not supported for content model "
626 . $this->getModelID()
632 * Returns overrides for action handlers.
633 * Classes listed here will be used instead of the default one when
634 * (and only when) $wgActions[$action] === true. This allows subclasses
635 * to override the default action handlers.
639 * @return array Always an empty array.
641 public function getActionOverrides() {
646 * Factory for creating an appropriate DifferenceEngine for this content model.
650 * @param IContextSource $context Context to use, anything else will be ignored.
651 * @param int $old Revision ID we want to show and diff with.
652 * @param int|string $new Either a revision ID or one of the strings 'cur', 'prev' or 'next'.
653 * @param int $rcid FIXME: Deprecated, no longer used. Defaults to 0.
654 * @param bool $refreshCache If set, refreshes the diff cache. Defaults to false.
655 * @param bool $unhide If set, allow viewing deleted revs. Defaults to false.
657 * @return DifferenceEngine
659 public function createDifferenceEngine( IContextSource
$context, $old = 0, $new = 0,
660 $rcid = 0, // FIXME: Deprecated, no longer used
661 $refreshCache = false, $unhide = false ) {
663 // hook: get difference engine
664 $differenceEngine = null;
665 if ( !Hooks
::run( 'GetDifferenceEngine',
666 array( $context, $old, $new, $refreshCache, $unhide, &$differenceEngine )
668 return $differenceEngine;
670 $diffEngineClass = $this->getDiffEngineClass();
671 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
675 * Get the language in which the content of the given page is written.
677 * This default implementation just returns $wgContLang (except for pages
678 * in the MediaWiki namespace)
680 * Note that the pages language is not cacheable, since it may in some
681 * cases depend on user settings.
683 * Also note that the page language may or may not depend on the actual content of the page,
684 * that is, this method may load the content in order to determine the language.
688 * @param Title $title The page to determine the language for.
689 * @param Content $content The page's content, if you have it handy, to avoid reloading it.
691 * @return Language The page's language
693 public function getPageLanguage( Title
$title, Content
$content = null ) {
694 global $wgContLang, $wgLang;
695 $pageLang = $wgContLang;
697 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
698 // Parse mediawiki messages with correct target language
699 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $title->getText() );
700 $pageLang = wfGetLangObj( $lang );
703 Hooks
::run( 'PageContentLanguage', array( $title, &$pageLang, $wgLang ) );
705 return wfGetLangObj( $pageLang );
709 * Get the language in which the content of this page is written when
710 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
711 * specified a preferred variant, the variant will be used.
713 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
714 * the user specified a preferred variant.
716 * Note that the pages view language is not cacheable, since it depends on user settings.
718 * Also note that the page language may or may not depend on the actual content of the page,
719 * that is, this method may load the content in order to determine the language.
723 * @param Title $title The page to determine the language for.
724 * @param Content $content The page's content, if you have it handy, to avoid reloading it.
726 * @return Language The page's language for viewing
728 public function getPageViewLanguage( Title
$title, Content
$content = null ) {
729 $pageLang = $this->getPageLanguage( $title, $content );
731 if ( $title->getNamespace() !== NS_MEDIAWIKI
) {
732 // If the user chooses a variant, the content is actually
733 // in a language whose code is the variant code.
734 $variant = $pageLang->getPreferredVariant();
735 if ( $pageLang->getCode() !== $variant ) {
736 $pageLang = Language
::factory( $variant );
744 * Determines whether the content type handled by this ContentHandler
745 * can be used on the given page.
747 * This default implementation always returns true.
748 * Subclasses may override this to restrict the use of this content model to specific locations,
749 * typically based on the namespace or some other aspect of the title, such as a special suffix
750 * (e.g. ".svg" for SVG content).
752 * @note this calls the ContentHandlerCanBeUsedOn hook which may be used to override which
753 * content model can be used where.
755 * @param Title $title The page's title.
757 * @return bool True if content of this kind can be used on the given page, false otherwise.
759 public function canBeUsedOn( Title
$title ) {
762 Hooks
::run( 'ContentModelCanBeUsedOn', array( $this->getModelID(), $title, &$ok ) );
768 * Returns the name of the diff engine to use.
774 protected function getDiffEngineClass() {
775 return 'DifferenceEngine';
779 * Attempts to merge differences between three versions. Returns a new
780 * Content object for a clean merge and false for failure or a conflict.
782 * This default implementation always returns false.
786 * @param Content $oldContent The page's previous content.
787 * @param Content $myContent One of the page's conflicting contents.
788 * @param Content $yourContent One of the page's conflicting contents.
790 * @return Content|bool Always false.
792 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
797 * Return an applicable auto-summary if one exists for the given edit.
801 * @param Content $oldContent The previous text of the page.
802 * @param Content $newContent The submitted text of the page.
803 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
805 * @return string An appropriate auto-summary, or an empty string.
807 public function getAutosummary( Content
$oldContent = null, Content
$newContent = null,
809 // Decide what kind of auto-summary is needed.
811 // Redirect auto-summaries
818 $ot = !is_null( $oldContent ) ?
$oldContent->getRedirectTarget() : null;
819 $rt = !is_null( $newContent ) ?
$newContent->getRedirectTarget() : null;
821 if ( is_object( $rt ) ) {
822 if ( !is_object( $ot )
823 ||
!$rt->equals( $ot )
824 ||
$ot->getFragment() != $rt->getFragment()
826 $truncatedtext = $newContent->getTextForSummary(
828 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
829 - strlen( $rt->getFullText() ) );
831 return wfMessage( 'autoredircomment', $rt->getFullText() )
832 ->rawParams( $truncatedtext )->inContentLanguage()->text();
836 // New page auto-summaries
837 if ( $flags & EDIT_NEW
&& $newContent->getSize() > 0 ) {
838 // If they're making a new article, give its text, truncated, in
841 $truncatedtext = $newContent->getTextForSummary(
842 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
844 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
845 ->inContentLanguage()->text();
848 // Blanking auto-summaries
849 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
850 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
851 } elseif ( !empty( $oldContent )
852 && $oldContent->getSize() > 10 * $newContent->getSize()
853 && $newContent->getSize() < 500
855 // Removing more than 90% of the article
857 $truncatedtext = $newContent->getTextForSummary(
858 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
860 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
861 ->inContentLanguage()->text();
864 // New blank article auto-summary
865 if ( $flags & EDIT_NEW
&& $newContent->isEmpty() ) {
866 return wfMessage( 'autosumm-newblank' )->inContentLanguage()->text();
869 // If we reach this point, there's no applicable auto-summary for our
870 // case, so our auto-summary is empty.
875 * Auto-generates a deletion reason
879 * @param Title $title The page's title
880 * @param bool &$hasHistory Whether the page has a history
882 * @return mixed String containing deletion reason or empty string, or
883 * boolean false if no revision occurred
885 * @todo &$hasHistory is extremely ugly, it's here because
886 * WikiPage::getAutoDeleteReason() and Article::generateReason()
889 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
890 $dbw = wfGetDB( DB_MASTER
);
892 // Get the last revision
893 $rev = Revision
::newFromTitle( $title );
895 if ( is_null( $rev ) ) {
899 // Get the article's contents
900 $content = $rev->getContent();
903 // If the page is blank, use the text from the previous revision,
904 // which can only be blank if there's a move/import/protect dummy
906 if ( !$content ||
$content->isEmpty() ) {
907 $prev = $rev->getPrevious();
911 $content = $rev->getContent();
916 $this->checkModelID( $rev->getContentModel() );
918 // Find out if there was only one contributor
919 // Only scan the last 20 revisions
920 $res = $dbw->select( 'revision', 'rev_user_text',
922 'rev_page' => $title->getArticleID(),
923 $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0'
926 array( 'LIMIT' => 20 )
929 if ( $res === false ) {
930 // This page has no revisions, which is very weird
934 $hasHistory = ( $res->numRows() > 1 );
935 $row = $dbw->fetchObject( $res );
937 if ( $row ) { // $row is false if the only contributor is hidden
938 $onlyAuthor = $row->rev_user_text
;
939 // Try to find a second contributor
940 foreach ( $res as $row ) {
941 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
950 // Generate the summary with a '$1' placeholder
952 // The current revision is blank and the one before is also
953 // blank. It's just not our lucky day
954 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
961 )->inContentLanguage()->text();
963 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
967 if ( $reason == '-' ) {
968 // Allow these UI messages to be blanked out cleanly
972 // Max content length = max comment length - length of the comment (excl. $1)
973 $text = $content ?
$content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) : '';
975 // Now replace the '$1' placeholder
976 $reason = str_replace( '$1', $text, $reason );
982 * Get the Content object that needs to be saved in order to undo all revisions
983 * between $undo and $undoafter. Revisions must belong to the same page,
984 * must exist and must not be deleted.
988 * @param Revision $current The current text
989 * @param Revision $undo The revision to undo
990 * @param Revision $undoafter Must be an earlier revision than $undo
992 * @return mixed String on success, false on failure
994 public function getUndoContent( Revision
$current, Revision
$undo, Revision
$undoafter ) {
995 $cur_content = $current->getContent();
997 if ( empty( $cur_content ) ) {
998 return false; // no page
1001 $undo_content = $undo->getContent();
1002 $undoafter_content = $undoafter->getContent();
1004 if ( !$undo_content ||
!$undoafter_content ) {
1005 return false; // no content to undo
1008 $this->checkModelID( $cur_content->getModel() );
1009 $this->checkModelID( $undo_content->getModel() );
1010 $this->checkModelID( $undoafter_content->getModel() );
1012 if ( $cur_content->equals( $undo_content ) ) {
1013 // No use doing a merge if it's just a straight revert.
1014 return $undoafter_content;
1017 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
1019 return $undone_content;
1023 * Get parser options suitable for rendering and caching the article
1025 * @param IContextSource|User|string $context One of the following:
1026 * - IContextSource: Use the User and the Language of the provided
1028 * - User: Use the provided User object and $wgLang for the language,
1029 * so use an IContextSource object if possible.
1030 * - 'canonical': Canonical options (anonymous user with default
1031 * preferences and content language).
1033 * @throws MWException
1034 * @return ParserOptions
1036 public function makeParserOptions( $context ) {
1037 global $wgContLang, $wgEnableParserLimitReporting;
1039 if ( $context instanceof IContextSource
) {
1040 $options = ParserOptions
::newFromContext( $context );
1041 } elseif ( $context instanceof User
) { // settings per user (even anons)
1042 $options = ParserOptions
::newFromUser( $context );
1043 } elseif ( $context === 'canonical' ) { // canonical settings
1044 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1046 throw new MWException( "Bad context for parser options: $context" );
1049 $options->enableLimitReport( $wgEnableParserLimitReporting ); // show inclusion/loop reports
1050 $options->setTidy( true ); // fix bad HTML
1056 * Returns true for content models that support caching using the
1057 * ParserCache mechanism. See WikiPage::shouldCheckParserCache().
1061 * @return bool Always false.
1063 public function isParserCacheSupported() {
1068 * Returns true if this content model supports sections.
1069 * This default implementation returns false.
1071 * Content models that return true here should also implement
1072 * Content::getSection, Content::replaceSection, etc. to handle sections..
1074 * @return bool Always false.
1076 public function supportsSections() {
1081 * Returns true if this content model supports redirects.
1082 * This default implementation returns false.
1084 * Content models that return true here should also implement
1085 * ContentHandler::makeRedirectContent to return a Content object.
1087 * @return bool Always false.
1089 public function supportsRedirects() {
1094 * Return true if this content model supports direct editing, such as via EditPage.
1096 * @return bool Default is false, and true for TextContent and it's derivatives.
1098 public function supportsDirectEditing() {
1103 * Whether or not this content model supports direct editing via ApiEditPage
1105 * @return bool Default is false, and true for TextContent and derivatives.
1107 public function supportsDirectApiEditing() {
1108 return $this->supportsDirectEditing();
1112 * Logs a deprecation warning, visible if $wgDevelopmentWarnings, but only if
1113 * self::$enableDeprecationWarnings is set to true.
1115 * @param string $func The name of the deprecated function
1116 * @param string $version The version since the method is deprecated. Usually 1.21
1117 * for ContentHandler related stuff.
1118 * @param string|bool $component : Component to which the function belongs.
1119 * If false, it is assumed the function is in MediaWiki core.
1121 * @see ContentHandler::$enableDeprecationWarnings
1124 public static function deprecated( $func, $version, $component = false ) {
1125 if ( self
::$enableDeprecationWarnings ) {
1126 wfDeprecated( $func, $version, $component, 3 );
1131 * Call a legacy hook that uses text instead of Content objects.
1132 * Will log a warning when a matching hook function is registered.
1133 * If the textual representation of the content is changed by the
1134 * hook function, a new Content object is constructed from the new
1137 * @param string $event Event name
1138 * @param array $args Parameters passed to hook functions
1139 * @param bool $warn Whether to log a warning.
1140 * Default to self::$enableDeprecationWarnings.
1141 * May be set to false for testing.
1143 * @return bool True if no handler aborted the hook
1145 * @see ContentHandler::$enableDeprecationWarnings
1147 public static function runLegacyHooks( $event, $args = array(),
1151 if ( $warn === null ) {
1152 $warn = self
::$enableDeprecationWarnings;
1155 if ( !Hooks
::isRegistered( $event ) ) {
1156 return true; // nothing to do here
1160 // Log information about which handlers are registered for the legacy hook,
1161 // so we can find and fix them.
1163 $handlers = Hooks
::getHandlers( $event );
1164 $handlerInfo = array();
1166 MediaWiki\
suppressWarnings();
1168 foreach ( $handlers as $handler ) {
1169 if ( is_array( $handler ) ) {
1170 if ( is_object( $handler[0] ) ) {
1171 $info = get_class( $handler[0] );
1173 $info = $handler[0];
1176 if ( isset( $handler[1] ) ) {
1177 $info .= '::' . $handler[1];
1179 } elseif ( is_object( $handler ) ) {
1180 $info = get_class( $handler[0] );
1181 $info .= '::on' . $event;
1186 $handlerInfo[] = $info;
1189 MediaWiki\restoreWarnings
();
1191 wfWarn( "Using obsolete hook $event via ContentHandler::runLegacyHooks()! Handlers: " .
1192 implode( ', ', $handlerInfo ), 2 );
1195 // convert Content objects to text
1196 $contentObjects = array();
1197 $contentTexts = array();
1199 foreach ( $args as $k => $v ) {
1200 if ( $v instanceof Content
) {
1201 /* @var Content $v */
1203 $contentObjects[$k] = $v;
1205 $v = $v->serialize();
1206 $contentTexts[$k] = $v;
1211 // call the hook functions
1212 $ok = Hooks
::run( $event, $args );
1214 // see if the hook changed the text
1215 foreach ( $contentTexts as $k => $orig ) {
1216 /* @var Content $content */
1218 $modified = $args[$k];
1219 $content = $contentObjects[$k];
1221 if ( $modified !== $orig ) {
1222 // text was changed, create updated Content object
1223 $content = $content->getContentHandler()->unserializeContent( $modified );
1226 $args[$k] = $content;