3 class MWContentSerializationException
extends MWException
{
9 * A content handler knows how do deal with a specific type of content on a wiki page.
10 * Content is stored in the database in a serialized form (using a serialization format aka mime type)
11 * and is be unserialized into it's native PHP represenation (the content model), which is wrappe in
12 * an instance of the appropriate subclass of Content.
14 * ContentHandler instances are stateless singletons that serve, among other things, as a factory for
15 * Content objects. Generally, there is one subclass of ContentHandler and one subclass of Content
16 * for every type of content model.
18 * Some content types have a flat model, that is, their native represenation is the
19 * same as their serialized form. Examples would be JavaScript and CSS code. As of now,
20 * this also applies to wikitext (mediawiki's default content type), but wikitext
21 * content may be represented by a DOM or AST structure in the future.
25 abstract class ContentHandler
{
28 * Conveniance function for getting flat text from a Content object. This should only
29 * be used in the context of backwards compatibility with code that is not yet able
30 * to handle Content objects!
32 * If $content is null, this method returns the empty string.
34 * If $content is an instance of TextContent, this method returns the flat text as returned by $content->getNativeData().
36 * If $content is not a TextContent object, the bahaviour of this method depends on the global $wgContentHandlerTextFallback:
37 * * If $wgContentHandlerTextFallback is 'fail' and $content is not a TextContent object, an MWException is thrown.
38 * * If $wgContentHandlerTextFallback is 'serialize' and $content is not a TextContent object, $content->serialize()
39 * is called to get a string form of the content.
40 * * If $wgContentHandlerTextFallback is 'ignore' and $content is not a TextContent object, this method returns null.
41 * * otherwise, the behaviour is undefined.
44 * @param Content|null $content
45 * @return null|string the textual form of $content, if available
46 * @throws MWException if $content is not an instance of TextContent and $wgContentHandlerTextFallback was set to 'fail'.
48 public static function getContentText( Content
$content = null ) {
49 global $wgContentHandlerTextFallback;
51 if ( is_null( $content ) ) {
55 if ( $content instanceof TextContent
) {
56 return $content->getNativeData();
59 if ( $wgContentHandlerTextFallback == 'fail' ) {
60 throw new MWException( "Attempt to get text from Content with model " . $content->getModel() );
63 if ( $wgContentHandlerTextFallback == 'serialize' ) {
64 return $content->serialize();
71 * Conveniance function for creating a Content object from a given textual representation.
73 * $text will be deserialized into a Content object of the model specified by $modelId (or,
74 * if that is not given, $title->getContentModel()) using the given format.
77 * @param string $text the textual represenation, will be unserialized to create the Content object
78 * @param Title $title the title of the page this text belongs to, required as a context for deserialization
79 * @param null|String $modelId the model to deserialize to. If not provided, $title->getContentModel() is used.
80 * @param null|String $format the format to use for deserialization. If not given, the model's default format is used.
82 * @return Content a Content object representing $text
83 * @throw MWException if $model or $format is not supported or if $text can not be unserialized using $format.
85 public static function makeContent( $text, Title
$title, $modelId = null, $format = null ) {
87 if ( is_null( $modelId ) ) {
88 $modelId = $title->getContentModel();
91 $handler = ContentHandler
::getForModelID( $modelId );
92 return $handler->unserializeContent( $text, $format );
96 * Returns the name of the default content model to be used for the page with the given title.
98 * Note: There should rarely be need to call this method directly.
99 * To determine the actual content model for a given page, use Title::getContentModel().
101 * Which model is to be used per default for the page is determined based on several factors:
102 * * The global setting $wgNamespaceContentModels specifies a content model per namespace.
103 * * The hook DefaultModelFor may be used to override the page's default model.
104 * * Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript model if they end in .js or .css, respectively.
105 * * Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
106 * * The hook TitleIsCssOrJsPage may be used to force a page to use the CSS or JavaScript model if they end in .js or .css, respectively.
107 * * The hook TitleIsWikitextPage may be used to force a page to use the wikitext model.
109 * If none of the above applies, the wikitext model is used.
111 * Note: this is used by, and may thus not use, Title::getContentModel()
114 * @param Title $title
115 * @return null|string default model name for the page given by $title
117 public static function getDefaultModelFor( Title
$title ) {
118 global $wgNamespaceContentModels;
120 // NOTE: this method must not rely on $title->getContentModel() directly or indirectly,
121 // because it is used to initialized the mContentModel memebr.
123 $ns = $title->getNamespace();
129 if ( !empty( $wgNamespaceContentModels[ $ns ] ) ) {
130 $model = $wgNamespaceContentModels[ $ns ];
133 // hook can determin default model
134 if ( !wfRunHooks( 'ContentHandlerDefaultModelFor', array( $title, &$model ) ) ) {
135 if ( !is_null( $model ) ) {
140 // Could this page contain custom CSS or JavaScript, based on the title?
141 $isCssOrJsPage = NS_MEDIAWIKI
== $ns && preg_match( '!\.(css|js)$!u', $title->getText(), $m );
142 if ( $isCssOrJsPage ) {
146 // hook can force js/css
147 wfRunHooks( 'TitleIsCssOrJsPage', array( $title, &$isCssOrJsPage ) );
149 // Is this a .css subpage of a user page?
150 $isJsCssSubpage = NS_USER
== $ns && !$isCssOrJsPage && preg_match( "/\\/.*\\.(js|css)$/", $title->getText(), $m );
151 if ( $isJsCssSubpage ) {
155 // is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
156 $isWikitext = is_null( $model ) ||
$model == CONTENT_MODEL_WIKITEXT
;
157 $isWikitext = $isWikitext && !$isCssOrJsPage && !$isJsCssSubpage;
159 // hook can override $isWikitext
160 wfRunHooks( 'TitleIsWikitextPage', array( $title, &$isWikitext ) );
162 if ( !$isWikitext ) {
165 return CONTENT_MODEL_JAVASCRIPT
;
167 return CONTENT_MODEL_CSS
;
169 return is_null( $model ) ? CONTENT_MODEL_TEXT
: $model;
173 // we established that is must be wikitext
175 return CONTENT_MODEL_WIKITEXT
;
179 * returns the appropriate ContentHandler singleton for the given title
182 * @param Title $title
183 * @return ContentHandler
185 public static function getForTitle( Title
$title ) {
186 $modelId = $title->getContentModel();
187 return ContentHandler
::getForModelID( $modelId );
191 * returns the appropriate ContentHandler singleton for the given Content object
194 * @param Content $content
195 * @return ContentHandler
197 public static function getForContent( Content
$content ) {
198 $modelId = $content->getModel();
199 return ContentHandler
::getForModelID( $modelId );
203 * returns the ContentHandler singleton for the given model id. Use the CONTENT_MODEL_XXX constants to
204 * identify the desired content model.
206 * ContentHandler singletons are take from the global $wgContentHandlers array. Keys in that array are
207 * model names, the values are either ContentHandler singleton objects, or strings specifying the appropriate
208 * subclass of ContentHandler.
210 * If a class name in encountered when looking up the singleton for a given model name, the class is
211 * instantiated and the class name is replaced by te resulting singleton in $wgContentHandlers.
213 * If no ContentHandler is defined for the desired $modelId, the ContentHandler may be provided by the
214 * a ContentHandlerForModelID hook. if no Contenthandler can be determined, an MWException is raised.
217 * @param $modelId int the id of the content model for which to get a handler. Use CONTENT_MODEL_XXX constants.
218 * @return ContentHandler the ContentHandler singleton for handling the model given by $modelId
219 * @throws MWException if no handler is known for $modelId.
221 public static function getForModelID( $modelId ) {
222 global $wgContentHandlers;
224 if ( empty( $wgContentHandlers[$modelId] ) ) {
227 wfRunHooks( 'ContentHandlerForModelID', array( $modelId, &$handler ) );
229 if ( $handler ) { // NOTE: may be a string or an object, either is fine!
230 $wgContentHandlers[$modelId] = $handler;
232 throw new MWException( "No handler for model #$modelId registered in \$wgContentHandlers" );
236 if ( is_string( $wgContentHandlers[$modelId] ) ) {
237 $class = $wgContentHandlers[$modelId];
238 $wgContentHandlers[$modelId] = new $class( $modelId );
241 return $wgContentHandlers[$modelId];
245 * Returns the appropriate mime type for a given content format,
246 * or null if no mime type is known for this format.
248 * Mime types can be registered in the global array $wgContentFormatMimeTypes.
251 * @param int $id the content format id, as given by a CONTENT_FORMAT_XXX constant
252 * or returned by Revision::getContentFormat().
254 * @return String|null the content format's mime type.
256 public static function getContentFormatMimeType( $id ) {
257 global $wgContentFormatMimeTypes;
259 if ( !isset( $wgContentFormatMimeTypes[ $id ] ) ) {
263 return $wgContentFormatMimeTypes[ $id ];
267 * Returns the content format if for a given mime type,
268 * or null if no format id if known for this mime type.
270 * Mime types can be registered in the global array $wgContentFormatMimeTypes.
273 * @param String $mime the mime type
275 * @return int|null the format id, as defined by a CONTENT_FORMAT_XXX constant
277 public static function getContentFormatID( $mime ) {
278 global $wgContentFormatMimeTypes;
280 static $format_ids = null;
282 if ( $format_ids === null ) {
283 $format_ids = array_flip( $wgContentFormatMimeTypes );
286 if ( !isset( $format_ids[ $mime ] ) ) {
290 return $format_ids[ $mime ];
294 * Returns the localized name for a given content model,
295 * or null of no mime type is known.
297 * Model names are localized using system messages. Message keys
298 * have the form conent-model-$id.
301 * @param int $id the content model id, as given by a CONTENT_MODEL_XXX constant
302 * or returned by Revision::getContentModel().
304 * @return String|null the content format's mime type.
306 public static function getContentModelName( $id ) {
307 $key = "content-model-$id";
309 if ( wfEmptyMsg( $key ) ) return null;
310 else return wfMsg( $key );
313 // ----------------------------------------------------------------------------------------------------------
316 protected $mSupportedFormats;
319 * Constructor, initializing the ContentHandler instance with it's model id and a list of supported formats.
320 * Values for the parameters are typically provided as literals by subclasses' constructors.
322 * @param int $modelId (use CONTENT_MODEL_XXX constants).
323 * @param array $formats list for supported serialization formats (typically as MIME types)
325 public function __construct( $modelId, $formats ) {
326 $this->mModelID
= $modelId;
327 $this->mSupportedFormats
= $formats;
332 * Serializes Content object of the type supported by this ContentHandler.
335 * @param Content $content the Content object to serialize
336 * @param null $format the desired serialization format
337 * @return String serialized form of the content
339 public abstract function serializeContent( Content
$content, $format = null );
342 * Unserializes a Content object of the type supported by this ContentHandler.
345 * @param $blob String serialized form of the content
346 * @param null $format the format used for serialization
347 * @return Content the Content object created by deserializing $blob
349 public abstract function unserializeContent( $blob, $format = null );
352 * Creates an empty Content object of the type supported by this ContentHandler.
356 public abstract function makeEmptyContent();
359 * Returns the model id that identifies the content model this ContentHandler can handle.
360 * Use with the CONTENT_MODEL_XXX constants.
362 * @return int the model id
364 public function getModelID() {
365 return $this->mModelID
;
369 * Throws an MWException if $model_id is not the id of the content model
370 * supported by this ContentHandler.
372 * @param int $model_id the model to check
374 protected function checkModelID( $model_id ) {
375 if ( $model_id !== $this->mModelID
) {
376 $model_name = ContentHandler
::getContentModelName( $model_id );
377 $own_model_name = ContentHandler
::getContentModelName( $this->mModelID
);
379 throw new MWException( "Bad content model: expected {$this->mModelID} ($own_model_name) but got found $model_id ($model_name)." );
384 * Returns a list of serialization formats supported by the serializeContent() and unserializeContent() methods of
385 * this ContentHandler.
387 * @return array of serialization formats as MIME type like strings
389 public function getSupportedFormats() {
390 return $this->mSupportedFormats
;
394 * The format used for serialization/deserialization per default by this ContentHandler.
396 * This default implementation will return the first element of the array of formats
397 * that was passed to the constructor.
399 * @return String the name of the default serialiozation format as a MIME type
401 public function getDefaultFormat() {
402 return $this->mSupportedFormats
[0];
406 * Returns true if $format is a serialization format supported by this ContentHandler,
407 * and false otherwise.
409 * Note that if $format is null, this method always returns true, because null
410 * means "use the default format".
412 * @param String $format the serialization format to check
415 public function isSupportedFormat( $format ) {
418 return true; // this means "use the default"
421 return in_array( $format, $this->mSupportedFormats
);
425 * Throws an MWException if isSupportedFormat( $format ) is not true. Convenient
426 * for checking whether a format provided as a parameter is actually supported.
428 * @param String $format the serialization format to check
430 protected function checkFormat( $format ) {
431 if ( !$this->isSupportedFormat( $format ) ) {
432 throw new MWException( "Format $format is not supported for content model " . $this->getModelID() );
437 * Returns overrides for action handlers.
438 * Classes listed here will be used instead of the default one when
439 * (and only when) $wgActions[$action] === true. This allows subclasses
440 * to override the default action handlers.
444 public function getActionOverrides() {
449 * Return an Article object suitable for viewing the given object
451 * NOTE: does *not* do special handling for Image and Category pages!
452 * Use Article::newFromTitle() for that!
454 * @param Title $title
456 * @todo Article is being refactored into an action class, keep track of that
457 * @todo Article really defines the view of the content... rename this method to createViewPage ?
459 public function createArticle( Title
$title ) {
460 $this->checkModelID( $title->getContentModel() );
462 $article = new Article($title);
467 * Return an EditPage object suitable for editing the given object
469 * @param Article $article
472 public function createEditPage( Article
$article ) {
473 $this->checkModelID( $article->getPage()->getContentModel() );
475 $editPage = new EditPage( $article );
480 * Return an ExternalEdit object suitable for editing the given object
482 * @param IContextSource $context
483 * @return ExternalEdit
484 * @todo does anyone or anythign actually use the external edit facility? Can we just deprecate and ignore it?
486 public function createExternalEdit( IContextSource
$context ) {
487 $this->checkModelID( $context->getTitle()->getContentModel() );
489 $externalEdit = new ExternalEdit( $context );
490 return $externalEdit;
495 * @param $context IContextSource context to use, anything else will be ignored
496 * @param $old Integer old ID we want to show and diff with.
497 * @param $new String either 'prev' or 'next'.
498 * @param $rcid Integer ??? FIXME (default 0)
499 * @param $refreshCache boolean If set, refreshes the diff cache
500 * @param $unhide boolean If set, allow viewing deleted revs
502 * @return DifferenceEngine
504 public function createDifferenceEngine( IContextSource
$context, $old = 0, $new = 0, $rcid = 0, #FIMXE: use everywhere!
505 $refreshCache = false, $unhide = false ) {
507 $this->checkModelID( $context->getTitle()->getContentModel() );
509 $diffEngineClass = $this->getDiffEngineClass();
511 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
515 * Returns the name of the diff engine to use.
521 protected function getDiffEngineClass() {
522 return 'DifferenceEngine';
526 * attempts to merge differences between three versions.
527 * Returns a new Content object for a clean merge and false for failure or a conflict.
529 * This default implementation always returns false.
531 * @param $oldContent String
532 * @param $myContent String
533 * @param $yourContent String
534 * @return Content|Bool
536 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
541 * Return an applicable autosummary if one exists for the given edit.
543 * @param $oldContent Content|null: the previous text of the page.
544 * @param $newContent Content|null: The submitted text of the page.
545 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
547 * @return string An appropriate autosummary, or an empty string.
549 public function getAutosummary( Content
$oldContent = null, Content
$newContent = null, $flags ) {
552 // Decide what kind of autosummary is needed.
554 // Redirect autosummaries
561 $ot = !is_null( $oldContent ) ?
$oldContent->getRedirectTarget() : null;
562 $rt = !is_null( $newContent ) ?
$newContent->getRedirectTarget() : null;
564 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
566 $truncatedtext = $newContent->getTextForSummary(
568 - strlen( wfMsgForContent( 'autoredircomment' ) )
569 - strlen( $rt->getFullText() ) );
571 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
574 // New page autosummaries
575 if ( $flags & EDIT_NEW
&& $newContent->getSize() > 0 ) {
576 // If they're making a new article, give its text, truncated, in the summary.
578 $truncatedtext = $newContent->getTextForSummary(
579 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) );
581 return wfMsgForContent( 'autosumm-new', $truncatedtext );
584 // Blanking autosummaries
585 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
586 return wfMsgForContent( 'autosumm-blank' );
587 } elseif ( !empty( $oldContent ) && $oldContent->getSize() > 10 * $newContent->getSize() && $newContent->getSize() < 500 ) {
588 // Removing more than 90% of the article
590 $truncatedtext = $newContent->getTextForSummary(
591 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) );
593 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
596 // If we reach this point, there's no applicable autosummary for our case, so our
597 // autosummary is empty.
603 * Auto-generates a deletion reason
605 * @param $title Title: the page's title
606 * @param &$hasHistory Boolean: whether the page has a history
607 * @return mixed String containing deletion reason or empty string, or boolean false
608 * if no revision occurred
610 * @XXX &$hasHistory is extremely ugly, it's here because WikiPage::getAutoDeleteReason() and Article::getReason() have it / want it.
612 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
613 $dbw = wfGetDB( DB_MASTER
);
615 // Get the last revision
616 $rev = Revision
::newFromTitle( $title );
618 if ( is_null( $rev ) ) {
622 // Get the article's contents
623 $content = $rev->getContent();
626 // If the page is blank, use the text from the previous revision,
627 // which can only be blank if there's a move/import/protect dummy revision involved
628 if ( $content->getSize() == 0 ) {
629 $prev = $rev->getPrevious();
632 $content = $rev->getContent();
637 // Find out if there was only one contributor
638 // Only scan the last 20 revisions
639 $res = $dbw->select( 'revision', 'rev_user_text',
640 array( 'rev_page' => $title->getArticleID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
642 array( 'LIMIT' => 20 )
645 if ( $res === false ) {
646 // This page has no revisions, which is very weird
650 $hasHistory = ( $res->numRows() > 1 );
651 $row = $dbw->fetchObject( $res );
653 if ( $row ) { // $row is false if the only contributor is hidden
654 $onlyAuthor = $row->rev_user_text
;
655 // Try to find a second contributor
656 foreach ( $res as $row ) {
657 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
666 // Generate the summary with a '$1' placeholder
668 // The current revision is blank and the one before is also
669 // blank. It's just not our lucky day
670 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
673 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
675 $reason = wfMsgForContent( 'excontent', '$1' );
679 if ( $reason == '-' ) {
680 // Allow these UI messages to be blanked out cleanly
684 // Max content length = max comment length - length of the comment (excl. $1)
685 $text = $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) );
687 // Now replace the '$1' placeholder
688 $reason = str_replace( '$1', $text, $reason );
693 #@TODO: getSecondaryUpdatesForDeletion( Content ) returns an array of SecondaryDataUpdate objects
694 #... or do that in the Content class?
697 * Get the Content object that needs to be saved in order to undo all revisions
698 * between $undo and $undoafter. Revisions must belong to the same page,
699 * must exist and must not be deleted
700 * @param $current Revision the current text
701 * @param $undo Revision the revision to undo
702 * @param $undoafter Revision Must be an earlier revision than $undo
703 * @return mixed string on success, false on failure
705 public function getUndoContent( Revision
$current, Revision
$undo, Revision
$undoafter ) {
706 $cur_content = $current->getContent();
708 if ( empty( $cur_content ) ) {
709 return false; // no page
712 $undo_content = $undo->getContent();
713 $undoafter_content = $undoafter->getContent();
715 if ( $cur_content->equals( $undo_content ) ) {
716 // No use doing a merge if it's just a straight revert.
717 return $undoafter_content;
720 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
722 return $undone_content;
726 * Returns true for content models that support caching using the ParserCache mechanism.
727 * See WikiPage::isParserCacheUser().
731 public function isParserCacheSupported() {
736 * @param $page WikiPage the page that was deleted (note: $page->getId() must still return the old page ID!)
738 * @return array a list of SecondaryDataUpdate instances that will clean up the database ofter deletion.
740 public function getDeletionUpdates( WikiPage
$page ) {
742 new LinksDeletionUpdate( $page ),
748 abstract class TextContentHandler
extends ContentHandler
{
750 public function __construct( $modelId, $formats ) {
751 parent
::__construct( $modelId, $formats );
754 public function serializeContent( Content
$content, $format = null ) {
755 $this->checkFormat( $format );
756 return $content->getNativeData();
760 * attempts to merge differences between three versions.
761 * Returns a new Content object for a clean merge and false for failure or a conflict.
763 * All three Content objects passed as parameters must have the same content model.
765 * This text-based implementation uses wfMerge().
767 * @param $oldContent String
768 * @param $myContent String
769 * @param $yourContent String
770 * @return Content|Bool
772 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
773 $this->checkModelID( $oldContent->getModel() );
774 $this->checkModelID( $myContent->getModel() );
775 $this->checkModelID( $yourContent->getModel() );
777 $format = $this->getDefaultFormat();
779 $old = $this->serializeContent( $oldContent, $format );
780 $mine = $this->serializeContent( $myContent, $format );
781 $yours = $this->serializeContent( $yourContent, $format );
783 $ok = wfMerge( $old, $mine, $yours, $result );
790 return $this->makeEmptyContent();
793 $mergedContent = $this->unserializeContent( $result, $format );
794 return $mergedContent;
799 class WikitextContentHandler
extends TextContentHandler
{
801 public function __construct( $modelId = CONTENT_MODEL_WIKITEXT
) {
802 parent
::__construct( $modelId, array( CONTENT_FORMAT_WIKITEXT
) );
805 public function unserializeContent( $text, $format = null ) {
806 $this->checkFormat( $format );
808 return new WikitextContent( $text );
811 public function makeEmptyContent() {
812 return new WikitextContent( '' );
818 #XXX: make ScriptContentHandler base class with plugin interface for syntax highlighting?
820 class JavaScriptContentHandler
extends TextContentHandler
{
822 public function __construct( $modelId = CONTENT_MODEL_JAVASCRIPT
) {
823 parent
::__construct( $modelId, array( CONTENT_FORMAT_JAVASCRIPT
) );
826 public function unserializeContent( $text, $format = null ) {
827 $this->checkFormat( $format );
829 return new JavaScriptContent( $text );
832 public function makeEmptyContent() {
833 return new JavaScriptContent( '' );
837 class CssContentHandler
extends TextContentHandler
{
839 public function __construct( $modelId = CONTENT_MODEL_CSS
) {
840 parent
::__construct( $modelId, array( CONTENT_FORMAT_CSS
) );
843 public function unserializeContent( $text, $format = null ) {
844 $this->checkFormat( $format );
846 return new CssContent( $text );
849 public function makeEmptyContent() {
850 return new CssContent( '' );