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.
23 abstract class ContentHandler
{
26 * Conveniance function for getting flat text from a Content object. This should only
27 * be used in the context of backwards compatibility with code that is not yet able
28 * to handle Content objects!
30 * If $content is null, this method returns the empty string.
32 * If $content is an instance of TextContent, this method returns the flat text as returned by $content->getNativeData().
34 * If $content is not a TextContent object, the bahaviour of this method depends on the global $wgContentHandlerTextFallback:
35 * * If $wgContentHandlerTextFallback is 'fail' and $content is not a TextContent object, an MWException is thrown.
36 * * If $wgContentHandlerTextFallback is 'serialize' and $content is not a TextContent object, $content->serialize()
37 * is called to get a string form of the content.
38 * * If $wgContentHandlerTextFallback is 'ignore' and $content is not a TextContent object, this method returns null.
39 * * otherwise, the behaviour is undefined.
42 * @param Content|null $content
43 * @return null|string the textual form of $content, if available
44 * @throws MWException if $content is not an instance of TextContent and $wgContentHandlerTextFallback was set to 'fail'.
46 public static function getContentText( Content
$content = null ) {
47 global $wgContentHandlerTextFallback;
49 if ( is_null( $content ) ) {
53 if ( $content instanceof TextContent
) {
54 return $content->getNativeData();
57 if ( $wgContentHandlerTextFallback == 'fail' ) {
58 throw new MWException( "Attempt to get text from Content with model " . $content->getModelName() );
61 if ( $wgContentHandlerTextFallback == 'serialize' ) {
62 return $content->serialize();
69 * Conveniance function for creating a Content object from a given textual representation.
71 * $text will be deserialized into a Content object of the model specified by $modelName (or,
72 * if that is not given, $title->getContentModelName()) using the given format.
75 * @param string $text the textual represenation, will be unserialized to create the Content object
76 * @param Title $title the title of the page this text belongs to, required as a context for deserialization
77 * @param null|String $modelName the model to deserialize to. If not provided, $title->getContentModelName() is used.
78 * @param null|String $format the format to use for deserialization. If not given, the model's default format is used.
80 * @return Content a Content object representing $text
81 * @throw MWException if $model or $format is not supported or if $text can not be unserialized using $format.
83 public static function makeContent( $text, Title
$title, $modelName = null, $format = null ) {
85 if ( is_null( $modelName ) ) {
86 $modelName = $title->getContentModelName();
89 $handler = ContentHandler
::getForModelName( $modelName );
90 return $handler->unserializeContent( $text, $format );
94 * Returns the name of the default content model to be used for the page with the given title.
96 * Note: There should rarely be need to call this method directly.
97 * To determine the actual content model for a given page, use Title::getContentModelName().
99 * Which model is to be used per default for the page is determined based on several factors:
100 * * The global setting $wgNamespaceContentModels specifies a content model per namespace.
101 * * The hook DefaultModelFor may be used to override the page's default model.
102 * * Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript model if they end in .js or .css, respectively.
103 * * Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
104 * * 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.
105 * * The hook TitleIsWikitextPage may be used to force a page to use the wikitext model.
107 * If none of the above applies, the wikitext model is used.
109 * Note: this is used by, and may thus not use, Title::getContentModelName()
112 * @param Title $title
113 * @return null|string default model name for the page given by $title
115 public static function getDefaultModelFor( Title
$title ) {
116 global $wgNamespaceContentModels;
118 // NOTE: this method must not rely on $title->getContentModelName() directly or indirectly,
119 // because it is used to initialized the mContentModelName memebr.
121 $ns = $title->getNamespace();
127 if ( !empty( $wgNamespaceContentModels[ $ns ] ) ) {
128 $model = $wgNamespaceContentModels[ $ns ];
131 // hook can determin default model
132 if ( !wfRunHooks( 'DefaultModelFor', array( $title, &$model ) ) ) { #FIXME: document new hook!
133 if ( !is_null( $model ) ) {
138 // Could this page contain custom CSS or JavaScript, based on the title?
139 $isCssOrJsPage = NS_MEDIAWIKI
== $ns && preg_match( '!\.(css|js)$!u', $title->getText(), $m );
140 if ( $isCssOrJsPage ) {
144 // hook can force js/css
145 wfRunHooks( 'TitleIsCssOrJsPage', array( $title, &$isCssOrJsPage ) );
147 // Is this a .css subpage of a user page?
148 $isJsCssSubpage = NS_USER
== $ns && !$isCssOrJsPage && preg_match( "/\\/.*\\.(js|css)$/", $title->getText(), $m );
149 if ( $isJsCssSubpage ) {
153 // is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
154 $isWikitext = is_null( $model ) ||
$model == CONTENT_MODEL_WIKITEXT
;
155 $isWikitext = $isWikitext && !$isCssOrJsPage && !$isJsCssSubpage;
157 // hook can override $isWikitext
158 wfRunHooks( 'TitleIsWikitextPage', array( $title, &$isWikitext ) );
160 if ( !$isWikitext ) {
163 return CONTENT_MODEL_JAVASCRIPT
;
165 return CONTENT_MODEL_CSS
;
167 return is_null( $model ) ? CONTENT_MODEL_TEXT
: $model;
171 // we established that is must be wikitext
173 return CONTENT_MODEL_WIKITEXT
;
177 * returns the appropriate ContentHandler singleton for the given title
180 * @param Title $title
181 * @return ContentHandler
183 public static function getForTitle( Title
$title ) {
184 $modelName = $title->getContentModelName();
185 return ContentHandler
::getForModelName( $modelName );
189 * returns the appropriate ContentHandler singleton for the given Content object
192 * @param Content $content
193 * @return ContentHandler
195 public static function getForContent( Content
$content ) {
196 $modelName = $content->getModelName();
197 return ContentHandler
::getForModelName( $modelName );
201 * returns the ContentHandler singleton for the given model name. Use the CONTENT_MODEL_XXX constants to
202 * identify the desired content model.
204 * ContentHandler singletons are take from the global $wgContentHandlers array. Keys in that array are
205 * model names, the values are either ContentHandler singleton objects, or strings specifying the appropriate
206 * subclass of ContentHandler.
208 * If a class name in encountered when looking up the singleton for a given model name, the class is
209 * instantiated and the class name is replaced by te resulting singleton in $wgContentHandlers.
211 * If no ContentHandler is defined for the desired $modelName, the ContentHandler may be provided by the
212 * a ContentHandlerForModelName hook. if no Contenthandler can be determined, an MWException is raised.
215 * @param $modelName String the name of the content model for which to get a handler. Use CONTENT_MODEL_XXX constants.
216 * @return ContentHandler the ContentHandler singleton for handling the model given by $modelName
217 * @throws MWException if no handler is known for $modelName.
219 public static function getForModelName( $modelName ) {
220 global $wgContentHandlers;
222 if ( empty( $wgContentHandlers[$modelName] ) ) {
225 // FIXME: document new hook
226 wfRunHooks( 'ContentHandlerForModelName', array( $modelName, &$handler ) );
228 if ( $handler ) { // NOTE: may be a string or an object, either is fine!
229 $wgContentHandlers[$modelName] = $handler;
231 throw new MWException( "No handler for model $modelName registered in \$wgContentHandlers" );
235 if ( is_string( $wgContentHandlers[$modelName] ) ) {
236 $class = $wgContentHandlers[$modelName];
237 $wgContentHandlers[$modelName] = new $class( $modelName );
240 return $wgContentHandlers[$modelName];
243 // ----------------------------------------------------------------------------------------------------------
246 * Constructor, initializing the ContentHandler instance with it's model name and a list of supported formats.
247 * Values for the parameters are typically provided as literals by subclasses' constructors.
249 * @param String $modelName (use CONTENT_MODEL_XXX constants).
250 * @param array $formats list for supported serialization formats (typically as MIME types)
252 public function __construct( $modelName, $formats ) {
253 $this->mModelName
= $modelName;
254 $this->mSupportedFormats
= $formats;
259 * Serializes Content object of the type supported by this ContentHandler.
262 * @param Content $content the Content object to serialize
263 * @param null $format the desired serialization format
264 * @return String serialized form of the content
266 public abstract function serializeContent( Content
$content, $format = null );
269 * Unserializes a Content object of the type supported by this ContentHandler.
272 * @param $blob String serialized form of the content
273 * @param null $format the format used for serialization
274 * @return Content the Content object created by deserializing $blob
276 public abstract function unserializeContent( $blob, $format = null );
279 * Creates an empty Content object of the type supported by this ContentHandler.
283 public abstract function makeEmptyContent();
286 * Returns the model name that identifies the content model this ContentHandler can handle.
287 * Use with the CONTENT_MODEL_XXX constants.
289 * @return String the model name
291 public function getModelName() {
292 return $this->mModelName
;
296 * Throws an MWException if $modelName is not the content model handeled by this ContentHandler.
298 * @param String $modelName the model name to check
300 protected function checkModelName( $modelName ) {
301 if ( $modelName !== $this->mModelName
) {
302 throw new MWException( "Bad content model: expected " . $this->mModelName
. " but got found " . $modelName );
307 * Returns a list of serialization formats supported by the serializeContent() and unserializeContent() methods of
308 * this ContentHandler.
310 * @return array of serialization formats as MIME type like strings
312 public function getSupportedFormats() {
313 return $this->mSupportedFormats
;
317 * The format used for serialization/deserialization per default by this ContentHandler.
319 * This default implementation will return the first element of the array of formats
320 * that was passed to the constructor.
322 * @return String the name of the default serialiozation format as a MIME type
324 public function getDefaultFormat() {
325 return $this->mSupportedFormats
[0];
329 * Returns true if $format is a serialization format supported by this ContentHandler,
330 * and false otherwise.
332 * Note that if $format is null, this method always returns true, because null
333 * means "use the default format".
335 * @param String $format the serialization format to check
338 public function isSupportedFormat( $format ) {
341 return true; // this means "use the default"
344 return in_array( $format, $this->mSupportedFormats
);
348 * Throws an MWException if isSupportedFormat( $format ) is not true. Convenient
349 * for checking whether a format provided as a parameter is actually supported.
351 * @param String $format the serialization format to check
353 protected function checkFormat( $format ) {
354 if ( !$this->isSupportedFormat( $format ) ) {
355 throw new MWException( "Format $format is not supported for content model " . $this->getModelName() );
360 * Returns overrides for action handlers.
361 * Classes listed here will be used instead of the default one when
362 * (and only when) $wgActions[$action] === true. This allows subclasses
363 * to override the default action handlers.
367 public function getActionOverrides() {
372 * Return an Article object suitable for viewing the given object
374 * NOTE: does *not* do special handling for Image and Category pages!
375 * Use Article::newFromTitle() for that!
377 * @param Title $title
379 * @todo Article is being refactored into an action class, keep track of that
380 * @todo Article really defines the view of the content... rename this method to createViewPage ?
382 public function createArticle( Title
$title ) {
383 $this->checkModelName( $title->getContentModelName() );
385 $article = new Article($title);
390 * Return an EditPage object suitable for editing the given object
392 * @param Article $article
395 public function createEditPage( Article
$article ) {
396 $this->checkModelName( $article->getContentModelName() );
398 $editPage = new EditPage( $article );
403 * Return an ExternalEdit object suitable for editing the given object
405 * @param IContextSource $context
406 * @return ExternalEdit
407 * @todo does anyone or anythign actually use the external edit facility? Can we just deprecate and ignore it?
409 public function createExternalEdit( IContextSource
$context ) {
410 $this->checkModelName( $context->getTitle()->getContentModelName() );
412 $externalEdit = new ExternalEdit( $context );
413 return $externalEdit;
418 * @param $context IContextSource context to use, anything else will be ignored
419 * @param $old Integer old ID we want to show and diff with.
420 * @param $new String either 'prev' or 'next'.
421 * @param $rcid Integer ??? FIXME (default 0)
422 * @param $refreshCache boolean If set, refreshes the diff cache
423 * @param $unhide boolean If set, allow viewing deleted revs
425 * @return DifferenceEngine
427 public function createDifferenceEngine( IContextSource
$context, $old = 0, $new = 0, $rcid = 0, #FIMXE: use everywhere!
428 $refreshCache = false, $unhide = false ) {
430 $this->checkModelName( $context->getTitle()->getContentModelName() );
432 $diffEngineClass = $this->getDiffEngineClass();
434 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
438 * Returns the name of the diff engine to use.
444 protected function getDiffEngineClass() {
445 return 'DifferenceEngine';
449 * attempts to merge differences between three versions.
450 * Returns a new Content object for a clean merge and false for failure or a conflict.
452 * This default implementation always returns false.
454 * @param $oldContent String
455 * @param $myContent String
456 * @param $yourContent String
457 * @return Content|Bool
459 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
464 * Return an applicable autosummary if one exists for the given edit.
466 * @param $oldContent Content|null: the previous text of the page.
467 * @param $newContent Content|null: The submitted text of the page.
468 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
470 * @return string An appropriate autosummary, or an empty string.
472 public function getAutosummary( Content
$oldContent = null, Content
$newContent = null, $flags ) {
475 // Decide what kind of autosummary is needed.
477 // Redirect autosummaries
484 $ot = !is_null( $oldContent ) ?
$oldContent->getRedirectTarget() : null;
485 $rt = !is_null( $newContent ) ?
$newContent->getRedirectTarget() : null;
487 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
489 $truncatedtext = $newContent->getTextForSummary(
491 - strlen( wfMsgForContent( 'autoredircomment' ) )
492 - strlen( $rt->getFullText() ) );
494 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
497 // New page autosummaries
498 if ( $flags & EDIT_NEW
&& $newContent->getSize() > 0 ) {
499 // If they're making a new article, give its text, truncated, in the summary.
501 $truncatedtext = $newContent->getTextForSummary(
502 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) );
504 return wfMsgForContent( 'autosumm-new', $truncatedtext );
507 // Blanking autosummaries
508 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
509 return wfMsgForContent( 'autosumm-blank' );
510 } elseif ( !empty( $oldContent ) && $oldContent->getSize() > 10 * $newContent->getSize() && $newContent->getSize() < 500 ) {
511 // Removing more than 90% of the article
513 $truncatedtext = $newContent->getTextForSummary(
514 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) );
516 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
519 // If we reach this point, there's no applicable autosummary for our case, so our
520 // autosummary is empty.
526 * Auto-generates a deletion reason
528 * @param $title Title: the page's title
529 * @param &$hasHistory Boolean: whether the page has a history
530 * @return mixed String containing deletion reason or empty string, or boolean false
531 * if no revision occurred
533 * @XXX &$hasHistory is extremely ugly, it's here because WikiPage::getAutoDeleteReason() and Article::getReason() have it / want it.
535 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
536 $dbw = wfGetDB( DB_MASTER
);
538 // Get the last revision
539 $rev = Revision
::newFromTitle( $title );
541 if ( is_null( $rev ) ) {
545 // Get the article's contents
546 $content = $rev->getContent();
549 // If the page is blank, use the text from the previous revision,
550 // which can only be blank if there's a move/import/protect dummy revision involved
551 if ( $content->getSize() == 0 ) {
552 $prev = $rev->getPrevious();
555 $content = $rev->getContent();
560 // Find out if there was only one contributor
561 // Only scan the last 20 revisions
562 $res = $dbw->select( 'revision', 'rev_user_text',
563 array( 'rev_page' => $title->getArticleID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
565 array( 'LIMIT' => 20 )
568 if ( $res === false ) {
569 // This page has no revisions, which is very weird
573 $hasHistory = ( $res->numRows() > 1 );
574 $row = $dbw->fetchObject( $res );
576 if ( $row ) { // $row is false if the only contributor is hidden
577 $onlyAuthor = $row->rev_user_text
;
578 // Try to find a second contributor
579 foreach ( $res as $row ) {
580 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
589 // Generate the summary with a '$1' placeholder
591 // The current revision is blank and the one before is also
592 // blank. It's just not our lucky day
593 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
596 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
598 $reason = wfMsgForContent( 'excontent', '$1' );
602 if ( $reason == '-' ) {
603 // Allow these UI messages to be blanked out cleanly
607 // Max content length = max comment length - length of the comment (excl. $1)
608 $text = $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) );
610 // Now replace the '$1' placeholder
611 $reason = str_replace( '$1', $text, $reason );
616 #@TODO: getSecondaryUpdatesForDeletion( Content ) returns an array of SecondaryDataUpdate objects
617 #... or do that in the Content class?
620 * Get the Content object that needs to be saved in order to undo all revisions
621 * between $undo and $undoafter. Revisions must belong to the same page,
622 * must exist and must not be deleted
623 * @param $current Revision the current text
624 * @param $undo Revision the revision to undo
625 * @param $undoafter Revision Must be an earlier revision than $undo
626 * @return mixed string on success, false on failure
628 public function getUndoContent( Revision
$current, Revision
$undo, Revision
$undoafter ) {
629 $cur_content = $current->getContent();
631 if ( empty( $cur_content ) ) {
632 return false; // no page
635 $undo_content = $undo->getContent();
636 $undoafter_content = $undoafter->getContent();
638 if ( $cur_content->equals( $undo_content ) ) {
639 // No use doing a merge if it's just a straight revert.
640 return $undoafter_content;
643 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
645 return $undone_content;
649 * Returns true for content models that support caching using the ParserCache mechanism.
650 * See WikiPage::isParserCacheUser().
654 public function isParserCacheSupported() {
660 abstract class TextContentHandler
extends ContentHandler
{
662 public function __construct( $modelName, $formats ) {
663 parent
::__construct( $modelName, $formats );
666 public function serializeContent( Content
$content, $format = null ) {
667 $this->checkFormat( $format );
668 return $content->getNativeData();
672 * attempts to merge differences between three versions.
673 * Returns a new Content object for a clean merge and false for failure or a conflict.
675 * All three Content objects passed as parameters must have the same content model.
677 * This text-based implementation uses wfMerge().
679 * @param $oldContent String
680 * @param $myContent String
681 * @param $yourContent String
682 * @return Content|Bool
684 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
685 $this->checkModelName( $oldContent->getModelName() );
686 $this->checkModelName( $myContent->getModelName() );
687 $this->checkModelName( $yourContent->getModelName() );
689 $format = $this->getDefaultFormat();
691 $old = $this->serializeContent( $oldContent, $format );
692 $mine = $this->serializeContent( $myContent, $format );
693 $yours = $this->serializeContent( $yourContent, $format );
695 $ok = wfMerge( $old, $mine, $yours, $result );
702 return $this->makeEmptyContent();
705 $mergedContent = $this->unserializeContent( $result, $format );
706 return $mergedContent;
711 class WikitextContentHandler
extends TextContentHandler
{
713 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
714 parent
::__construct( $modelName, array( 'text/x-wiki' ) );
717 public function unserializeContent( $text, $format = null ) {
718 $this->checkFormat( $format );
720 return new WikitextContent( $text );
723 public function makeEmptyContent() {
724 return new WikitextContent( '' );
730 #XXX: make ScriptContentHandler base class with plugin interface for syntax highlighting?
732 class JavaScriptContentHandler
extends TextContentHandler
{
734 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
735 parent
::__construct( $modelName, array( 'text/javascript' ) ); #XXX: or use $wgJsMimeType? this is for internal storage, not HTTP...
738 public function unserializeContent( $text, $format = null ) {
739 $this->checkFormat( $format );
741 return new JavaScriptContent( $text );
744 public function makeEmptyContent() {
745 return new JavaScriptContent( '' );
749 class CssContentHandler
extends TextContentHandler
{
751 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
752 parent
::__construct( $modelName, array( 'text/css' ) );
755 public function unserializeContent( $text, $format = null ) {
756 $this->checkFormat( $format );
758 return new CssContent( $text );
761 public function makeEmptyContent() {
762 return new CssContent( '' );