merge latest master.
[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 returns $wgContLang->getCode().
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.
556 *
557 * Also note that the page language may or may not depend on the actual content of the page,
558 * that is, this method may load the content in order to determine the language.
559 *
560 * @since 1.WD
561 *
562 * @param Title $title the page to determine the language for.
563 * @param Content|null $content the page's content, if you have it handy, to avoid reloading it.
564 *
565 * @return Language the page's language code
566 */
567 public function getPageLanguage( Title $title, Content $content = null ) {
568 global $wgContLang;
569 return $wgContLang;
570 }
571
572 /**
573 * Returns the name of the diff engine to use.
574 *
575 * @since WD.1
576 *
577 * @return string
578 */
579 protected function getDiffEngineClass() {
580 return 'DifferenceEngine';
581 }
582
583 /**
584 * Attempts to merge differences between three versions.
585 * Returns a new Content object for a clean merge and false for failure or
586 * a conflict.
587 *
588 * This default implementation always returns false.
589 *
590 * @since WD.1
591 *
592 * @param $oldContent Content|string String
593 * @param $myContent Content|string String
594 * @param $yourContent Content|string String
595 *
596 * @return Content|Bool
597 */
598 public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
599 return false;
600 }
601
602 /**
603 * Return an applicable auto-summary if one exists for the given edit.
604 *
605 * @since WD.1
606 *
607 * @param $oldContent Content|null: the previous text of the page.
608 * @param $newContent Content|null: The submitted text of the page.
609 * @param $flags int Bit mask: a bit mask of flags submitted for the edit.
610 *
611 * @return string An appropriate auto-summary, or an empty string.
612 */
613 public function getAutosummary( Content $oldContent = null, Content $newContent = null, $flags ) {
614 global $wgContLang;
615
616 // Decide what kind of auto-summary is needed.
617
618 // Redirect auto-summaries
619
620 /**
621 * @var $ot Title
622 * @var $rt Title
623 */
624
625 $ot = !is_null( $oldContent ) ? $oldContent->getRedirectTarget() : null;
626 $rt = !is_null( $newContent ) ? $newContent->getRedirectTarget() : null;
627
628 if ( is_object( $rt ) ) {
629 if ( !is_object( $ot )
630 || !$rt->equals( $ot )
631 || $ot->getFragment() != $rt->getFragment() )
632 {
633 $truncatedtext = $newContent->getTextForSummary(
634 250
635 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
636 - strlen( $rt->getFullText() ) );
637
638 return wfMessage( 'autoredircomment', $rt->getFullText() )
639 ->rawParams( $truncatedtext )->inContentLanguage()->text();
640 }
641 }
642
643 // New page auto-summaries
644 if ( $flags & EDIT_NEW && $newContent->getSize() > 0 ) {
645 // If they're making a new article, give its text, truncated, in
646 // the summary.
647
648 $truncatedtext = $newContent->getTextForSummary(
649 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
650
651 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
652 ->inContentLanguage()->text();
653 }
654
655 // Blanking auto-summaries
656 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
657 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
658 } elseif ( !empty( $oldContent )
659 && $oldContent->getSize() > 10 * $newContent->getSize()
660 && $newContent->getSize() < 500 )
661 {
662 // Removing more than 90% of the article
663
664 $truncatedtext = $newContent->getTextForSummary(
665 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
666
667 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
668 ->inContentLanguage()->text();
669 }
670
671 // If we reach this point, there's no applicable auto-summary for our
672 // case, so our auto-summary is empty.
673 return '';
674 }
675
676 /**
677 * Auto-generates a deletion reason
678 *
679 * @since WD.1
680 *
681 * @param $title Title: the page's title
682 * @param &$hasHistory Boolean: whether the page has a history
683 * @return mixed String containing deletion reason or empty string, or
684 * boolean false if no revision occurred
685 *
686 * @XXX &$hasHistory is extremely ugly, it's here because
687 * WikiPage::getAutoDeleteReason() and Article::getReason()
688 * have it / want it.
689 */
690 public function getAutoDeleteReason( Title $title, &$hasHistory ) {
691 $dbw = wfGetDB( DB_MASTER );
692
693 // Get the last revision
694 $rev = Revision::newFromTitle( $title );
695
696 if ( is_null( $rev ) ) {
697 return false;
698 }
699
700 // Get the article's contents
701 $content = $rev->getContent();
702 $blank = false;
703
704 $this->checkModelID( $content->getModel() );
705
706 // If the page is blank, use the text from the previous revision,
707 // which can only be blank if there's a move/import/protect dummy
708 // revision involved
709 if ( $content->getSize() == 0 ) {
710 $prev = $rev->getPrevious();
711
712 if ( $prev ) {
713 $content = $prev->getContent();
714 $blank = true;
715 }
716 }
717
718 // Find out if there was only one contributor
719 // Only scan the last 20 revisions
720 $res = $dbw->select( 'revision', 'rev_user_text',
721 array(
722 'rev_page' => $title->getArticleID(),
723 $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0'
724 ),
725 __METHOD__,
726 array( 'LIMIT' => 20 )
727 );
728
729 if ( $res === false ) {
730 // This page has no revisions, which is very weird
731 return false;
732 }
733
734 $hasHistory = ( $res->numRows() > 1 );
735 $row = $dbw->fetchObject( $res );
736
737 if ( $row ) { // $row is false if the only contributor is hidden
738 $onlyAuthor = $row->rev_user_text;
739 // Try to find a second contributor
740 foreach ( $res as $row ) {
741 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
742 $onlyAuthor = false;
743 break;
744 }
745 }
746 } else {
747 $onlyAuthor = false;
748 }
749
750 // Generate the summary with a '$1' placeholder
751 if ( $blank ) {
752 // The current revision is blank and the one before is also
753 // blank. It's just not our lucky day
754 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
755 } else {
756 if ( $onlyAuthor ) {
757 $reason = wfMessage(
758 'excontentauthor',
759 '$1',
760 $onlyAuthor
761 )->inContentLanguage()->text();
762 } else {
763 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
764 }
765 }
766
767 if ( $reason == '-' ) {
768 // Allow these UI messages to be blanked out cleanly
769 return '';
770 }
771
772 // Max content length = max comment length - length of the comment (excl. $1)
773 $text = $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) );
774
775 // Now replace the '$1' placeholder
776 $reason = str_replace( '$1', $text, $reason );
777
778 return $reason;
779 }
780
781 /**
782 * Get the Content object that needs to be saved in order to undo all revisions
783 * between $undo and $undoafter. Revisions must belong to the same page,
784 * must exist and must not be deleted.
785 *
786 * @since WD.1
787 *
788 * @param $current Revision The current text
789 * @param $undo Revision The revision to undo
790 * @param $undoafter Revision Must be an earlier revision than $undo
791 *
792 * @return mixed String on success, false on failure
793 */
794 public function getUndoContent( Revision $current, Revision $undo, Revision $undoafter ) {
795 $cur_content = $current->getContent();
796
797 if ( empty( $cur_content ) ) {
798 return false; // no page
799 }
800
801 $undo_content = $undo->getContent();
802 $undoafter_content = $undoafter->getContent();
803
804 $this->checkModelID( $cur_content->getModel() );
805 $this->checkModelID( $undo_content->getModel() );
806 $this->checkModelID( $undoafter_content->getModel() );
807
808 if ( $cur_content->equals( $undo_content ) ) {
809 // No use doing a merge if it's just a straight revert.
810 return $undoafter_content;
811 }
812
813 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
814
815 return $undone_content;
816 }
817
818 /**
819 * Returns true for content models that support caching using the
820 * ParserCache mechanism. See WikiPage::isParserCacheUser().
821 *
822 * @since WD.1
823 *
824 * @return bool
825 */
826 public function isParserCacheSupported() {
827 return true;
828 }
829
830 /**
831 * Returns true if this content model supports sections.
832 *
833 * This default implementation returns false.
834 *
835 * @return boolean whether sections are supported.
836 */
837 public function supportsSections() {
838 return false;
839 }
840
841 /**
842 * Call a legacy hook that uses text instead of Content objects.
843 * Will log a warning when a matching hook function is registered.
844 * If the textual representation of the content is changed by the
845 * hook function, a new Content object is constructed from the new
846 * text.
847 *
848 * @param $event String: event name
849 * @param $args Array: parameters passed to hook functions
850 * @param $warn bool: whether to log a warning (default: true). Should generally be true,
851 * may be set to false for testing.
852 *
853 * @return Boolean True if no handler aborted the hook
854 */
855 public static function runLegacyHooks( $event, $args = array(), $warn = true ) {
856 if ( !Hooks::isRegistered( $event ) ) {
857 return true; // nothing to do here
858 }
859
860 if ( $warn ) {
861 wfWarn( "Using obsolete hook $event" );
862 }
863
864 // convert Content objects to text
865 $contentObjects = array();
866 $contentTexts = array();
867
868 foreach ( $args as $k => $v ) {
869 if ( $v instanceof Content ) {
870 /* @var Content $v */
871
872 $contentObjects[$k] = $v;
873
874 $v = $v->serialize();
875 $contentTexts[ $k ] = $v;
876 $args[ $k ] = $v;
877 }
878 }
879
880 // call the hook functions
881 $ok = wfRunHooks( $event, $args );
882
883 // see if the hook changed the text
884 foreach ( $contentTexts as $k => $orig ) {
885 /* @var Content $content */
886
887 $modified = $args[ $k ];
888 $content = $contentObjects[$k];
889
890 if ( $modified !== $orig ) {
891 // text was changed, create updated Content object
892 $content = $content->getContentHandler()->unserializeContent( $modified );
893 }
894
895 $args[ $k ] = $content;
896 }
897
898 return $ok;
899 }
900 }
901
902 /**
903 * @since WD.1
904 */
905 abstract class TextContentHandler extends ContentHandler {
906
907 public function __construct( $modelId, $formats ) {
908 parent::__construct( $modelId, $formats );
909 }
910
911 /**
912 * Returns the content's text as-is.
913 *
914 * @param $content Content
915 * @param $format string|null
916 * @return mixed
917 */
918 public function serializeContent( Content $content, $format = null ) {
919 $this->checkFormat( $format );
920 return $content->getNativeData();
921 }
922
923 /**
924 * Attempts to merge differences between three versions. Returns a new
925 * Content object for a clean merge and false for failure or a conflict.
926 *
927 * All three Content objects passed as parameters must have the same
928 * content model.
929 *
930 * This text-based implementation uses wfMerge().
931 *
932 * @param $oldContent \Content|string String
933 * @param $myContent \Content|string String
934 * @param $yourContent \Content|string String
935 *
936 * @return Content|Bool
937 */
938 public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
939 $this->checkModelID( $oldContent->getModel() );
940 $this->checkModelID( $myContent->getModel() );
941 $this->checkModelID( $yourContent->getModel() );
942
943 $format = $this->getDefaultFormat();
944
945 $old = $this->serializeContent( $oldContent, $format );
946 $mine = $this->serializeContent( $myContent, $format );
947 $yours = $this->serializeContent( $yourContent, $format );
948
949 $ok = wfMerge( $old, $mine, $yours, $result );
950
951 if ( !$ok ) {
952 return false;
953 }
954
955 if ( !$result ) {
956 return $this->makeEmptyContent();
957 }
958
959 $mergedContent = $this->unserializeContent( $result, $format );
960 return $mergedContent;
961 }
962
963 }
964
965 /**
966 * @since WD.1
967 */
968 class WikitextContentHandler extends TextContentHandler {
969
970 public function __construct( $modelId = CONTENT_MODEL_WIKITEXT ) {
971 parent::__construct( $modelId, array( CONTENT_FORMAT_WIKITEXT ) );
972 }
973
974 public function unserializeContent( $text, $format = null ) {
975 $this->checkFormat( $format );
976
977 return new WikitextContent( $text );
978 }
979
980 public function makeEmptyContent() {
981 return new WikitextContent( '' );
982 }
983
984 /**
985 * Returns true because wikitext supports sections.
986 *
987 * @return boolean whether sections are supported.
988 */
989 public function supportsSections() {
990 return true;
991 }
992 }
993
994 # XXX: make ScriptContentHandler base class, do highlighting stuff there?
995
996 /**
997 * @since WD.1
998 */
999 class JavaScriptContentHandler extends TextContentHandler {
1000
1001 public function __construct( $modelId = CONTENT_MODEL_JAVASCRIPT ) {
1002 parent::__construct( $modelId, array( CONTENT_FORMAT_JAVASCRIPT ) );
1003 }
1004
1005 public function unserializeContent( $text, $format = null ) {
1006 $this->checkFormat( $format );
1007
1008 return new JavaScriptContent( $text );
1009 }
1010
1011 public function makeEmptyContent() {
1012 return new JavaScriptContent( '' );
1013 }
1014
1015 /**
1016 * Returns the english language, because JS is english, and should be handled as such.
1017 *
1018 * @return Language wfGetLangObj( 'en' )
1019 *
1020 * @see ContentHandler::getPageLanguage()
1021 */
1022 public function getPageLanguage( Title $title, Content $content = null ) {
1023 return wfGetLangObj( 'en' );
1024 }
1025 }
1026
1027 /**
1028 * @since WD.1
1029 */
1030 class CssContentHandler extends TextContentHandler {
1031
1032 public function __construct( $modelId = CONTENT_MODEL_CSS ) {
1033 parent::__construct( $modelId, array( CONTENT_FORMAT_CSS ) );
1034 }
1035
1036 public function unserializeContent( $text, $format = null ) {
1037 $this->checkFormat( $format );
1038
1039 return new CssContent( $text );
1040 }
1041
1042 public function makeEmptyContent() {
1043 return new CssContent( '' );
1044 }
1045
1046 /**
1047 * Returns the english language, because CSS is english, and should be handled as such.
1048 *
1049 * @return Language wfGetLangObj( 'en' )
1050 *
1051 * @see ContentHandler::getPageLanguage()
1052 */
1053 public function getPageLanguage( Title $title, Content $content = null ) {
1054 return wfGetLangObj( 'en' );
1055 }
1056 }