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