7bf33c5d9977178c0fcab40b72c521430fd83e0e
[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 int 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 appropriate MIME type for a given content format,
315 * or null if no MIME type is known for this format.
316 *
317 * MIME types can be registered in the global array $wgContentFormatMimeTypes.
318 *
319 * @static
320 * @param $id int The content format id, as given by a CONTENT_FORMAT_XXX
321 * constant or returned by Revision::getContentFormat().
322 *
323 * @return string|null The content format's MIME type.
324 */
325 public static function getContentFormatMimeType( $id ) {
326 global $wgContentFormatMimeTypes;
327
328 if ( !isset( $wgContentFormatMimeTypes[ $id ] ) ) {
329 return null;
330 }
331
332 return $wgContentFormatMimeTypes[ $id ];
333 }
334
335 /**
336 * Returns the content format if for a given MIME type,
337 * or null if no format ID if known for this MIME type.
338 *
339 * Mime types can be registered in the global array $wgContentFormatMimeTypes.
340 *
341 * @static
342 * @param $mime string the MIME type
343 *
344 * @return int|null The format ID, as defined by a CONTENT_FORMAT_XXX constant
345 */
346 public static function getContentFormatID( $mime ) {
347 global $wgContentFormatMimeTypes;
348
349 static $format_ids = null;
350
351 if ( $format_ids === null ) {
352 $format_ids = array_flip( $wgContentFormatMimeTypes );
353 }
354
355 if ( !isset( $format_ids[ $mime ] ) ) {
356 return null;
357 }
358
359 return $format_ids[ $mime ];
360 }
361
362 /**
363 * Returns the symbolic name for a given content model.
364 *
365 * @param $id int The content model ID, as given by a CONTENT_MODEL_XXX
366 * constant or returned by Revision::getContentModel().
367 *
368 * @return string The content model's symbolic name.
369 * @throws MWException if the model id isn't known.
370 */
371 public static function getContentModelName( $id ) {
372 $handler = self::getForModelID( $id );
373 return $handler->getModelName();
374 }
375
376
377 /**
378 * Returns the localized name for a given content model.
379 *
380 * Model names are localized using system messages. Message keys
381 * have the form content-model-$name, where $name is getContentModelName( $id ).
382 *
383 * @static
384 * @param $id int The content model ID, as given by a CONTENT_MODEL_XXX
385 * constant or returned by Revision::getContentModel().
386 * @todo also accept a symbolic name instead of a numeric id
387 *
388 * @return string The content format's localized name.
389 * @throws MWException if the model id isn't known.
390 */
391 public static function getLocalizedName( $id ) {
392 $name = self::getContentModelName( $id );
393 $key = "content-model-$name";
394
395 if ( wfEmptyMsg( $key ) ) return $name;
396 else return wfMsg( $key );
397 }
398
399 // ------------------------------------------------------------------------
400
401 protected $mModelID;
402 protected $mModelName;
403 protected $mSupportedFormats;
404
405 /**
406 * Constructor, initializing the ContentHandler instance with its model ID
407 * and a list of supported formats. Values for the parameters are typically
408 * provided as literals by subclass's constructors.
409 *
410 * @param $modelId int (use CONTENT_MODEL_XXX constants).
411 * @param $formats array List for supported serialization formats
412 * (typically as MIME types)
413 */
414 public function __construct( $modelId, $formats ) {
415 $this->mModelID = $modelId;
416 $this->mSupportedFormats = $formats;
417
418 $this->mModelName = preg_replace( '/(Content)?Handler$/', '', get_class( $this ) );
419 $this->mModelName = preg_replace( '/[_\\\\]/', '', $this->mModelName );
420 $this->mModelName = strtolower( $this->mModelName );
421 }
422
423 /**
424 * Serializes a Content object of the type supported by this ContentHandler.
425 *
426 * @since WD.1
427 *
428 * @abstract
429 * @param $content Content The Content object to serialize
430 * @param $format null The desired serialization format
431 * @return string Serialized form of the content
432 */
433 public abstract function serializeContent( Content $content, $format = null );
434
435 /**
436 * Unserializes a Content object of the type supported by this ContentHandler.
437 *
438 * @since WD.1
439 *
440 * @abstract
441 * @param $blob string serialized form of the content
442 * @param $format null the format used for serialization
443 * @return Content the Content object created by deserializing $blob
444 */
445 public abstract function unserializeContent( $blob, $format = null );
446
447 /**
448 * Creates an empty Content object of the type supported by this
449 * ContentHandler.
450 *
451 * @since WD.1
452 *
453 * @return Content
454 */
455 public abstract function makeEmptyContent();
456
457 /**
458 * Returns the model id that identifies the content model this
459 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
460 *
461 * @since WD.1
462 *
463 * @return int The model ID
464 */
465 public function getModelID() {
466 return $this->mModelID;
467 }
468
469 /**
470 * Returns the content model's symbolic name.
471 *
472 * The symbolic name is is this object's class name in lower case with the trailing "ContentHandler"
473 * and and special characters removed.
474 *
475 * @since WD.1
476 *
477 * @return String The content model's name
478 */
479 public function getModelName() {
480 return $this->mModelName;
481 }
482
483 /**
484 * Throws an MWException if $model_id is not the ID of the content model
485 * supported by this ContentHandler.
486 *
487 * @since WD.1
488 *
489 * @param $model_id int The model to check
490 *
491 * @throws MWException
492 */
493 protected function checkModelID( $model_id ) {
494 if ( $model_id !== $this->mModelID ) {
495 $model_name = ContentHandler::getContentModelName( $model_id );
496 $own_model_name = ContentHandler::getContentModelName( $this->mModelID );
497
498 throw new MWException( "Bad content model: " .
499 "expected {$this->mModelID} ($own_model_name) " .
500 "but got $model_id ($model_name)." );
501 }
502 }
503
504 /**
505 * Returns a list of serialization formats supported by the
506 * serializeContent() and unserializeContent() methods of this
507 * ContentHandler.
508 *
509 * @since WD.1
510 *
511 * @return array of serialization formats as MIME type like strings
512 */
513 public function getSupportedFormats() {
514 return $this->mSupportedFormats;
515 }
516
517 /**
518 * The format used for serialization/deserialization by default by this
519 * ContentHandler.
520 *
521 * This default implementation will return the first element of the array
522 * of formats that was passed to the constructor.
523 *
524 * @since WD.1
525 *
526 * @return string the name of the default serialization format as a MIME type
527 */
528 public function getDefaultFormat() {
529 return $this->mSupportedFormats[0];
530 }
531
532 /**
533 * Returns true if $format is a serialization format supported by this
534 * ContentHandler, and false otherwise.
535 *
536 * Note that if $format is null, this method always returns true, because
537 * null means "use the default format".
538 *
539 * @since WD.1
540 *
541 * @param $format string the serialization format to check
542 * @return bool
543 */
544 public function isSupportedFormat( $format ) {
545
546 if ( !$format ) {
547 return true; // this means "use the default"
548 }
549
550 return in_array( $format, $this->mSupportedFormats );
551 }
552
553 /**
554 * Throws an MWException if isSupportedFormat( $format ) is not true.
555 * Convenient for checking whether a format provided as a parameter is
556 * actually supported.
557 *
558 * @param $format string the serialization format to check
559 *
560 * @throws MWException
561 */
562 protected function checkFormat( $format ) {
563 if ( !$this->isSupportedFormat( $format ) ) {
564 throw new MWException(
565 "Format $format is not supported for content model "
566 . $this->getModelID()
567 );
568 }
569 }
570
571 /**
572 * Returns true if the content is consistent with the database, that is if
573 * saving it to the database would not violate any global constraints.
574 *
575 * Content needs to be valid using this method before it can be saved.
576 *
577 * This default implementation always returns true.
578 *
579 * @since WD.1
580 *
581 * @param $content \Content
582 *
583 * @return boolean
584 */
585 public function isConsistentWithDatabase( Content $content ) {
586 return true;
587 }
588
589 /**
590 * Returns overrides for action handlers.
591 * Classes listed here will be used instead of the default one when
592 * (and only when) $wgActions[$action] === true. This allows subclasses
593 * to override the default action handlers.
594 *
595 * @since WD.1
596 *
597 * @return Array
598 */
599 public function getActionOverrides() {
600 return array();
601 }
602
603 /**
604 * Factory for creating an appropriate DifferenceEngine for this content model.
605 *
606 * @since WD.1
607 *
608 * @param $context IContextSource context to use, anything else will be
609 * ignored
610 * @param $old Integer Old ID we want to show and diff with.
611 * @param $new int|string String either 'prev' or 'next'.
612 * @param $rcid Integer ??? FIXME (default 0)
613 * @param $refreshCache boolean If set, refreshes the diff cache
614 * @param $unhide boolean If set, allow viewing deleted revs
615 *
616 * @return DifferenceEngine
617 */
618 public function createDifferenceEngine( IContextSource $context,
619 $old = 0, $new = 0,
620 $rcid = 0, # FIXME: use everywhere!
621 $refreshCache = false, $unhide = false
622 ) {
623 $this->checkModelID( $context->getTitle()->getContentModel() );
624
625 $diffEngineClass = $this->getDiffEngineClass();
626
627 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
628 }
629
630 /**
631 * Returns the name of the diff engine to use.
632 *
633 * @since WD.1
634 *
635 * @return string
636 */
637 protected function getDiffEngineClass() {
638 return 'DifferenceEngine';
639 }
640
641 /**
642 * Attempts to merge differences between three versions.
643 * Returns a new Content object for a clean merge and false for failure or
644 * a conflict.
645 *
646 * This default implementation always returns false.
647 *
648 * @since WD.1
649 *
650 * @param $oldContent Content|string String
651 * @param $myContent Content|string String
652 * @param $yourContent Content|string String
653 *
654 * @return Content|Bool
655 */
656 public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
657 return false;
658 }
659
660 /**
661 * Return an applicable auto-summary if one exists for the given edit.
662 *
663 * @since WD.1
664 *
665 * @param $oldContent Content|null: the previous text of the page.
666 * @param $newContent Content|null: The submitted text of the page.
667 * @param $flags int Bit mask: a bit mask of flags submitted for the edit.
668 *
669 * @return string An appropriate auto-summary, or an empty string.
670 */
671 public function getAutosummary( Content $oldContent = null, Content $newContent = null, $flags ) {
672 global $wgContLang;
673
674 // Decide what kind of auto-summary is needed.
675
676 // Redirect auto-summaries
677
678 /**
679 * @var $ot Title
680 * @var $rt Title
681 */
682
683 $ot = !is_null( $oldContent ) ? $oldContent->getRedirectTarget() : null;
684 $rt = !is_null( $newContent ) ? $newContent->getRedirectTarget() : null;
685
686 if ( is_object( $rt ) ) {
687 if ( !is_object( $ot )
688 || !$rt->equals( $ot )
689 || $ot->getFragment() != $rt->getFragment() )
690 {
691 $truncatedtext = $newContent->getTextForSummary(
692 250
693 - strlen( wfMsgForContent( 'autoredircomment' ) )
694 - strlen( $rt->getFullText() ) );
695
696 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
697 }
698 }
699
700 // New page auto-summaries
701 if ( $flags & EDIT_NEW && $newContent->getSize() > 0 ) {
702 // If they're making a new article, give its text, truncated, in
703 // the summary.
704
705 $truncatedtext = $newContent->getTextForSummary(
706 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) );
707
708 return wfMsgForContent( 'autosumm-new', $truncatedtext );
709 }
710
711 // Blanking auto-summaries
712 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
713 return wfMsgForContent( 'autosumm-blank' );
714 } elseif ( !empty( $oldContent )
715 && $oldContent->getSize() > 10 * $newContent->getSize()
716 && $newContent->getSize() < 500 )
717 {
718 // Removing more than 90% of the article
719
720 $truncatedtext = $newContent->getTextForSummary(
721 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) );
722
723 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
724 }
725
726 // If we reach this point, there's no applicable auto-summary for our
727 // case, so our auto-summary is empty.
728
729 return '';
730 }
731
732 /**
733 * Auto-generates a deletion reason
734 *
735 * @since WD.1
736 *
737 * @param $title Title: the page's title
738 * @param &$hasHistory Boolean: whether the page has a history
739 * @return mixed String containing deletion reason or empty string, or
740 * boolean false if no revision occurred
741 *
742 * @XXX &$hasHistory is extremely ugly, it's here because
743 * WikiPage::getAutoDeleteReason() and Article::getReason()
744 * have it / want it.
745 */
746 public function getAutoDeleteReason( Title $title, &$hasHistory ) {
747 $dbw = wfGetDB( DB_MASTER );
748
749 // Get the last revision
750 $rev = Revision::newFromTitle( $title );
751
752 if ( is_null( $rev ) ) {
753 return false;
754 }
755
756 // Get the article's contents
757 $content = $rev->getContent();
758 $blank = false;
759
760 $this->checkModelID( $content->getModel() );
761
762 // If the page is blank, use the text from the previous revision,
763 // which can only be blank if there's a move/import/protect dummy
764 // revision involved
765 if ( $content->getSize() == 0 ) {
766 $prev = $rev->getPrevious();
767
768 if ( $prev ) {
769 $content = $prev->getContent();
770 $blank = true;
771 }
772 }
773
774 // Find out if there was only one contributor
775 // Only scan the last 20 revisions
776 $res = $dbw->select( 'revision', 'rev_user_text',
777 array(
778 'rev_page' => $title->getArticleID(),
779 $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0'
780 ),
781 __METHOD__,
782 array( 'LIMIT' => 20 )
783 );
784
785 if ( $res === false ) {
786 // This page has no revisions, which is very weird
787 return false;
788 }
789
790 $hasHistory = ( $res->numRows() > 1 );
791 $row = $dbw->fetchObject( $res );
792
793 if ( $row ) { // $row is false if the only contributor is hidden
794 $onlyAuthor = $row->rev_user_text;
795 // Try to find a second contributor
796 foreach ( $res as $row ) {
797 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
798 $onlyAuthor = false;
799 break;
800 }
801 }
802 } else {
803 $onlyAuthor = false;
804 }
805
806 // Generate the summary with a '$1' placeholder
807 if ( $blank ) {
808 // The current revision is blank and the one before is also
809 // blank. It's just not our lucky day
810 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
811 } else {
812 if ( $onlyAuthor ) {
813 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
814 } else {
815 $reason = wfMsgForContent( 'excontent', '$1' );
816 }
817 }
818
819 if ( $reason == '-' ) {
820 // Allow these UI messages to be blanked out cleanly
821 return '';
822 }
823
824 // Max content length = max comment length - length of the comment (excl. $1)
825 $text = $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) );
826
827 // Now replace the '$1' placeholder
828 $reason = str_replace( '$1', $text, $reason );
829
830 return $reason;
831 }
832
833 /**
834 * Parse the Content object and generate a ParserOutput from the result.
835 * $result->getText() can be used to obtain the generated HTML. If no HTML
836 * is needed, $generateHtml can be set to false; in that case,
837 * $result->getText() may return null.
838 *
839 * @param $content Content the content to render
840 * @param $title Title The page title to use as a context for rendering
841 * @param $revId null|int The revision being rendered (optional)
842 * @param $options null|ParserOptions Any parser options
843 * @param $generateHtml Boolean Whether to generate HTML (default: true). If false,
844 * the result of calling getText() on the ParserOutput object returned by
845 * this method is undefined.
846 *
847 * @since WD.1
848 *
849 * @return ParserOutput
850 */
851 public abstract function getParserOutput( Content $content, Title $title,
852 $revId = null,
853 ParserOptions $options = null, $generateHtml = true );
854 # TODO: make RenderOutput and RenderOptions base classes
855
856 /**
857 * Returns a list of DataUpdate objects for recording information about this
858 * Content in some secondary data store. If the optional second argument,
859 * $old, is given, the updates may model only the changes that need to be
860 * made to replace information about the old content with information about
861 * the new content.
862 *
863 * This default implementation calls
864 * $this->getParserOutput( $content, $title, null, null, false ),
865 * and then calls getSecondaryDataUpdates( $title, $recursive ) on the
866 * resulting ParserOutput object.
867 *
868 * Subclasses may implement this to determine the necessary updates more
869 * efficiently, or make use of information about the old content.
870 *
871 * @param $content Content The content for determining the necessary updates
872 * @param $title Title The context for determining the necessary updates
873 * @param $old Content|null An optional Content object representing the
874 * previous content, i.e. the content being replaced by this Content
875 * object.
876 * @param $recursive boolean Whether to include recursive updates (default:
877 * false).
878 * @param $parserOutput ParserOutput|null Optional ParserOutput object.
879 * Provide if you have one handy, to avoid re-parsing of the content.
880 *
881 * @return Array. A list of DataUpdate objects for putting information
882 * about this content object somewhere.
883 *
884 * @since WD.1
885 */
886 public function getSecondaryDataUpdates( Content $content, Title $title,
887 Content $old = null,
888 $recursive = true, ParserOutput $parserOutput = null
889 ) {
890 if ( !$parserOutput ) {
891 $parserOutput = $this->getParserOutput( $content, $title, null, null, false );
892 }
893
894 return $parserOutput->getSecondaryDataUpdates( $title, $recursive );
895 }
896
897
898 /**
899 * Get the Content object that needs to be saved in order to undo all revisions
900 * between $undo and $undoafter. Revisions must belong to the same page,
901 * must exist and must not be deleted.
902 *
903 * @since WD.1
904 *
905 * @param $current Revision The current text
906 * @param $undo Revision The revision to undo
907 * @param $undoafter Revision Must be an earlier revision than $undo
908 *
909 * @return mixed String on success, false on failure
910 */
911 public function getUndoContent( Revision $current, Revision $undo, Revision $undoafter ) {
912 $cur_content = $current->getContent();
913
914 if ( empty( $cur_content ) ) {
915 return false; // no page
916 }
917
918 $undo_content = $undo->getContent();
919 $undoafter_content = $undoafter->getContent();
920
921 $this->checkModelID( $cur_content->getModel() );
922 $this->checkModelID( $undo_content->getModel() );
923 $this->checkModelID( $undoafter_content->getModel() );
924
925 if ( $cur_content->equals( $undo_content ) ) {
926 // No use doing a merge if it's just a straight revert.
927 return $undoafter_content;
928 }
929
930 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
931
932 return $undone_content;
933 }
934
935 /**
936 * Returns true for content models that support caching using the
937 * ParserCache mechanism. See WikiPage::isParserCacheUser().
938 *
939 * @since WD.1
940 *
941 * @return bool
942 */
943 public function isParserCacheSupported() {
944 return true;
945 }
946
947 /**
948 * Returns a list of updates to perform when the given content is deleted.
949 * The necessary updates may be taken from the Content object, or depend on
950 * the current state of the database.
951 *
952 * @since WD.1
953 *
954 * @param $content \Content the Content object for deletion
955 * @param $title \Title the title of the deleted page
956 * @param $parserOutput null|\ParserOutput optional parser output object
957 * for efficient access to meta-information about the content object.
958 * Provide if you have one handy.
959 *
960 * @return array A list of DataUpdate instances that will clean up the
961 * database after deletion.
962 */
963 public function getDeletionUpdates( Content $content, Title $title,
964 ParserOutput $parserOutput = null )
965 {
966 return array(
967 new LinksDeletionUpdate( $title ),
968 );
969 }
970
971 /**
972 * Returns true if this content model supports sections.
973 *
974 * This default implementation returns false.
975 *
976 * @return boolean whether sections are supported.
977 */
978 public function supportsSections() {
979 return false;
980 }
981 }
982
983 /**
984 * @since WD.1
985 */
986 abstract class TextContentHandler extends ContentHandler {
987
988 public function __construct( $modelId, $formats ) {
989 parent::__construct( $modelId, $formats );
990 }
991
992 /**
993 * Returns the content's text as-is.
994 *
995 * @param $content Content
996 * @param $format string|null
997 * @return mixed
998 */
999 public function serializeContent( Content $content, $format = null ) {
1000 $this->checkFormat( $format );
1001 return $content->getNativeData();
1002 }
1003
1004 /**
1005 * Attempts to merge differences between three versions. Returns a new
1006 * Content object for a clean merge and false for failure or a conflict.
1007 *
1008 * All three Content objects passed as parameters must have the same
1009 * content model.
1010 *
1011 * This text-based implementation uses wfMerge().
1012 *
1013 * @param $oldContent \Content|string String
1014 * @param $myContent \Content|string String
1015 * @param $yourContent \Content|string String
1016 *
1017 * @return Content|Bool
1018 */
1019 public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
1020 $this->checkModelID( $oldContent->getModel() );
1021 $this->checkModelID( $myContent->getModel() );
1022 $this->checkModelID( $yourContent->getModel() );
1023
1024 $format = $this->getDefaultFormat();
1025
1026 $old = $this->serializeContent( $oldContent, $format );
1027 $mine = $this->serializeContent( $myContent, $format );
1028 $yours = $this->serializeContent( $yourContent, $format );
1029
1030 $ok = wfMerge( $old, $mine, $yours, $result );
1031
1032 if ( !$ok ) {
1033 return false;
1034 }
1035
1036 if ( !$result ) {
1037 return $this->makeEmptyContent();
1038 }
1039
1040 $mergedContent = $this->unserializeContent( $result, $format );
1041 return $mergedContent;
1042 }
1043
1044 /**
1045 * Returns a generic ParserOutput object, wrapping the HTML returned by
1046 * getHtml().
1047 *
1048 * @param $content Content The content to render
1049 * @param $title Title Context title for parsing
1050 * @param $revId int|null Revision ID (for {{REVISIONID}})
1051 * @param $options ParserOptions|null Parser options
1052 * @param $generateHtml bool Whether or not to generate HTML
1053 *
1054 * @return ParserOutput representing the HTML form of the text
1055 */
1056 public function getParserOutput( Content $content, Title $title,
1057 $revId = null,
1058 ParserOptions $options = null, $generateHtml = true
1059 ) {
1060 $this->checkModelID( $content->getModel() );
1061
1062 # Generic implementation, relying on $this->getHtml()
1063
1064 if ( $generateHtml ) {
1065 $html = $this->getHtml( $content );
1066 } else {
1067 $html = '';
1068 }
1069
1070 $po = new ParserOutput( $html );
1071 return $po;
1072 }
1073
1074 /**
1075 * Generates an HTML version of the content, for display. Used by
1076 * getParserOutput() to construct a ParserOutput object.
1077 *
1078 * This default implementation just calls getHighlightHtml(). Content
1079 * models that have another mapping to HTML (as is the case for markup
1080 * languages like wikitext) should override this method to generate the
1081 * appropriate HTML.
1082 *
1083 * @param $content Content The content to render
1084 *
1085 * @return string An HTML representation of the content
1086 */
1087 protected function getHtml( Content $content ) {
1088 $this->checkModelID( $content->getModel() );
1089
1090 return $this->getHighlightHtml( $content );
1091 }
1092
1093 /**
1094 * Generates a syntax-highlighted version the content, as HTML.
1095 * Used by the default implementation of getHtml().
1096 *
1097 * @param $content Content the content to render
1098 *
1099 * @return string an HTML representation of the content's markup
1100 */
1101 protected function getHighlightHtml( Content $content ) {
1102 $this->checkModelID( $content->getModel() );
1103
1104 # TODO: make Highlighter interface, use highlighter here, if available
1105 return htmlspecialchars( $content->getNativeData() );
1106 }
1107
1108
1109 }
1110
1111 /**
1112 * @since WD.1
1113 */
1114 class WikitextContentHandler extends TextContentHandler {
1115
1116 public function __construct( $modelId = CONTENT_MODEL_WIKITEXT ) {
1117 parent::__construct( $modelId, array( CONTENT_FORMAT_WIKITEXT ) );
1118 }
1119
1120 public function unserializeContent( $text, $format = null ) {
1121 $this->checkFormat( $format );
1122
1123 return new WikitextContent( $text );
1124 }
1125
1126 public function makeEmptyContent() {
1127 return new WikitextContent( '' );
1128 }
1129
1130 /**
1131 * Returns a ParserOutput object resulting from parsing the content's text
1132 * using $wgParser.
1133 *
1134 * @since WD.1
1135 *
1136 * @param $content Content the content to render
1137 * @param $title \Title
1138 * @param $revId null
1139 * @param $options null|ParserOptions
1140 * @param $generateHtml bool
1141 *
1142 * @internal param \IContextSource|null $context
1143 * @return ParserOutput representing the HTML form of the text
1144 */
1145 public function getParserOutput( Content $content, Title $title,
1146 $revId = null,
1147 ParserOptions $options = null, $generateHtml = true
1148 ) {
1149 global $wgParser;
1150
1151 $this->checkModelID( $content->getModel() );
1152
1153 if ( !$options ) {
1154 $options = new ParserOptions();
1155 }
1156
1157 $po = $wgParser->parse( $content->getNativeData(), $title, $options, true, true, $revId );
1158 return $po;
1159 }
1160
1161 protected function getHtml( Content $content ) {
1162 throw new MWException(
1163 "getHtml() not implemented for wikitext. "
1164 . "Use getParserOutput()->getText()."
1165 );
1166 }
1167
1168 /**
1169 * Returns true because wikitext supports sections.
1170 *
1171 * @return boolean whether sections are supported.
1172 */
1173 public function supportsSections() {
1174 return true;
1175 }
1176 }
1177
1178 # XXX: make ScriptContentHandler base class, do highlighting stuff there?
1179
1180 /**
1181 * @since WD.1
1182 */
1183 class JavaScriptContentHandler extends TextContentHandler {
1184
1185 public function __construct( $modelId = CONTENT_MODEL_JAVASCRIPT ) {
1186 parent::__construct( $modelId, array( CONTENT_FORMAT_JAVASCRIPT ) );
1187 }
1188
1189 public function unserializeContent( $text, $format = null ) {
1190 $this->checkFormat( $format );
1191
1192 return new JavaScriptContent( $text );
1193 }
1194
1195 public function makeEmptyContent() {
1196 return new JavaScriptContent( '' );
1197 }
1198
1199 protected function getHtml( Content $content ) {
1200 $html = "";
1201 $html .= "<pre class=\"mw-code mw-js\" dir=\"ltr\">\n";
1202 $html .= $this->getHighlightHtml( $content );
1203 $html .= "\n</pre>\n";
1204
1205 return $html;
1206 }
1207 }
1208
1209 /**
1210 * @since WD.1
1211 */
1212 class CssContentHandler extends TextContentHandler {
1213
1214 public function __construct( $modelId = CONTENT_MODEL_CSS ) {
1215 parent::__construct( $modelId, array( CONTENT_FORMAT_CSS ) );
1216 }
1217
1218 public function unserializeContent( $text, $format = null ) {
1219 $this->checkFormat( $format );
1220
1221 return new CssContent( $text );
1222 }
1223
1224 public function makeEmptyContent() {
1225 return new CssContent( '' );
1226 }
1227
1228
1229 protected function getHtml( Content $content ) {
1230 $html = "";
1231 $html .= "<pre class=\"mw-code mw-css\" dir=\"ltr\">\n";
1232 $html .= $this->getHighlightHtml( $content );
1233 $html .= "\n</pre>\n";
1234
1235 return $html;
1236 }
1237 }