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->getModelName() );
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 $modelName (or,
74 * if that is not given, $title->getContentModelName()) 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 $modelName the model to deserialize to. If not provided, $title->getContentModelName() 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, $modelName = null, $format = null ) {
87 if ( is_null( $modelName ) ) {
88 $modelName = $title->getContentModelName();
91 $handler = ContentHandler
::getForModelName( $modelName );
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::getContentModelName().
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::getContentModelName()
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->getContentModelName() directly or indirectly,
121 // because it is used to initialized the mContentModelName 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 $modelName = $title->getContentModelName();
187 return ContentHandler
::getForModelName( $modelName );
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 $modelName = $content->getModelName();
199 return ContentHandler
::getForModelName( $modelName );
203 * returns the ContentHandler singleton for the given model name. 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 $modelName, the ContentHandler may be provided by the
214 * a ContentHandlerForModelName hook. if no Contenthandler can be determined, an MWException is raised.
217 * @param $modelName String the name 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 $modelName
219 * @throws MWException if no handler is known for $modelName.
221 public static function getForModelName( $modelName ) {
222 global $wgContentHandlers;
224 if ( empty( $wgContentHandlers[$modelName] ) ) {
227 wfRunHooks( 'ContentHandlerForModelName', array( $modelName, &$handler ) );
229 if ( $handler ) { // NOTE: may be a string or an object, either is fine!
230 $wgContentHandlers[$modelName] = $handler;
232 throw new MWException( "No handler for model $modelName registered in \$wgContentHandlers" );
236 if ( is_string( $wgContentHandlers[$modelName] ) ) {
237 $class = $wgContentHandlers[$modelName];
238 $wgContentHandlers[$modelName] = new $class( $modelName );
241 return $wgContentHandlers[$modelName];
244 // ----------------------------------------------------------------------------------------------------------
247 * Constructor, initializing the ContentHandler instance with it's model name and a list of supported formats.
248 * Values for the parameters are typically provided as literals by subclasses' constructors.
250 * @param String $modelName (use CONTENT_MODEL_XXX constants).
251 * @param array $formats list for supported serialization formats (typically as MIME types)
253 public function __construct( $modelName, $formats ) {
254 $this->mModelName
= $modelName;
255 $this->mSupportedFormats
= $formats;
260 * Serializes Content object of the type supported by this ContentHandler.
263 * @param Content $content the Content object to serialize
264 * @param null $format the desired serialization format
265 * @return String serialized form of the content
267 public abstract function serializeContent( Content
$content, $format = null );
270 * Unserializes a Content object of the type supported by this ContentHandler.
273 * @param $blob String serialized form of the content
274 * @param null $format the format used for serialization
275 * @return Content the Content object created by deserializing $blob
277 public abstract function unserializeContent( $blob, $format = null );
280 * Creates an empty Content object of the type supported by this ContentHandler.
284 public abstract function makeEmptyContent();
287 * Returns the model name that identifies the content model this ContentHandler can handle.
288 * Use with the CONTENT_MODEL_XXX constants.
290 * @return String the model name
292 public function getModelName() {
293 return $this->mModelName
;
297 * Throws an MWException if $modelName is not the content model handeled by this ContentHandler.
299 * @param String $modelName the model name to check
301 protected function checkModelName( $modelName ) {
302 if ( $modelName !== $this->mModelName
) {
303 throw new MWException( "Bad content model: expected " . $this->mModelName
. " but got found " . $modelName );
308 * Returns a list of serialization formats supported by the serializeContent() and unserializeContent() methods of
309 * this ContentHandler.
311 * @return array of serialization formats as MIME type like strings
313 public function getSupportedFormats() {
314 return $this->mSupportedFormats
;
318 * The format used for serialization/deserialization per default by this ContentHandler.
320 * This default implementation will return the first element of the array of formats
321 * that was passed to the constructor.
323 * @return String the name of the default serialiozation format as a MIME type
325 public function getDefaultFormat() {
326 return $this->mSupportedFormats
[0];
330 * Returns true if $format is a serialization format supported by this ContentHandler,
331 * and false otherwise.
333 * Note that if $format is null, this method always returns true, because null
334 * means "use the default format".
336 * @param String $format the serialization format to check
339 public function isSupportedFormat( $format ) {
342 return true; // this means "use the default"
345 return in_array( $format, $this->mSupportedFormats
);
349 * Throws an MWException if isSupportedFormat( $format ) is not true. Convenient
350 * for checking whether a format provided as a parameter is actually supported.
352 * @param String $format the serialization format to check
354 protected function checkFormat( $format ) {
355 if ( !$this->isSupportedFormat( $format ) ) {
356 throw new MWException( "Format $format is not supported for content model " . $this->getModelName() );
361 * Returns overrides for action handlers.
362 * Classes listed here will be used instead of the default one when
363 * (and only when) $wgActions[$action] === true. This allows subclasses
364 * to override the default action handlers.
368 public function getActionOverrides() {
373 * Return an Article object suitable for viewing the given object
375 * NOTE: does *not* do special handling for Image and Category pages!
376 * Use Article::newFromTitle() for that!
378 * @param Title $title
380 * @todo Article is being refactored into an action class, keep track of that
381 * @todo Article really defines the view of the content... rename this method to createViewPage ?
383 public function createArticle( Title
$title ) {
384 $this->checkModelName( $title->getContentModelName() );
386 $article = new Article($title);
391 * Return an EditPage object suitable for editing the given object
393 * @param Article $article
396 public function createEditPage( Article
$article ) {
397 $this->checkModelName( $article->getContentModelName() );
399 $editPage = new EditPage( $article );
404 * Return an ExternalEdit object suitable for editing the given object
406 * @param IContextSource $context
407 * @return ExternalEdit
408 * @todo does anyone or anythign actually use the external edit facility? Can we just deprecate and ignore it?
410 public function createExternalEdit( IContextSource
$context ) {
411 $this->checkModelName( $context->getTitle()->getContentModelName() );
413 $externalEdit = new ExternalEdit( $context );
414 return $externalEdit;
419 * @param $context IContextSource context to use, anything else will be ignored
420 * @param $old Integer old ID we want to show and diff with.
421 * @param $new String either 'prev' or 'next'.
422 * @param $rcid Integer ??? FIXME (default 0)
423 * @param $refreshCache boolean If set, refreshes the diff cache
424 * @param $unhide boolean If set, allow viewing deleted revs
426 * @return DifferenceEngine
428 public function createDifferenceEngine( IContextSource
$context, $old = 0, $new = 0, $rcid = 0, #FIMXE: use everywhere!
429 $refreshCache = false, $unhide = false ) {
431 $this->checkModelName( $context->getTitle()->getContentModelName() );
433 $diffEngineClass = $this->getDiffEngineClass();
435 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
439 * Returns the name of the diff engine to use.
445 protected function getDiffEngineClass() {
446 return 'DifferenceEngine';
450 * attempts to merge differences between three versions.
451 * Returns a new Content object for a clean merge and false for failure or a conflict.
453 * This default implementation always returns false.
455 * @param $oldContent String
456 * @param $myContent String
457 * @param $yourContent String
458 * @return Content|Bool
460 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
465 * Return an applicable autosummary if one exists for the given edit.
467 * @param $oldContent Content|null: the previous text of the page.
468 * @param $newContent Content|null: The submitted text of the page.
469 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
471 * @return string An appropriate autosummary, or an empty string.
473 public function getAutosummary( Content
$oldContent = null, Content
$newContent = null, $flags ) {
476 // Decide what kind of autosummary is needed.
478 // Redirect autosummaries
485 $ot = !is_null( $oldContent ) ?
$oldContent->getRedirectTarget() : null;
486 $rt = !is_null( $newContent ) ?
$newContent->getRedirectTarget() : null;
488 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
490 $truncatedtext = $newContent->getTextForSummary(
492 - strlen( wfMsgForContent( 'autoredircomment' ) )
493 - strlen( $rt->getFullText() ) );
495 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
498 // New page autosummaries
499 if ( $flags & EDIT_NEW
&& $newContent->getSize() > 0 ) {
500 // If they're making a new article, give its text, truncated, in the summary.
502 $truncatedtext = $newContent->getTextForSummary(
503 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) );
505 return wfMsgForContent( 'autosumm-new', $truncatedtext );
508 // Blanking autosummaries
509 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
510 return wfMsgForContent( 'autosumm-blank' );
511 } elseif ( !empty( $oldContent ) && $oldContent->getSize() > 10 * $newContent->getSize() && $newContent->getSize() < 500 ) {
512 // Removing more than 90% of the article
514 $truncatedtext = $newContent->getTextForSummary(
515 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) );
517 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
520 // If we reach this point, there's no applicable autosummary for our case, so our
521 // autosummary is empty.
527 * Auto-generates a deletion reason
529 * @param $title Title: the page's title
530 * @param &$hasHistory Boolean: whether the page has a history
531 * @return mixed String containing deletion reason or empty string, or boolean false
532 * if no revision occurred
534 * @XXX &$hasHistory is extremely ugly, it's here because WikiPage::getAutoDeleteReason() and Article::getReason() have it / want it.
536 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
537 $dbw = wfGetDB( DB_MASTER
);
539 // Get the last revision
540 $rev = Revision
::newFromTitle( $title );
542 if ( is_null( $rev ) ) {
546 // Get the article's contents
547 $content = $rev->getContent();
550 // If the page is blank, use the text from the previous revision,
551 // which can only be blank if there's a move/import/protect dummy revision involved
552 if ( $content->getSize() == 0 ) {
553 $prev = $rev->getPrevious();
556 $content = $rev->getContent();
561 // Find out if there was only one contributor
562 // Only scan the last 20 revisions
563 $res = $dbw->select( 'revision', 'rev_user_text',
564 array( 'rev_page' => $title->getArticleID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
566 array( 'LIMIT' => 20 )
569 if ( $res === false ) {
570 // This page has no revisions, which is very weird
574 $hasHistory = ( $res->numRows() > 1 );
575 $row = $dbw->fetchObject( $res );
577 if ( $row ) { // $row is false if the only contributor is hidden
578 $onlyAuthor = $row->rev_user_text
;
579 // Try to find a second contributor
580 foreach ( $res as $row ) {
581 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
590 // Generate the summary with a '$1' placeholder
592 // The current revision is blank and the one before is also
593 // blank. It's just not our lucky day
594 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
597 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
599 $reason = wfMsgForContent( 'excontent', '$1' );
603 if ( $reason == '-' ) {
604 // Allow these UI messages to be blanked out cleanly
608 // Max content length = max comment length - length of the comment (excl. $1)
609 $text = $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) );
611 // Now replace the '$1' placeholder
612 $reason = str_replace( '$1', $text, $reason );
617 #@TODO: getSecondaryUpdatesForDeletion( Content ) returns an array of SecondaryDataUpdate objects
618 #... or do that in the Content class?
621 * Get the Content object that needs to be saved in order to undo all revisions
622 * between $undo and $undoafter. Revisions must belong to the same page,
623 * must exist and must not be deleted
624 * @param $current Revision the current text
625 * @param $undo Revision the revision to undo
626 * @param $undoafter Revision Must be an earlier revision than $undo
627 * @return mixed string on success, false on failure
629 public function getUndoContent( Revision
$current, Revision
$undo, Revision
$undoafter ) {
630 $cur_content = $current->getContent();
632 if ( empty( $cur_content ) ) {
633 return false; // no page
636 $undo_content = $undo->getContent();
637 $undoafter_content = $undoafter->getContent();
639 if ( $cur_content->equals( $undo_content ) ) {
640 // No use doing a merge if it's just a straight revert.
641 return $undoafter_content;
644 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
646 return $undone_content;
650 * Returns true for content models that support caching using the ParserCache mechanism.
651 * See WikiPage::isParserCacheUser().
655 public function isParserCacheSupported() {
660 * @param $page WikiPage the page that was deleted (note: $page->getId() must still return the old page ID!)
662 * @return array a list of SecondaryDataUpdate instances that will clean up the database ofter deletion.
664 public function getDeletionUpdates( WikiPage
$page ) {
666 new LinksDeletionUpdate( $page ),
672 abstract class TextContentHandler
extends ContentHandler
{
674 public function __construct( $modelName, $formats ) {
675 parent
::__construct( $modelName, $formats );
678 public function serializeContent( Content
$content, $format = null ) {
679 $this->checkFormat( $format );
680 return $content->getNativeData();
684 * attempts to merge differences between three versions.
685 * Returns a new Content object for a clean merge and false for failure or a conflict.
687 * All three Content objects passed as parameters must have the same content model.
689 * This text-based implementation uses wfMerge().
691 * @param $oldContent String
692 * @param $myContent String
693 * @param $yourContent String
694 * @return Content|Bool
696 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
697 $this->checkModelName( $oldContent->getModelName() );
698 $this->checkModelName( $myContent->getModelName() );
699 $this->checkModelName( $yourContent->getModelName() );
701 $format = $this->getDefaultFormat();
703 $old = $this->serializeContent( $oldContent, $format );
704 $mine = $this->serializeContent( $myContent, $format );
705 $yours = $this->serializeContent( $yourContent, $format );
707 $ok = wfMerge( $old, $mine, $yours, $result );
714 return $this->makeEmptyContent();
717 $mergedContent = $this->unserializeContent( $result, $format );
718 return $mergedContent;
723 class WikitextContentHandler
extends TextContentHandler
{
725 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
726 parent
::__construct( $modelName, array( 'text/x-wiki' ) );
729 public function unserializeContent( $text, $format = null ) {
730 $this->checkFormat( $format );
732 return new WikitextContent( $text );
735 public function makeEmptyContent() {
736 return new WikitextContent( '' );
742 #XXX: make ScriptContentHandler base class with plugin interface for syntax highlighting?
744 class JavaScriptContentHandler
extends TextContentHandler
{
746 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
747 parent
::__construct( $modelName, array( 'text/javascript' ) ); #XXX: or use $wgJsMimeType? this is for internal storage, not HTTP...
750 public function unserializeContent( $text, $format = null ) {
751 $this->checkFormat( $format );
753 return new JavaScriptContent( $text );
756 public function makeEmptyContent() {
757 return new JavaScriptContent( '' );
761 class CssContentHandler
extends TextContentHandler
{
763 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
764 parent
::__construct( $modelName, array( 'text/css' ) );
767 public function unserializeContent( $text, $format = null ) {
768 $this->checkFormat( $format );
770 return new CssContent( $text );
773 public function makeEmptyContent() {
774 return new CssContent( '' );