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 * Convenience function for getting flat text from a Content object. This
33 * should only be used in the context of backwards compatibility with code
34 * that is not yet able to handle Content objects!
36 * If $content is null, this method returns the empty string.
38 * If $content is an instance of TextContent, this method returns the flat
39 * text as returned by $content->getNativeData().
41 * If $content is not a TextContent object, the behavior of this method
42 * depends on the global $wgContentHandlerTextFallback:
43 * - If $wgContentHandlerTextFallback is 'fail' and $content is not a
44 * TextContent object, an MWException is thrown.
45 * - If $wgContentHandlerTextFallback is 'serialize' and $content is not a
46 * TextContent object, $content->serialize() is called to get a string
47 * form of the content.
48 * - If $wgContentHandlerTextFallback is 'ignore' and $content is not a
49 * TextContent object, this method returns null.
50 * - otherwise, the behaviour is undefined.
53 * @deprecated since 1.21. Always try to use the content object.
56 * @param $content Content|null
57 * @return null|string the textual form of $content, if available
58 * @throws MWException if $content is not an instance of TextContent and
59 * $wgContentHandlerTextFallback was set to 'fail'.
61 public static function getContentText( Content
$content = null ) {
62 global $wgContentHandlerTextFallback;
64 if ( is_null( $content ) ) {
68 if ( $content instanceof TextContent
) {
69 return $content->getNativeData();
72 if ( $wgContentHandlerTextFallback == 'fail' ) {
73 throw new MWException(
74 "Attempt to get text from Content with model " .
79 if ( $wgContentHandlerTextFallback == 'serialize' ) {
80 return $content->serialize();
87 * Convenience function for creating a Content object from a given textual
90 * $text will be deserialized into a Content object of the model specified
91 * by $modelId (or, if that is not given, $title->getContentModel()) using
98 * @param $text string the textual representation, will be
99 * unserialized to create the Content object
100 * @param $title null|Title the title of the page this text belongs to.
101 * Required if $modelId is not provided.
102 * @param $modelId null|string the model to deserialize to. If not provided,
103 * $title->getContentModel() is used.
104 * @param $format null|string the format to use for deserialization. If not
105 * given, the model's default format is used.
107 * @return Content a Content object representing $text
109 * @throw MWException if $model or $format is not supported or if $text can
110 * not be unserialized using $format.
112 public static function makeContent( $text, Title
$title = null,
113 $modelId = null, $format = null )
115 if ( is_null( $modelId ) ) {
116 if ( is_null( $title ) ) {
117 throw new MWException( "Must provide a Title object or a content model ID." );
120 $modelId = $title->getContentModel();
123 $handler = ContentHandler
::getForModelID( $modelId );
124 return $handler->unserializeContent( $text, $format );
128 * Returns the name of the default content model to be used for the page
129 * with the given title.
131 * Note: There should rarely be need to call this method directly.
132 * To determine the actual content model for a given page, use
133 * Title::getContentModel().
135 * Which model is to be used by default for the page is determined based
136 * on several factors:
137 * - The global setting $wgNamespaceContentModels specifies a content model
139 * - The hook ContentHandlerDefaultModelFor may be used to override the page's default
141 * - Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript
142 * model if they end in .js or .css, respectively.
143 * - Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
144 * - The hook TitleIsCssOrJsPage may be used to force a page to use the CSS
145 * or JavaScript model. This is a compatibility feature. The ContentHandlerDefaultModelFor
146 * hook should be used instead if possible.
147 * - The hook TitleIsWikitextPage may be used to force a page to use the
148 * wikitext model. This is a compatibility feature. The ContentHandlerDefaultModelFor
149 * hook should be used instead if possible.
151 * If none of the above applies, the wikitext model is used.
153 * Note: this is used by, and may thus not use, Title::getContentModel()
158 * @param $title Title
159 * @return null|string default model name for the page given by $title
161 public static function getDefaultModelFor( Title
$title ) {
162 global $wgNamespaceContentModels;
164 // NOTE: this method must not rely on $title->getContentModel() directly or indirectly,
165 // because it is used to initialize the mContentModel member.
167 $ns = $title->getNamespace();
173 if ( !empty( $wgNamespaceContentModels[ $ns ] ) ) {
174 $model = $wgNamespaceContentModels[ $ns ];
177 // Hook can determine default model
178 if ( !wfRunHooks( 'ContentHandlerDefaultModelFor', array( $title, &$model ) ) ) {
179 if ( !is_null( $model ) ) {
184 // Could this page contain custom CSS or JavaScript, based on the title?
185 $isCssOrJsPage = NS_MEDIAWIKI
== $ns && preg_match( '!\.(css|js)$!u', $title->getText(), $m );
186 if ( $isCssOrJsPage ) {
190 // Hook can force JS/CSS
191 wfRunHooks( 'TitleIsCssOrJsPage', array( $title, &$isCssOrJsPage ) );
193 // Is this a .css subpage of a user page?
194 $isJsCssSubpage = NS_USER
== $ns
196 && preg_match( "/\\/.*\\.(js|css)$/", $title->getText(), $m );
197 if ( $isJsCssSubpage ) {
201 // Is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
202 $isWikitext = is_null( $model ) ||
$model == CONTENT_MODEL_WIKITEXT
;
203 $isWikitext = $isWikitext && !$isCssOrJsPage && !$isJsCssSubpage;
205 // Hook can override $isWikitext
206 wfRunHooks( 'TitleIsWikitextPage', array( $title, &$isWikitext ) );
208 if ( !$isWikitext ) {
211 return CONTENT_MODEL_JAVASCRIPT
;
213 return CONTENT_MODEL_CSS
;
215 return is_null( $model ) ? CONTENT_MODEL_TEXT
: $model;
219 // We established that it must be wikitext
221 return CONTENT_MODEL_WIKITEXT
;
225 * Returns the appropriate ContentHandler singleton for the given title.
230 * @param $title Title
231 * @return ContentHandler
233 public static function getForTitle( Title
$title ) {
234 $modelId = $title->getContentModel();
235 return ContentHandler
::getForModelID( $modelId );
239 * Returns the appropriate ContentHandler singleton for the given Content
245 * @param $content Content
246 * @return ContentHandler
248 public static function getForContent( Content
$content ) {
249 $modelId = $content->getModel();
250 return ContentHandler
::getForModelID( $modelId );
254 * @var Array A Cache of ContentHandler instances by model id
259 * Returns the ContentHandler singleton for the given model ID. Use the
260 * CONTENT_MODEL_XXX constants to identify the desired content model.
262 * ContentHandler singletons are taken from the global $wgContentHandlers
263 * array. Keys in that array are model names, the values are either
264 * ContentHandler singleton objects, or strings specifying the appropriate
265 * subclass of ContentHandler.
267 * If a class name is encountered when looking up the singleton for a given
268 * model name, the class is instantiated and the class name is replaced by
269 * the resulting singleton in $wgContentHandlers.
271 * If no ContentHandler is defined for the desired $modelId, the
272 * ContentHandler may be provided by the ContentHandlerForModelID hook.
273 * If no ContentHandler can be determined, an MWException is raised.
278 * @param $modelId String The ID of the content model for which to get a
279 * handler. Use CONTENT_MODEL_XXX constants.
280 * @return ContentHandler The ContentHandler singleton for handling the
281 * model given by $modelId
282 * @throws MWException if no handler is known for $modelId.
284 public static function getForModelID( $modelId ) {
285 global $wgContentHandlers;
287 if ( isset( ContentHandler
::$handlers[$modelId] ) ) {
288 return ContentHandler
::$handlers[$modelId];
291 if ( empty( $wgContentHandlers[$modelId] ) ) {
294 wfRunHooks( 'ContentHandlerForModelID', array( $modelId, &$handler ) );
296 if ( $handler === null ) {
297 throw new MWException( "No handler for model #$modelId registered in \$wgContentHandlers" );
300 if ( !( $handler instanceof ContentHandler
) ) {
301 throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
304 $class = $wgContentHandlers[$modelId];
305 $handler = new $class( $modelId );
307 if ( !( $handler instanceof ContentHandler
) ) {
308 throw new MWException( "$class from \$wgContentHandlers is not compatible with ContentHandler" );
312 ContentHandler
::$handlers[$modelId] = $handler;
313 return ContentHandler
::$handlers[$modelId];
317 * Returns the localized name for a given content model.
319 * Model names are localized using system messages. Message keys
320 * have the form content-model-$name, where $name is getContentModelName( $id ).
323 * @param $name String The content model ID, as given by a CONTENT_MODEL_XXX
324 * constant or returned by Revision::getContentModel().
326 * @return string The content format's localized name.
327 * @throws MWException if the model id isn't known.
329 public static function getLocalizedName( $name ) {
330 $key = "content-model-$name";
332 $msg = wfMessage( $key );
334 return $msg->exists() ?
$msg->plain() : $name;
337 public static function getContentModels() {
338 global $wgContentHandlers;
340 return array_keys( $wgContentHandlers );
343 public static function getAllContentFormats() {
344 global $wgContentHandlers;
348 foreach ( $wgContentHandlers as $model => $class ) {
349 $handler = ContentHandler
::getForModelID( $model );
350 $formats = array_merge( $formats, $handler->getSupportedFormats() );
353 $formats = array_unique( $formats );
357 // ------------------------------------------------------------------------
360 protected $mSupportedFormats;
363 * Constructor, initializing the ContentHandler instance with its model ID
364 * and a list of supported formats. Values for the parameters are typically
365 * provided as literals by subclass's constructors.
367 * @param $modelId String (use CONTENT_MODEL_XXX constants).
368 * @param $formats array List for supported serialization formats
369 * (typically as MIME types)
371 public function __construct( $modelId, $formats ) {
372 $this->mModelID
= $modelId;
373 $this->mSupportedFormats
= $formats;
375 $this->mModelName
= preg_replace( '/(Content)?Handler$/', '', get_class( $this ) );
376 $this->mModelName
= preg_replace( '/[_\\\\]/', '', $this->mModelName
);
377 $this->mModelName
= strtolower( $this->mModelName
);
381 * Serializes a Content object of the type supported by this ContentHandler.
386 * @param $content Content The Content object to serialize
387 * @param $format null|String The desired serialization format
388 * @return string Serialized form of the content
390 public abstract function serializeContent( Content
$content, $format = null );
393 * Unserializes a Content object of the type supported by this ContentHandler.
398 * @param $blob string serialized form of the content
399 * @param $format null|String the format used for serialization
400 * @return Content the Content object created by deserializing $blob
402 public abstract function unserializeContent( $blob, $format = null );
405 * Creates an empty Content object of the type supported by this
412 public abstract function makeEmptyContent();
415 * Returns the model id that identifies the content model this
416 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
420 * @return String The model ID
422 public function getModelID() {
423 return $this->mModelID
;
427 * Throws an MWException if $model_id is not the ID of the content model
428 * supported by this ContentHandler.
432 * @param String $model_id The model to check
434 * @throws MWException
436 protected function checkModelID( $model_id ) {
437 if ( $model_id !== $this->mModelID
) {
438 throw new MWException( "Bad content model: " .
439 "expected {$this->mModelID} " .
440 "but got $model_id." );
445 * Returns a list of serialization formats supported by the
446 * serializeContent() and unserializeContent() methods of this
451 * @return array of serialization formats as MIME type like strings
453 public function getSupportedFormats() {
454 return $this->mSupportedFormats
;
458 * The format used for serialization/deserialization by default by this
461 * This default implementation will return the first element of the array
462 * of formats that was passed to the constructor.
466 * @return string the name of the default serialization format as a MIME type
468 public function getDefaultFormat() {
469 return $this->mSupportedFormats
[0];
473 * Returns true if $format is a serialization format supported by this
474 * ContentHandler, and false otherwise.
476 * Note that if $format is null, this method always returns true, because
477 * null means "use the default format".
481 * @param $format string the serialization format to check
484 public function isSupportedFormat( $format ) {
487 return true; // this means "use the default"
490 return in_array( $format, $this->mSupportedFormats
);
494 * Throws an MWException if isSupportedFormat( $format ) is not true.
495 * Convenient for checking whether a format provided as a parameter is
496 * actually supported.
498 * @param $format string the serialization format to check
500 * @throws MWException
502 protected function checkFormat( $format ) {
503 if ( !$this->isSupportedFormat( $format ) ) {
504 throw new MWException(
505 "Format $format is not supported for content model "
506 . $this->getModelID()
512 * Returns overrides for action handlers.
513 * Classes listed here will be used instead of the default one when
514 * (and only when) $wgActions[$action] === true. This allows subclasses
515 * to override the default action handlers.
521 public function getActionOverrides() {
526 * Factory for creating an appropriate DifferenceEngine for this content model.
530 * @param $context IContextSource context to use, anything else will be
532 * @param $old Integer Old ID we want to show and diff with.
533 * @param $new int|string String either 'prev' or 'next'.
534 * @param $rcid Integer ??? FIXME (default 0)
535 * @param $refreshCache boolean If set, refreshes the diff cache
536 * @param $unhide boolean If set, allow viewing deleted revs
538 * @return DifferenceEngine
540 public function createDifferenceEngine( IContextSource
$context,
542 $rcid = 0, # FIXME: use everywhere!
543 $refreshCache = false, $unhide = false
545 $this->checkModelID( $context->getTitle()->getContentModel() );
547 $diffEngineClass = $this->getDiffEngineClass();
549 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
553 * Get the language in which the content of the given page is written.
555 * This default implementation just returns $wgContLang (except for pages in the MediaWiki namespace)
557 * Note that the pages language is not cacheable, since it may in some cases depend on user settings.
559 * Also note that the page language may or may not depend on the actual content of the page,
560 * that is, this method may load the content in order to determine the language.
564 * @param Title $title the page to determine the language for.
565 * @param Content|null $content the page's content, if you have it handy, to avoid reloading it.
567 * @return Language the page's language
569 public function getPageLanguage( Title
$title, Content
$content = null ) {
572 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
573 // Parse mediawiki messages with correct target language
574 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $title->getText() );
575 return wfGetLangObj( $lang );
582 * Get the language in which the content of this page is written when
583 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
584 * specified a preferred variant, the variant will be used.
586 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
587 * the user specified a preferred variant.
589 * Note that the pages view language is not cacheable, since it depends on user settings.
591 * Also note that the page language may or may not depend on the actual content of the page,
592 * that is, this method may load the content in order to determine the language.
596 * @param Title $title the page to determine the language for.
597 * @param Content|null $content the page's content, if you have it handy, to avoid reloading it.
599 * @return Language the page's language for viewing
601 public function getPageViewLanguage( Title
$title, Content
$content = null ) {
602 $pageLang = $this->getPageLanguage( $title, $content );
604 if ( $title->getNamespace() !== NS_MEDIAWIKI
) {
605 // If the user chooses a variant, the content is actually
606 // in a language whose code is the variant code.
607 $variant = $pageLang->getPreferredVariant();
608 if ( $pageLang->getCode() !== $variant ) {
609 $pageLang = Language
::factory( $variant );
617 * Determines whether the content type handled by this ContentHandler
618 * can be used on the given page.
620 * This default implementation always returns true.
621 * Subclasses may override this to restrict the use of this content model to specific locations,
622 * typically based on the namespace or some other aspect of the title, such as a special suffix
623 * (e.g. ".svg" for SVG content).
625 * @param Title $title the page's title.
627 * @return bool true if content of this kind can be used on the given page, false otherwise.
629 public function canBeUsedOn( Title
$title ) {
634 * Returns the name of the diff engine to use.
640 protected function getDiffEngineClass() {
641 return 'DifferenceEngine';
645 * Attempts to merge differences between three versions.
646 * Returns a new Content object for a clean merge and false for failure or
649 * This default implementation always returns false.
653 * @param $oldContent Content|string String
654 * @param $myContent Content|string String
655 * @param $yourContent Content|string String
657 * @return Content|Bool
659 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
664 * Return an applicable auto-summary if one exists for the given edit.
668 * @param $oldContent Content|null: the previous text of the page.
669 * @param $newContent Content|null: The submitted text of the page.
670 * @param $flags int Bit mask: a bit mask of flags submitted for the edit.
672 * @return string An appropriate auto-summary, or an empty string.
674 public function getAutosummary( Content
$oldContent = null, Content
$newContent = null, $flags ) {
677 // Decide what kind of auto-summary is needed.
679 // Redirect auto-summaries
686 $ot = !is_null( $oldContent ) ?
$oldContent->getRedirectTarget() : null;
687 $rt = !is_null( $newContent ) ?
$newContent->getRedirectTarget() : null;
689 if ( is_object( $rt ) ) {
690 if ( !is_object( $ot )
691 ||
!$rt->equals( $ot )
692 ||
$ot->getFragment() != $rt->getFragment() )
694 $truncatedtext = $newContent->getTextForSummary(
696 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
697 - strlen( $rt->getFullText() ) );
699 return wfMessage( 'autoredircomment', $rt->getFullText() )
700 ->rawParams( $truncatedtext )->inContentLanguage()->text();
704 // New page auto-summaries
705 if ( $flags & EDIT_NEW
&& $newContent->getSize() > 0 ) {
706 // If they're making a new article, give its text, truncated, in
709 $truncatedtext = $newContent->getTextForSummary(
710 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
712 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
713 ->inContentLanguage()->text();
716 // Blanking auto-summaries
717 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
718 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
719 } elseif ( !empty( $oldContent )
720 && $oldContent->getSize() > 10 * $newContent->getSize()
721 && $newContent->getSize() < 500 )
723 // Removing more than 90% of the article
725 $truncatedtext = $newContent->getTextForSummary(
726 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
728 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
729 ->inContentLanguage()->text();
732 // If we reach this point, there's no applicable auto-summary for our
733 // case, so our auto-summary is empty.
738 * Auto-generates a deletion reason
742 * @param $title Title: the page's title
743 * @param &$hasHistory Boolean: whether the page has a history
744 * @return mixed String containing deletion reason or empty string, or
745 * boolean false if no revision occurred
747 * @XXX &$hasHistory is extremely ugly, it's here because
748 * WikiPage::getAutoDeleteReason() and Article::getReason()
751 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
752 $dbw = wfGetDB( DB_MASTER
);
754 // Get the last revision
755 $rev = Revision
::newFromTitle( $title );
757 if ( is_null( $rev ) ) {
761 // Get the article's contents
762 $content = $rev->getContent();
765 $this->checkModelID( $content->getModel() );
767 // If the page is blank, use the text from the previous revision,
768 // which can only be blank if there's a move/import/protect dummy
770 if ( $content->getSize() == 0 ) {
771 $prev = $rev->getPrevious();
774 $content = $prev->getContent();
779 // Find out if there was only one contributor
780 // Only scan the last 20 revisions
781 $res = $dbw->select( 'revision', 'rev_user_text',
783 'rev_page' => $title->getArticleID(),
784 $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0'
787 array( 'LIMIT' => 20 )
790 if ( $res === false ) {
791 // This page has no revisions, which is very weird
795 $hasHistory = ( $res->numRows() > 1 );
796 $row = $dbw->fetchObject( $res );
798 if ( $row ) { // $row is false if the only contributor is hidden
799 $onlyAuthor = $row->rev_user_text
;
800 // Try to find a second contributor
801 foreach ( $res as $row ) {
802 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
811 // Generate the summary with a '$1' placeholder
813 // The current revision is blank and the one before is also
814 // blank. It's just not our lucky day
815 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
822 )->inContentLanguage()->text();
824 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
828 if ( $reason == '-' ) {
829 // Allow these UI messages to be blanked out cleanly
833 // Max content length = max comment length - length of the comment (excl. $1)
834 $text = $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) );
836 // Now replace the '$1' placeholder
837 $reason = str_replace( '$1', $text, $reason );
843 * Get the Content object that needs to be saved in order to undo all revisions
844 * between $undo and $undoafter. Revisions must belong to the same page,
845 * must exist and must not be deleted.
849 * @param $current Revision The current text
850 * @param $undo Revision The revision to undo
851 * @param $undoafter Revision Must be an earlier revision than $undo
853 * @return mixed String on success, false on failure
855 public function getUndoContent( Revision
$current, Revision
$undo, Revision
$undoafter ) {
856 $cur_content = $current->getContent();
858 if ( empty( $cur_content ) ) {
859 return false; // no page
862 $undo_content = $undo->getContent();
863 $undoafter_content = $undoafter->getContent();
865 $this->checkModelID( $cur_content->getModel() );
866 $this->checkModelID( $undo_content->getModel() );
867 $this->checkModelID( $undoafter_content->getModel() );
869 if ( $cur_content->equals( $undo_content ) ) {
870 // No use doing a merge if it's just a straight revert.
871 return $undoafter_content;
874 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
876 return $undone_content;
880 * Get parser options suitable for rendering the primary article wikitext
882 * @param IContextSource|User|string $context One of the following:
883 * - IContextSource: Use the User and the Language of the provided
885 * - User: Use the provided User object and $wgLang for the language,
886 * so use an IContextSource object if possible.
887 * - 'canonical': Canonical options (anonymous user with default
888 * preferences and content language).
890 * @param IContextSource|User|string $context
892 * @throws MWException
893 * @return ParserOptions
895 public function makeParserOptions( $context ) {
898 if ( $context instanceof IContextSource
) {
899 $options = ParserOptions
::newFromContext( $context );
900 } elseif ( $context instanceof User
) { // settings per user (even anons)
901 $options = ParserOptions
::newFromUser( $context );
902 } elseif ( $context === 'canonical' ) { // canonical settings
903 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
905 throw new MWException( "Bad context for parser options: $context" );
908 $options->enableLimitReport(); // show inclusion/loop reports
909 $options->setTidy( true ); // fix bad HTML
915 * Returns true for content models that support caching using the
916 * ParserCache mechanism. See WikiPage::isParserCacheUser().
922 public function isParserCacheSupported() {
927 * Returns true if this content model supports sections.
929 * This default implementation returns false.
931 * @return boolean whether sections are supported.
933 public function supportsSections() {
938 * Call a legacy hook that uses text instead of Content objects.
939 * Will log a warning when a matching hook function is registered.
940 * If the textual representation of the content is changed by the
941 * hook function, a new Content object is constructed from the new
944 * @param $event String: event name
945 * @param $args Array: parameters passed to hook functions
946 * @param $warn bool: whether to log a warning (default: true). Should generally be true,
947 * may be set to false for testing.
949 * @return Boolean True if no handler aborted the hook
951 public static function runLegacyHooks( $event, $args = array(), $warn = true ) {
952 if ( !Hooks
::isRegistered( $event ) ) {
953 return true; // nothing to do here
957 wfWarn( "Using obsolete hook $event" );
960 // convert Content objects to text
961 $contentObjects = array();
962 $contentTexts = array();
964 foreach ( $args as $k => $v ) {
965 if ( $v instanceof Content
) {
966 /* @var Content $v */
968 $contentObjects[$k] = $v;
970 $v = $v->serialize();
971 $contentTexts[ $k ] = $v;
976 // call the hook functions
977 $ok = wfRunHooks( $event, $args );
979 // see if the hook changed the text
980 foreach ( $contentTexts as $k => $orig ) {
981 /* @var Content $content */
983 $modified = $args[ $k ];
984 $content = $contentObjects[$k];
986 if ( $modified !== $orig ) {
987 // text was changed, create updated Content object
988 $content = $content->getContentHandler()->unserializeContent( $modified );
991 $args[ $k ] = $content;
1001 abstract class TextContentHandler
extends ContentHandler
{
1003 public function __construct( $modelId, $formats ) {
1004 parent
::__construct( $modelId, $formats );
1008 * Returns the content's text as-is.
1010 * @param $content Content
1011 * @param $format string|null
1014 public function serializeContent( Content
$content, $format = null ) {
1015 $this->checkFormat( $format );
1016 return $content->getNativeData();
1020 * Attempts to merge differences between three versions. Returns a new
1021 * Content object for a clean merge and false for failure or a conflict.
1023 * All three Content objects passed as parameters must have the same
1026 * This text-based implementation uses wfMerge().
1028 * @param $oldContent \Content|string String
1029 * @param $myContent \Content|string String
1030 * @param $yourContent \Content|string String
1032 * @return Content|Bool
1034 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
1035 $this->checkModelID( $oldContent->getModel() );
1036 $this->checkModelID( $myContent->getModel() );
1037 $this->checkModelID( $yourContent->getModel() );
1039 $format = $this->getDefaultFormat();
1041 $old = $this->serializeContent( $oldContent, $format );
1042 $mine = $this->serializeContent( $myContent, $format );
1043 $yours = $this->serializeContent( $yourContent, $format );
1045 $ok = wfMerge( $old, $mine, $yours, $result );
1052 return $this->makeEmptyContent();
1055 $mergedContent = $this->unserializeContent( $result, $format );
1056 return $mergedContent;
1064 class WikitextContentHandler
extends TextContentHandler
{
1066 public function __construct( $modelId = CONTENT_MODEL_WIKITEXT
) {
1067 parent
::__construct( $modelId, array( CONTENT_FORMAT_WIKITEXT
) );
1070 public function unserializeContent( $text, $format = null ) {
1071 $this->checkFormat( $format );
1073 return new WikitextContent( $text );
1076 public function makeEmptyContent() {
1077 return new WikitextContent( '' );
1081 * Returns true because wikitext supports sections.
1083 * @return boolean whether sections are supported.
1085 public function supportsSections() {
1090 # XXX: make ScriptContentHandler base class, do highlighting stuff there?
1095 class JavaScriptContentHandler
extends TextContentHandler
{
1097 public function __construct( $modelId = CONTENT_MODEL_JAVASCRIPT
) {
1098 parent
::__construct( $modelId, array( CONTENT_FORMAT_JAVASCRIPT
) );
1101 public function unserializeContent( $text, $format = null ) {
1102 $this->checkFormat( $format );
1104 return new JavaScriptContent( $text );
1107 public function makeEmptyContent() {
1108 return new JavaScriptContent( '' );
1112 * Returns the english language, because JS is english, and should be handled as such.
1114 * @return Language wfGetLangObj( 'en' )
1116 * @see ContentHandler::getPageLanguage()
1118 public function getPageLanguage( Title
$title, Content
$content = null ) {
1119 return wfGetLangObj( 'en' );
1123 * Returns the english language, because CSS is english, and should be handled as such.
1125 * @return Language wfGetLangObj( 'en' )
1127 * @see ContentHandler::getPageViewLanguage()
1129 public function getPageViewLanguage( Title
$title, Content
$content = null ) {
1130 return wfGetLangObj( 'en' );
1137 class CssContentHandler
extends TextContentHandler
{
1139 public function __construct( $modelId = CONTENT_MODEL_CSS
) {
1140 parent
::__construct( $modelId, array( CONTENT_FORMAT_CSS
) );
1143 public function unserializeContent( $text, $format = null ) {
1144 $this->checkFormat( $format );
1146 return new CssContent( $text );
1149 public function makeEmptyContent() {
1150 return new CssContent( '' );
1154 * Returns the english language, because CSS is english, and should be handled as such.
1156 * @return Language wfGetLangObj( 'en' )
1158 * @see ContentHandler::getPageLanguage()
1160 public function getPageLanguage( Title
$title, Content
$content = null ) {
1161 return wfGetLangObj( 'en' );
1165 * Returns the english language, because CSS is english, and should be handled as such.
1167 * @return Language wfGetLangObj( 'en' )
1169 * @see ContentHandler::getPageViewLanguage()
1171 public function getPageViewLanguage( Title
$title, Content
$content = null ) {
1172 return wfGetLangObj( 'en' );