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