4 * A content handler knows how do deal with a specific type of content on a wiki page.
5 * Content is stored in the database in a serialized form (using a serialization format aka mime type)
6 * and is be unserialized into it's native PHP represenation (the content model).
8 * Some content types have a flat model, that is, their native represenation is the
9 * same as their serialized form. Examples would be JavaScript and CSS code. As of now,
10 * this also applies to wikitext (mediawiki's default content type), but wikitext
11 * content may be represented by a DOM or AST structure in the future.
14 abstract class ContentHandler
{
16 public static function getContentText( Content
$content = null ) {
17 global $wgContentHandlerTextFallback;
19 if ( !$content ) return '';
21 if ( $content instanceof TextContent
) {
22 return $content->getNativeData();
25 if ( $wgContentHandlerTextFallback == 'fail' ) throw new MWException( "Attempt to get text from Content with model " . $content->getModelName() );
26 if ( $wgContentHandlerTextFallback == 'serialize' ) return $content->serialize();
31 public static function makeContent( $text, Title
$title, $modelName = null, $format = null ) {
33 $modelName = $title->getContentModelName();
36 $handler = ContentHandler
::getForModelName( $modelName );
37 return $handler->unserialize( $text, $format );
40 public static function getDefaultModelFor( Title
$title ) {
41 global $wgNamespaceContentModels;
43 # NOTE: this method must not rely on $title->getContentModelName() directly or indirectly,
44 # because it is used to initialized the mContentModelName memebr.
46 $ns = $title->getNamespace();
52 if ( !empty( $wgNamespaceContentModels[ $ns ] ) ) {
53 $model = $wgNamespaceContentModels[ $ns ];
56 # hook can determin default model
57 if ( !wfRunHooks( 'DefaultModelFor', array( $title, &$model ) ) ) { #FIXME: document new hook!
58 if ( $model ) return $model;
61 # Could this page contain custom CSS or JavaScript, based on the title?
62 $isCssOrJsPage = ( NS_MEDIAWIKI
== $ns && preg_match( "!\.(css|js)$!u", $title->getText(), $m ) );
63 if ( $isCssOrJsPage ) $ext = $m[1];
65 # hook can force js/css
66 wfRunHooks( 'TitleIsCssOrJsPage', array( $title, &$isCssOrJsPage, &$ext ) ); #FIXME: add $ext to hook interface spec
68 # Is this a .css subpage of a user page?
69 $isJsCssSubpage = ( NS_USER
== $ns && !$isCssOrJsPage && preg_match( "/\\/.*\\.(js|css)$/", $title->getText(), $m ) );
70 if ( $isJsCssSubpage ) $ext = $m[1];
72 # is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
73 $isWikitext = ( $model == CONTENT_MODEL_WIKITEXT ||
$model === null );
74 $isWikitext = ( $isWikitext && !$isCssOrJsPage && !$isJsCssSubpage );
76 # hook can override $isWikitext
77 wfRunHooks( 'TitleIsWikitextPage', array( $title, &$isWikitext ) );
82 return CONTENT_MODEL_JAVASCRIPT
;
83 else if ( $ext == 'css' )
84 return CONTENT_MODEL_CSS
;
89 return CONTENT_MODEL_TEXT
;
92 # we established that is must be wikitext
93 return CONTENT_MODEL_WIKITEXT
;
96 public static function getForTitle( Title
$title ) {
97 $modelName = $title->getContentModelName();
98 return ContentHandler
::getForModelName( $modelName );
101 public static function getForContent( Content
$content ) {
102 $modelName = $content->getModelName();
103 return ContentHandler
::getForModelName( $modelName );
108 * @param $modelName String the name of the content model for which to get a handler. Use CONTENT_MODEL_XXX constants.
109 * @return ContentHandler
110 * @throws MWException
112 public static function getForModelName( $modelName ) {
113 global $wgContentHandlers;
115 if ( empty( $wgContentHandlers[$modelName] ) ) {
117 throw new MWException( "No handler for model $modelName registered in \$wgContentHandlers" );
120 if ( is_string( $wgContentHandlers[$modelName] ) ) {
121 $class = $wgContentHandlers[$modelName];
122 $wgContentHandlers[$modelName] = new $class( $modelName );
125 return $wgContentHandlers[$modelName];
128 # ----------------------------------------------------------------------------------------------------------
129 public function __construct( $modelName, $formats ) {
130 $this->mModelName
= $modelName;
131 $this->mSupportedFormats
= $formats;
134 public function getModelName() {
135 # for wikitext: wikitext; in the future: wikiast, wikidom?
136 # for wikidata: wikidata
137 return $this->mModelName
;
141 public function getSupportedFormats() {
142 # for wikitext: "text/x-mediawiki-1", "text/x-mediawiki-2", etc
143 # for wikidata: "application/json", "application/x-php", etc
144 return $this->mSupportedFormats
;
147 public function getDefaultFormat() {
148 return $this->mSupportedFormats
[0];
153 * @param Content $content
154 * @param null $format
157 public abstract function serialize( Content
$content, $format = null );
161 * @param $blob String
162 * @param null $format
165 public abstract function unserialize( $blob, $format = null );
167 public abstract function emptyContent();
170 * Return an Article object suitable for viewing the given object
172 * NOTE: does *not* do special handling for Image and Category pages!
173 * Use Article::newFromTitle() for that!
177 * @todo Article is being refactored into an action class, keep track of that
179 public function createArticle( Title
$title ) {
180 #XXX: assert that $title->getContentModelName() == $this->getModelname()?
181 $article = new Article($title);
186 * Return an EditPage object suitable for editing the given object
188 * @param type $article
191 public function createEditPage( Article
$article ) {
192 #XXX: assert that $article->getContentObject()->getModelName() == $this->getModelname()?
193 $editPage = new EditPage( $article );
198 * Return an ExternalEdit object suitable for editing the given object
200 * @param type $article
201 * @return \ExternalEdit
203 public function createExternalEdit( IContextSource
$context ) {
204 #XXX: assert that $article->getContentObject()->getModelName() == $this->getModelname()?
205 $externalEdit = new ExternalEdit( $context );
206 return $externalEdit;
211 * @param $context IContextSource context to use, anything else will be ignored
212 * @param $old Integer old ID we want to show and diff with.
213 * @param $new String either 'prev' or 'next'.
214 * @param $rcid Integer ??? FIXME (default 0)
215 * @param $refreshCache boolean If set, refreshes the diff cache
216 * @param $unhide boolean If set, allow viewing deleted revs
218 public function getDifferenceEngine( IContextSource
$context, $old = 0, $new = 0, $rcid = 0, #FIMXE: use everywhere!
219 $refreshCache = false, $unhide = false ) {
221 $de = new DifferenceEngine( $context, $old, $new, $rcid, $refreshCache, $unhide );
227 * attempts to merge differences between three versions.
228 * Returns a new Content object for a clean merge and false for failure or a conflict.
230 * This default implementation always returns false.
232 * @param $oldContent String
233 * @param $myContent String
234 * @param $yourContent String
235 * @return Content|Bool
237 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
242 * Return an applicable autosummary if one exists for the given edit.
244 * @param $oldContent Content: the previous text of the page.
245 * @param $newContent Content: The submitted text of the page.
246 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
248 * @return string An appropriate autosummary, or an empty string.
250 public function getAutosummary( Content
$oldContent, Content
$newContent, $flags ) {
253 # Decide what kind of autosummary is needed.
255 # Redirect autosummaries
256 $ot = $oldContent->getRedirectTarget();
257 $rt = $newContent->getRedirectTarget();
259 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
261 $truncatedtext = $newContent->getTextForSummary(
263 - strlen( wfMsgForContent( 'autoredircomment' ) )
264 - strlen( $rt->getFullText() ) );
266 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
269 # New page autosummaries
270 if ( $flags & EDIT_NEW
&& $newContent->getSize() > 0 ) {
271 # If they're making a new article, give its text, truncated, in the summary.
273 $truncatedtext = $newContent->getTextForSummary(
274 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) );
276 return wfMsgForContent( 'autosumm-new', $truncatedtext );
279 # Blanking autosummaries
280 if ( $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
281 return wfMsgForContent( 'autosumm-blank' );
282 } elseif ( $oldContent->getSize() > 10 * $newContent->getSize() && $newContent->getSize() < 500 ) {
283 # Removing more than 90% of the article
285 $truncatedtext = $newContent->getTextForSummary(
286 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) );
288 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
291 # If we reach this point, there's no applicable autosummary for our case, so our
292 # autosummary is empty.
297 * Auto-generates a deletion reason
299 * @param $title Title: the page's title
300 * @param &$hasHistory Boolean: whether the page has a history
301 * @return mixed String containing deletion reason or empty string, or boolean false
302 * if no revision occurred
304 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
308 $dbw = wfGetDB( DB_MASTER
);
310 // Get the last revision
311 $rev = Revision
::newFromTitle( $title );
313 if ( is_null( $rev ) ) {
317 // Get the article's contents
318 $content = $rev->getContent();
321 // If the page is blank, use the text from the previous revision,
322 // which can only be blank if there's a move/import/protect dummy revision involved
323 if ( $content->getSize() == 0 ) {
324 $prev = $rev->getPrevious();
327 $content = $rev->getContent();
332 // Find out if there was only one contributor
333 // Only scan the last 20 revisions
334 $res = $dbw->select( 'revision', 'rev_user_text',
335 array( 'rev_page' => $title->getArticleID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
337 array( 'LIMIT' => 20 )
340 if ( $res === false ) {
341 // This page has no revisions, which is very weird
345 $hasHistory = ( $res->numRows() > 1 );
346 $row = $dbw->fetchObject( $res );
348 if ( $row ) { // $row is false if the only contributor is hidden
349 $onlyAuthor = $row->rev_user_text
;
350 // Try to find a second contributor
351 foreach ( $res as $row ) {
352 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
361 // Generate the summary with a '$1' placeholder
363 // The current revision is blank and the one before is also
364 // blank. It's just not our lucky day
365 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
368 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
370 $reason = wfMsgForContent( 'excontent', '$1' );
374 if ( $reason == '-' ) {
375 // Allow these UI messages to be blanked out cleanly
379 // Max content length = max comment length - length of the comment (excl. $1)
380 $text = $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) );
382 // Now replace the '$1' placeholder
383 $reason = str_replace( '$1', $text, $reason );
386 } catch (MWException
$e) {
387 # if a page is horribly broken, we still want to be able to delete it. so be lenient about errors here.
388 wfDebug("Error while building auto delete summary: $e");
395 * Get the Content object that needs to be saved in order to undo all revisions
396 * between $undo and $undoafter. Revisions must belong to the same page,
397 * must exist and must not be deleted
398 * @param $undo Revision
399 * @param $undoafter null|Revision Must be an earlier revision than $undo
400 * @return mixed string on success, false on failure
402 public function getUndoContent( Revision
$current, Revision
$undo, Revision
$undoafter = null ) {
403 $cur_content = $current->getContent();
405 if ( empty( $cur_content ) ) {
406 return false; // no page
409 $undo_content = $undo->getContent();
410 $undoafter_content = $undoafter->getContent();
412 if ( $cur_content->equals( $undo_content ) ) {
413 # No use doing a merge if it's just a straight revert.
414 return $undoafter_content;
417 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
419 return $undone_content;
422 #TODO: how to handle extra message for JS/CSS previews??
423 #TODO: Article::showCssOrJsPage ---> specialized classes!
425 #XXX: ImagePage and CategoryPage... wrappers that use ContentHandler? or ContentHandler creates wrappers?
429 abstract class TextContentHandler
extends ContentHandler
{
431 public function __construct( $modelName, $formats ) {
432 parent
::__construct( $modelName, $formats );
435 public function serialize( Content
$content, $format = null ) {
436 #FIXME: assert format
437 return $content->getNativeData();
441 * attempts to merge differences between three versions.
442 * Returns a new Content object for a clean merge and false for failure or a conflict.
444 * This text-based implementation uses wfMerge().
446 * @param $oldContent String
447 * @param $myContent String
448 * @param $yourContent String
449 * @return Content|Bool
451 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
452 $format = $this->getDefaultFormat();
454 $old = $this->serialize( $oldContent, $format );
455 $mine = $this->serialize( $myContent, $format );
456 $yours = $this->serialize( $yourContent, $format );
458 $ok = wfMerge( $old, $mine, $yours, $result );
460 if ( !$ok ) return false;
461 if ( !$result ) return $this->emptyContent();
463 $mergedContent = $this->unserialize( $result, $format );
464 return $mergedContent;
469 class WikitextContentHandler
extends TextContentHandler
{
471 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
472 parent
::__construct( $modelName, array( 'application/x-wikitext' ) ); #FIXME: mime
475 public function unserialize( $text, $format = null ) {
476 #FIXME: assert format
477 return new WikitextContent($text);
480 public function emptyContent() {
481 return new WikitextContent("");
487 class JavaScriptContentHandler
extends TextContentHandler
{
489 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
490 parent
::__construct( $modelName, array( 'text/javascript' ) );
493 public function unserialize( $text, $format = null ) {
494 return new JavaScriptContent($text);
497 public function emptyContent() {
498 return new JavaScriptContent("");
502 class CssContentHandler
extends TextContentHandler
{
504 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
505 parent
::__construct( $modelName, array( 'text/css' ) );
508 public function unserialize( $text, $format = null ) {
509 return new CssContent($text);
512 public function emptyContent() {
513 return new CssContent("");