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 shleould 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 equal to null or false, 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 * Otherwise, this method returns null.
41 * @param Content|null $content
42 * @return null|string the textual form of $content, if available
43 * @throws MWException if $content is not an instance of TextContent and $wgContentHandlerTextFallback was set to 'fail'.
45 public static function getContentText( Content
$content = null ) {
46 global $wgContentHandlerTextFallback;
48 if ( is_null( $content ) ) {
52 if ( $content instanceof TextContent
) {
53 return $content->getNativeData();
56 if ( $wgContentHandlerTextFallback == 'fail' ) {
57 throw new MWException( "Attempt to get text from Content with model " . $content->getModelName() );
60 if ( $wgContentHandlerTextFallback == 'serialize' ) {
61 return $content->serialize();
68 * Conveniance function for creating a Content object from a given textual representation.
70 * $text will be deserialized into a Content object of the model specified by $modelName (or,
71 * if that is not given, $title->getContentModelName()) using the given format.
74 * @param $text the textual represenation, will be unserialized to create the Content object
75 * @param Title $title the title of the page this text belongs to, required as a context for deserialization
76 * @param null|String $modelName the model to deserialize to. If not provided, $title->getContentModelName() is used.
77 * @param null|String $format the format to use for deserialization. If not given, the model's default format is used.
79 * @return Content a Content object representing $text
81 public static function makeContent( $text, Title
$title, $modelName = null, $format = null ) {
83 if ( is_null( $modelName ) ) {
84 $modelName = $title->getContentModelName();
87 $handler = ContentHandler
::getForModelName( $modelName );
88 return $handler->unserializeContent( $text, $format );
92 * Returns the name of the default content model to be used for the page with the given title.
94 * Note: There should rarely be need to call this method directly.
95 * To determine the actual content model for a given page, use Title::getContentModelName().
97 * Which model is to be used per default for the page is determined based on several factors:
98 * * The global setting $wgNamespaceContentModels specifies a content model per namespace.
99 * * The hook DefaultModelFor may be used to override the page's default model.
100 * * Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript model if they end in .js or .css, respectively.
101 * * Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
102 * * 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.
103 * * The hook TitleIsWikitextPage may be used to force a page to use the wikitext model.
105 * If none of the above applies, the wikitext model is used.
107 * Note: this is used by, and may thus not use, Title::getContentModelName()
110 * @param Title $title
111 * @return null|string default model name for the page given by $title
113 public static function getDefaultModelFor( Title
$title ) {
114 global $wgNamespaceContentModels;
116 // NOTE: this method must not rely on $title->getContentModelName() directly or indirectly,
117 // because it is used to initialized the mContentModelName memebr.
119 $ns = $title->getNamespace();
125 if ( !empty( $wgNamespaceContentModels[ $ns ] ) ) {
126 $model = $wgNamespaceContentModels[ $ns ];
129 // hook can determin default model
130 if ( !wfRunHooks( 'DefaultModelFor', array( $title, &$model ) ) ) { #FIXME: document new hook!
131 if ( !is_null( $model ) ) {
136 // Could this page contain custom CSS or JavaScript, based on the title?
137 $isCssOrJsPage = NS_MEDIAWIKI
== $ns && preg_match( '!\.(css|js)$!u', $title->getText(), $m );
138 if ( $isCssOrJsPage ) {
142 // hook can force js/css
143 wfRunHooks( 'TitleIsCssOrJsPage', array( $title, &$isCssOrJsPage ) );
145 // Is this a .css subpage of a user page?
146 $isJsCssSubpage = NS_USER
== $ns && !$isCssOrJsPage && preg_match( "/\\/.*\\.(js|css)$/", $title->getText(), $m );
147 if ( $isJsCssSubpage ) {
151 // is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
152 $isWikitext = is_null( $model ) ||
$model == CONTENT_MODEL_WIKITEXT
;
153 $isWikitext = $isWikitext && !$isCssOrJsPage && !$isJsCssSubpage;
155 // hook can override $isWikitext
156 wfRunHooks( 'TitleIsWikitextPage', array( $title, &$isWikitext ) );
158 if ( !$isWikitext ) {
161 return CONTENT_MODEL_JAVASCRIPT
;
163 return CONTENT_MODEL_CSS
;
165 return is_null( $model ) ? CONTENT_MODEL_TEXT
: $model;
169 // we established that is must be wikitext
171 return CONTENT_MODEL_WIKITEXT
;
175 * returns the appropriate ContentHandler singleton for the given title
178 * @param Title $title
179 * @return ContentHandler
181 public static function getForTitle( Title
$title ) {
182 $modelName = $title->getContentModelName();
183 return ContentHandler
::getForModelName( $modelName );
187 * returns the appropriate ContentHandler singleton for the given Content object
190 * @param Content $content
191 * @return ContentHandler
193 public static function getForContent( Content
$content ) {
194 $modelName = $content->getModelName();
195 return ContentHandler
::getForModelName( $modelName );
199 * returns the ContentHandler singleton for the given model name. Use the CONTENT_MODEL_XXX constants to
200 * identify the desired content model.
202 * ContentHandler singletons are take from the global $wgContentHandlers array. Keys in that array are
203 * model names, the values are either ContentHandler singleton objects, or strings specifying the appropriate
204 * subclass of ContentHandler.
206 * If a class name in encountered when looking up the singleton for a given model name, the class is
207 * instantiated and the class name is replaced by te resulting singleton in $wgContentHandlers.
209 * If no ContentHandler is defined for the desired $modelName, the ContentHandler may be provided by the
210 * a ContentHandlerForModelName hook. if no Contenthandler can be determined, an MWException is raised.
213 * @param $modelName String the name of the content model for which to get a handler. Use CONTENT_MODEL_XXX constants.
214 * @return ContentHandler the ContentHandler singleton for handling the model given by $modelName
215 * @throws MWException if no handler is known for $modelName.
217 public static function getForModelName( $modelName ) {
218 global $wgContentHandlers;
220 if ( empty( $wgContentHandlers[$modelName] ) ) {
223 // TODO: document new hook
224 wfRunHooks( 'ContentHandlerForModelName', array( $modelName, &$handler ) );
226 if ( $handler ) { // NOTE: may be a string or an object, either is fine!
227 $wgContentHandlers[$modelName] = $handler;
229 throw new MWException( "No handler for model $modelName registered in \$wgContentHandlers" );
233 if ( is_string( $wgContentHandlers[$modelName] ) ) {
234 $class = $wgContentHandlers[$modelName];
235 $wgContentHandlers[$modelName] = new $class( $modelName );
238 return $wgContentHandlers[$modelName];
241 // ----------------------------------------------------------------------------------------------------------
244 * Constructor, initializing the ContentHandler instance with it's model name and a list of supported formats.
245 * Values for the parameters are typically provided as literals by subclasses' constructors.
247 * @param String $modelName (use CONTENT_MODEL_XXX constants).
248 * @param array $formats list for supported serialization formats (typically as MIME types)
250 public function __construct( $modelName, $formats ) {
251 $this->mModelName
= $modelName;
252 $this->mSupportedFormats
= $formats;
257 * Serializes Content object of the type supported by this ContentHandler.
260 * @param Content $content the Content object to serialize
261 * @param null $format the desired serialization format
262 * @return String serialized form of the content
264 public abstract function serializeContent( Content
$content, $format = null );
267 * Unserializes a Content object of the type supported by this ContentHandler.
270 * @param $blob String serialized form of the content
271 * @param null $format the format used for serialization
272 * @return Content the Content object created by deserializing $blob
274 public abstract function unserializeContent( $blob, $format = null );
277 * Creates an empty Content object of the type supported by this ContentHandler.
280 public abstract function makeEmptyContent();
283 * Returns the model name that identifies the content model this ContentHandler can handle.
284 * Use with the CONTENT_MODEL_XXX constants.
286 * @return String the model name
288 public function getModelName() {
289 return $this->mModelName
;
293 * Throws an MWException if $modelName is not the content model handeled by this ContentHandler.
295 * @param $modelName the model name to check
297 protected function checkModelName( $modelName ) {
298 if ( $modelName !== $this->mModelName
) {
299 throw new MWException( "Bad content model: expected " . $this->mModelName
. " but got found " . $modelName );
304 * Returns a list of serialization formats supported by the serializeContent() and unserializeContent() methods of
305 * this ContentHandler.
307 * @return array of serialization formats as MIME type like strings
309 public function getSupportedFormats() {
310 return $this->mSupportedFormats
;
314 * The format used for serialization/deserialization per default by this ContentHandler.
316 * This default implementation will return the first element of the array of formats
317 * that was passed to the constructor.
319 * @return String the name of the default serialiozation format as a MIME type
321 public function getDefaultFormat() {
322 return $this->mSupportedFormats
[0];
326 * Returns true if $format is a serialization format supported by this ContentHandler,
327 * and false otherwise.
329 * Note that if $format is null, this method always returns true, because null
330 * means "use the default format".
332 * @param $format the serialization format to check
335 public function isSupportedFormat( $format ) {
338 return true; // this means "use the default"
341 return in_array( $format, $this->mSupportedFormats
);
345 * Throws an MWException if isSupportedFormat( $format ) is not true. Convenient
346 * for checking whether a format provided as a parameter is actually supported.
348 * @param $format the serialization format to check
350 protected function checkFormat( $format ) {
351 if ( !$this->isSupportedFormat( $format ) ) {
352 throw new MWException( "Format $format is not supported for content model " . $this->getModelName() );
357 * Returns overrides for action handlers.
358 * Classes listed here will be used instead of the default one when
359 * (and only when) $wgActions[$action] === true. This allows subclasses
360 * to override the default actiuon handlers.
364 public function getActionOverrides() {
369 * Return an Article object suitable for viewing the given object
371 * NOTE: does *not* do special handling for Image and Category pages!
372 * Use Article::newFromTitle() for that!
374 * @param Title $title
376 * @todo Article is being refactored into an action class, keep track of that
377 * @todo Article really defines the view of the content... rename this method to createViewPage ?
379 public function createArticle( Title
$title ) {
380 $this->checkModelName( $title->getContentModelName() );
382 $article = new Article($title);
387 * Return an EditPage object suitable for editing the given object
389 * @param Article $article
392 public function createEditPage( Article
$article ) {
393 $this->checkModelName( $article->getContentModelName() );
395 $editPage = new EditPage( $article );
400 * Return an ExternalEdit object suitable for editing the given object
402 * @param IContextSource $context
403 * @return ExternalEdit
404 * @todo does anyone or anythign actually use the external edit facility? Can we just deprecate and ignore it?
406 public function createExternalEdit( IContextSource
$context ) {
407 $this->checkModelName( $context->getTitle()->getModelName() );
409 $externalEdit = new ExternalEdit( $context );
410 return $externalEdit;
415 * @param $context IContextSource context to use, anything else will be ignored
416 * @param $old Integer old ID we want to show and diff with.
417 * @param $new String either 'prev' or 'next'.
418 * @param $rcid Integer ??? FIXME (default 0)
419 * @param $refreshCache boolean If set, refreshes the diff cache
420 * @param $unhide boolean If set, allow viewing deleted revs
422 * @return DifferenceEngine
423 * @todo rename to createDifferenceEngine for consistency.
425 public function getDifferenceEngine( IContextSource
$context, $old = 0, $new = 0, $rcid = 0, #FIMXE: use everywhere!
426 $refreshCache = false, $unhide = false ) {
428 $this->checkModelName( $context->getTitle()->getModelName() );
430 $diffEngineClass = $this->getDiffEngineClass();
432 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
436 * Returns the name of the diff engine to use.
442 protected function getDiffEngineClass() {
443 return 'DifferenceEngine';
447 * attempts to merge differences between three versions.
448 * Returns a new Content object for a clean merge and false for failure or a conflict.
450 * This default implementation always returns false.
452 * @param $oldContent String
453 * @param $myContent String
454 * @param $yourContent String
455 * @return Content|Bool
457 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
462 * Return an applicable autosummary if one exists for the given edit.
464 * @param $oldContent Content|null: the previous text of the page.
465 * @param $newContent Content|null: The submitted text of the page.
466 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
468 * @return string An appropriate autosummary, or an empty string.
470 public function getAutosummary( Content
$oldContent = null, Content
$newContent = null, $flags ) {
473 // Decide what kind of autosummary is needed.
475 // Redirect autosummaries
477 $ot = !empty( $ot ) ?
$oldContent->getRedirectTarget() : false;
478 $rt = !empty( $rt ) ?
$newContent->getRedirectTarget() : false;
480 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
482 $truncatedtext = $newContent->getTextForSummary(
484 - strlen( wfMsgForContent( 'autoredircomment' ) )
485 - strlen( $rt->getFullText() ) );
487 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
490 // New page autosummaries
491 if ( $flags & EDIT_NEW
&& $newContent->getSize() > 0 ) {
492 // If they're making a new article, give its text, truncated, in the summary.
494 $truncatedtext = $newContent->getTextForSummary(
495 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) );
497 return wfMsgForContent( 'autosumm-new', $truncatedtext );
500 // Blanking autosummaries
501 if ( $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
502 return wfMsgForContent( 'autosumm-blank' );
503 } elseif ( $oldContent->getSize() > 10 * $newContent->getSize() && $newContent->getSize() < 500 ) {
504 // Removing more than 90% of the article
506 $truncatedtext = $newContent->getTextForSummary(
507 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) );
509 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
512 // If we reach this point, there's no applicable autosummary for our case, so our
513 // autosummary is empty.
519 * Auto-generates a deletion reason
521 * @param $title Title: the page's title
522 * @param &$hasHistory Boolean: whether the page has a history
523 * @return mixed String containing deletion reason or empty string, or boolean false
524 * if no revision occurred
526 * @todo &$hasHistory is extremely ugly, it's here because WikiPage::getAutoDeleteReason() and Article::getReason() have it / want it.
528 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
529 $dbw = wfGetDB( DB_MASTER
);
531 // Get the last revision
532 $rev = Revision
::newFromTitle( $title );
534 if ( is_null( $rev ) ) {
538 // Get the article's contents
539 $content = $rev->getContent();
542 // If the page is blank, use the text from the previous revision,
543 // which can only be blank if there's a move/import/protect dummy revision involved
544 if ( $content->getSize() == 0 ) {
545 $prev = $rev->getPrevious();
548 $content = $rev->getContent();
553 // Find out if there was only one contributor
554 // Only scan the last 20 revisions
555 $res = $dbw->select( 'revision', 'rev_user_text',
556 array( 'rev_page' => $title->getArticleID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
558 array( 'LIMIT' => 20 )
561 if ( $res === false ) {
562 // This page has no revisions, which is very weird
566 $hasHistory = ( $res->numRows() > 1 );
567 $row = $dbw->fetchObject( $res );
569 if ( $row ) { // $row is false if the only contributor is hidden
570 $onlyAuthor = $row->rev_user_text
;
571 // Try to find a second contributor
572 foreach ( $res as $row ) {
573 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
582 // Generate the summary with a '$1' placeholder
584 // The current revision is blank and the one before is also
585 // blank. It's just not our lucky day
586 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
589 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
591 $reason = wfMsgForContent( 'excontent', '$1' );
595 if ( $reason == '-' ) {
596 // Allow these UI messages to be blanked out cleanly
600 // Max content length = max comment length - length of the comment (excl. $1)
601 $text = $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) );
603 // Now replace the '$1' placeholder
604 $reason = str_replace( '$1', $text, $reason );
610 * Get the Content object that needs to be saved in order to undo all revisions
611 * between $undo and $undoafter. Revisions must belong to the same page,
612 * must exist and must not be deleted
613 * @param $undo Revision
614 * @param $undoafter null|Revision Must be an earlier revision than $undo
615 * @return mixed string on success, false on failure
617 public function getUndoContent( Revision
$current, Revision
$undo, Revision
$undoafter = null ) {
618 $cur_content = $current->getContent();
620 if ( empty( $cur_content ) ) {
621 return false; // no page
624 $undo_content = $undo->getContent();
625 $undoafter_content = $undoafter->getContent();
627 if ( $cur_content->equals( $undo_content ) ) {
628 // No use doing a merge if it's just a straight revert.
629 return $undoafter_content;
632 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
634 return $undone_content;
639 abstract class TextContentHandler
extends ContentHandler
{
641 public function __construct( $modelName, $formats ) {
642 parent
::__construct( $modelName, $formats );
645 public function serializeContent( Content
$content, $format = null ) {
646 $this->checkFormat( $format );
647 return $content->getNativeData();
651 * attempts to merge differences between three versions.
652 * Returns a new Content object for a clean merge and false for failure or a conflict.
654 * This text-based implementation uses wfMerge().
656 * @param $oldContent String
657 * @param $myContent String
658 * @param $yourContent String
659 * @return Content|Bool
661 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
662 $this->checkModelName( $oldContent->getModelName() );
663 #TODO: check that all Content objects have the same content model! #XXX: what to do if they don't?
665 $format = $this->getDefaultFormat();
667 $old = $this->serializeContent( $oldContent, $format );
668 $mine = $this->serializeContent( $myContent, $format );
669 $yours = $this->serializeContent( $yourContent, $format );
671 $ok = wfMerge( $old, $mine, $yours, $result );
678 return $this->makeEmptyContent();
681 $mergedContent = $this->unserializeContent( $result, $format );
682 return $mergedContent;
687 class WikitextContentHandler
extends TextContentHandler
{
689 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
690 parent
::__construct( $modelName, array( 'application/x-wikitext' ) ); #FIXME: mime
693 public function unserializeContent( $text, $format = null ) {
694 $this->checkFormat( $format );
696 return new WikitextContent( $text );
699 public function makeEmptyContent() {
700 return new WikitextContent( '' );
706 #TODO: make ScriptContentHandler base class with plugin interface for syntax highlighting!
708 class JavaScriptContentHandler
extends TextContentHandler
{
710 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
711 parent
::__construct( $modelName, array( 'text/javascript' ) ); #XXX: or use $wgJsMimeType? this is for internal storage, not HTTP...
714 public function unserializeContent( $text, $format = null ) {
715 return new JavaScriptContent( $text );
718 public function makeEmptyContent() {
719 return new JavaScriptContent( '' );
723 class CssContentHandler
extends TextContentHandler
{
725 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
726 parent
::__construct( $modelName, array( 'text/css' ) );
729 public function unserializeContent( $text, $format = null ) {
730 return new CssContent( $text );
733 public function makeEmptyContent() {
734 return new CssContent( '' );