minor cleanup in comments in ContentHandler
[lhc/web/wiklou.git] / includes / ContentHandler.php
1 <?php
2
3 /**
4 * Exception representing a failure to serialize or unserialize a content object.
5 */
6 class MWContentSerializationException extends MWException {
7
8 }
9
10 /**
11 * A content handler knows how do deal with a specific type of content on a wiki page.
12 * Content is stored in the database in a serialized form (using a serialization format aka mime type)
13 * and is be unserialized into it's native PHP representation (the content model), which is wrapped in
14 * an instance of the appropriate subclass of Content.
15 *
16 * ContentHandler instances are stateless singletons that serve, among other things, as a factory for
17 * Content objects. Generally, there is one subclass of ContentHandler and one subclass of Content
18 * for every type of content model.
19 *
20 * Some content types have a flat model, that is, their native representation is the
21 * same as their serialized form. Examples would be JavaScript and CSS code. As of now,
22 * this also applies to wikitext (mediawiki's default content type), but wikitext
23 * content may be represented by a DOM or AST structure in the future.
24 *
25 * @since 1.WD
26 */
27 abstract class ContentHandler {
28
29 /**
30 * Convenience function for getting flat text from a Content object. This should only
31 * be used in the context of backwards compatibility with code that is not yet able
32 * to handle Content objects!
33 *
34 * If $content is null, this method returns the empty string.
35 *
36 * If $content is an instance of TextContent, this method returns the flat text as returned by $content->getNativeData().
37 *
38 * If $content is not a TextContent object, the behavior of this method depends on the global $wgContentHandlerTextFallback:
39 * * If $wgContentHandlerTextFallback is 'fail' and $content is not a TextContent object, an MWException is thrown.
40 * * If $wgContentHandlerTextFallback is 'serialize' and $content is not a TextContent object, $content->serialize()
41 * is called to get a string form of the content.
42 * * If $wgContentHandlerTextFallback is 'ignore' and $content is not a TextContent object, this method returns null.
43 * * otherwise, the behaviour is undefined.
44 *
45 * @since WD.1
46 *
47 * @static
48 * @param Content|null $content
49 * @return null|string the textual form of $content, if available
50 * @throws MWException if $content is not an instance of TextContent and $wgContentHandlerTextFallback was set to 'fail'.
51 */
52 public static function getContentText( Content $content = null ) {
53 global $wgContentHandlerTextFallback;
54
55 if ( is_null( $content ) ) {
56 return '';
57 }
58
59 if ( $content instanceof TextContent ) {
60 return $content->getNativeData();
61 }
62
63 if ( $wgContentHandlerTextFallback == 'fail' ) {
64 throw new MWException( "Attempt to get text from Content with model " . $content->getModel() );
65 }
66
67 if ( $wgContentHandlerTextFallback == 'serialize' ) {
68 return $content->serialize();
69 }
70
71 return null;
72 }
73
74 /**
75 * Convenience function for creating a Content object from a given textual representation.
76 *
77 * $text will be deserialized into a Content object of the model specified by $modelId (or,
78 * if that is not given, $title->getContentModel()) using the given format.
79 *
80 * @since WD.1
81 *
82 * @static
83 *
84 * @param string $text the textual representation, will be unserialized to create the Content object
85 * @param null|Title $title the title of the page this text belongs to. Required if $modelId is not provided.
86 * @param null|String $modelId the model to deserialize to. If not provided, $title->getContentModel() is used.
87 * @param null|String $format the format to use for deserialization. If not given, the model's default format is used.
88 *
89 * @return Content a Content object representing $text
90 *
91 * @throw MWException if $model or $format is not supported or if $text can not be unserialized using $format.
92 */
93 public static function makeContent( $text, Title $title = null, $modelId = null, $format = null ) {
94
95 if ( is_null( $modelId ) ) {
96 if ( is_null( $title ) ) {
97 throw new MWException( "Must provide a Title object or a content model ID." );
98 }
99
100 $modelId = $title->getContentModel();
101 }
102
103 $handler = ContentHandler::getForModelID( $modelId );
104 return $handler->unserializeContent( $text, $format );
105 }
106
107 /**
108 * Returns the name of the default content model to be used for the page with the given title.
109 *
110 * Note: There should rarely be need to call this method directly.
111 * To determine the actual content model for a given page, use Title::getContentModel().
112 *
113 * Which model is to be used per default for the page is determined based on several factors:
114 * * The global setting $wgNamespaceContentModels specifies a content model per namespace.
115 * * The hook DefaultModelFor may be used to override the page's default model.
116 * * Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript model if they end in .js or .css, respectively.
117 * * Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
118 * * 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.
119 * * The hook TitleIsWikitextPage may be used to force a page to use the wikitext model.
120 *
121 * If none of the above applies, the wikitext model is used.
122 *
123 * Note: this is used by, and may thus not use, Title::getContentModel()
124 *
125 * @since WD.1
126 *
127 * @static
128 * @param Title $title
129 * @return null|string default model name for the page given by $title
130 */
131 public static function getDefaultModelFor( Title $title ) {
132 global $wgNamespaceContentModels;
133
134 // NOTE: this method must not rely on $title->getContentModel() directly or indirectly,
135 // because it is used to initialized the mContentModel member.
136
137 $ns = $title->getNamespace();
138
139 $ext = false;
140 $m = null;
141 $model = null;
142
143 if ( !empty( $wgNamespaceContentModels[ $ns ] ) ) {
144 $model = $wgNamespaceContentModels[ $ns ];
145 }
146
147 // hook can determin default model
148 if ( !wfRunHooks( 'ContentHandlerDefaultModelFor', array( $title, &$model ) ) ) {
149 if ( !is_null( $model ) ) {
150 return $model;
151 }
152 }
153
154 // Could this page contain custom CSS or JavaScript, based on the title?
155 $isCssOrJsPage = NS_MEDIAWIKI == $ns && preg_match( '!\.(css|js)$!u', $title->getText(), $m );
156 if ( $isCssOrJsPage ) {
157 $ext = $m[1];
158 }
159
160 // hook can force js/css
161 wfRunHooks( 'TitleIsCssOrJsPage', array( $title, &$isCssOrJsPage ) );
162
163 // Is this a .css subpage of a user page?
164 $isJsCssSubpage = NS_USER == $ns && !$isCssOrJsPage && preg_match( "/\\/.*\\.(js|css)$/", $title->getText(), $m );
165 if ( $isJsCssSubpage ) {
166 $ext = $m[1];
167 }
168
169 // is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
170 $isWikitext = is_null( $model ) || $model == CONTENT_MODEL_WIKITEXT;
171 $isWikitext = $isWikitext && !$isCssOrJsPage && !$isJsCssSubpage;
172
173 // hook can override $isWikitext
174 wfRunHooks( 'TitleIsWikitextPage', array( $title, &$isWikitext ) );
175
176 if ( !$isWikitext ) {
177 switch ( $ext ) {
178 case 'js':
179 return CONTENT_MODEL_JAVASCRIPT;
180 case 'css':
181 return CONTENT_MODEL_CSS;
182 default:
183 return is_null( $model ) ? CONTENT_MODEL_TEXT : $model;
184 }
185 }
186
187 // we established that is must be wikitext
188
189 return CONTENT_MODEL_WIKITEXT;
190 }
191
192 /**
193 * returns the appropriate ContentHandler singleton for the given title
194 *
195 * @since WD.1
196 *
197 * @static
198 * @param Title $title
199 * @return ContentHandler
200 */
201 public static function getForTitle( Title $title ) {
202 $modelId = $title->getContentModel();
203 return ContentHandler::getForModelID( $modelId );
204 }
205
206 /**
207 * returns the appropriate ContentHandler singleton for the given Content object
208 *
209 * @since WD.1
210 *
211 * @static
212 * @param Content $content
213 * @return ContentHandler
214 */
215 public static function getForContent( Content $content ) {
216 $modelId = $content->getModel();
217 return ContentHandler::getForModelID( $modelId );
218 }
219
220 /**
221 * returns the ContentHandler singleton for the given model id. Use the CONTENT_MODEL_XXX constants to
222 * identify the desired content model.
223 *
224 * ContentHandler singletons are take from the global $wgContentHandlers array. Keys in that array are
225 * model names, the values are either ContentHandler singleton objects, or strings specifying the appropriate
226 * subclass of ContentHandler.
227 *
228 * If a class name in encountered when looking up the singleton for a given model name, the class is
229 * instantiated and the class name is replaced by te resulting singleton in $wgContentHandlers.
230 *
231 * If no ContentHandler is defined for the desired $modelId, the ContentHandler may be provided by the
232 * a ContentHandlerForModelID hook. if no ContentHandler can be determined, an MWException is raised.
233 *
234 * @since WD.1
235 *
236 * @static
237 * @param $modelId int the id of the content model for which to get a handler. Use CONTENT_MODEL_XXX constants.
238 * @return ContentHandler the ContentHandler singleton for handling the model given by $modelId
239 * @throws MWException if no handler is known for $modelId.
240 */
241 public static function getForModelID( $modelId ) {
242 global $wgContentHandlers;
243
244 if ( empty( $wgContentHandlers[$modelId] ) ) {
245 $handler = null;
246
247 wfRunHooks( 'ContentHandlerForModelID', array( $modelId, &$handler ) );
248
249 if ( $handler ) { // NOTE: may be a string or an object, either is fine!
250 $wgContentHandlers[$modelId] = $handler;
251 } else {
252 throw new MWException( "No handler for model #$modelId registered in \$wgContentHandlers" );
253 }
254 }
255
256 if ( is_string( $wgContentHandlers[$modelId] ) ) {
257 $class = $wgContentHandlers[$modelId];
258 $wgContentHandlers[$modelId] = new $class( $modelId );
259 }
260
261 return $wgContentHandlers[$modelId];
262 }
263
264 /**
265 * Returns the appropriate mime type for a given content format,
266 * or null if no mime type is known for this format.
267 *
268 * Mime types can be registered in the global array $wgContentFormatMimeTypes.
269 *
270 * @static
271 * @param int $id the content format id, as given by a CONTENT_FORMAT_XXX constant
272 * or returned by Revision::getContentFormat().
273 *
274 * @return String|null the content format's mime type.
275 */
276 public static function getContentFormatMimeType( $id ) {
277 global $wgContentFormatMimeTypes;
278
279 if ( !isset( $wgContentFormatMimeTypes[ $id ] ) ) {
280 return null;
281 }
282
283 return $wgContentFormatMimeTypes[ $id ];
284 }
285
286 /**
287 * Returns the content format if for a given mime type,
288 * or null if no format id if known for this mime type.
289 *
290 * Mime types can be registered in the global array $wgContentFormatMimeTypes.
291 *
292 * @static
293 * @param String $mime the mime type
294 *
295 * @return int|null the format id, as defined by a CONTENT_FORMAT_XXX constant
296 */
297 public static function getContentFormatID( $mime ) {
298 global $wgContentFormatMimeTypes;
299
300 static $format_ids = null;
301
302 if ( $format_ids === null ) {
303 $format_ids = array_flip( $wgContentFormatMimeTypes );
304 }
305
306 if ( !isset( $format_ids[ $mime ] ) ) {
307 return null;
308 }
309
310 return $format_ids[ $mime ];
311 }
312
313 /**
314 * Returns the localized name for a given content model,
315 * or null of no mime type is known.
316 *
317 * Model names are localized using system messages. Message keys
318 * have the form content-model-$id.
319 *
320 * @static
321 * @param int $id the content model id, as given by a CONTENT_MODEL_XXX constant
322 * or returned by Revision::getContentModel().
323 *
324 * @return String|null the content format's mime type.
325 */
326 public static function getContentModelName( $id ) {
327 $key = "content-model-$id";
328
329 if ( wfEmptyMsg( $key ) ) return null;
330 else return wfMsg( $key );
331 }
332
333 // ----------------------------------------------------------------------------------------------------------
334
335 protected $mModelID;
336 protected $mSupportedFormats;
337
338 /**
339 * Constructor, initializing the ContentHandler instance with it's model id and a list of supported formats.
340 * Values for the parameters are typically provided as literals by subclasses' constructors.
341 *
342 * @param int $modelId (use CONTENT_MODEL_XXX constants).
343 * @param array $formats list for supported serialization formats (typically as MIME types)
344 */
345 public function __construct( $modelId, $formats ) {
346 $this->mModelID = $modelId;
347 $this->mSupportedFormats = $formats;
348 }
349
350
351 /**
352 * Serializes Content object of the type supported by this ContentHandler.
353 *
354 * @since WD.1
355 *
356 * @abstract
357 * @param Content $content the Content object to serialize
358 * @param null $format the desired serialization format
359 * @return String serialized form of the content
360 */
361 public abstract function serializeContent( Content $content, $format = null );
362
363 /**
364 * Unserializes a Content object of the type supported by this ContentHandler.
365 *
366 * @since WD.1
367 *
368 * @abstract
369 * @param $blob String serialized form of the content
370 * @param null $format the format used for serialization
371 * @return Content the Content object created by deserializing $blob
372 */
373 public abstract function unserializeContent( $blob, $format = null );
374
375 /**
376 * Creates an empty Content object of the type supported by this ContentHandler.
377 *
378 * @since WD.1
379 *
380 * @return Content
381 */
382 public abstract function makeEmptyContent();
383
384 /**
385 * Returns the model id that identifies the content model this ContentHandler can handle.
386 * Use with the CONTENT_MODEL_XXX constants.
387 *
388 * @since WD.1
389 *
390 * @return int the model id
391 */
392 public function getModelID() {
393 return $this->mModelID;
394 }
395
396 /**
397 * Throws an MWException if $model_id is not the id of the content model
398 * supported by this ContentHandler.
399 *
400 * @since WD.1
401 *
402 * @param int $model_id the model to check
403 *
404 * @throws MWException
405 */
406 protected function checkModelID( $model_id ) {
407 if ( $model_id !== $this->mModelID ) {
408 $model_name = ContentHandler::getContentModelName( $model_id );
409 $own_model_name = ContentHandler::getContentModelName( $this->mModelID );
410
411 throw new MWException( "Bad content model: expected {$this->mModelID} ($own_model_name) but got found $model_id ($model_name)." );
412 }
413 }
414
415 /**
416 * Returns a list of serialization formats supported by the serializeContent() and unserializeContent() methods of
417 * this ContentHandler.
418 *
419 * @since WD.1
420 *
421 * @return array of serialization formats as MIME type like strings
422 */
423 public function getSupportedFormats() {
424 return $this->mSupportedFormats;
425 }
426
427 /**
428 * The format used for serialization/deserialization per default by this ContentHandler.
429 *
430 * This default implementation will return the first element of the array of formats
431 * that was passed to the constructor.
432 *
433 * @since WD.1
434 *
435 * @return String the name of the default serialization format as a MIME type
436 */
437 public function getDefaultFormat() {
438 return $this->mSupportedFormats[0];
439 }
440
441 /**
442 * Returns true if $format is a serialization format supported by this ContentHandler,
443 * and false otherwise.
444 *
445 * Note that if $format is null, this method always returns true, because null
446 * means "use the default format".
447 *
448 * @since WD.1
449 *
450 * @param String $format the serialization format to check
451 * @return bool
452 */
453 public function isSupportedFormat( $format ) {
454
455 if ( !$format ) {
456 return true; // this means "use the default"
457 }
458
459 return in_array( $format, $this->mSupportedFormats );
460 }
461
462 /**
463 * Throws an MWException if isSupportedFormat( $format ) is not true. Convenient
464 * for checking whether a format provided as a parameter is actually supported.
465 *
466 * @param String $format the serialization format to check
467 *
468 * @throws MWException
469 */
470 protected function checkFormat( $format ) {
471 if ( !$this->isSupportedFormat( $format ) ) {
472 throw new MWException( "Format $format is not supported for content model " . $this->getModelID() );
473 }
474 }
475
476 /**
477 * Returns if the content is consistent with the database, that is if saving it to the database would not violate any
478 * global constraints.
479 *
480 * Content needs to be valid using this method before it can be saved.
481 *
482 * This default implementation always returns true.
483 *
484 * @since WD.1
485 *
486 * @param \Content $content
487 *
488 * @return boolean
489 */
490 public function isConsistentWithDatabase( Content $content ) {
491 return true;
492 }
493
494 /**
495 * Returns overrides for action handlers.
496 * Classes listed here will be used instead of the default one when
497 * (and only when) $wgActions[$action] === true. This allows subclasses
498 * to override the default action handlers.
499 *
500 * @since WD.1
501 *
502 * @return Array
503 */
504 public function getActionOverrides() {
505 return array();
506 }
507
508 /**
509 * Factory creating an appropriate DifferenceEngine for this content model.
510 *
511 * @since WD.1
512 *
513 * @param $context IContextSource context to use, anything else will be ignored
514 * @param $old Integer old ID we want to show and diff with.
515 * @param int|String $new String either 'prev' or 'next'.
516 * @param $rcid Integer ??? FIXME (default 0)
517 * @param $refreshCache boolean If set, refreshes the diff cache
518 * @param $unhide boolean If set, allow viewing deleted revs
519 *
520 * @return DifferenceEngine
521 */
522 public function createDifferenceEngine( IContextSource $context, $old = 0, $new = 0, $rcid = 0, #FIMXE: use everywhere!
523 $refreshCache = false, $unhide = false ) {
524
525 $this->checkModelID( $context->getTitle()->getContentModel() );
526
527 $diffEngineClass = $this->getDiffEngineClass();
528
529 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
530 }
531
532 /**
533 * Returns the name of the diff engine to use.
534 *
535 * @since WD.1
536 *
537 * @return string
538 */
539 protected function getDiffEngineClass() {
540 return 'DifferenceEngine';
541 }
542
543 /**
544 * attempts to merge differences between three versions.
545 * Returns a new Content object for a clean merge and false for failure or a conflict.
546 *
547 * This default implementation always returns false.
548 *
549 * @since WD.1
550 *
551 * @param Content|String $oldContent String
552 * @param Content|String $myContent String
553 * @param Content|String $yourContent String
554 *
555 * @return Content|Bool
556 */
557 public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
558 return false;
559 }
560
561 /**
562 * Return an applicable auto-summary if one exists for the given edit.
563 *
564 * @since WD.1
565 *
566 * @param $oldContent Content|null: the previous text of the page.
567 * @param $newContent Content|null: The submitted text of the page.
568 * @param $flags Int bit mask: a bit mask of flags submitted for the edit.
569 *
570 * @return string An appropriate auto-summary, or an empty string.
571 */
572 public function getAutosummary( Content $oldContent = null, Content $newContent = null, $flags ) {
573 global $wgContLang;
574
575 // Decide what kind of auto-summary is needed.
576
577 // Redirect auto-summaries
578
579 /**
580 * @var $ot Title
581 * @var $rt Title
582 */
583
584 $ot = !is_null( $oldContent ) ? $oldContent->getRedirectTarget() : null;
585 $rt = !is_null( $newContent ) ? $newContent->getRedirectTarget() : null;
586
587 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
588
589 $truncatedtext = $newContent->getTextForSummary(
590 250
591 - strlen( wfMsgForContent( 'autoredircomment' ) )
592 - strlen( $rt->getFullText() ) );
593
594 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
595 }
596
597 // New page auto-summaries
598 if ( $flags & EDIT_NEW && $newContent->getSize() > 0 ) {
599 // If they're making a new article, give its text, truncated, in the summary.
600
601 $truncatedtext = $newContent->getTextForSummary(
602 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) );
603
604 return wfMsgForContent( 'autosumm-new', $truncatedtext );
605 }
606
607 // Blanking auto-summaries
608 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
609 return wfMsgForContent( 'autosumm-blank' );
610 } elseif ( !empty( $oldContent ) && $oldContent->getSize() > 10 * $newContent->getSize() && $newContent->getSize() < 500 ) {
611 // Removing more than 90% of the article
612
613 $truncatedtext = $newContent->getTextForSummary(
614 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) );
615
616 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
617 }
618
619 // If we reach this point, there's no applicable auto-summary for our case, so our
620 // auto-summary is empty.
621
622 return '';
623 }
624
625 /**
626 * Auto-generates a deletion reason
627 *
628 * @since WD.1
629 *
630 * @param $title Title: the page's title
631 * @param &$hasHistory Boolean: whether the page has a history
632 * @return mixed String containing deletion reason or empty string, or boolean false
633 * if no revision occurred
634 *
635 * @XXX &$hasHistory is extremely ugly, it's here because WikiPage::getAutoDeleteReason() and Article::getReason() have it / want it.
636 */
637 public function getAutoDeleteReason( Title $title, &$hasHistory ) {
638 $dbw = wfGetDB( DB_MASTER );
639
640 // Get the last revision
641 $rev = Revision::newFromTitle( $title );
642
643 if ( is_null( $rev ) ) {
644 return false;
645 }
646
647 // Get the article's contents
648 $content = $rev->getContent();
649 $blank = false;
650
651 $this->checkModelID( $content->getModel() );
652
653 // If the page is blank, use the text from the previous revision,
654 // which can only be blank if there's a move/import/protect dummy revision involved
655 if ( $content->getSize() == 0 ) {
656 $prev = $rev->getPrevious();
657
658 if ( $prev ) {
659 $content = $prev->getContent();
660 $blank = true;
661 }
662 }
663
664 // Find out if there was only one contributor
665 // Only scan the last 20 revisions
666 $res = $dbw->select( 'revision', 'rev_user_text',
667 array( 'rev_page' => $title->getArticleID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
668 __METHOD__,
669 array( 'LIMIT' => 20 )
670 );
671
672 if ( $res === false ) {
673 // This page has no revisions, which is very weird
674 return false;
675 }
676
677 $hasHistory = ( $res->numRows() > 1 );
678 $row = $dbw->fetchObject( $res );
679
680 if ( $row ) { // $row is false if the only contributor is hidden
681 $onlyAuthor = $row->rev_user_text;
682 // Try to find a second contributor
683 foreach ( $res as $row ) {
684 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
685 $onlyAuthor = false;
686 break;
687 }
688 }
689 } else {
690 $onlyAuthor = false;
691 }
692
693 // Generate the summary with a '$1' placeholder
694 if ( $blank ) {
695 // The current revision is blank and the one before is also
696 // blank. It's just not our lucky day
697 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
698 } else {
699 if ( $onlyAuthor ) {
700 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
701 } else {
702 $reason = wfMsgForContent( 'excontent', '$1' );
703 }
704 }
705
706 if ( $reason == '-' ) {
707 // Allow these UI messages to be blanked out cleanly
708 return '';
709 }
710
711 // Max content length = max comment length - length of the comment (excl. $1)
712 $text = $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) );
713
714 // Now replace the '$1' placeholder
715 $reason = str_replace( '$1', $text, $reason );
716
717 return $reason;
718 }
719
720 /**
721 * Parse the Content object and generate a ParserObject from the result. $result->getText() can
722 * be used to obtain the generated HTML. If no HTML is needed, $generateHtml can be set to false;
723 * in that case, $result->getText() may return null.
724 *
725 * @param Content $content the content to render
726 * @param Title $title the page title to use as a context for rendering
727 * @param null|int $revId the revision being rendered (optional)
728 * @param null|ParserOptions $options any parser options
729 * @param Boolean $generateHtml whether to generate Html (default: true). If false,
730 * the result of calling getText() on the ParserOutput object returned by
731 * this method is undefined.
732 *
733 * @since WD.1
734 *
735 * @return ParserOutput
736 */
737 public abstract function getParserOutput( Content $content, Title $title, $revId = null, ParserOptions $options = null, $generateHtml = true );
738 #TODO: make RenderOutput and RenderOptions base classes
739
740 /**
741 * Returns a list of DataUpdate objects for recording information about this Content in some secondary
742 * data store. If the optional second argument, $old, is given, the updates may model only the changes that
743 * need to be made to replace information about the old content with information about the new content.
744 *
745 * This default implementation calls $this->getParserOutput( $content, $title, null, null, false ), and then
746 * calls getSecondaryDataUpdates( $title, $recursive ) on the resulting ParserOutput object.
747 *
748 * Subclasses may implement this to determine the necessary updates more efficiently, or make use of information
749 * about the old content.
750 *
751 * @param Content $content the content for determining the necessary updates
752 * @param Title $title the context for determining the necessary updates
753 * @param Content|null $old an optional Content object representing the previous content, i.e. the content being
754 * replaced by this Content object.
755 * @param boolean $recursive whether to include recursive updates (default: false).
756 * @param ParserOutput|null $parserOutput optional ParserOutput object. Provide if you have one handy, to avoid re-parsing
757 * of the content.
758 *
759 * @return Array. A list of DataUpdate objects for putting information about this content object somewhere.
760 *
761 * @since WD.1
762 */
763 public function getSecondaryDataUpdates( Content $content, Title $title, Content $old = null,
764 $recursive = true, ParserOutput $parserOutput = null ) {
765
766 if ( !$parserOutput ) {
767 $parserOutput = $this->getParserOutput( $content, $title, null, null, false );
768 }
769
770 return $parserOutput->getSecondaryDataUpdates( $title, $recursive );
771 }
772
773
774 /**
775 * Get the Content object that needs to be saved in order to undo all revisions
776 * between $undo and $undoafter. Revisions must belong to the same page,
777 * must exist and must not be deleted
778 *
779 * @since WD.1
780 *
781 * @param $current Revision the current text
782 * @param $undo Revision the revision to undo
783 * @param $undoafter Revision Must be an earlier revision than $undo
784 *
785 * @return mixed string on success, false on failure
786 */
787 public function getUndoContent( Revision $current, Revision $undo, Revision $undoafter ) {
788 $cur_content = $current->getContent();
789
790 if ( empty( $cur_content ) ) {
791 return false; // no page
792 }
793
794 $undo_content = $undo->getContent();
795 $undoafter_content = $undoafter->getContent();
796
797 $this->checkModelID( $cur_content->getModel() );
798 $this->checkModelID( $undo_content->getModel() );
799 $this->checkModelID( $undoafter_content->getModel() );
800
801 if ( $cur_content->equals( $undo_content ) ) {
802 // No use doing a merge if it's just a straight revert.
803 return $undoafter_content;
804 }
805
806 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
807
808 return $undone_content;
809 }
810
811 /**
812 * Returns true for content models that support caching using the ParserCache mechanism.
813 * See WikiPage::isParserCacheUser().
814 *
815 * @since WD.1
816 *
817 * @return bool
818 */
819 public function isParserCacheSupported() {
820 return true;
821 }
822
823 /**
824 * Returns a lost of updates to perform when the given content is deleted.
825 * The necessary updates may be taken from the Content object, or depend on the current state of the database.
826 *
827 * @since WD.1
828 *
829 * @param \Content $content the Content object for deletion
830 * @param \Title $title the title of the deleted page
831 * @param null|\ParserOutput $parserOutput optional parser output object for efficient access to meta-information
832 * about the content object. Provide if you have one handy.
833 *
834 * @return array a list of DataUpdate instances that will clean up the database ofter deletion.
835 */
836 public function getDeletionUpdates( Content $content, Title $title, ParserOutput $parserOutput = null ) {
837 return array(
838 new LinksDeletionUpdate( $title ),
839 );
840 }
841
842 /**
843 * Returns true iff this content model supports sections.
844 *
845 * This default implementation returns false,
846 *
847 * @return boolean whether sections are supported.
848 */
849 public function supportsSections() {
850 return false;
851 }
852 }
853
854 /**
855 * @since WD.1
856 */
857 abstract class TextContentHandler extends ContentHandler {
858
859 public function __construct( $modelId, $formats ) {
860 parent::__construct( $modelId, $formats );
861 }
862
863 /**
864 * Returns the content's text as-is.
865 *
866 * @param Content $content
867 * @param String|null $format
868 * @return mixed
869 */
870 public function serializeContent( Content $content, $format = null ) {
871 $this->checkFormat( $format );
872 return $content->getNativeData();
873 }
874
875 /**
876 * attempts to merge differences between three versions.
877 * Returns a new Content object for a clean merge and false for failure or a conflict.
878 *
879 * All three Content objects passed as parameters must have the same content model.
880 *
881 * This text-based implementation uses wfMerge().
882 *
883 * @param \Content|String $oldContent String
884 * @param \Content|String $myContent String
885 * @param \Content|String $yourContent String
886 *
887 * @return Content|Bool
888 */
889 public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
890 $this->checkModelID( $oldContent->getModel() );
891 $this->checkModelID( $myContent->getModel() );
892 $this->checkModelID( $yourContent->getModel() );
893
894 $format = $this->getDefaultFormat();
895
896 $old = $this->serializeContent( $oldContent, $format );
897 $mine = $this->serializeContent( $myContent, $format );
898 $yours = $this->serializeContent( $yourContent, $format );
899
900 $ok = wfMerge( $old, $mine, $yours, $result );
901
902 if ( !$ok ) {
903 return false;
904 }
905
906 if ( !$result ) {
907 return $this->makeEmptyContent();
908 }
909
910 $mergedContent = $this->unserializeContent( $result, $format );
911 return $mergedContent;
912 }
913
914 /**
915 * Returns a generic ParserOutput object, wrapping the HTML returned by getHtml().
916 *
917 * @param Content $content the content to render
918 * @param Title $title context title for parsing
919 * @param int|null $revId revision id (the parser wants that for some reason)
920 * @param ParserOptions|null $options parser options
921 * @param bool $generateHtml whether or not to generate HTML
922 *
923 * @return ParserOutput representing the HTML form of the text
924 */
925 public function getParserOutput( Content $content, Title $title, $revId = null, ParserOptions $options = null, $generateHtml = true ) {
926 $this->checkModelID( $content->getModel() );
927
928 # generic implementation, relying on $this->getHtml()
929
930 if ( $generateHtml ) $html = $this->getHtml( $content );
931 else $html = '';
932
933 $po = new ParserOutput( $html );
934 return $po;
935 }
936
937 /**
938 * Generates an HTML version of the content, for display.
939 * Used by getParserOutput() to construct a ParserOutput object.
940 *
941 * This default implementation just calls getHighlightHtml(). Content models that
942 * have another mapping to HTML (as is the case for markup languages like wikitext)
943 * should override this method to generate the appropriate html.
944 *
945 * @param Content $content the content to render
946 *
947 * @return String an HTML representation of the content
948 */
949 protected function getHtml( Content $content ) {
950 $this->checkModelID( $content->getModel() );
951
952 return $this->getHighlightHtml( $content );
953 }
954
955 /**
956 * Generates a syntax-highlighted version the content, as HTML.
957 * Used by the default implementation if getHtml().
958 *
959 * @param Content $content the content to render
960 *
961 * @return String an HTML representation of the content's markup
962 */
963 protected function getHighlightHtml( Content $content ) {
964 $this->checkModelID( $content->getModel() );
965
966 #TODO: make Highlighter interface, use here highlighter, if available
967 return htmlspecialchars( $content->getNativeData() );
968 }
969
970
971 }
972
973 /**
974 * @since WD.1
975 */
976 class WikitextContentHandler extends TextContentHandler {
977
978 public function __construct( $modelId = CONTENT_MODEL_WIKITEXT ) {
979 parent::__construct( $modelId, array( CONTENT_FORMAT_WIKITEXT ) );
980 }
981
982 public function unserializeContent( $text, $format = null ) {
983 $this->checkFormat( $format );
984
985 return new WikitextContent( $text );
986 }
987
988 public function makeEmptyContent() {
989 return new WikitextContent( '' );
990 }
991
992 /**
993 * Returns a ParserOutput object resulting from parsing the content's text using $wgParser.
994 *
995 * @since WD.1
996 *
997 * @param Content $content the content to render
998 * @param \Title $title
999 * @param null $revId
1000 * @param null|ParserOptions $options
1001 * @param bool $generateHtml
1002 *
1003 * @internal param \IContextSource|null $context
1004 * @return ParserOutput representing the HTML form of the text
1005 */
1006 public function getParserOutput( Content $content, Title $title, $revId = null, ParserOptions $options = null, $generateHtml = true ) {
1007 global $wgParser;
1008
1009 $this->checkModelID( $content->getModel() );
1010
1011 if ( !$options ) {
1012 $options = new ParserOptions();
1013 }
1014
1015 $po = $wgParser->parse( $content->getNativeData(), $title, $options, true, true, $revId );
1016 return $po;
1017 }
1018
1019 protected function getHtml( Content $content ) {
1020 throw new MWException( "getHtml() not implemented for wikitext. Use getParserOutput()->getText()." );
1021 }
1022
1023 /**
1024 * Returns true because wikitext supports sections.
1025 *
1026 * @return boolean whether sections are supported.
1027 */
1028 public function supportsSections() {
1029 return true;
1030 }
1031 }
1032
1033 #XXX: make ScriptContentHandler base class, do highlighting stuff there?
1034
1035 /**
1036 * @since WD.1
1037 */
1038 class JavaScriptContentHandler extends TextContentHandler {
1039
1040 public function __construct( $modelId = CONTENT_MODEL_JAVASCRIPT ) {
1041 parent::__construct( $modelId, array( CONTENT_FORMAT_JAVASCRIPT ) );
1042 }
1043
1044 public function unserializeContent( $text, $format = null ) {
1045 $this->checkFormat( $format );
1046
1047 return new JavaScriptContent( $text );
1048 }
1049
1050 public function makeEmptyContent() {
1051 return new JavaScriptContent( '' );
1052 }
1053
1054 protected function getHtml( Content $content ) {
1055 $html = "";
1056 $html .= "<pre class=\"mw-code mw-js\" dir=\"ltr\">\n";
1057 $html .= $this->getHighlightHtml( $content );
1058 $html .= "\n</pre>\n";
1059
1060 return $html;
1061 }
1062 }
1063
1064 /**
1065 * @since WD.1
1066 */
1067 class CssContentHandler extends TextContentHandler {
1068
1069 public function __construct( $modelId = CONTENT_MODEL_CSS ) {
1070 parent::__construct( $modelId, array( CONTENT_FORMAT_CSS ) );
1071 }
1072
1073 public function unserializeContent( $text, $format = null ) {
1074 $this->checkFormat( $format );
1075
1076 return new CssContent( $text );
1077 }
1078
1079 public function makeEmptyContent() {
1080 return new CssContent( '' );
1081 }
1082
1083
1084 protected function getHtml( Content $content ) {
1085 $html = "";
1086 $html .= "<pre class=\"mw-code mw-css\" dir=\"ltr\">\n";
1087 $html .= $this->getHighlightHtml( $content );
1088 $html .= "\n</pre>\n";
1089
1090 return $html;
1091 }
1092 }