Merge "Add MessagesBi.php"
[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 use Wikimedia\Assert\Assert;
29 use MediaWiki\Logger\LoggerFactory;
30 use MediaWiki\MediaWikiServices;
31 use MediaWiki\Revision\SlotRenderingProvider;
32 use MediaWiki\Search\ParserOutputSearchDataExtractor;
33
34 /**
35 * A content handler knows how do deal with a specific type of content on a wiki
36 * page. Content is stored in the database in a serialized form (using a
37 * serialization format a.k.a. MIME type) and is unserialized into its native
38 * PHP representation (the content model), which is wrapped in an instance of
39 * the appropriate subclass of Content.
40 *
41 * ContentHandler instances are stateless singletons that serve, among other
42 * things, as a factory for Content objects. Generally, there is one subclass
43 * of ContentHandler and one subclass of Content for every type of content model.
44 *
45 * Some content types have a flat model, that is, their native representation
46 * is the same as their serialized form. Examples would be JavaScript and CSS
47 * code. As of now, this also applies to wikitext (MediaWiki's default content
48 * type), but wikitext content may be represented by a DOM or AST structure in
49 * the future.
50 *
51 * @ingroup Content
52 */
53 abstract class ContentHandler {
54 /**
55 * Convenience function for getting flat text from a Content object. This
56 * should only be used in the context of backwards compatibility with code
57 * that is not yet able to handle Content objects!
58 *
59 * If $content is null, this method returns the empty string.
60 *
61 * If $content is an instance of TextContent, this method returns the flat
62 * text as returned by $content->getNativeData().
63 *
64 * If $content is not a TextContent object, the behavior of this method
65 * depends on the global $wgContentHandlerTextFallback:
66 * - If $wgContentHandlerTextFallback is 'fail' and $content is not a
67 * TextContent object, an MWException is thrown.
68 * - If $wgContentHandlerTextFallback is 'serialize' and $content is not a
69 * TextContent object, $content->serialize() is called to get a string
70 * form of the content.
71 * - If $wgContentHandlerTextFallback is 'ignore' and $content is not a
72 * TextContent object, this method returns null.
73 * - otherwise, the behavior is undefined.
74 *
75 * @since 1.21
76 *
77 * @param Content|null $content
78 *
79 * @throws MWException If the content is not an instance of TextContent and
80 * wgContentHandlerTextFallback was set to 'fail'.
81 * @return string|null Textual form of the content, if available.
82 */
83 public static function getContentText( Content $content = null ) {
84 global $wgContentHandlerTextFallback;
85
86 if ( is_null( $content ) ) {
87 return '';
88 }
89
90 if ( $content instanceof TextContent ) {
91 return $content->getNativeData();
92 }
93
94 wfDebugLog( 'ContentHandler', 'Accessing ' . $content->getModel() . ' content as text!' );
95
96 if ( $wgContentHandlerTextFallback == 'fail' ) {
97 throw new MWException(
98 "Attempt to get text from Content with model " .
99 $content->getModel()
100 );
101 }
102
103 if ( $wgContentHandlerTextFallback == 'serialize' ) {
104 return $content->serialize();
105 }
106
107 return null;
108 }
109
110 /**
111 * Convenience function for creating a Content object from a given textual
112 * representation.
113 *
114 * $text will be deserialized into a Content object of the model specified
115 * by $modelId (or, if that is not given, $title->getContentModel()) using
116 * the given format.
117 *
118 * @since 1.21
119 *
120 * @param string $text The textual representation, will be
121 * unserialized to create the Content object
122 * @param Title|null $title The title of the page this text belongs to.
123 * Required if $modelId is not provided.
124 * @param string|null $modelId The model to deserialize to. If not provided,
125 * $title->getContentModel() is used.
126 * @param string|null $format The format to use for deserialization. If not
127 * given, the model's default format is used.
128 *
129 * @throws MWException If model ID or format is not supported or if the text can not be
130 * unserialized using the format.
131 * @return Content A Content object representing the text.
132 */
133 public static function makeContent( $text, Title $title = null,
134 $modelId = null, $format = null ) {
135 if ( is_null( $modelId ) ) {
136 if ( is_null( $title ) ) {
137 throw new MWException( "Must provide a Title object or a content model ID." );
138 }
139
140 $modelId = $title->getContentModel();
141 }
142
143 $handler = self::getForModelID( $modelId );
144
145 return $handler->unserializeContent( $text, $format );
146 }
147
148 /**
149 * Returns the name of the default content model to be used for the page
150 * with the given title.
151 *
152 * Note: There should rarely be need to call this method directly.
153 * To determine the actual content model for a given page, use
154 * Title::getContentModel().
155 *
156 * Which model is to be used by default for the page is determined based
157 * on several factors:
158 * - The global setting $wgNamespaceContentModels specifies a content model
159 * per namespace.
160 * - The hook ContentHandlerDefaultModelFor may be used to override the page's default
161 * model.
162 * - Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript
163 * model if they end in .js or .css, respectively.
164 * - Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
165 * - The hook TitleIsCssOrJsPage may be used to force a page to use the CSS
166 * or JavaScript model. This is a compatibility feature. The ContentHandlerDefaultModelFor
167 * hook should be used instead if possible.
168 * - The hook TitleIsWikitextPage may be used to force a page to use the
169 * wikitext model. This is a compatibility feature. The ContentHandlerDefaultModelFor
170 * hook should be used instead if possible.
171 *
172 * If none of the above applies, the wikitext model is used.
173 *
174 * Note: this is used by, and may thus not use, Title::getContentModel()
175 *
176 * @since 1.21
177 *
178 * @param Title $title
179 *
180 * @return string Default model name for the page given by $title
181 */
182 public static function getDefaultModelFor( Title $title ) {
183 // NOTE: this method must not rely on $title->getContentModel() directly or indirectly,
184 // because it is used to initialize the mContentModel member.
185
186 $ns = $title->getNamespace();
187
188 $ext = false;
189 $m = null;
190 $model = MWNamespace::getNamespaceContentModel( $ns );
191
192 // Hook can determine default model
193 if ( !Hooks::run( 'ContentHandlerDefaultModelFor', [ $title, &$model ] ) ) {
194 if ( !is_null( $model ) ) {
195 return $model;
196 }
197 }
198
199 // Could this page contain code based on the title?
200 $isCodePage = NS_MEDIAWIKI == $ns && preg_match( '!\.(css|js|json)$!u', $title->getText(), $m );
201 if ( $isCodePage ) {
202 $ext = $m[1];
203 }
204
205 // Is this a user subpage containing code?
206 $isCodeSubpage = NS_USER == $ns
207 && !$isCodePage
208 && preg_match( "/\\/.*\\.(js|css|json)$/", $title->getText(), $m );
209 if ( $isCodeSubpage ) {
210 $ext = $m[1];
211 }
212
213 // Is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
214 $isWikitext = is_null( $model ) || $model == CONTENT_MODEL_WIKITEXT;
215 $isWikitext = $isWikitext && !$isCodePage && !$isCodeSubpage;
216
217 if ( !$isWikitext ) {
218 switch ( $ext ) {
219 case 'js':
220 return CONTENT_MODEL_JAVASCRIPT;
221 case 'css':
222 return CONTENT_MODEL_CSS;
223 case 'json':
224 return CONTENT_MODEL_JSON;
225 default:
226 return is_null( $model ) ? CONTENT_MODEL_TEXT : $model;
227 }
228 }
229
230 // We established that it must be wikitext
231
232 return CONTENT_MODEL_WIKITEXT;
233 }
234
235 /**
236 * Returns the appropriate ContentHandler singleton for the given title.
237 *
238 * @since 1.21
239 *
240 * @param Title $title
241 *
242 * @return ContentHandler
243 */
244 public static function getForTitle( Title $title ) {
245 $modelId = $title->getContentModel();
246
247 return self::getForModelID( $modelId );
248 }
249
250 /**
251 * Returns the appropriate ContentHandler singleton for the given Content
252 * object.
253 *
254 * @since 1.21
255 *
256 * @param Content $content
257 *
258 * @return ContentHandler
259 */
260 public static function getForContent( Content $content ) {
261 $modelId = $content->getModel();
262
263 return self::getForModelID( $modelId );
264 }
265
266 /**
267 * @var array A Cache of ContentHandler instances by model id
268 */
269 protected static $handlers;
270
271 /**
272 * Returns the ContentHandler singleton for the given model ID. Use the
273 * CONTENT_MODEL_XXX constants to identify the desired content model.
274 *
275 * ContentHandler singletons are taken from the global $wgContentHandlers
276 * array. Keys in that array are model names, the values are either
277 * ContentHandler singleton objects, or strings specifying the appropriate
278 * subclass of ContentHandler.
279 *
280 * If a class name is encountered when looking up the singleton for a given
281 * model name, the class is instantiated and the class name is replaced by
282 * the resulting singleton in $wgContentHandlers.
283 *
284 * If no ContentHandler is defined for the desired $modelId, the
285 * ContentHandler may be provided by the ContentHandlerForModelID hook.
286 * If no ContentHandler can be determined, an MWException is raised.
287 *
288 * @since 1.21
289 *
290 * @param string $modelId The ID of the content model for which to get a
291 * handler. Use CONTENT_MODEL_XXX constants.
292 *
293 * @throws MWException For internal errors and problems in the configuration.
294 * @throws MWUnknownContentModelException If no handler is known for the model ID.
295 * @return ContentHandler The ContentHandler singleton for handling the model given by the ID.
296 */
297 public static function getForModelID( $modelId ) {
298 global $wgContentHandlers;
299
300 if ( isset( self::$handlers[$modelId] ) ) {
301 return self::$handlers[$modelId];
302 }
303
304 if ( empty( $wgContentHandlers[$modelId] ) ) {
305 $handler = null;
306
307 Hooks::run( 'ContentHandlerForModelID', [ $modelId, &$handler ] );
308
309 if ( $handler === null ) {
310 throw new MWUnknownContentModelException( $modelId );
311 }
312
313 if ( !( $handler instanceof ContentHandler ) ) {
314 throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
315 }
316 } else {
317 $classOrCallback = $wgContentHandlers[$modelId];
318
319 if ( is_callable( $classOrCallback ) ) {
320 $handler = call_user_func( $classOrCallback, $modelId );
321 } else {
322 $handler = new $classOrCallback( $modelId );
323 }
324
325 if ( !( $handler instanceof ContentHandler ) ) {
326 throw new MWException( "$classOrCallback from \$wgContentHandlers is not " .
327 "compatible with ContentHandler" );
328 }
329 }
330
331 wfDebugLog( 'ContentHandler', 'Created handler for ' . $modelId
332 . ': ' . get_class( $handler ) );
333
334 self::$handlers[$modelId] = $handler;
335
336 return self::$handlers[$modelId];
337 }
338
339 /**
340 * Clean up handlers cache.
341 */
342 public static function cleanupHandlersCache() {
343 self::$handlers = [];
344 }
345
346 /**
347 * Returns the localized name for a given content model.
348 *
349 * Model names are localized using system messages. Message keys
350 * have the form content-model-$name, where $name is getContentModelName( $id ).
351 *
352 * @param string $name The content model ID, as given by a CONTENT_MODEL_XXX
353 * constant or returned by Revision::getContentModel().
354 * @param Language|null $lang The language to parse the message in (since 1.26)
355 *
356 * @throws MWException If the model ID isn't known.
357 * @return string The content model's localized name.
358 */
359 public static function getLocalizedName( $name, Language $lang = null ) {
360 // Messages: content-model-wikitext, content-model-text,
361 // content-model-javascript, content-model-css
362 $key = "content-model-$name";
363
364 $msg = wfMessage( $key );
365 if ( $lang ) {
366 $msg->inLanguage( $lang );
367 }
368
369 return $msg->exists() ? $msg->plain() : $name;
370 }
371
372 public static function getContentModels() {
373 global $wgContentHandlers;
374
375 $models = array_keys( $wgContentHandlers );
376 Hooks::run( 'GetContentModels', [ &$models ] );
377 return $models;
378 }
379
380 public static function getAllContentFormats() {
381 global $wgContentHandlers;
382
383 $formats = [];
384
385 foreach ( $wgContentHandlers as $model => $class ) {
386 $handler = self::getForModelID( $model );
387 $formats = array_merge( $formats, $handler->getSupportedFormats() );
388 }
389
390 $formats = array_unique( $formats );
391
392 return $formats;
393 }
394
395 // ------------------------------------------------------------------------
396
397 /**
398 * @var string
399 */
400 protected $mModelID;
401
402 /**
403 * @var string[]
404 */
405 protected $mSupportedFormats;
406
407 /**
408 * Constructor, initializing the ContentHandler instance with its model ID
409 * and a list of supported formats. Values for the parameters are typically
410 * provided as literals by subclass's constructors.
411 *
412 * @param string $modelId (use CONTENT_MODEL_XXX constants).
413 * @param string[] $formats List for supported serialization formats
414 * (typically as MIME types)
415 */
416 public function __construct( $modelId, $formats ) {
417 $this->mModelID = $modelId;
418 $this->mSupportedFormats = $formats;
419 }
420
421 /**
422 * Serializes a Content object of the type supported by this ContentHandler.
423 *
424 * @since 1.21
425 *
426 * @param Content $content The Content object to serialize
427 * @param string|null $format The desired serialization format
428 *
429 * @return string Serialized form of the content
430 */
431 abstract public function serializeContent( Content $content, $format = null );
432
433 /**
434 * Applies transformations on export (returns the blob unchanged per default).
435 * Subclasses may override this to perform transformations such as conversion
436 * of legacy formats or filtering of internal meta-data.
437 *
438 * @param string $blob The blob to be exported
439 * @param string|null $format The blob's serialization format
440 *
441 * @return string
442 */
443 public function exportTransform( $blob, $format = null ) {
444 return $blob;
445 }
446
447 /**
448 * Unserializes a Content object of the type supported by this ContentHandler.
449 *
450 * @since 1.21
451 *
452 * @param string $blob Serialized form of the content
453 * @param string|null $format The format used for serialization
454 *
455 * @return Content The Content object created by deserializing $blob
456 */
457 abstract public function unserializeContent( $blob, $format = null );
458
459 /**
460 * Apply import transformation (per default, returns $blob unchanged).
461 * This gives subclasses an opportunity to transform data blobs on import.
462 *
463 * @since 1.24
464 *
465 * @param string $blob
466 * @param string|null $format
467 *
468 * @return string
469 */
470 public function importTransform( $blob, $format = null ) {
471 return $blob;
472 }
473
474 /**
475 * Creates an empty Content object of the type supported by this
476 * ContentHandler.
477 *
478 * @since 1.21
479 *
480 * @return Content
481 */
482 abstract public function makeEmptyContent();
483
484 /**
485 * Creates a new Content object that acts as a redirect to the given page,
486 * or null if redirects are not supported by this content model.
487 *
488 * This default implementation always returns null. Subclasses supporting redirects
489 * must override this method.
490 *
491 * Note that subclasses that override this method to return a Content object
492 * should also override supportsRedirects() to return true.
493 *
494 * @since 1.21
495 *
496 * @param Title $destination The page to redirect to.
497 * @param string $text Text to include in the redirect, if possible.
498 *
499 * @return Content Always null.
500 */
501 public function makeRedirectContent( Title $destination, $text = '' ) {
502 return null;
503 }
504
505 /**
506 * Returns the model id that identifies the content model this
507 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
508 *
509 * @since 1.21
510 *
511 * @return string The model ID
512 */
513 public function getModelID() {
514 return $this->mModelID;
515 }
516
517 /**
518 * @since 1.21
519 *
520 * @param string $model_id The model to check
521 *
522 * @throws MWException If the model ID is not the ID of the content model supported by this
523 * ContentHandler.
524 */
525 protected function checkModelID( $model_id ) {
526 if ( $model_id !== $this->mModelID ) {
527 throw new MWException( "Bad content model: " .
528 "expected {$this->mModelID} " .
529 "but got $model_id." );
530 }
531 }
532
533 /**
534 * Returns a list of serialization formats supported by the
535 * serializeContent() and unserializeContent() methods of this
536 * ContentHandler.
537 *
538 * @since 1.21
539 *
540 * @return string[] List of serialization formats as MIME type like strings
541 */
542 public function getSupportedFormats() {
543 return $this->mSupportedFormats;
544 }
545
546 /**
547 * The format used for serialization/deserialization by default by this
548 * ContentHandler.
549 *
550 * This default implementation will return the first element of the array
551 * of formats that was passed to the constructor.
552 *
553 * @since 1.21
554 *
555 * @return string The name of the default serialization format as a MIME type
556 */
557 public function getDefaultFormat() {
558 return $this->mSupportedFormats[0];
559 }
560
561 /**
562 * Returns true if $format is a serialization format supported by this
563 * ContentHandler, and false otherwise.
564 *
565 * Note that if $format is null, this method always returns true, because
566 * null means "use the default format".
567 *
568 * @since 1.21
569 *
570 * @param string $format The serialization format to check
571 *
572 * @return bool
573 */
574 public function isSupportedFormat( $format ) {
575 if ( !$format ) {
576 return true; // this means "use the default"
577 }
578
579 return in_array( $format, $this->mSupportedFormats );
580 }
581
582 /**
583 * Convenient for checking whether a format provided as a parameter is actually supported.
584 *
585 * @param string $format The serialization format to check
586 *
587 * @throws MWException If the format is not supported by this content handler.
588 */
589 protected function checkFormat( $format ) {
590 if ( !$this->isSupportedFormat( $format ) ) {
591 throw new MWException(
592 "Format $format is not supported for content model "
593 . $this->getModelID()
594 );
595 }
596 }
597
598 /**
599 * Returns overrides for action handlers.
600 * Classes listed here will be used instead of the default one when
601 * (and only when) $wgActions[$action] === true. This allows subclasses
602 * to override the default action handlers.
603 *
604 * @since 1.21
605 *
606 * @return array An array mapping action names (typically "view", "edit", "history" etc.) to
607 * either the full qualified class name of an Action class, a callable taking ( Page $page,
608 * IContextSource $context = null ) as parameters and returning an Action object, or an actual
609 * Action object. An empty array in this default implementation.
610 *
611 * @see Action::factory
612 */
613 public function getActionOverrides() {
614 return [];
615 }
616
617 /**
618 * Factory for creating an appropriate DifferenceEngine for this content model.
619 * Since 1.32, this is only used for page-level diffs; to diff two content objects,
620 * use getSlotDiffRenderer.
621 *
622 * The DifferenceEngine subclass to use is selected in getDiffEngineClass(). The
623 * GetDifferenceEngine hook will receive the DifferenceEngine object and can replace or
624 * wrap it.
625 * (Note that in older versions of MediaWiki the hook documentation instructed extensions
626 * to return false from the hook; you should not rely on always being able to decorate
627 * the DifferenceEngine instance from the hook. If the owner of the content type wants to
628 * decorare the instance, overriding this method is a safer approach.)
629 *
630 * @todo This is page-level functionality so it should not belong to ContentHandler.
631 * Move it to a better place once one exists (e.g. PageTypeHandler).
632 *
633 * @since 1.21
634 *
635 * @param IContextSource $context Context to use, anything else will be ignored.
636 * @param int $old Revision ID we want to show and diff with.
637 * @param int|string $new Either a revision ID or one of the strings 'cur', 'prev' or 'next'.
638 * @param int $rcid FIXME: Deprecated, no longer used. Defaults to 0.
639 * @param bool $refreshCache If set, refreshes the diff cache. Defaults to false.
640 * @param bool $unhide If set, allow viewing deleted revs. Defaults to false.
641 *
642 * @return DifferenceEngine
643 */
644 public function createDifferenceEngine( IContextSource $context, $old = 0, $new = 0,
645 $rcid = 0, // FIXME: Deprecated, no longer used
646 $refreshCache = false, $unhide = false
647 ) {
648 $diffEngineClass = $this->getDiffEngineClass();
649 $differenceEngine = new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
650 Hooks::run( 'GetDifferenceEngine', [ $context, $old, $new, $refreshCache, $unhide,
651 &$differenceEngine ] );
652 return $differenceEngine;
653 }
654
655 /**
656 * Get an appropriate SlotDiffRenderer for this content model.
657 * @since 1.32
658 * @param IContextSource $context
659 * @return SlotDiffRenderer
660 */
661 final public function getSlotDiffRenderer( IContextSource $context ) {
662 $slotDiffRenderer = $this->getSlotDiffRendererInternal( $context );
663 if ( get_class( $slotDiffRenderer ) === TextSlotDiffRenderer::class ) {
664 // To keep B/C, when SlotDiffRenderer is not overridden for a given content type
665 // but DifferenceEngine is, use that instead.
666 $differenceEngine = $this->createDifferenceEngine( $context );
667 if ( get_class( $differenceEngine ) !== DifferenceEngine::class ) {
668 // TODO turn this into a deprecation warning in a later release
669 LoggerFactory::getInstance( 'diff' )->info(
670 'Falling back to DifferenceEngineSlotDiffRenderer', [
671 'modelID' => $this->getModelID(),
672 'DifferenceEngine' => get_class( $differenceEngine ),
673 ] );
674 $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
675 }
676 }
677 Hooks::run( 'GetSlotDiffRenderer', [ $this, &$slotDiffRenderer, $context ] );
678 return $slotDiffRenderer;
679 }
680
681 /**
682 * Return the SlotDiffRenderer appropriate for this content handler.
683 * @param IContextSource $context
684 * @return SlotDiffRenderer
685 */
686 protected function getSlotDiffRendererInternal( IContextSource $context ) {
687 $contentLanguage = MediaWikiServices::getInstance()->getContentLanguage();
688 $statsdDataFactory = MediaWikiServices::getInstance()->getStatsdDataFactory();
689 $slotDiffRenderer = new TextSlotDiffRenderer();
690 $slotDiffRenderer->setStatsdDataFactory( $statsdDataFactory );
691 // XXX using the page language would be better, but it's unclear how that should be injected
692 $slotDiffRenderer->setLanguage( $contentLanguage );
693 $slotDiffRenderer->setWikiDiff2MovedParagraphDetectionCutoff(
694 $context->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
695 );
696
697 $engine = DifferenceEngine::getEngine();
698 if ( $engine === false ) {
699 $slotDiffRenderer->setEngine( TextSlotDiffRenderer::ENGINE_PHP );
700 } elseif ( $engine === 'wikidiff2' ) {
701 $slotDiffRenderer->setEngine( TextSlotDiffRenderer::ENGINE_WIKIDIFF2 );
702 } else {
703 $slotDiffRenderer->setEngine( TextSlotDiffRenderer::ENGINE_EXTERNAL, $engine );
704 }
705
706 return $slotDiffRenderer;
707 }
708
709 /**
710 * Get the language in which the content of the given page is written.
711 *
712 * This default implementation just returns the content language (except for pages
713 * in the MediaWiki namespace)
714 *
715 * Note that the pages language is not cacheable, since it may in some
716 * cases depend on user settings.
717 *
718 * Also note that the page language may or may not depend on the actual content of the page,
719 * that is, this method may load the content in order to determine the language.
720 *
721 * @since 1.21
722 *
723 * @param Title $title The page to determine the language for.
724 * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
725 *
726 * @return Language The page's language
727 */
728 public function getPageLanguage( Title $title, Content $content = null ) {
729 global $wgLang;
730 $pageLang = MediaWikiServices::getInstance()->getContentLanguage();
731
732 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
733 // Parse mediawiki messages with correct target language
734 list( /* $unused */, $lang ) = MessageCache::singleton()->figureMessage( $title->getText() );
735 $pageLang = Language::factory( $lang );
736 }
737
738 Hooks::run( 'PageContentLanguage', [ $title, &$pageLang, $wgLang ] );
739
740 return wfGetLangObj( $pageLang );
741 }
742
743 /**
744 * Get the language in which the content of this page is written when
745 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
746 * specified a preferred variant, the variant will be used.
747 *
748 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
749 * the user specified a preferred variant.
750 *
751 * Note that the pages view language is not cacheable, since it depends on user settings.
752 *
753 * Also note that the page language may or may not depend on the actual content of the page,
754 * that is, this method may load the content in order to determine the language.
755 *
756 * @since 1.21
757 *
758 * @param Title $title The page to determine the language for.
759 * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
760 *
761 * @return Language The page's language for viewing
762 */
763 public function getPageViewLanguage( Title $title, Content $content = null ) {
764 $pageLang = $this->getPageLanguage( $title, $content );
765
766 if ( $title->getNamespace() !== NS_MEDIAWIKI ) {
767 // If the user chooses a variant, the content is actually
768 // in a language whose code is the variant code.
769 $variant = $pageLang->getPreferredVariant();
770 if ( $pageLang->getCode() !== $variant ) {
771 $pageLang = Language::factory( $variant );
772 }
773 }
774
775 return $pageLang;
776 }
777
778 /**
779 * Determines whether the content type handled by this ContentHandler
780 * can be used on the given page.
781 *
782 * This default implementation always returns true.
783 * Subclasses may override this to restrict the use of this content model to specific locations,
784 * typically based on the namespace or some other aspect of the title, such as a special suffix
785 * (e.g. ".svg" for SVG content).
786 *
787 * @note this calls the ContentHandlerCanBeUsedOn hook which may be used to override which
788 * content model can be used where.
789 *
790 * @param Title $title The page's title.
791 *
792 * @return bool True if content of this kind can be used on the given page, false otherwise.
793 */
794 public function canBeUsedOn( Title $title ) {
795 $ok = true;
796
797 Hooks::run( 'ContentModelCanBeUsedOn', [ $this->getModelID(), $title, &$ok ] );
798
799 return $ok;
800 }
801
802 /**
803 * Returns the name of the diff engine to use.
804 *
805 * @since 1.21
806 *
807 * @return string
808 */
809 protected function getDiffEngineClass() {
810 return DifferenceEngine::class;
811 }
812
813 /**
814 * Attempts to merge differences between three versions. Returns a new
815 * Content object for a clean merge and false for failure or a conflict.
816 *
817 * This default implementation always returns false.
818 *
819 * @since 1.21
820 *
821 * @param Content $oldContent The page's previous content.
822 * @param Content $myContent One of the page's conflicting contents.
823 * @param Content $yourContent One of the page's conflicting contents.
824 *
825 * @return Content|bool Always false.
826 */
827 public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
828 return false;
829 }
830
831 /**
832 * Return type of change if one exists for the given edit.
833 *
834 * @since 1.31
835 *
836 * @param Content|null $oldContent The previous text of the page.
837 * @param Content|null $newContent The submitted text of the page.
838 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
839 *
840 * @return string|null String key representing type of change, or null.
841 */
842 private function getChangeType(
843 Content $oldContent = null,
844 Content $newContent = null,
845 $flags = 0
846 ) {
847 $oldTarget = $oldContent !== null ? $oldContent->getRedirectTarget() : null;
848 $newTarget = $newContent !== null ? $newContent->getRedirectTarget() : null;
849
850 // We check for the type of change in the given edit, and return string key accordingly
851
852 // Blanking of a page
853 if ( $oldContent && $oldContent->getSize() > 0 &&
854 $newContent && $newContent->getSize() === 0
855 ) {
856 return 'blank';
857 }
858
859 // Redirects
860 if ( $newTarget ) {
861 if ( !$oldTarget ) {
862 // New redirect page (by creating new page or by changing content page)
863 return 'new-redirect';
864 } elseif ( !$newTarget->equals( $oldTarget ) ||
865 $oldTarget->getFragment() !== $newTarget->getFragment()
866 ) {
867 // Redirect target changed
868 return 'changed-redirect-target';
869 }
870 } elseif ( $oldTarget ) {
871 // Changing an existing redirect into a non-redirect
872 return 'removed-redirect';
873 }
874
875 // New page created
876 if ( $flags & EDIT_NEW && $newContent ) {
877 if ( $newContent->getSize() === 0 ) {
878 // New blank page
879 return 'newblank';
880 } else {
881 return 'newpage';
882 }
883 }
884
885 // Removing more than 90% of the page
886 if ( $oldContent && $newContent && $oldContent->getSize() > 10 * $newContent->getSize() ) {
887 return 'replace';
888 }
889
890 // Content model changed
891 if ( $oldContent && $newContent && $oldContent->getModel() !== $newContent->getModel() ) {
892 return 'contentmodelchange';
893 }
894
895 return null;
896 }
897
898 /**
899 * Return an applicable auto-summary if one exists for the given edit.
900 *
901 * @since 1.21
902 *
903 * @param Content|null $oldContent The previous text of the page.
904 * @param Content|null $newContent The submitted text of the page.
905 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
906 *
907 * @return string An appropriate auto-summary, or an empty string.
908 */
909 public function getAutosummary(
910 Content $oldContent = null,
911 Content $newContent = null,
912 $flags = 0
913 ) {
914 $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
915
916 // There's no applicable auto-summary for our case, so our auto-summary is empty.
917 if ( !$changeType ) {
918 return '';
919 }
920
921 // Decide what kind of auto-summary is needed.
922 switch ( $changeType ) {
923 case 'new-redirect':
924 $newTarget = $newContent->getRedirectTarget();
925 $truncatedtext = $newContent->getTextForSummary(
926 250
927 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
928 - strlen( $newTarget->getFullText() )
929 );
930
931 return wfMessage( 'autoredircomment', $newTarget->getFullText() )
932 ->plaintextParams( $truncatedtext )->inContentLanguage()->text();
933 case 'changed-redirect-target':
934 $oldTarget = $oldContent->getRedirectTarget();
935 $newTarget = $newContent->getRedirectTarget();
936
937 $truncatedtext = $newContent->getTextForSummary(
938 250
939 - strlen( wfMessage( 'autosumm-changed-redirect-target' )
940 ->inContentLanguage()->text() )
941 - strlen( $oldTarget->getFullText() )
942 - strlen( $newTarget->getFullText() )
943 );
944
945 return wfMessage( 'autosumm-changed-redirect-target',
946 $oldTarget->getFullText(),
947 $newTarget->getFullText() )
948 ->rawParams( $truncatedtext )->inContentLanguage()->text();
949 case 'removed-redirect':
950 $oldTarget = $oldContent->getRedirectTarget();
951 $truncatedtext = $newContent->getTextForSummary(
952 250
953 - strlen( wfMessage( 'autosumm-removed-redirect' )
954 ->inContentLanguage()->text() )
955 - strlen( $oldTarget->getFullText() ) );
956
957 return wfMessage( 'autosumm-removed-redirect', $oldTarget->getFullText() )
958 ->rawParams( $truncatedtext )->inContentLanguage()->text();
959 case 'newpage':
960 // If they're making a new article, give its text, truncated, in the summary.
961 $truncatedtext = $newContent->getTextForSummary(
962 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
963
964 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
965 ->inContentLanguage()->text();
966 case 'blank':
967 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
968 case 'replace':
969 $truncatedtext = $newContent->getTextForSummary(
970 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
971
972 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
973 ->inContentLanguage()->text();
974 case 'newblank':
975 return wfMessage( 'autosumm-newblank' )->inContentLanguage()->text();
976 default:
977 return '';
978 }
979 }
980
981 /**
982 * Return an applicable tag if one exists for the given edit or return null.
983 *
984 * @since 1.31
985 *
986 * @param Content|null $oldContent The previous text of the page.
987 * @param Content|null $newContent The submitted text of the page.
988 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
989 *
990 * @return string|null An appropriate tag, or null.
991 */
992 public function getChangeTag(
993 Content $oldContent = null,
994 Content $newContent = null,
995 $flags = 0
996 ) {
997 $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
998
999 // There's no applicable tag for this change.
1000 if ( !$changeType ) {
1001 return null;
1002 }
1003
1004 // Core tags use the same keys as ones returned from $this->getChangeType()
1005 // but prefixed with pseudo namespace 'mw-', so we add the prefix before checking
1006 // if this type of change should be tagged
1007 $tag = 'mw-' . $changeType;
1008
1009 // Not all change types are tagged, so we check against the list of defined tags.
1010 if ( in_array( $tag, ChangeTags::getSoftwareTags() ) ) {
1011 return $tag;
1012 }
1013
1014 return null;
1015 }
1016
1017 /**
1018 * Auto-generates a deletion reason
1019 *
1020 * @since 1.21
1021 *
1022 * @param Title $title The page's title
1023 * @param bool &$hasHistory Whether the page has a history
1024 *
1025 * @return mixed String containing deletion reason or empty string, or
1026 * boolean false if no revision occurred
1027 *
1028 * @todo &$hasHistory is extremely ugly, it's here because
1029 * WikiPage::getAutoDeleteReason() and Article::generateReason()
1030 * have it / want it.
1031 */
1032 public function getAutoDeleteReason( Title $title, &$hasHistory ) {
1033 $dbr = wfGetDB( DB_REPLICA );
1034
1035 // Get the last revision
1036 $rev = Revision::newFromTitle( $title );
1037
1038 if ( is_null( $rev ) ) {
1039 return false;
1040 }
1041
1042 // Get the article's contents
1043 $content = $rev->getContent();
1044 $blank = false;
1045
1046 // If the page is blank, use the text from the previous revision,
1047 // which can only be blank if there's a move/import/protect dummy
1048 // revision involved
1049 if ( !$content || $content->isEmpty() ) {
1050 $prev = $rev->getPrevious();
1051
1052 if ( $prev ) {
1053 $rev = $prev;
1054 $content = $rev->getContent();
1055 $blank = true;
1056 }
1057 }
1058
1059 $this->checkModelID( $rev->getContentModel() );
1060
1061 // Find out if there was only one contributor
1062 // Only scan the last 20 revisions
1063 $revQuery = Revision::getQueryInfo();
1064 $res = $dbr->select(
1065 $revQuery['tables'],
1066 [ 'rev_user_text' => $revQuery['fields']['rev_user_text'] ],
1067 [
1068 'rev_page' => $title->getArticleID(),
1069 $dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0'
1070 ],
1071 __METHOD__,
1072 [ 'LIMIT' => 20 ],
1073 $revQuery['joins']
1074 );
1075
1076 if ( $res === false ) {
1077 // This page has no revisions, which is very weird
1078 return false;
1079 }
1080
1081 $hasHistory = ( $res->numRows() > 1 );
1082 $row = $dbr->fetchObject( $res );
1083
1084 if ( $row ) { // $row is false if the only contributor is hidden
1085 $onlyAuthor = $row->rev_user_text;
1086 // Try to find a second contributor
1087 foreach ( $res as $row ) {
1088 if ( $row->rev_user_text != $onlyAuthor ) { // T24999
1089 $onlyAuthor = false;
1090 break;
1091 }
1092 }
1093 } else {
1094 $onlyAuthor = false;
1095 }
1096
1097 // Generate the summary with a '$1' placeholder
1098 if ( $blank ) {
1099 // The current revision is blank and the one before is also
1100 // blank. It's just not our lucky day
1101 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
1102 } else {
1103 if ( $onlyAuthor ) {
1104 $reason = wfMessage(
1105 'excontentauthor',
1106 '$1',
1107 $onlyAuthor
1108 )->inContentLanguage()->text();
1109 } else {
1110 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
1111 }
1112 }
1113
1114 if ( $reason == '-' ) {
1115 // Allow these UI messages to be blanked out cleanly
1116 return '';
1117 }
1118
1119 // Max content length = max comment length - length of the comment (excl. $1)
1120 $text = $content ? $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) : '';
1121
1122 // Now replace the '$1' placeholder
1123 $reason = str_replace( '$1', $text, $reason );
1124
1125 return $reason;
1126 }
1127
1128 /**
1129 * Get the Content object that needs to be saved in order to undo all revisions
1130 * between $undo and $undoafter. Revisions must belong to the same page,
1131 * must exist and must not be deleted.
1132 *
1133 * @since 1.21
1134 * @since 1.32 accepts Content objects for all parameters instead of Revision objects.
1135 * Passing Revision objects is deprecated.
1136 *
1137 * @param Revision|Content $current The current text
1138 * @param Revision|Content $undo The content of the revision to undo
1139 * @param Revision|Content $undoafter Must be from an earlier revision than $undo
1140 * @param bool $undoIsLatest Set true if $undo is from the current revision (since 1.32)
1141 *
1142 * @return mixed Content on success, false on failure
1143 */
1144 public function getUndoContent( $current, $undo, $undoafter, $undoIsLatest = false ) {
1145 Assert::parameterType( Revision::class . '|' . Content::class, $current, '$current' );
1146 if ( $current instanceof Content ) {
1147 Assert::parameter( $undo instanceof Content, '$undo',
1148 'Must be Content when $current is Content' );
1149 Assert::parameter( $undoafter instanceof Content, '$undoafter',
1150 'Must be Content when $current is Content' );
1151 $cur_content = $current;
1152 $undo_content = $undo;
1153 $undoafter_content = $undoafter;
1154 } else {
1155 Assert::parameter( $undo instanceof Revision, '$undo',
1156 'Must be Revision when $current is Revision' );
1157 Assert::parameter( $undoafter instanceof Revision, '$undoafter',
1158 'Must be Revision when $current is Revision' );
1159
1160 $cur_content = $current->getContent();
1161
1162 if ( empty( $cur_content ) ) {
1163 return false; // no page
1164 }
1165
1166 $undo_content = $undo->getContent();
1167 $undoafter_content = $undoafter->getContent();
1168
1169 if ( !$undo_content || !$undoafter_content ) {
1170 return false; // no content to undo
1171 }
1172
1173 $undoIsLatest = $current->getId() === $undo->getId();
1174 }
1175
1176 try {
1177 $this->checkModelID( $cur_content->getModel() );
1178 $this->checkModelID( $undo_content->getModel() );
1179 if ( !$undoIsLatest ) {
1180 // If we are undoing the most recent revision,
1181 // its ok to revert content model changes. However
1182 // if we are undoing a revision in the middle, then
1183 // doing that will be confusing.
1184 $this->checkModelID( $undoafter_content->getModel() );
1185 }
1186 } catch ( MWException $e ) {
1187 // If the revisions have different content models
1188 // just return false
1189 return false;
1190 }
1191
1192 if ( $cur_content->equals( $undo_content ) ) {
1193 // No use doing a merge if it's just a straight revert.
1194 return $undoafter_content;
1195 }
1196
1197 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
1198
1199 return $undone_content;
1200 }
1201
1202 /**
1203 * Get parser options suitable for rendering and caching the article
1204 *
1205 * @deprecated since 1.32, use WikiPage::makeParserOptions() or
1206 * ParserOptions::newCanonical() instead.
1207 * @param IContextSource|User|string $context One of the following:
1208 * - IContextSource: Use the User and the Language of the provided
1209 * context
1210 * - User: Use the provided User object and $wgLang for the language,
1211 * so use an IContextSource object if possible.
1212 * - 'canonical': Canonical options (anonymous user with default
1213 * preferences and content language).
1214 *
1215 * @throws MWException
1216 * @return ParserOptions
1217 */
1218 public function makeParserOptions( $context ) {
1219 wfDeprecated( __METHOD__, '1.32' );
1220 return ParserOptions::newCanonical( $context );
1221 }
1222
1223 /**
1224 * Returns true for content models that support caching using the
1225 * ParserCache mechanism. See WikiPage::shouldCheckParserCache().
1226 *
1227 * @since 1.21
1228 *
1229 * @return bool Always false.
1230 */
1231 public function isParserCacheSupported() {
1232 return false;
1233 }
1234
1235 /**
1236 * Returns true if this content model supports sections.
1237 * This default implementation returns false.
1238 *
1239 * Content models that return true here should also implement
1240 * Content::getSection, Content::replaceSection, etc. to handle sections..
1241 *
1242 * @return bool Always false.
1243 */
1244 public function supportsSections() {
1245 return false;
1246 }
1247
1248 /**
1249 * Returns true if this content model supports categories.
1250 * The default implementation returns true.
1251 *
1252 * @return bool Always true.
1253 */
1254 public function supportsCategories() {
1255 return true;
1256 }
1257
1258 /**
1259 * Returns true if this content model supports redirects.
1260 * This default implementation returns false.
1261 *
1262 * Content models that return true here should also implement
1263 * ContentHandler::makeRedirectContent to return a Content object.
1264 *
1265 * @return bool Always false.
1266 */
1267 public function supportsRedirects() {
1268 return false;
1269 }
1270
1271 /**
1272 * Return true if this content model supports direct editing, such as via EditPage.
1273 *
1274 * @return bool Default is false, and true for TextContent and it's derivatives.
1275 */
1276 public function supportsDirectEditing() {
1277 return false;
1278 }
1279
1280 /**
1281 * Whether or not this content model supports direct editing via ApiEditPage
1282 *
1283 * @return bool Default is false, and true for TextContent and derivatives.
1284 */
1285 public function supportsDirectApiEditing() {
1286 return $this->supportsDirectEditing();
1287 }
1288
1289 /**
1290 * Get fields definition for search index
1291 *
1292 * @todo Expose title, redirect, namespace, text, source_text, text_bytes
1293 * field mappings here. (see T142670 and T143409)
1294 *
1295 * @param SearchEngine $engine
1296 * @return SearchIndexField[] List of fields this content handler can provide.
1297 * @since 1.28
1298 */
1299 public function getFieldsForSearchIndex( SearchEngine $engine ) {
1300 $fields['category'] = $engine->makeSearchFieldMapping(
1301 'category',
1302 SearchIndexField::INDEX_TYPE_TEXT
1303 );
1304 $fields['category']->setFlag( SearchIndexField::FLAG_CASEFOLD );
1305
1306 $fields['external_link'] = $engine->makeSearchFieldMapping(
1307 'external_link',
1308 SearchIndexField::INDEX_TYPE_KEYWORD
1309 );
1310
1311 $fields['outgoing_link'] = $engine->makeSearchFieldMapping(
1312 'outgoing_link',
1313 SearchIndexField::INDEX_TYPE_KEYWORD
1314 );
1315
1316 $fields['template'] = $engine->makeSearchFieldMapping(
1317 'template',
1318 SearchIndexField::INDEX_TYPE_KEYWORD
1319 );
1320 $fields['template']->setFlag( SearchIndexField::FLAG_CASEFOLD );
1321
1322 $fields['content_model'] = $engine->makeSearchFieldMapping(
1323 'content_model',
1324 SearchIndexField::INDEX_TYPE_KEYWORD
1325 );
1326
1327 return $fields;
1328 }
1329
1330 /**
1331 * Add new field definition to array.
1332 * @param SearchIndexField[] &$fields
1333 * @param SearchEngine $engine
1334 * @param string $name
1335 * @param int $type
1336 * @return SearchIndexField[] new field defs
1337 * @since 1.28
1338 */
1339 protected function addSearchField( &$fields, SearchEngine $engine, $name, $type ) {
1340 $fields[$name] = $engine->makeSearchFieldMapping( $name, $type );
1341 return $fields;
1342 }
1343
1344 /**
1345 * Return fields to be indexed by search engine
1346 * as representation of this document.
1347 * Overriding class should call parent function or take care of calling
1348 * the SearchDataForIndex hook.
1349 * @param WikiPage $page Page to index
1350 * @param ParserOutput $output
1351 * @param SearchEngine $engine Search engine for which we are indexing
1352 * @return array Map of name=>value for fields
1353 * @since 1.28
1354 */
1355 public function getDataForSearchIndex(
1356 WikiPage $page,
1357 ParserOutput $output,
1358 SearchEngine $engine
1359 ) {
1360 $fieldData = [];
1361 $content = $page->getContent();
1362
1363 if ( $content ) {
1364 $searchDataExtractor = new ParserOutputSearchDataExtractor();
1365
1366 $fieldData['category'] = $searchDataExtractor->getCategories( $output );
1367 $fieldData['external_link'] = $searchDataExtractor->getExternalLinks( $output );
1368 $fieldData['outgoing_link'] = $searchDataExtractor->getOutgoingLinks( $output );
1369 $fieldData['template'] = $searchDataExtractor->getTemplates( $output );
1370
1371 $text = $content->getTextForSearchIndex();
1372
1373 $fieldData['text'] = $text;
1374 $fieldData['source_text'] = $text;
1375 $fieldData['text_bytes'] = $content->getSize();
1376 $fieldData['content_model'] = $content->getModel();
1377 }
1378
1379 Hooks::run( 'SearchDataForIndex', [ &$fieldData, $this, $page, $output, $engine ] );
1380 return $fieldData;
1381 }
1382
1383 /**
1384 * Produce page output suitable for indexing.
1385 *
1386 * Specific content handlers may override it if they need different content handling.
1387 *
1388 * @param WikiPage $page
1389 * @param ParserCache|null $cache
1390 * @return ParserOutput
1391 */
1392 public function getParserOutputForIndexing( WikiPage $page, ParserCache $cache = null ) {
1393 // TODO: MCR: ContentHandler should be called per slot, not for the whole page.
1394 // See T190066.
1395 $parserOptions = $page->makeParserOptions( 'canonical' );
1396 if ( $cache ) {
1397 $parserOutput = $cache->get( $page, $parserOptions );
1398 }
1399
1400 if ( empty( $parserOutput ) ) {
1401 $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
1402 $parserOutput =
1403 $renderer->getRenderedRevision(
1404 $page->getRevision()->getRevisionRecord(),
1405 $parserOptions
1406 )->getRevisionParserOutput();
1407 if ( $cache ) {
1408 $cache->save( $parserOutput, $page, $parserOptions );
1409 }
1410 }
1411 return $parserOutput;
1412 }
1413
1414 /**
1415 * Returns a list of DeferrableUpdate objects for recording information about the
1416 * given Content in some secondary data store.
1417 *
1418 * Application logic should not call this method directly. Instead, it should call
1419 * DerivedPageDataUpdater::getSecondaryDataUpdates().
1420 *
1421 * @note Implementations must not return a LinksUpdate instance. Instead, a LinksUpdate
1422 * is created by the calling code in DerivedPageDataUpdater, on the combined ParserOutput
1423 * of all slots, not for each slot individually. This is in contrast to the old
1424 * getSecondaryDataUpdates method defined by AbstractContent, which returned a LinksUpdate.
1425 *
1426 * @note Implementations should not call $content->getParserOutput, they should call
1427 * $slotOutput->getSlotRendering( $role, false ) instead if they need to access a ParserOutput
1428 * of $content. This allows existing ParserOutput objects to be re-used, while avoiding
1429 * creating a ParserOutput when none is needed.
1430 *
1431 * @param Title $title The title of the page to supply the updates for
1432 * @param Content $content The content to generate data updates for.
1433 * @param string $role The role (slot) in which the content is being used. Which updates
1434 * are performed should generally not depend on the role the content has, but the
1435 * DeferrableUpdates themselves may need to know the role, to track to which slot the
1436 * data refers, and to avoid overwriting data of the same kind from another slot.
1437 * @param SlotRenderingProvider $slotOutput A provider that can be used to gain access to
1438 * a ParserOutput of $content by calling $slotOutput->getSlotParserOutput( $role, false ).
1439 * @return DeferrableUpdate[] A list of DeferrableUpdate objects for putting information
1440 * about this content object somewhere. The default implementation returns an empty
1441 * array.
1442 * @since 1.32
1443 */
1444 public function getSecondaryDataUpdates(
1445 Title $title,
1446 Content $content,
1447 $role,
1448 SlotRenderingProvider $slotOutput
1449 ) {
1450 return [];
1451 }
1452
1453 /**
1454 * Returns a list of DeferrableUpdate objects for removing information about content
1455 * in some secondary data store. This is used when a page is deleted, and also when
1456 * a slot is removed from a page.
1457 *
1458 * Application logic should not call this method directly. Instead, it should call
1459 * WikiPage::getSecondaryDataUpdates().
1460 *
1461 * @note Implementations must not return a LinksDeletionUpdate instance. Instead, a
1462 * LinksDeletionUpdate is created by the calling code in WikiPage.
1463 * This is in contrast to the old getDeletionUpdates method defined by AbstractContent,
1464 * which returned a LinksUpdate.
1465 *
1466 * @note Implementations should not rely on the page's current content, but rather the current
1467 * state of the secondary data store.
1468 *
1469 * @param Title $title The title of the page to supply the updates for
1470 * @param string $role The role (slot) in which the content is being used. Which updates
1471 * are performed should generally not depend on the role the content has, but the
1472 * DeferrableUpdates themselves may need to know the role, to track to which slot the
1473 * data refers, and to avoid overwriting data of the same kind from another slot.
1474 *
1475 * @return DeferrableUpdate[] A list of DeferrableUpdate objects for putting information
1476 * about this content object somewhere. The default implementation returns an empty
1477 * array.
1478 *
1479 * @since 1.32
1480 */
1481 public function getDeletionUpdates( Title $title, $role ) {
1482 return [];
1483 }
1484
1485 }