4 * Exception representing a failure to serialize or unserialize a content object.
6 class MWContentSerializationException
extends MWException
{
11 * A content handler knows how do deal with a specific type of content on a wiki
12 * page. Content is stored in the database in a serialized form (using a
13 * serialization format a.k.a. MIME type) and is unserialized into its native
14 * PHP representation (the content model), which is wrapped in an instance of
15 * the appropriate subclass of Content.
17 * ContentHandler instances are stateless singletons that serve, among other
18 * things, as a factory for Content objects. Generally, there is one subclass
19 * of ContentHandler and one subclass of Content for every type of content model.
21 * Some content types have a flat model, that is, their native representation
22 * is the same as their serialized form. Examples would be JavaScript and CSS
23 * code. As of now, this also applies to wikitext (MediaWiki's default content
24 * type), but wikitext content may be represented by a DOM or AST structure in
29 abstract class ContentHandler
{
32 * Switch for enabling deprecation warnings. Used by ContentHandler::deprecated()
33 * and ContentHandler::runLegacyHooks().
35 * Once the ContentHandler code has settled in a bit, this should be set to true to
36 * make extensions etc. show warnings when using deprecated functions and hooks.
38 protected static $enableDeprecationWarnings = false;
41 * Convenience function for getting flat text from a Content object. This
42 * should only be used in the context of backwards compatibility with code
43 * that is not yet able to handle Content objects!
45 * If $content is null, this method returns the empty string.
47 * If $content is an instance of TextContent, this method returns the flat
48 * text as returned by $content->getNativeData().
50 * If $content is not a TextContent object, the behavior of this method
51 * depends on the global $wgContentHandlerTextFallback:
52 * - If $wgContentHandlerTextFallback is 'fail' and $content is not a
53 * TextContent object, an MWException is thrown.
54 * - If $wgContentHandlerTextFallback is 'serialize' and $content is not a
55 * TextContent object, $content->serialize() is called to get a string
56 * form of the content.
57 * - If $wgContentHandlerTextFallback is 'ignore' and $content is not a
58 * TextContent object, this method returns null.
59 * - otherwise, the behaviour is undefined.
64 * @param $content Content|null
65 * @return null|string the textual form of $content, if available
66 * @throws MWException if $content is not an instance of TextContent and
67 * $wgContentHandlerTextFallback was set to 'fail'.
69 public static function getContentText( Content
$content = null ) {
70 global $wgContentHandlerTextFallback;
72 if ( is_null( $content ) ) {
76 if ( $content instanceof TextContent
) {
77 return $content->getNativeData();
80 if ( $wgContentHandlerTextFallback == 'fail' ) {
81 throw new MWException(
82 "Attempt to get text from Content with model " .
87 if ( $wgContentHandlerTextFallback == 'serialize' ) {
88 return $content->serialize();
95 * Convenience function for creating a Content object from a given textual
98 * $text will be deserialized into a Content object of the model specified
99 * by $modelId (or, if that is not given, $title->getContentModel()) using
106 * @param $text string the textual representation, will be
107 * unserialized to create the Content object
108 * @param $title null|Title the title of the page this text belongs to.
109 * Required if $modelId is not provided.
110 * @param $modelId null|string the model to deserialize to. If not provided,
111 * $title->getContentModel() is used.
112 * @param $format null|string the format to use for deserialization. If not
113 * given, the model's default format is used.
115 * @return Content a Content object representing $text
117 * @throw MWException if $model or $format is not supported or if $text can
118 * not be unserialized using $format.
120 public static function makeContent( $text, Title
$title = null,
121 $modelId = null, $format = null )
123 if ( is_null( $modelId ) ) {
124 if ( is_null( $title ) ) {
125 throw new MWException( "Must provide a Title object or a content model ID." );
128 $modelId = $title->getContentModel();
131 $handler = ContentHandler
::getForModelID( $modelId );
132 return $handler->unserializeContent( $text, $format );
136 * Returns the name of the default content model to be used for the page
137 * with the given title.
139 * Note: There should rarely be need to call this method directly.
140 * To determine the actual content model for a given page, use
141 * Title::getContentModel().
143 * Which model is to be used by default for the page is determined based
144 * on several factors:
145 * - The global setting $wgNamespaceContentModels specifies a content model
147 * - The hook ContentHandlerDefaultModelFor may be used to override the page's default
149 * - Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript
150 * model if they end in .js or .css, respectively.
151 * - Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
152 * - The hook TitleIsCssOrJsPage may be used to force a page to use the CSS
153 * or JavaScript model. This is a compatibility feature. The ContentHandlerDefaultModelFor
154 * hook should be used instead if possible.
155 * - The hook TitleIsWikitextPage may be used to force a page to use the
156 * wikitext model. This is a compatibility feature. The ContentHandlerDefaultModelFor
157 * hook should be used instead if possible.
159 * If none of the above applies, the wikitext model is used.
161 * Note: this is used by, and may thus not use, Title::getContentModel()
166 * @param $title Title
167 * @return null|string default model name for the page given by $title
169 public static function getDefaultModelFor( Title
$title ) {
170 global $wgNamespaceContentModels;
172 // NOTE: this method must not rely on $title->getContentModel() directly or indirectly,
173 // because it is used to initialize the mContentModel member.
175 $ns = $title->getNamespace();
181 if ( !empty( $wgNamespaceContentModels[ $ns ] ) ) {
182 $model = $wgNamespaceContentModels[ $ns ];
185 // Hook can determine default model
186 if ( !wfRunHooks( 'ContentHandlerDefaultModelFor', array( $title, &$model ) ) ) {
187 if ( !is_null( $model ) ) {
192 // Could this page contain custom CSS or JavaScript, based on the title?
193 $isCssOrJsPage = NS_MEDIAWIKI
== $ns && preg_match( '!\.(css|js)$!u', $title->getText(), $m );
194 if ( $isCssOrJsPage ) {
198 // Hook can force JS/CSS
199 wfRunHooks( 'TitleIsCssOrJsPage', array( $title, &$isCssOrJsPage ) );
201 // Is this a .css subpage of a user page?
202 $isJsCssSubpage = NS_USER
== $ns
204 && preg_match( "/\\/.*\\.(js|css)$/", $title->getText(), $m );
205 if ( $isJsCssSubpage ) {
209 // Is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
210 $isWikitext = is_null( $model ) ||
$model == CONTENT_MODEL_WIKITEXT
;
211 $isWikitext = $isWikitext && !$isCssOrJsPage && !$isJsCssSubpage;
213 // Hook can override $isWikitext
214 wfRunHooks( 'TitleIsWikitextPage', array( $title, &$isWikitext ) );
216 if ( !$isWikitext ) {
219 return CONTENT_MODEL_JAVASCRIPT
;
221 return CONTENT_MODEL_CSS
;
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.
238 * @param $title Title
239 * @return ContentHandler
241 public static function getForTitle( Title
$title ) {
242 $modelId = $title->getContentModel();
243 return ContentHandler
::getForModelID( $modelId );
247 * Returns the appropriate ContentHandler singleton for the given Content
253 * @param $content Content
254 * @return ContentHandler
256 public static function getForContent( Content
$content ) {
257 $modelId = $content->getModel();
258 return ContentHandler
::getForModelID( $modelId );
262 * @var Array A Cache of ContentHandler instances by model id
267 * Returns the ContentHandler singleton for the given model ID. Use the
268 * CONTENT_MODEL_XXX constants to identify the desired content model.
270 * ContentHandler singletons are taken from the global $wgContentHandlers
271 * array. Keys in that array are model names, the values are either
272 * ContentHandler singleton objects, or strings specifying the appropriate
273 * subclass of ContentHandler.
275 * If a class name is encountered when looking up the singleton for a given
276 * model name, the class is instantiated and the class name is replaced by
277 * the resulting singleton in $wgContentHandlers.
279 * If no ContentHandler is defined for the desired $modelId, the
280 * ContentHandler may be provided by the ContentHandlerForModelID hook.
281 * If no ContentHandler can be determined, an MWException is raised.
286 * @param $modelId String The ID of the content model for which to get a
287 * handler. Use CONTENT_MODEL_XXX constants.
288 * @return ContentHandler The ContentHandler singleton for handling the
289 * model given by $modelId
290 * @throws MWException if no handler is known for $modelId.
292 public static function getForModelID( $modelId ) {
293 global $wgContentHandlers;
295 if ( isset( ContentHandler
::$handlers[$modelId] ) ) {
296 return ContentHandler
::$handlers[$modelId];
299 if ( empty( $wgContentHandlers[$modelId] ) ) {
302 wfRunHooks( 'ContentHandlerForModelID', array( $modelId, &$handler ) );
304 if ( $handler === null ) {
305 throw new MWException( "No handler for model '$modelId'' registered in \$wgContentHandlers" );
308 if ( !( $handler instanceof ContentHandler
) ) {
309 throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
312 $class = $wgContentHandlers[$modelId];
313 $handler = new $class( $modelId );
315 if ( !( $handler instanceof ContentHandler
) ) {
316 throw new MWException( "$class from \$wgContentHandlers is not compatible with ContentHandler" );
320 ContentHandler
::$handlers[$modelId] = $handler;
321 return ContentHandler
::$handlers[$modelId];
325 * Returns the localized name for a given content model.
327 * Model names are localized using system messages. Message keys
328 * have the form content-model-$name, where $name is getContentModelName( $id ).
331 * @param $name String The content model ID, as given by a CONTENT_MODEL_XXX
332 * constant or returned by Revision::getContentModel().
334 * @return string The content format's localized name.
335 * @throws MWException if the model id isn't known.
337 public static function getLocalizedName( $name ) {
338 $key = "content-model-$name";
340 $msg = wfMessage( $key );
342 return $msg->exists() ?
$msg->plain() : $name;
345 public static function getContentModels() {
346 global $wgContentHandlers;
348 return array_keys( $wgContentHandlers );
351 public static function getAllContentFormats() {
352 global $wgContentHandlers;
356 foreach ( $wgContentHandlers as $model => $class ) {
357 $handler = ContentHandler
::getForModelID( $model );
358 $formats = array_merge( $formats, $handler->getSupportedFormats() );
361 $formats = array_unique( $formats );
365 // ------------------------------------------------------------------------
368 protected $mSupportedFormats;
371 * Constructor, initializing the ContentHandler instance with its model ID
372 * and a list of supported formats. Values for the parameters are typically
373 * provided as literals by subclass's constructors.
375 * @param $modelId String (use CONTENT_MODEL_XXX constants).
376 * @param $formats array List for supported serialization formats
377 * (typically as MIME types)
379 public function __construct( $modelId, $formats ) {
380 $this->mModelID
= $modelId;
381 $this->mSupportedFormats
= $formats;
383 $this->mModelName
= preg_replace( '/(Content)?Handler$/', '', get_class( $this ) );
384 $this->mModelName
= preg_replace( '/[_\\\\]/', '', $this->mModelName
);
385 $this->mModelName
= strtolower( $this->mModelName
);
389 * Serializes a Content object of the type supported by this ContentHandler.
394 * @param $content Content The Content object to serialize
395 * @param $format null|String The desired serialization format
396 * @return string Serialized form of the content
398 public abstract function serializeContent( Content
$content, $format = null );
401 * Unserializes a Content object of the type supported by this ContentHandler.
406 * @param $blob string serialized form of the content
407 * @param $format null|String the format used for serialization
408 * @return Content the Content object created by deserializing $blob
410 public abstract function unserializeContent( $blob, $format = null );
413 * Creates an empty Content object of the type supported by this
420 public abstract function makeEmptyContent();
423 * Creates a new Content object that acts as a redirect to the given page,
424 * or null of redirects are not supported by this content model.
426 * This default implementation always returns null. Subclasses supporting redirects
427 * must override this method.
431 * @param Title $destination the page to redirect to.
435 public function makeRedirectContent( Title
$destination ) {
440 * Returns the model id that identifies the content model this
441 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
445 * @return String The model ID
447 public function getModelID() {
448 return $this->mModelID
;
452 * Throws an MWException if $model_id is not the ID of the content model
453 * supported by this ContentHandler.
457 * @param String $model_id The model to check
459 * @throws MWException
461 protected function checkModelID( $model_id ) {
462 if ( $model_id !== $this->mModelID
) {
463 throw new MWException( "Bad content model: " .
464 "expected {$this->mModelID} " .
465 "but got $model_id." );
470 * Returns a list of serialization formats supported by the
471 * serializeContent() and unserializeContent() methods of this
476 * @return array of serialization formats as MIME type like strings
478 public function getSupportedFormats() {
479 return $this->mSupportedFormats
;
483 * The format used for serialization/deserialization by default by this
486 * This default implementation will return the first element of the array
487 * of formats that was passed to the constructor.
491 * @return string the name of the default serialization format as a MIME type
493 public function getDefaultFormat() {
494 return $this->mSupportedFormats
[0];
498 * Returns true if $format is a serialization format supported by this
499 * ContentHandler, and false otherwise.
501 * Note that if $format is null, this method always returns true, because
502 * null means "use the default format".
506 * @param $format string the serialization format to check
509 public function isSupportedFormat( $format ) {
512 return true; // this means "use the default"
515 return in_array( $format, $this->mSupportedFormats
);
519 * Throws an MWException if isSupportedFormat( $format ) is not true.
520 * Convenient for checking whether a format provided as a parameter is
521 * actually supported.
523 * @param $format string the serialization format to check
525 * @throws MWException
527 protected function checkFormat( $format ) {
528 if ( !$this->isSupportedFormat( $format ) ) {
529 throw new MWException(
530 "Format $format is not supported for content model "
531 . $this->getModelID()
537 * Returns overrides for action handlers.
538 * Classes listed here will be used instead of the default one when
539 * (and only when) $wgActions[$action] === true. This allows subclasses
540 * to override the default action handlers.
546 public function getActionOverrides() {
551 * Factory for creating an appropriate DifferenceEngine for this content model.
555 * @param $context IContextSource context to use, anything else will be
557 * @param $old Integer Old ID we want to show and diff with.
558 * @param $new int|string String either 'prev' or 'next'.
559 * @param $rcid Integer ??? FIXME (default 0)
560 * @param $refreshCache boolean If set, refreshes the diff cache
561 * @param $unhide boolean If set, allow viewing deleted revs
563 * @return DifferenceEngine
565 public function createDifferenceEngine( IContextSource
$context,
567 $rcid = 0, # FIXME: use everywhere!
568 $refreshCache = false, $unhide = false
570 $this->checkModelID( $context->getTitle()->getContentModel() );
572 $diffEngineClass = $this->getDiffEngineClass();
574 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
578 * Get the language in which the content of the given page is written.
580 * This default implementation just returns $wgContLang (except for pages in the MediaWiki namespace)
582 * Note that the pages language is not cacheable, since it may in some cases depend on user settings.
584 * Also note that the page language may or may not depend on the actual content of the page,
585 * that is, this method may load the content in order to determine the language.
589 * @param Title $title the page to determine the language for.
590 * @param Content|null $content the page's content, if you have it handy, to avoid reloading it.
592 * @return Language the page's language
594 public function getPageLanguage( Title
$title, Content
$content = null ) {
597 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
598 // Parse mediawiki messages with correct target language
599 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $title->getText() );
600 return wfGetLangObj( $lang );
607 * Get the language in which the content of this page is written when
608 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
609 * specified a preferred variant, the variant will be used.
611 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
612 * the user specified a preferred variant.
614 * Note that the pages view language is not cacheable, since it depends on user settings.
616 * Also note that the page language may or may not depend on the actual content of the page,
617 * that is, this method may load the content in order to determine the language.
621 * @param Title $title the page to determine the language for.
622 * @param Content|null $content the page's content, if you have it handy, to avoid reloading it.
624 * @return Language the page's language for viewing
626 public function getPageViewLanguage( Title
$title, Content
$content = null ) {
627 $pageLang = $this->getPageLanguage( $title, $content );
629 if ( $title->getNamespace() !== NS_MEDIAWIKI
) {
630 // If the user chooses a variant, the content is actually
631 // in a language whose code is the variant code.
632 $variant = $pageLang->getPreferredVariant();
633 if ( $pageLang->getCode() !== $variant ) {
634 $pageLang = Language
::factory( $variant );
642 * Determines whether the content type handled by this ContentHandler
643 * can be used on the given page.
645 * This default implementation always returns true.
646 * Subclasses may override this to restrict the use of this content model to specific locations,
647 * typically based on the namespace or some other aspect of the title, such as a special suffix
648 * (e.g. ".svg" for SVG content).
650 * @param Title $title the page's title.
652 * @return bool true if content of this kind can be used on the given page, false otherwise.
654 public function canBeUsedOn( Title
$title ) {
659 * Returns the name of the diff engine to use.
665 protected function getDiffEngineClass() {
666 return 'DifferenceEngine';
670 * Attempts to merge differences between three versions.
671 * Returns a new Content object for a clean merge and false for failure or
674 * This default implementation always returns false.
678 * @param $oldContent Content|string String
679 * @param $myContent Content|string String
680 * @param $yourContent Content|string String
682 * @return Content|Bool
684 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
689 * Return an applicable auto-summary if one exists for the given edit.
693 * @param $oldContent Content|null: the previous text of the page.
694 * @param $newContent Content|null: The submitted text of the page.
695 * @param $flags int Bit mask: a bit mask of flags submitted for the edit.
697 * @return string An appropriate auto-summary, or an empty string.
699 public function getAutosummary( Content
$oldContent = null, Content
$newContent = null, $flags ) {
702 // Decide what kind of auto-summary is needed.
704 // Redirect auto-summaries
711 $ot = !is_null( $oldContent ) ?
$oldContent->getRedirectTarget() : null;
712 $rt = !is_null( $newContent ) ?
$newContent->getRedirectTarget() : null;
714 if ( is_object( $rt ) ) {
715 if ( !is_object( $ot )
716 ||
!$rt->equals( $ot )
717 ||
$ot->getFragment() != $rt->getFragment() )
719 $truncatedtext = $newContent->getTextForSummary(
721 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
722 - strlen( $rt->getFullText() ) );
724 return wfMessage( 'autoredircomment', $rt->getFullText() )
725 ->rawParams( $truncatedtext )->inContentLanguage()->text();
729 // New page auto-summaries
730 if ( $flags & EDIT_NEW
&& $newContent->getSize() > 0 ) {
731 // If they're making a new article, give its text, truncated, in
734 $truncatedtext = $newContent->getTextForSummary(
735 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
737 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
738 ->inContentLanguage()->text();
741 // Blanking auto-summaries
742 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
743 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
744 } elseif ( !empty( $oldContent )
745 && $oldContent->getSize() > 10 * $newContent->getSize()
746 && $newContent->getSize() < 500 )
748 // Removing more than 90% of the article
750 $truncatedtext = $newContent->getTextForSummary(
751 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
753 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
754 ->inContentLanguage()->text();
757 // If we reach this point, there's no applicable auto-summary for our
758 // case, so our auto-summary is empty.
763 * Auto-generates a deletion reason
767 * @param $title Title: the page's title
768 * @param &$hasHistory Boolean: whether the page has a history
769 * @return mixed String containing deletion reason or empty string, or
770 * boolean false if no revision occurred
772 * @XXX &$hasHistory is extremely ugly, it's here because
773 * WikiPage::getAutoDeleteReason() and Article::getReason()
776 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
777 $dbw = wfGetDB( DB_MASTER
);
779 // Get the last revision
780 $rev = Revision
::newFromTitle( $title );
782 if ( is_null( $rev ) ) {
786 // Get the article's contents
787 $content = $rev->getContent();
790 $this->checkModelID( $content->getModel() );
792 // If the page is blank, use the text from the previous revision,
793 // which can only be blank if there's a move/import/protect dummy
795 if ( $content->getSize() == 0 ) {
796 $prev = $rev->getPrevious();
799 $content = $prev->getContent();
804 // Find out if there was only one contributor
805 // Only scan the last 20 revisions
806 $res = $dbw->select( 'revision', 'rev_user_text',
808 'rev_page' => $title->getArticleID(),
809 $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0'
812 array( 'LIMIT' => 20 )
815 if ( $res === false ) {
816 // This page has no revisions, which is very weird
820 $hasHistory = ( $res->numRows() > 1 );
821 $row = $dbw->fetchObject( $res );
823 if ( $row ) { // $row is false if the only contributor is hidden
824 $onlyAuthor = $row->rev_user_text
;
825 // Try to find a second contributor
826 foreach ( $res as $row ) {
827 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
836 // Generate the summary with a '$1' placeholder
838 // The current revision is blank and the one before is also
839 // blank. It's just not our lucky day
840 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
847 )->inContentLanguage()->text();
849 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
853 if ( $reason == '-' ) {
854 // Allow these UI messages to be blanked out cleanly
858 // Max content length = max comment length - length of the comment (excl. $1)
859 $text = $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) );
861 // Now replace the '$1' placeholder
862 $reason = str_replace( '$1', $text, $reason );
868 * Get the Content object that needs to be saved in order to undo all revisions
869 * between $undo and $undoafter. Revisions must belong to the same page,
870 * must exist and must not be deleted.
874 * @param $current Revision The current text
875 * @param $undo Revision The revision to undo
876 * @param $undoafter Revision Must be an earlier revision than $undo
878 * @return mixed String on success, false on failure
880 public function getUndoContent( Revision
$current, Revision
$undo, Revision
$undoafter ) {
881 $cur_content = $current->getContent();
883 if ( empty( $cur_content ) ) {
884 return false; // no page
887 $undo_content = $undo->getContent();
888 $undoafter_content = $undoafter->getContent();
890 $this->checkModelID( $cur_content->getModel() );
891 $this->checkModelID( $undo_content->getModel() );
892 $this->checkModelID( $undoafter_content->getModel() );
894 if ( $cur_content->equals( $undo_content ) ) {
895 // No use doing a merge if it's just a straight revert.
896 return $undoafter_content;
899 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
901 return $undone_content;
905 * Get parser options suitable for rendering the primary article wikitext
907 * @param IContextSource|User|string $context One of the following:
908 * - IContextSource: Use the User and the Language of the provided
910 * - User: Use the provided User object and $wgLang for the language,
911 * so use an IContextSource object if possible.
912 * - 'canonical': Canonical options (anonymous user with default
913 * preferences and content language).
915 * @param IContextSource|User|string $context
917 * @throws MWException
918 * @return ParserOptions
920 public function makeParserOptions( $context ) {
923 if ( $context instanceof IContextSource
) {
924 $options = ParserOptions
::newFromContext( $context );
925 } elseif ( $context instanceof User
) { // settings per user (even anons)
926 $options = ParserOptions
::newFromUser( $context );
927 } elseif ( $context === 'canonical' ) { // canonical settings
928 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
930 throw new MWException( "Bad context for parser options: $context" );
933 $options->enableLimitReport(); // show inclusion/loop reports
934 $options->setTidy( true ); // fix bad HTML
940 * Returns true for content models that support caching using the
941 * ParserCache mechanism. See WikiPage::isParserCacheUsed().
947 public function isParserCacheSupported() {
952 * Returns true if this content model supports sections.
954 * This default implementation returns false.
956 * @return boolean whether sections are supported.
958 public function supportsSections() {
963 * Logs a deprecation warning, visible if $wgDevelopmentWarnings, but only if
964 * self::$enableDeprecationWarnings is set to true.
966 * @param String $func The name of the deprecated function
967 * @param string $version The version since the method is deprecated. Usually 1.21
968 * for ContentHandler related stuff.
969 * @param String|bool $component: Component to which the function belongs.
970 * If false, it is assumed the function is in MediaWiki core.
972 * @see ContentHandler::$enableDeprecationWarnings
975 public static function deprecated( $func, $version, $component = false ) {
976 if ( self
::$enableDeprecationWarnings ) {
977 wfDeprecated( $func, $version, $component, 3 );
982 * Call a legacy hook that uses text instead of Content objects.
983 * Will log a warning when a matching hook function is registered.
984 * If the textual representation of the content is changed by the
985 * hook function, a new Content object is constructed from the new
988 * @param $event String: event name
989 * @param $args Array: parameters passed to hook functions
990 * @param $warn bool: whether to log a warning.
991 * Default to self::$enableDeprecationWarnings.
992 * May be set to false for testing.
994 * @return Boolean True if no handler aborted the hook
996 * @see ContentHandler::$enableDeprecationWarnings
998 public static function runLegacyHooks( $event, $args = array(),
1001 if ( $warn === null ) {
1002 $warn = self
::$enableDeprecationWarnings;
1005 if ( !Hooks
::isRegistered( $event ) ) {
1006 return true; // nothing to do here
1010 // Log information about which handlers are registered for the legacy hook,
1011 // so we can find and fix them.
1013 $handlers = Hooks
::getHandlers( $event );
1014 $handlerInfo = array();
1016 wfSuppressWarnings();
1018 foreach ( $handlers as $handler ) {
1021 if ( is_array( $handler ) ) {
1022 if ( is_object( $handler[0] ) ) {
1023 $info = get_class( $handler[0] );
1025 $info = $handler[0];
1028 if ( isset( $handler[1] ) ) {
1029 $info .= '::' . $handler[1];
1031 } else if ( is_object( $handler ) ) {
1032 $info = get_class( $handler[0] );
1033 $info .= '::on' . $event;
1038 $handlerInfo[] = $info;
1041 wfRestoreWarnings();
1043 wfWarn( "Using obsolete hook $event via ContentHandler::runLegacyHooks()! Handlers: " . implode(', ', $handlerInfo), 2 );
1046 // convert Content objects to text
1047 $contentObjects = array();
1048 $contentTexts = array();
1050 foreach ( $args as $k => $v ) {
1051 if ( $v instanceof Content
) {
1052 /* @var Content $v */
1054 $contentObjects[$k] = $v;
1056 $v = $v->serialize();
1057 $contentTexts[ $k ] = $v;
1062 // call the hook functions
1063 $ok = wfRunHooks( $event, $args );
1065 // see if the hook changed the text
1066 foreach ( $contentTexts as $k => $orig ) {
1067 /* @var Content $content */
1069 $modified = $args[ $k ];
1070 $content = $contentObjects[$k];
1072 if ( $modified !== $orig ) {
1073 // text was changed, create updated Content object
1074 $content = $content->getContentHandler()->unserializeContent( $modified );
1077 $args[ $k ] = $content;