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