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