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 $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 // TODO: 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.
282 public abstract function makeEmptyContent();
285 * Returns the model name that identifies the content model this ContentHandler can handle.
286 * Use with the CONTENT_MODEL_XXX constants.
288 * @return String the model name
290 public function getModelName() {
291 return $this->mModelName
;
295 * Throws an MWException if $modelName is not the content model handeled by this ContentHandler.
297 * @param $modelName the model name to check
299 protected function checkModelName( $modelName ) {
300 if ( $modelName !== $this->mModelName
) {
301 throw new MWException( "Bad content model: expected " . $this->mModelName
. " but got found " . $modelName );
306 * Returns a list of serialization formats supported by the serializeContent() and unserializeContent() methods of
307 * this ContentHandler.
309 * @return array of serialization formats as MIME type like strings
311 public function getSupportedFormats() {
312 return $this->mSupportedFormats
;
316 * The format used for serialization/deserialization per default by this ContentHandler.
318 * This default implementation will return the first element of the array of formats
319 * that was passed to the constructor.
321 * @return String the name of the default serialiozation format as a MIME type
323 public function getDefaultFormat() {
324 return $this->mSupportedFormats
[0];
328 * Returns true if $format is a serialization format supported by this ContentHandler,
329 * and false otherwise.
331 * Note that if $format is null, this method always returns true, because null
332 * means "use the default format".
334 * @param $format the serialization format to check
337 public function isSupportedFormat( $format ) {
340 return true; // this means "use the default"
343 return in_array( $format, $this->mSupportedFormats
);
347 * Throws an MWException if isSupportedFormat( $format ) is not true. Convenient
348 * for checking whether a format provided as a parameter is actually supported.
350 * @param $format the serialization format to check
352 protected function checkFormat( $format ) {
353 if ( !$this->isSupportedFormat( $format ) ) {
354 throw new MWException( "Format $format is not supported for content model " . $this->getModelName() );
359 * Returns overrides for action handlers.
360 * Classes listed here will be used instead of the default one when
361 * (and only when) $wgActions[$action] === true. This allows subclasses
362 * to override the default action handlers.
366 public function getActionOverrides() {
371 * Return an Article object suitable for viewing the given object
373 * NOTE: does *not* do special handling for Image and Category pages!
374 * Use Article::newFromTitle() for that!
376 * @param Title $title
378 * @todo Article is being refactored into an action class, keep track of that
379 * @todo Article really defines the view of the content... rename this method to createViewPage ?
381 public function createArticle( Title
$title ) {
382 $this->checkModelName( $title->getContentModelName() );
384 $article = new Article($title);
389 * Return an EditPage object suitable for editing the given object
391 * @param Article $article
394 public function createEditPage( Article
$article ) {
395 $this->checkModelName( $article->getContentModelName() );
397 $editPage = new EditPage( $article );
402 * Return an ExternalEdit object suitable for editing the given object
404 * @param IContextSource $context
405 * @return ExternalEdit
406 * @todo does anyone or anythign actually use the external edit facility? Can we just deprecate and ignore it?
408 public function createExternalEdit( IContextSource
$context ) {
409 $this->checkModelName( $context->getTitle()->getModelName() );
411 $externalEdit = new ExternalEdit( $context );
412 return $externalEdit;
417 * @param $context IContextSource context to use, anything else will be ignored
418 * @param $old Integer old ID we want to show and diff with.
419 * @param $new String either 'prev' or 'next'.
420 * @param $rcid Integer ??? FIXME (default 0)
421 * @param $refreshCache boolean If set, refreshes the diff cache
422 * @param $unhide boolean If set, allow viewing deleted revs
424 * @return DifferenceEngine
426 public function createDifferenceEngine( IContextSource
$context, $old = 0, $new = 0, $rcid = 0, #FIMXE: use everywhere!
427 $refreshCache = false, $unhide = false ) {
429 $this->checkModelName( $context->getTitle()->getModelName() );
431 $diffEngineClass = $this->getDiffEngineClass();
433 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
437 * Returns the name of the diff engine to use.
443 protected function getDiffEngineClass() {
444 return 'DifferenceEngine';
448 * attempts to merge differences between three versions.
449 * Returns a new Content object for a clean merge and false for failure or a conflict.
451 * This default implementation always returns false.
453 * @param $oldContent String
454 * @param $myContent String
455 * @param $yourContent String
456 * @return Content|Bool
458 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
463 * Return an applicable autosummary if one exists for the given edit.
465 * @param $oldContent Content|null: the previous text of the page.
466 * @param $newContent Content|null: The submitted text of the page.
467 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
469 * @return string An appropriate autosummary, or an empty string.
471 public function getAutosummary( Content
$oldContent = null, Content
$newContent = null, $flags ) {
474 // Decide what kind of autosummary is needed.
476 // Redirect autosummaries
478 $ot = !empty( $ot ) ?
$oldContent->getRedirectTarget() : false;
479 $rt = !empty( $rt ) ?
$newContent->getRedirectTarget() : false;
481 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
483 $truncatedtext = $newContent->getTextForSummary(
485 - strlen( wfMsgForContent( 'autoredircomment' ) )
486 - strlen( $rt->getFullText() ) );
488 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
491 // New page autosummaries
492 if ( $flags & EDIT_NEW
&& $newContent->getSize() > 0 ) {
493 // If they're making a new article, give its text, truncated, in the summary.
495 $truncatedtext = $newContent->getTextForSummary(
496 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) );
498 return wfMsgForContent( 'autosumm-new', $truncatedtext );
501 // Blanking autosummaries
502 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
503 return wfMsgForContent( 'autosumm-blank' );
504 } elseif ( !empty( $oldContent ) && $oldContent->getSize() > 10 * $newContent->getSize() && $newContent->getSize() < 500 ) {
505 // Removing more than 90% of the article
507 $truncatedtext = $newContent->getTextForSummary(
508 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) );
510 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
513 // If we reach this point, there's no applicable autosummary for our case, so our
514 // autosummary is empty.
520 * Auto-generates a deletion reason
522 * @param $title Title: the page's title
523 * @param &$hasHistory Boolean: whether the page has a history
524 * @return mixed String containing deletion reason or empty string, or boolean false
525 * if no revision occurred
527 * @todo &$hasHistory is extremely ugly, it's here because WikiPage::getAutoDeleteReason() and Article::getReason() have it / want it.
529 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
530 $dbw = wfGetDB( DB_MASTER
);
532 // Get the last revision
533 $rev = Revision
::newFromTitle( $title );
535 if ( is_null( $rev ) ) {
539 // Get the article's contents
540 $content = $rev->getContent();
543 // If the page is blank, use the text from the previous revision,
544 // which can only be blank if there's a move/import/protect dummy revision involved
545 if ( $content->getSize() == 0 ) {
546 $prev = $rev->getPrevious();
549 $content = $rev->getContent();
554 // Find out if there was only one contributor
555 // Only scan the last 20 revisions
556 $res = $dbw->select( 'revision', 'rev_user_text',
557 array( 'rev_page' => $title->getArticleID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
559 array( 'LIMIT' => 20 )
562 if ( $res === false ) {
563 // This page has no revisions, which is very weird
567 $hasHistory = ( $res->numRows() > 1 );
568 $row = $dbw->fetchObject( $res );
570 if ( $row ) { // $row is false if the only contributor is hidden
571 $onlyAuthor = $row->rev_user_text
;
572 // Try to find a second contributor
573 foreach ( $res as $row ) {
574 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
583 // Generate the summary with a '$1' placeholder
585 // The current revision is blank and the one before is also
586 // blank. It's just not our lucky day
587 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
590 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
592 $reason = wfMsgForContent( 'excontent', '$1' );
596 if ( $reason == '-' ) {
597 // Allow these UI messages to be blanked out cleanly
601 // Max content length = max comment length - length of the comment (excl. $1)
602 $text = $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) );
604 // Now replace the '$1' placeholder
605 $reason = str_replace( '$1', $text, $reason );
610 #TODO: getSecondaryUpdatesForDeletion( Content ) returns an array of SecondaryDataUpdate objects
611 #... or do that in the Content class?
614 * Get the Content object that needs to be saved in order to undo all revisions
615 * between $undo and $undoafter. Revisions must belong to the same page,
616 * must exist and must not be deleted
617 * @param $undo Revision
618 * @param $undoafter null|Revision Must be an earlier revision than $undo
619 * @return mixed string on success, false on failure
621 public function getUndoContent( Revision
$current, Revision
$undo, Revision
$undoafter = null ) {
622 $cur_content = $current->getContent();
624 if ( empty( $cur_content ) ) {
625 return false; // no page
628 $undo_content = $undo->getContent();
629 $undoafter_content = $undoafter->getContent();
631 if ( $cur_content->equals( $undo_content ) ) {
632 // No use doing a merge if it's just a straight revert.
633 return $undoafter_content;
636 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
638 return $undone_content;
643 abstract class TextContentHandler
extends ContentHandler
{
645 public function __construct( $modelName, $formats ) {
646 parent
::__construct( $modelName, $formats );
649 public function serializeContent( Content
$content, $format = null ) {
650 $this->checkFormat( $format );
651 return $content->getNativeData();
655 * attempts to merge differences between three versions.
656 * Returns a new Content object for a clean merge and false for failure or a conflict.
658 * This text-based implementation uses wfMerge().
660 * @param $oldContent String
661 * @param $myContent String
662 * @param $yourContent String
663 * @return Content|Bool
665 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
666 $this->checkModelName( $oldContent->getModelName() );
667 #TODO: check that all Content objects have the same content model! #XXX: what to do if they don't?
669 $format = $this->getDefaultFormat();
671 $old = $this->serializeContent( $oldContent, $format );
672 $mine = $this->serializeContent( $myContent, $format );
673 $yours = $this->serializeContent( $yourContent, $format );
675 $ok = wfMerge( $old, $mine, $yours, $result );
682 return $this->makeEmptyContent();
685 $mergedContent = $this->unserializeContent( $result, $format );
686 return $mergedContent;
691 class WikitextContentHandler
extends TextContentHandler
{
693 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
694 parent
::__construct( $modelName, array( 'application/x-wikitext' ) ); #FIXME: mime
697 public function unserializeContent( $text, $format = null ) {
698 $this->checkFormat( $format );
700 return new WikitextContent( $text );
703 public function makeEmptyContent() {
704 return new WikitextContent( '' );
710 #TODO: make ScriptContentHandler base class with plugin interface for syntax highlighting!
712 class JavaScriptContentHandler
extends TextContentHandler
{
714 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
715 parent
::__construct( $modelName, array( 'text/javascript' ) ); #XXX: or use $wgJsMimeType? this is for internal storage, not HTTP...
718 public function unserializeContent( $text, $format = null ) {
719 $this->checkFormat( $format );
721 return new JavaScriptContent( $text );
724 public function makeEmptyContent() {
725 return new JavaScriptContent( '' );
729 class CssContentHandler
extends TextContentHandler
{
731 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
732 parent
::__construct( $modelName, array( 'text/css' ) );
735 public function unserializeContent( $text, $format = null ) {
736 $this->checkFormat( $format );
738 return new CssContent( $text );
741 public function makeEmptyContent() {
742 return new CssContent( '' );