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