Debian Codegraph @

includes/content/ContentHandler.php

raw symbols SCIP
1 <?php
2
3 /**
4 * Base class for content handling.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @since 1.21
22 *
23 * @file
24 * @ingroup Content
25 *
26 * @author Daniel Kinzler
27 */
28
29 namespace MediaWiki\Content;
30
31 use Action;
32 use DifferenceEngine;
33 use DifferenceEngineSlotDiffRenderer;
34 use InvalidArgumentException;
35 use JsonException;
36 use LogicException;
37 use MediaWiki\CommentStore\CommentStore;
38 use MediaWiki\Content\Renderer\ContentParseParams;
39 use MediaWiki\Content\Transform\PreloadTransformParams;
40 use MediaWiki\Content\Transform\PreSaveTransformParams;
41 use MediaWiki\Context\IContextSource;
42 use MediaWiki\Context\RequestContext;
43 use MediaWiki\Deferred\DeferrableUpdate;
44 use MediaWiki\Diff\TextDiffer\ManifoldTextDiffer;
45 use MediaWiki\HookContainer\HookRunner;
46 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
47 use MediaWiki\Language\ILanguageConverter;
48 use MediaWiki\Language\Language;
49 use MediaWiki\Logger\LoggerFactory;
50 use MediaWiki\MainConfigNames;
51 use MediaWiki\MediaWikiServices;
52 use MediaWiki\Page\ParserOutputAccess;
53 use MediaWiki\Parser\ParserCache;
54 use MediaWiki\Parser\ParserOutput;
55 use MediaWiki\Revision\RevisionRecord;
56 use MediaWiki\Revision\SlotRecord;
57 use MediaWiki\Revision\SlotRenderingProvider;
58 use MediaWiki\Search\ParserOutputSearchDataExtractor;
59 use MediaWiki\Title\Title;
60 use MWContentSerializationException;
61 use MWException;
62 use MWUnknownContentModelException;
63 use SearchEngine;
64 use SearchIndexField;
65 use SlotDiffRenderer;
66 use StatusValue;
67 use TextSlotDiffRenderer;
68 use UnexpectedValueException;
69 use Wikimedia\Assert\Assert;
70 use Wikimedia\Rdbms\IDBAccessObject;
71 use Wikimedia\ScopedCallback;
72 use WikiPage;
73
74 /**
75 * A content handler knows how do deal with a specific type of content on a wiki
76 * page. Content is stored in the database in a serialized form (using a
77 * serialization format a.k.a. MIME type) and is unserialized into its native
78 * PHP representation (the content model), which is wrapped in an instance of
79 * the appropriate subclass of Content.
80 *
81 * ContentHandler instances are stateless singletons that serve, among other
82 * things, as a factory for Content objects. Generally, there is one subclass
83 * of ContentHandler and one subclass of Content for every type of content model.
84 *
85 * Some content types have a flat model, that is, their native representation
86 * is the same as their serialized form. Examples would be JavaScript and CSS
87 * code. As of now, this also applies to wikitext (MediaWiki's default content
88 * type), but wikitext content may be represented by a DOM or AST structure in
89 * the future.
90 *
91 * @stable to extend
92 *
93 * @ingroup Content
94 */
95 abstract class ContentHandler {
96 use ProtectedHookAccessorTrait;
97
98 /**
99 * Convenience function for getting flat text from a Content object. This
100 * should only be used in the context of backwards compatibility with code
101 * that is not yet able to handle Content objects!
102 *
103 * If $content is null, this method returns the empty string.
104 *
105 * If $content is an instance of TextContent, this method returns the flat
106 * text as returned by $content->getText().
107 *
108 * If $content is not a TextContent object, this method returns null.
109 *
110 * @since 1.21
111 *
112 * @deprecated since 1.37, use Content::getText() for TextContent instances
113 * instead. Hard deprecated since 1.43.
114 *
115 * @param Content|null $content
116 * @return string|null Textual form of the content, if available.
117 */
118 public static function getContentText( ?Content $content = null ) {
119 wfDeprecated( __METHOD__, '1.37' );
120 if ( $content === null ) {
121 return '';
122 }
123
124 if ( $content instanceof TextContent ) {
125 return $content->getText();
126 }
127
128 wfDebugLog( 'ContentHandler', 'Accessing ' . $content->getModel() . ' content as text!' );
129 return null;
130 }
131
132 /**
133 * Convenience function for creating a Content object from a given textual
134 * representation.
135 *
136 * $text will be deserialized into a Content object of the model specified
137 * by $modelId (or, if that is not given, $title->getContentModel()) using
138 * the given format.
139 *
140 * @since 1.21
141 *
142 * @param string $text The textual representation, will be
143 * unserialized to create the Content object
144 * @param Title|null $title The title of the page this text belongs to.
145 * Required if $modelId is not provided.
146 * @param string|null $modelId The model to deserialize to. If not provided,
147 * $title->getContentModel() is used.
148 * @param string|null $format The format to use for deserialization. If not
149 * given, the model's default format is used.
150 *
151 * @throws MWContentSerializationException
152 * @throws MWUnknownContentModelException
153 * @return Content A Content object representing the text.
154 */
155 public static function makeContent( $text, ?Title $title = null,
156 $modelId = null, $format = null ) {
157 if ( !$title && !$modelId ) {
158 throw new InvalidArgumentException( "Must provide a Title object or a content model ID." );
159 }
160
161 return MediaWikiServices::getInstance()
162 ->getContentHandlerFactory()
163 ->getContentHandler( $modelId ?? $title->getContentModel() )
164 ->unserializeContent( $text, $format );
165 }
166
167 /**
168 * Returns the name of the default content model to be used for the page
169 * with the given title.
170 *
171 * Note: There should rarely be need to call this method directly.
172 * To determine the actual content model for a given page, use
173 * Title::getContentModel().
174 *
175 * Which model is to be used by default for the page is determined based
176 * on several factors:
177 * - The global setting $wgNamespaceContentModels specifies a content model
178 * per namespace.
179 * - The hook ContentHandlerDefaultModelFor may be used to override the page's default
180 * model.
181 * - Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript
182 * model if they end in .js or .css, respectively.
183 * - Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
184 * - The hook TitleIsCssOrJsPage may be used to force a page to use the CSS
185 * or JavaScript model. This is a compatibility feature. The ContentHandlerDefaultModelFor
186 * hook should be used instead if possible.
187 * - The hook TitleIsWikitextPage may be used to force a page to use the
188 * wikitext model. This is a compatibility feature. The ContentHandlerDefaultModelFor
189 * hook should be used instead if possible.
190 *
191 * If none of the above applies, the wikitext model is used.
192 *
193 * @since 1.21
194 * @deprecated since 1.33, use SlotRoleHandler::getDefaultModel() together with
195 * SlotRoleRegistry::getRoleHandler(). Hard deprecated since 1.43.
196 *
197 * @param Title $title
198 *
199 * @return string Default model name for the page given by $title
200 */
201 public static function getDefaultModelFor( Title $title ) {
202 wfDeprecated( __METHOD__, '1.33' );
203 $slotRoleregistry = MediaWikiServices::getInstance()->getSlotRoleRegistry();
204 $mainSlotHandler = $slotRoleregistry->getRoleHandler( 'main' );
205 return $mainSlotHandler->getDefaultModel( $title );
206 }
207
208 /**
209 * Returns the appropriate ContentHandler singleton for the given Content
210 * object.
211 *
212 * @deprecated since 1.35, instead use
213 * ContentHandlerFactory::getContentHandler( $content->getModel() ).
214 * Hard deprecated since 1.43.
215 *
216 * @since 1.21
217 *
218 * @param Content $content
219 *
220 * @return ContentHandler
221 * @throws MWUnknownContentModelException
222 */
223 public static function getForContent( Content $content ) {
224 wfDeprecated( __METHOD__, '1.35' );
225 return MediaWikiServices::getInstance()
226 ->getContentHandlerFactory()
227 ->getContentHandler( $content->getModel() );
228 }
229
230 /**
231 * Returns the ContentHandler singleton for the given model ID. Use the
232 * CONTENT_MODEL_XXX constants to identify the desired content model.
233 *
234 * ContentHandler singletons are taken from the global $wgContentHandlers
235 * array. Keys in that array are model names, the values are either
236 * ContentHandler singleton objects, or strings specifying the appropriate
237 * subclass of ContentHandler.
238 *
239 * If a class name is encountered when looking up the singleton for a given
240 * model name, the class is instantiated and the class name is replaced by
241 * the resulting singleton in $wgContentHandlers.
242 *
243 * If no ContentHandler is defined for the desired $modelId, the
244 * ContentHandler may be provided by the ContentHandlerForModelID hook.
245 * If no ContentHandler can be determined, an MWUnknownContentModelException is raised.
246 *
247 * @since 1.21
248 *
249 * @deprecated since 1.35, use ContentHandlerFactory::getContentHandler
250 * Hard deprecated since 1.43.
251 * @see ContentHandlerFactory::getContentHandler()
252 *
253 * @param string $modelId The ID of the content model for which to get a
254 * handler. Use CONTENT_MODEL_XXX constants.
255 *
256 * @throws MWUnknownContentModelException If no handler is known for the model ID.
257 * @return ContentHandler The ContentHandler singleton for handling the model given by the ID.
258 */
259 public static function getForModelID( $modelId ) {
260 wfDeprecated( __METHOD__, '1.35' );
261 return MediaWikiServices::getInstance()
262 ->getContentHandlerFactory()
263 ->getContentHandler( $modelId );
264 }
265
266 /**
267 * Returns the localized name for a given content model.
268 *
269 * Model names are localized using system messages. Message keys
270 * have the form content-model-$name, where $name is getContentModelName( $id ).
271 *
272 * @param string $name The content model ID, as given by a CONTENT_MODEL_XXX
273 * constant or returned by Content::getModel() or SlotRecord::getModel().
274 * @param Language|null $lang The language to parse the message in (since 1.26)
275 *
276 * @return string The content model's localized name.
277 */
278 public static function getLocalizedName( $name, ?Language $lang = null ) {
279 // Messages: content-model-wikitext, content-model-text,
280 // content-model-javascript, content-model-css
281 // Lowercase the name as message keys need to be in lowercase, T358341
282 $key = "content-model-" . strtolower( $name ?? '' );
283
284 $msg = wfMessage( $key );
285 if ( $lang ) {
286 $msg->inLanguage( $lang );
287 }
288
289 return $msg->exists() ? $msg->plain() : $name;
290 }
291
292 /**
293 * @deprecated since 1.35, use ContentHandlerFactory::getContentModels
294 * Hard deprecated since 1.43.
295 * @see ContentHandlerFactory::getContentModels
296 *
297 * @return string[]
298 */
299 public static function getContentModels() {
300 wfDeprecated( __METHOD__, '1.35' );
301 return MediaWikiServices::getInstance()->getContentHandlerFactory()->getContentModels();
302 }
303
304 /**
305 * @return string[]
306 *
307 * @deprecated since 1.35, use ContentHandlerFactory::getAllContentFormats
308 * Hard deprecated since 1.43.
309 * @see ContentHandlerFactory::getAllContentFormats
310 */
311 public static function getAllContentFormats() {
312 wfDeprecated( __METHOD__, '1.35' );
313 return MediaWikiServices::getInstance()->getContentHandlerFactory()->getAllContentFormats();
314 }
315
316 // ------------------------------------------------------------------------
317
318 /**
319 * @var string
320 */
321 protected $mModelID;
322
323 /**
324 * @var string[]
325 */
326 protected $mSupportedFormats;
327
328 /**
329 * Constructor, initializing the ContentHandler instance with its model ID
330 * and a list of supported formats. Values for the parameters are typically
331 * provided as literals by subclass's constructors.
332 *
333 * @stable to call
334 *
335 * @param string $modelId (use CONTENT_MODEL_XXX constants).
336 * @param string[] $formats List for supported serialization formats
337 * (typically as MIME types)
338 */
339 public function __construct( $modelId, $formats ) {
340 $this->mModelID = $modelId;
341 $this->mSupportedFormats = $formats;
342 }
343
344 /**
345 * Serializes a Content object of the type supported by this ContentHandler.
346 *
347 * @stable to override
348 *
349 * @since 1.21
350 *
351 * @param Content $content The Content object to serialize
352 * @param string|null $format The desired serialization format
353 *
354 * @return string Serialized form of the content
355 */
356 abstract public function serializeContent( Content $content, $format = null );
357
358 /**
359 * Serializes a Content object of the type supported by this
360 * ContentHandler to an array which is JsonCodecable.
361 *
362 * @since 1.45
363 *
364 * @param Content $content The Content object to serialize
365 *
366 * @return array An array of JsonCodecable content
367 */
368 public function serializeContentToJsonArray( Content $content ): array {
369 $format = $this->getJsonFormat();
370 $blob = $this->serializeContent( $content, $format );
371 return [
372 'format' => $format,
373 'blob' => $blob,
374 ];
375 }
376
377 /**
378 * Applies transformations on export (returns the blob unchanged by default).
379 * Subclasses may override this to perform transformations such as conversion
380 * of legacy formats or filtering of internal meta-data.
381 *
382 * @stable to override
383 *
384 * @param string $blob The blob to be exported
385 * @param string|null $format The blob's serialization format
386 *
387 * @return string
388 */
389 public function exportTransform( $blob, $format = null ) {
390 return $blob;
391 }
392
393 /**
394 * Unserializes a Content object of the type supported by this ContentHandler.
395 *
396 * @stable to override
397 * @since 1.21
398 *
399 * @param string $blob Serialized form of the content
400 * @param string|null $format The format used for serialization
401 *
402 * @return Content The Content object created by deserializing $blob
403 * @throws MWContentSerializationException
404 * @see ContentJsonCodec
405 */
406 abstract public function unserializeContent( $blob, $format = null );
407
408 /**
409 * Deserializes a Content object of the type supported by this
410 * ContentHandler from a JsonCodecable array.
411 *
412 * @since 1.45
413 *
414 * @param array $json Serialized form of the content
415 *
416 * @return Content The Content object created by deserializing $blob
417 * @throws JsonException
418 * @see ContentJsonCodec
419 */
420 public function deserializeContentFromJsonArray( array $json ): Content {
421 try {
422 return $this->unserializeContent( $json['blob'], $json['format'] );
423 } catch ( MWContentSerializationException $e ) {
424 throw new JsonException( $e->getMessage() );
425 }
426 }
427
428 /**
429 * Apply import transformation (by default, returns $blob unchanged).
430 * This gives subclasses an opportunity to transform data blobs on import.
431 *
432 * @stable to override
433 * @since 1.24
434 *
435 * @param string $blob
436 * @param string|null $format
437 *
438 * @return string
439 */
440 public function importTransform( $blob, $format = null ) {
441 return $blob;
442 }
443
444 /**
445 * Creates an empty Content object of the type supported by this
446 * ContentHandler.
447 *
448 * @stable to override
449 * @since 1.21
450 *
451 * @return Content
452 */
453 abstract public function makeEmptyContent();
454
455 /**
456 * Creates a new Content object that acts as a redirect to the given page,
457 * or null if redirects are not supported by this content model.
458 *
459 * This default implementation always returns null. Subclasses supporting redirects
460 * must override this method.
461 *
462 * Note that subclasses that override this method to return a Content object
463 * should also override supportsRedirects() to return true.
464 *
465 * @stable to override
466 * @since 1.21
467 *
468 * @param Title $destination The page to redirect to.
469 * @param string $text Text to include in the redirect, if possible.
470 *
471 * @return Content|null Always null.
472 */
473 public function makeRedirectContent( Title $destination, $text = '' ) {
474 return null;
475 }
476
477 /**
478 * Returns the model id that identifies the content model this
479 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
480 *
481 * @since 1.21
482 *
483 * @return string The model ID
484 */
485 public function getModelID() {
486 return $this->mModelID;
487 }
488
489 /**
490 * @since 1.21
491 *
492 * @param string $model_id The model to check
493 *
494 * @throws MWException If the model ID is not the ID of the content model supported by this
495 * ContentHandler.
496 */
497 protected function checkModelID( $model_id ) {
498 if ( $model_id !== $this->mModelID ) {
499 throw new MWException( "Bad content model: " .
500 "expected {$this->mModelID} " .
501 "but got $model_id." );
502 }
503 }
504
505 /**
506 * Returns a list of serialization formats supported by the
507 * serializeContent() and unserializeContent() methods of this
508 * ContentHandler.
509 *
510 * @stable to override
511 * @since 1.21
512 *
513 * @return string[] List of serialization formats as MIME type like strings
514 */
515 public function getSupportedFormats() {
516 return $this->mSupportedFormats;
517 }
518
519 /**
520 * The format used for serialization/deserialization by default by this
521 * ContentHandler.
522 *
523 * This default implementation will return the first element of the array
524 * of formats that was passed to the constructor.
525 *
526 * @stable to override
527 * @since 1.21
528 *
529 * @return string The name of the default serialization format as a MIME type
530 */
531 public function getDefaultFormat() {
532 return $this->mSupportedFormats[0];
533 }
534
535 /**
536 * Allow ContentHandler to chose a non-default format for JSON
537 * serialization.
538 *
539 * In most cases will return the same as `::getDefaultFormat()`.
540 */
541 public function getJsonFormat(): string {
542 return $this->getDefaultFormat();
543 }
544
545 /**
546 * Returns true if $format is a serialization format supported by this
547 * ContentHandler, and false otherwise.
548 *
549 * Note that if $format is null, this method always returns true, because
550 * null means "use the default format".
551 *
552 * @stable to override
553 * @since 1.21
554 *
555 * @param string $format The serialization format to check
556 *
557 * @return bool
558 */
559 public function isSupportedFormat( $format ) {
560 if ( !$format ) {
561 return true; // this means "use the default"
562 }
563
564 return in_array( $format, $this->mSupportedFormats );
565 }
566
567 /**
568 * Convenient for checking whether a format provided as a parameter is actually supported.
569 *
570 * @param string $format The serialization format to check
571 *
572 * @throws MWException If the format is not supported by this content handler.
573 */
574 protected function checkFormat( $format ) {
575 if ( !$this->isSupportedFormat( $format ) ) {
576 throw new MWException(
577 "Format $format is not supported for content model "
578 . $this->getModelID()
579 );
580 }
581 }
582
583 /**
584 * Returns overrides for action handlers.
585 * Classes listed here will be used instead of the default one when
586 * (and only when) $wgActions[$action] === true. This allows subclasses
587 * to override the default action handlers.
588 *
589 * @stable to override
590 * @since 1.21
591 *
592 * @return array<string,class-string|callable|false|Action|array> An array mapping action names
593 * (typically "view", "edit", "history" etc.) to a specification according to
594 * {@see ActionFactory::getActionSpec}. Can be the full qualified class name of an Action
595 * class, a callable taking ( Article $article, IContextSource $context ) as parameters and
596 * returning an Action object, false to disable an action, an actual Action object,
597 * or an ObjectFactory specification array (can have 'class', 'services', etc.).
598 * An empty array in this default implementation.
599 *
600 * @see Action::factory
601 */
602 public function getActionOverrides() {
603 return [];
604 }
605
606 /**
607 * Factory for creating an appropriate DifferenceEngine for this content model.
608 * Since 1.32, this is only used for page-level diffs; to diff two content objects,
609 * use getSlotDiffRenderer.
610 *
611 * The DifferenceEngine subclass to use is selected in getDiffEngineClass(). The
612 * GetDifferenceEngine hook will receive the DifferenceEngine object and can replace or
613 * wrap it.
614 * (Note that in older versions of MediaWiki the hook documentation instructed extensions
615 * to return false from the hook; you should not rely on always being able to decorate
616 * the DifferenceEngine instance from the hook. If the owner of the content type wants to
617 * decorate the instance, overriding this method is a safer approach.)
618 *
619 * @todo This is page-level functionality so it should not belong to ContentHandler.
620 * Move it to a better place once one exists (e.g. PageTypeHandler).
621 *
622 * @since 1.21
623 *
624 * @param IContextSource $context Context to use, anything else will be ignored.
625 * @param int $old Revision ID we want to show and diff with.
626 * @param int|string $new Either a revision ID or one of the strings 'cur', 'prev' or 'next'.
627 * @param int $rcid FIXME: Deprecated, no longer used. Defaults to 0.
628 * @param bool $refreshCache If set, refreshes the diff cache. Defaults to false.
629 * @param bool $unhide If set, allow viewing deleted revs. Defaults to false.
630 *
631 * @return DifferenceEngine
632 */
633 public function createDifferenceEngine( IContextSource $context, $old = 0, $new = 0,
634 $rcid = 0, // FIXME: Deprecated, no longer used
635 $refreshCache = false, $unhide = false
636 ) {
637 $diffEngineClass = $this->getDiffEngineClass();
638 $differenceEngine = new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
639 $this->getHookRunner()->onGetDifferenceEngine(
640 $context, $old, $new, $refreshCache, $unhide, $differenceEngine );
641 return $differenceEngine;
642 }
643
644 /**
645 * Get an appropriate SlotDiffRenderer for this content model.
646 *
647 * @stable to override
648 * @since 1.32
649 *
650 * @param IContextSource $context
651 * @param array $options An associative array of options passed to the SlotDiffRenderer:
652 * - diff-type: (string) The text diff format
653 * - contentLanguage: (string) The language code of the content language,
654 * to be passed to the TextDiffer constructor. This is ignored if a
655 * TextDiffer object is provided.
656 * - textDiffer: (TextDiffer) A TextDiffer object to use for text
657 * comparison.
658 * @return SlotDiffRenderer
659 */
660 final public function getSlotDiffRenderer( IContextSource $context, array $options = [] ) {
661 $slotDiffRenderer = $this->getSlotDiffRendererWithOptions( $context, $options );
662 if ( get_class( $slotDiffRenderer ) === TextSlotDiffRenderer::class ) {
663 // To keep B/C, when SlotDiffRenderer is not overridden for a given content type
664 // but DifferenceEngine is, use that instead.
665 $differenceEngine = $this->createDifferenceEngine( $context );
666 if ( get_class( $differenceEngine ) !== DifferenceEngine::class ) {
667 // TODO turn this into a deprecation warning in a later release
668 LoggerFactory::getInstance( 'diff' )->info(
669 'Falling back to DifferenceEngineSlotDiffRenderer', [
670 'modelID' => $this->getModelID(),
671 'DifferenceEngine' => get_class( $differenceEngine ),
672 ] );
673 $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
674 }
675 }
676 $this->getHookRunner()->onGetSlotDiffRenderer( $this, $slotDiffRenderer, $context );
677 return $slotDiffRenderer;
678 }
679
680 /**
681 * Return the SlotDiffRenderer appropriate for this content handler.
682 * @deprecated since 1.35; use getSlotDiffRendererWithOptions instead
683 * Emitting deprecation warnings since 1.41.
684 * @param IContextSource $context
685 * @return SlotDiffRenderer|null
686 */
687 protected function getSlotDiffRendererInternal( IContextSource $context ) {
688 return null;
689 }
690
691 /**
692 * Return the SlotDiffRenderer appropriate for this content handler.
693 * @stable to override
694 *
695 * @param IContextSource $context
696 * @param array $options See getSlotDiffRenderer()
697 *
698 * @return SlotDiffRenderer
699 */
700 protected function getSlotDiffRendererWithOptions( IContextSource $context, $options = [] ) {
701 $internalRenderer = $this->getSlotDiffRendererInternal( $context );
702 // `getSlotDiffRendererInternal` has been overridden by a class using the deprecated method.
703 // Options will not work so exit early!
704 if ( $internalRenderer !== null ) {
705 wfDeprecated( 'ContentHandler::getSlotDiffRendererInternal', '1.35' );
706 return $internalRenderer;
707 }
708 return $this->createTextSlotDiffRenderer( $options );
709 }
710
711 /**
712 * Create a TextSlotDiffRenderer and inject dependencies
713 *
714 * @since 1.41
715 * @param array $options See getSlotDiffRenderer()
716 * @return TextSlotDiffRenderer
717 */
718 final protected function createTextSlotDiffRenderer( array $options = [] ): TextSlotDiffRenderer {
719 $slotDiffRenderer = new TextSlotDiffRenderer();
720
721 $services = MediaWikiServices::getInstance();
722 $slotDiffRenderer->setStatsFactory( $services->getStatsFactory() );
723 $slotDiffRenderer->setHookContainer( $services->getHookContainer() );
724 $slotDiffRenderer->setContentModel( $this->getModelID() );
725
726 if ( isset( $options['textDiffer'] ) ) {
727 $textDiffer = $options['textDiffer'];
728 } else {
729 if ( isset( $options['contentLanguage'] ) ) {
730 $language = $services->getLanguageFactory()->getLanguage( $options['contentLanguage'] );
731 } else {
732 $language = $services->getContentLanguage();
733 }
734 $config = $services->getMainConfig();
735 $textDiffer = new ManifoldTextDiffer(
736 RequestContext::getMain(),
737 $language,
738 $config->get( MainConfigNames::DiffEngine ),
739 $config->get( MainConfigNames::ExternalDiffEngine ),
740 $config->get( MainConfigNames::Wikidiff2Options )
741 );
742 }
743 $format = $options['diff-type'] ?? 'table';
744 if ( !$textDiffer->hasFormat( $format ) ) {
745 // Maybe it would be better to throw an exception here, but at
746 // present, the value comes straight from user input without
747 // validation, so we have to fall back.
748 $format = 'table';
749 }
750 $slotDiffRenderer->setFormat( $format );
751 $slotDiffRenderer->setTextDiffer( $textDiffer );
752 if ( $options['inline-toggle'] ?? false ) {
753 $slotDiffRenderer->setInlineToggleEnabled();
754 }
755
756 return $slotDiffRenderer;
757 }
758
759 /**
760 * Get the language in which the content of the given page is written.
761 *
762 * This default implementation just returns the content language (except for pages
763 * in the MediaWiki namespace)
764 *
765 * Note that the page's language is not cacheable, since it may in some
766 * cases depend on user settings.
767 *
768 * Also note that the page language may or may not depend on the actual content of the page,
769 * that is, this method may load the content in order to determine the language.
770 *
771 * @stable to override
772 * @since 1.21
773 *
774 * @param Title $title The page to determine the language for.
775 * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
776 *
777 * @return Language
778 */
779 public function getPageLanguage( Title $title, ?Content $content = null ) {
780 $services = MediaWikiServices::getInstance();
781 $pageLang = $services->getContentLanguage();
782
783 if ( $title->inNamespace( NS_MEDIAWIKI ) ) {
784 // Parse mediawiki messages with correct target language
785 [ /* $unused */, $lang ] = $services->getMessageCache()->figureMessage( $title->getText() );
786 $pageLang = $services->getLanguageFactory()->getLanguage( $lang );
787 }
788
789 // Unused, T299369
790 $userLang = null;
791 $this->getHookRunner()->onPageContentLanguage( $title, $pageLang, $userLang );
792
793 if ( !$pageLang instanceof Language ) {
794 throw new UnexpectedValueException( 'onPageContentLanguage() hook provided an invalid $pageLang object.' );
795 }
796
797 return $pageLang;
798 }
799
800 /**
801 * Get the language in which the content of this page is written when
802 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
803 * specified a preferred variant, the variant will be used.
804 *
805 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
806 * the user specified a preferred variant.
807 *
808 * Note that the pages view language is not cacheable, since it depends on user settings.
809 *
810 * Also note that the page language may or may not depend on the actual content of the page,
811 * that is, this method may load the content in order to determine the language.
812 *
813 * @stable to override
814 * @deprecated since 1.42 Use ParserOutput::getLanguage instead. See also OutputPage::getContLangForJS.
815 * @since 1.21
816 * @param Title $title The page to determine the language for.
817 * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
818 * @return Language The page's language for viewing
819 */
820 public function getPageViewLanguage( Title $title, ?Content $content = null ) {
821 $pageLang = $this->getPageLanguage( $title, $content );
822
823 if ( $title->getNamespace() !== NS_MEDIAWIKI ) {
824 // If the user chooses a variant, the content is actually
825 // in a language whose code is the variant code.
826 $variant = $this->getLanguageConverter( $pageLang )->getPreferredVariant();
827 if ( $pageLang->getCode() !== $variant ) {
828 $pageLang = MediaWikiServices::getInstance()->getLanguageFactory()
829 ->getLanguage( $variant );
830 }
831 }
832
833 return $pageLang;
834 }
835
836 /**
837 * Determines whether the content type handled by this ContentHandler
838 * can be used for the main slot of the given page.
839 *
840 * This default implementation always returns true.
841 * Subclasses may override this to restrict the use of this content model to specific locations,
842 * typically based on the namespace or some other aspect of the title, such as a special suffix
843 * (e.g. ".svg" for SVG content).
844 *
845 * @note this calls the ContentHandlerCanBeUsedOn hook which may be used to override which
846 * content model can be used where.
847 *
848 * @stable to override
849 *
850 * @see SlotRoleHandler::isAllowedModel
851 *
852 * @param Title $title The page's title.
853 *
854 * @return bool True if content of this kind can be used on the given page, false otherwise.
855 */
856 public function canBeUsedOn( Title $title ) {
857 $ok = true;
858
859 $this->getHookRunner()->onContentModelCanBeUsedOn( $this->getModelID(), $title, $ok );
860
861 return $ok;
862 }
863
864 /**
865 * Returns the name of the diff engine to use.
866 *
867 * @stable to override
868 * @since 1.21
869 *
870 * @return class-string<DifferenceEngine>
871 */
872 protected function getDiffEngineClass() {
873 return DifferenceEngine::class;
874 }
875
876 /**
877 * Attempts to merge differences between three versions. Returns a new
878 * Content object for a clean merge and false for failure or a conflict.
879 *
880 * This default implementation always returns false.
881 *
882 * @stable to override
883 * @since 1.21
884 *
885 * @param Content $oldContent The page's previous content.
886 * @param Content $myContent One of the page's conflicting contents.
887 * @param Content $yourContent One of the page's conflicting contents.
888 *
889 * @return Content|false Always false.
890 */
891 public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
892 return false;
893 }
894
895 /**
896 * Shorthand for getting a Language Converter for specific language
897 * @param Language $language Language of converter
898 * @return ILanguageConverter
899 */
900 private function getLanguageConverter( $language ): ILanguageConverter {
901 return MediaWikiServices::getInstance()->getLanguageConverterFactory()
902 ->getLanguageConverter( $language );
903 }
904
905 /**
906 * Return type of change if one exists for the given edit.
907 *
908 * @stable to override
909 * @since 1.31
910 *
911 * @param Content|null $oldContent The previous text of the page.
912 * @param Content|null $newContent The submitted text of the page.
913 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
914 *
915 * @return string|null String key representing type of change, or null.
916 */
917 private function getChangeType(
918 ?Content $oldContent = null,
919 ?Content $newContent = null,
920 $flags = 0
921 ) {
922 $oldTarget = $oldContent !== null ? $oldContent->getRedirectTarget() : null;
923 $newTarget = $newContent !== null ? $newContent->getRedirectTarget() : null;
924
925 // We check for the type of change in the given edit, and return string key accordingly
926
927 // Blanking of a page
928 if ( $oldContent && $oldContent->getSize() > 0 &&
929 $newContent && $newContent->getSize() === 0
930 ) {
931 return 'blank';
932 }
933
934 // Redirects
935 if ( $newTarget ) {
936 if ( !$oldTarget ) {
937 // New redirect page (by creating new page or by changing content page)
938 return 'new-redirect';
939 } elseif ( !$newTarget->equals( $oldTarget ) ||
940 $oldTarget->getFragment() !== $newTarget->getFragment()
941 ) {
942 // Redirect target changed
943 return 'changed-redirect-target';
944 }
945 } elseif ( $oldTarget ) {
946 // Changing an existing redirect into a non-redirect
947 return 'removed-redirect';
948 }
949
950 // New page created
951 if ( $flags & EDIT_NEW && $newContent ) {
952 if ( $newContent->getSize() === 0 ) {
953 // New blank page
954 return 'newblank';
955 } else {
956 return 'newpage';
957 }
958 }
959
960 // Removing more than 90% of the page
961 if ( $oldContent && $newContent && $oldContent->getSize() > 10 * $newContent->getSize() ) {
962 return 'replace';
963 }
964
965 // Content model changed
966 if ( $oldContent && $newContent && $oldContent->getModel() !== $newContent->getModel() ) {
967 return 'contentmodelchange';
968 }
969
970 return null;
971 }
972
973 /**
974 * Return an applicable auto-summary if one exists for the given edit.
975 *
976 * @stable to override
977 * @since 1.21
978 *
979 * @param Content|null $oldContent The previous text of the page.
980 * @param Content|null $newContent The submitted text of the page.
981 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
982 *
983 * @return string An appropriate auto-summary, or an empty string.
984 */
985 public function getAutosummary(
986 ?Content $oldContent = null,
987 ?Content $newContent = null,
988 $flags = 0
989 ) {
990 $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
991
992 // There's no applicable auto-summary for our case, so our auto-summary is empty.
993 if ( !$changeType ) {
994 return '';
995 }
996
997 // Set the maximum auto-summary length to the general maximum summary length
998 // T221617
999 $summaryLimit = CommentStore::COMMENT_CHARACTER_LIMIT;
1000
1001 // Decide what kind of auto-summary is needed.
1002 switch ( $changeType ) {
1003 case 'new-redirect':
1004 $newTarget = $newContent->getRedirectTarget();
1005 $truncatedtext = $newContent->getTextForSummary(
1006 $summaryLimit
1007 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
1008 - strlen( $newTarget->getFullText() )
1009 );
1010
1011 return wfMessage( 'autoredircomment', $newTarget->getFullText() )
1012 ->plaintextParams( $truncatedtext )->inContentLanguage()->text();
1013 case 'changed-redirect-target':
1014 $oldTarget = $oldContent->getRedirectTarget();
1015 $newTarget = $newContent->getRedirectTarget();
1016
1017 $truncatedtext = $newContent->getTextForSummary(
1018 $summaryLimit
1019 - strlen( wfMessage( 'autosumm-changed-redirect-target' )
1020 ->inContentLanguage()->text() )
1021 - strlen( $oldTarget->getFullText() )
1022 - strlen( $newTarget->getFullText() )
1023 );
1024
1025 return wfMessage( 'autosumm-changed-redirect-target',
1026 $oldTarget->getFullText(),
1027 $newTarget->getFullText() )
1028 ->rawParams( $truncatedtext )->inContentLanguage()->text();
1029 case 'removed-redirect':
1030 $oldTarget = $oldContent->getRedirectTarget();
1031 $truncatedtext = $newContent->getTextForSummary(
1032 $summaryLimit
1033 - strlen( wfMessage( 'autosumm-removed-redirect' )
1034 ->inContentLanguage()->text() )
1035 - strlen( $oldTarget->getFullText() ) );
1036
1037 return wfMessage( 'autosumm-removed-redirect', $oldTarget->getFullText() )
1038 ->rawParams( $truncatedtext )->inContentLanguage()->text();
1039 case 'newpage':
1040 // If they're making a new article, give its text, truncated, in the summary.
1041 $truncatedtext = $newContent->getTextForSummary(
1042 $summaryLimit - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
1043
1044 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
1045 ->inContentLanguage()->text();
1046 case 'blank':
1047 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
1048 case 'replace':
1049 $truncatedtext = $newContent->getTextForSummary(
1050 $summaryLimit - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
1051
1052 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
1053 ->inContentLanguage()->text();
1054 case 'newblank':
1055 return wfMessage( 'autosumm-newblank' )->inContentLanguage()->text();
1056 default:
1057 return '';
1058 }
1059 }
1060
1061 /**
1062 * Return an applicable tag if one exists for the given edit or return null.
1063 *
1064 * @stable to override
1065 * @since 1.31
1066 *
1067 * @param Content|null $oldContent The previous text of the page.
1068 * @param Content|null $newContent The submitted text of the page.
1069 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
1070 *
1071 * @return string|null An appropriate tag, or null.
1072 */
1073 public function getChangeTag(
1074 ?Content $oldContent = null,
1075 ?Content $newContent = null,
1076 $flags = 0
1077 ) {
1078 $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
1079
1080 // There's no applicable tag for this change.
1081 if ( !$changeType ) {
1082 return null;
1083 }
1084
1085 // Core tags use the same keys as ones returned from $this->getChangeType()
1086 // but prefixed with pseudo namespace 'mw-', so we add the prefix before checking
1087 // if this type of change should be tagged
1088 $tag = 'mw-' . $changeType;
1089
1090 // Not all change types are tagged, so we check against the list of defined tags.
1091 if ( in_array( $tag, MediaWikiServices::getInstance()->getChangeTagsStore()->getSoftwareTags() ) ) {
1092 return $tag;
1093 }
1094
1095 return null;
1096 }
1097
1098 /**
1099 * Auto-generates a deletion reason
1100 *
1101 * @stable to override
1102 * @since 1.21
1103 *
1104 * @param Title $title The page's title
1105 * @param bool &$hasHistory Whether the page has a history
1106 *
1107 * @return string|false String containing deletion reason or empty string, or
1108 * boolean false if no revision occurred
1109 */
1110 public function getAutoDeleteReason( Title $title, &$hasHistory = false ) {
1111 if ( func_num_args() === 2 ) {
1112 wfDeprecated( __METHOD__ . ': $hasHistory parameter', '1.38' );
1113 }
1114 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
1115 $revStore = MediaWikiServices::getInstance()->getRevisionStore();
1116
1117 // Get the last revision
1118 $revRecord = $revStore->getRevisionByTitle( $title );
1119
1120 if ( $revRecord === null ) {
1121 return false;
1122 }
1123
1124 // Get the article's contents
1125 $content = $revRecord->getContent( SlotRecord::MAIN );
1126 $blank = false;
1127
1128 // If the page is blank, use the text from the previous revision,
1129 // which can only be blank if there's a move/import/protect dummy
1130 // revision involved
1131 if ( !$content || $content->isEmpty() ) {
1132 $prev = $revStore->getPreviousRevision( $revRecord );
1133
1134 if ( $prev ) {
1135 $revRecord = $prev;
1136 $content = $prev->getContent( SlotRecord::MAIN );
1137 $blank = true;
1138 }
1139 }
1140
1141 $this->checkModelID( $revRecord->getSlot( SlotRecord::MAIN )->getModel() );
1142
1143 // Find out if there was only one contributor
1144 // Only scan the last 20 revisions
1145 $queryBuilder = $revStore->newSelectQueryBuilder( $dbr )
1146 ->where( [
1147 'rev_page' => $title->getArticleID(),
1148 $dbr->bitAnd( 'rev_deleted', RevisionRecord::DELETED_USER ) . ' = 0'
1149 ] )
1150 ->limit( 20 );
1151 $res = $queryBuilder->caller( __METHOD__ )->fetchResultSet();
1152
1153 if ( !$res->numRows() ) {
1154 // This page has no revisions, which is very weird
1155 return false;
1156 }
1157
1158 $hasHistory = ( $res->numRows() > 1 );
1159 $row = $res->fetchObject();
1160
1161 if ( $row ) { // $row is false if the only contributor is hidden
1162 $onlyAuthor = $row->rev_user_text;
1163 // Try to find a second contributor
1164 foreach ( $res as $row ) {
1165 if ( $row->rev_user_text != $onlyAuthor ) { // T24999
1166 $onlyAuthor = false;
1167 break;
1168 }
1169 }
1170 } else {
1171 $onlyAuthor = false;
1172 }
1173
1174 // Generate the summary with a '$1' placeholder
1175 if ( $blank ) {
1176 // The current revision is blank and the one before is also
1177 // blank. It's just not our lucky day
1178 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
1179 } else {
1180 if ( $onlyAuthor ) {
1181 $reason = wfMessage(
1182 'excontentauthor',
1183 '$1',
1184 $onlyAuthor
1185 )->inContentLanguage()->text();
1186 } else {
1187 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
1188 }
1189 }
1190
1191 if ( $reason == '-' ) {
1192 // Allow these UI messages to be blanked out cleanly
1193 return '';
1194 }
1195
1196 // Max content length = max comment length - length of the comment (excl. $1)
1197 $maxLength = CommentStore::COMMENT_CHARACTER_LIMIT - ( strlen( $reason ) - 2 );
1198 $text = $content ? $content->getTextForSummary( $maxLength ) : '';
1199
1200 // Now replace the '$1' placeholder
1201 $reason = str_replace( '$1', $text, $reason );
1202
1203 return $reason;
1204 }
1205
1206 /**
1207 * Get the Content object that needs to be saved in order to undo all changes
1208 * between $undo and $undoafter.
1209 *
1210 * @stable to override
1211 * @since 1.21
1212 * @since 1.32 accepts Content objects for all parameters instead of Revision objects.
1213 * Passing Revision objects is deprecated.
1214 * @since 1.37 only accepts Content objects
1215 *
1216 * @param Content $currentContent The current text
1217 * @param Content $undoContent The content of the revision to undo
1218 * @param Content $undoAfterContent Must be from an earlier revision than $undo
1219 * @param bool $undoIsLatest Set true if $undo is from the current revision (since 1.32)
1220 *
1221 * @return Content|false Content on success, false on failure
1222 */
1223 public function getUndoContent(
1224 Content $currentContent,
1225 Content $undoContent,
1226 Content $undoAfterContent,
1227 $undoIsLatest = false
1228 ) {
1229 try {
1230 $this->checkModelID( $currentContent->getModel() );
1231 $this->checkModelID( $undoContent->getModel() );
1232 if ( !$undoIsLatest ) {
1233 // If we are undoing the most recent revision,
1234 // its ok to revert content model changes. However
1235 // if we are undoing a revision in the middle, then
1236 // doing that will be confusing.
1237 $this->checkModelID( $undoAfterContent->getModel() );
1238 }
1239 } catch ( MWException $e ) {
1240 // If the revisions have different content models
1241 // just return false
1242 return false;
1243 }
1244
1245 if ( $currentContent->equals( $undoContent ) ) {
1246 // No use doing a merge if it's just a straight revert.
1247 return $undoAfterContent;
1248 }
1249
1250 $undone_content = $this->merge3( $undoContent, $undoAfterContent, $currentContent );
1251
1252 return $undone_content;
1253 }
1254
1255 /**
1256 * Returns true for content models that support caching using the
1257 * ParserCache mechanism. See WikiPage::shouldCheckParserCache().
1258 *
1259 * @stable to override
1260 * @since 1.21
1261 *
1262 * @return bool Always false.
1263 */
1264 public function isParserCacheSupported() {
1265 return false;
1266 }
1267
1268 /**
1269 * Returns true if this content model supports sections.
1270 * This default implementation returns false.
1271 *
1272 * Content models that return true here should also implement
1273 * Content::getSection, Content::replaceSection, etc. to handle sections.
1274 *
1275 * @stable to override
1276 *
1277 * @return bool Always false.
1278 */
1279 public function supportsSections() {
1280 return false;
1281 }
1282
1283 /**
1284 * Returns true if this content model supports categories.
1285 * The default implementation returns true.
1286 *
1287 * @stable to override
1288 *
1289 * @return bool Always true.
1290 */
1291 public function supportsCategories() {
1292 return true;
1293 }
1294
1295 /**
1296 * Returns true if this content model supports redirects.
1297 * This default implementation returns false.
1298 *
1299 * Content models that return true here should also implement
1300 * ContentHandler::makeRedirectContent to return a Content object.
1301 *
1302 * @stable to override
1303 *
1304 * @return bool Always false.
1305 */
1306 public function supportsRedirects() {
1307 return false;
1308 }
1309
1310 /**
1311 * Return true if this content model supports direct editing, such as via EditPage.
1312 * This should return true for TextContent and its derivatives, and return false
1313 * for structured data content.
1314 *
1315 * @stable to override
1316 *
1317 * @return bool Default is false.
1318 */
1319 public function supportsDirectEditing() {
1320 return false;
1321 }
1322
1323 /**
1324 * If a non-existing page can be created with the contents from another (arbitrary) page being
1325 * preloaded in the editor, see {@see EditPage::getContentObject}. Only makes sense together
1326 * with {@see supportsDirectEditing}.
1327 *
1328 * @stable to override
1329 * @since 1.39
1330 *
1331 * @return bool
1332 */
1333 public function supportsPreloadContent(): bool {
1334 return false;
1335 }
1336
1337 /**
1338 * Whether an edit on the content should trigger an HTML render and ParserCache entry.
1339 *
1340 * @stable to override
1341 * @since 1.37
1342 *
1343 * @return bool true if edit should trigger an HTML render false otherwise
1344 */
1345 public function generateHTMLOnEdit(): bool {
1346 return true;
1347 }
1348
1349 /**
1350 * Whether or not this content model supports direct editing via ApiEditPage
1351 *
1352 * @stable to override
1353 *
1354 * @return bool Default is false, and true for TextContent and derivatives.
1355 */
1356 public function supportsDirectApiEditing() {
1357 return $this->supportsDirectEditing();
1358 }
1359
1360 /**
1361 * Get fields definition for search index
1362 *
1363 * @todo Expose title, redirect, namespace, text, source_text, text_bytes
1364 * field mappings here. (see T142670 and T143409)
1365 *
1366 * @stable to override
1367 *
1368 * @param SearchEngine $engine
1369 * @return SearchIndexField[] List of fields this content handler can provide.
1370 * @since 1.28
1371 */
1372 public function getFieldsForSearchIndex( SearchEngine $engine ) {
1373 $fields = [];
1374 $fields['category'] = $engine->makeSearchFieldMapping(
1375 'category',
1376 SearchIndexField::INDEX_TYPE_TEXT
1377 );
1378 $fields['category']->setFlag( SearchIndexField::FLAG_CASEFOLD );
1379
1380 $fields['external_link'] = $engine->makeSearchFieldMapping(
1381 'external_link',
1382 SearchIndexField::INDEX_TYPE_KEYWORD
1383 );
1384
1385 $fields['outgoing_link'] = $engine->makeSearchFieldMapping(
1386 'outgoing_link',
1387 SearchIndexField::INDEX_TYPE_KEYWORD
1388 );
1389
1390 $fields['template'] = $engine->makeSearchFieldMapping(
1391 'template',
1392 SearchIndexField::INDEX_TYPE_KEYWORD
1393 );
1394 $fields['template']->setFlag( SearchIndexField::FLAG_CASEFOLD );
1395
1396 $fields['content_model'] = $engine->makeSearchFieldMapping(
1397 'content_model',
1398 SearchIndexField::INDEX_TYPE_KEYWORD
1399 );
1400
1401 return $fields;
1402 }
1403
1404 /**
1405 * Add new field definition to array.
1406 * @param SearchIndexField[] &$fields
1407 * @param SearchEngine $engine
1408 * @param string $name
1409 * @param string $type
1410 * @return SearchIndexField[] new field defs
1411 * @since 1.28
1412 */
1413 protected function addSearchField( &$fields, SearchEngine $engine, $name, $type ) {
1414 $fields[$name] = $engine->makeSearchFieldMapping( $name, $type );
1415 return $fields;
1416 }
1417
1418 /**
1419 * Return fields to be indexed by search engine
1420 * as representation of this document.
1421 * Overriding class should call parent function or take care of calling
1422 * the SearchDataForIndex hook.
1423 *
1424 * The $output must be the result of a call to {@link getParserOutputForIndexing()}
1425 * on the same content handler. That method may return ParserOutput
1426 * {@link ParserOutput::hasText() without HTML}; this base implementation
1427 * does not rely on the HTML being present, so it is safe to call
1428 * even by subclasses that override {@link getParserOutputForIndexing()}
1429 * to skip HTML generation. On the other hand,
1430 * since the default implementation of {@link getParserOutputForIndexing()}
1431 * does generate HTML, subclasses are free to rely on the HTML here
1432 * if they do not override {@link getParserOutputForIndexing()}.
1433 *
1434 * @stable to override
1435 * @param WikiPage $page Page to index
1436 * @param ParserOutput $output
1437 * @param SearchEngine $engine Search engine for which we are indexing
1438 * @param RevisionRecord|null $revision Revision content to fetch if provided or use the latest revision
1439 * from WikiPage::getRevisionRecord() if not
1440 * @return array Map of name=>value for fields, an empty array is returned if the latest
1441 * revision cannot be retrieved.
1442 * @since 1.28
1443 */
1444 public function getDataForSearchIndex(
1445 WikiPage $page,
1446 ParserOutput $output,
1447 SearchEngine $engine,
1448 ?RevisionRecord $revision = null
1449 ) {
1450 $revision ??= $page->getRevisionRecord();
1451 if ( $revision === null ) {
1452 LoggerFactory::getInstance( 'search' )->warning(
1453 "Called getDataForSearchIndex on the page {page_id} for which the " .
1454 "latest revision cannot be loaded.",
1455 [ "page_id" => $page->getId() ]
1456 );
1457 return [];
1458 }
1459 Assert::invariant( $revision->getPageId() === $page->getId(),
1460 '$revision and $page must target the same page_id' );
1461
1462 $fieldData = [];
1463 $content = $revision->getContent( SlotRecord::MAIN );
1464
1465 if ( $content ) {
1466 $searchDataExtractor = new ParserOutputSearchDataExtractor();
1467
1468 $fieldData['category'] = $searchDataExtractor->getCategories( $output );
1469 $fieldData['external_link'] = $searchDataExtractor->getExternalLinks( $output );
1470 $fieldData['outgoing_link'] = $searchDataExtractor->getOutgoingLinks( $output );
1471 $fieldData['template'] = $searchDataExtractor->getTemplates( $output );
1472
1473 $text = $content->getTextForSearchIndex();
1474
1475 $fieldData['text'] = $text;
1476 $fieldData['source_text'] = $text;
1477 $fieldData['text_bytes'] = $content->getSize();
1478 $fieldData['content_model'] = $content->getModel();
1479 }
1480
1481 $this->getHookRunner()->onSearchDataForIndex( $fieldData, $this, $page, $output, $engine );
1482 $this->getHookRunner()->onSearchDataForIndex2( $fieldData, $this, $page, $output, $engine, $revision );
1483
1484 return $fieldData;
1485 }
1486
1487 /**
1488 * Produce page output suitable for indexing.
1489 * Typically used with {@link getDataForSearchIndex()}.
1490 *
1491 * Specific content handlers may override it if they need different content handling.
1492 *
1493 * The default implementation returns output {@link ParserOutput::hasText() with HTML},
1494 * but callers should not rely on this, and subclasses may override this method
1495 * and skip HTML generation if it is not needed for indexing.
1496 * (In that case, they should not attempt to store the output in the $cache.)
1497 *
1498 * @stable to override
1499 *
1500 * @param WikiPage $page
1501 * @param ParserCache|null $cache deprecated since 1.38 and won't have any effect
1502 * @param RevisionRecord|null $revision
1503 * @return ParserOutput|null null when the ParserOutput cannot be obtained
1504 * @see ParserOutputAccess::getParserOutput() for failure modes
1505 */
1506 public function getParserOutputForIndexing(
1507 WikiPage $page,
1508 ?ParserCache $cache = null,
1509 ?RevisionRecord $revision = null
1510 ) {
1511 // TODO: MCR: ContentHandler should be called per slot, not for the whole page.
1512 // See T190066.
1513 $parserOptions = $page->makeParserOptions( 'canonical' );
1514 $parserOptions->setRenderReason( 'ParserOutputForIndexing' );
1515 $parserOutputAccess = MediaWikiServices::getInstance()->getParserOutputAccess();
1516 return $parserOutputAccess->getParserOutput(
1517 $page,
1518 $parserOptions,
1519 $revision,
1520 ParserOutputAccess::OPT_NO_UPDATE_CACHE
1521 )->getValue();
1522 }
1523
1524 /**
1525 * Get the latest revision of the given $page,
1526 * fetching it from the primary if necessary.
1527 *
1528 * @param WikiPage $page
1529 * @return RevisionRecord
1530 * @since 1.36 (previously private)
1531 */
1532 protected function latestRevision( WikiPage $page ): RevisionRecord {
1533 $revRecord = $page->getRevisionRecord();
1534 if ( $revRecord == null ) {
1535 // If the content represents a brand new page it's possible
1536 // we need to fetch it from the primary.
1537 $page->loadPageData( IDBAccessObject::READ_LATEST );
1538 $revRecord = $page->getRevisionRecord();
1539 if ( $revRecord == null ) {
1540 $text = $page->getTitle()->getPrefixedText();
1541 throw new MWException(
1542 "No revision could be loaded for page: $text" );
1543 }
1544 }
1545
1546 return $revRecord;
1547 }
1548
1549 /**
1550 * Returns a list of DeferrableUpdate objects for recording information about the
1551 * given Content in some secondary data store.
1552 *
1553 * Application logic should not call this method directly. Instead, it should call
1554 * DerivedPageDataUpdater::getSecondaryDataUpdates().
1555 *
1556 * @note Implementations must not return a LinksUpdate instance. Instead, a LinksUpdate
1557 * is created by the calling code in DerivedPageDataUpdater, on the combined ParserOutput
1558 * of all slots, not for each slot individually. This is in contrast to the old
1559 * getSecondaryDataUpdates method defined by AbstractContent, which returned a LinksUpdate.
1560 *
1561 * @note Implementations should not call $content->getParserOutput, they should call
1562 * $slotOutput->getSlotRendering( $role, false ) instead if they need to access a ParserOutput
1563 * of $content. This allows existing ParserOutput objects to be re-used, while avoiding
1564 * creating a ParserOutput when none is needed.
1565 *
1566 * @stable to override
1567 *
1568 * @param Title $title The title of the page to supply the updates for
1569 * @param Content $content The content to generate data updates for.
1570 * @param string $role The role (slot) in which the content is being used. Which updates
1571 * are performed should generally not depend on the role the content has, but the
1572 * DeferrableUpdates themselves may need to know the role, to track to which slot the
1573 * data refers, and to avoid overwriting data of the same kind from another slot.
1574 * @param SlotRenderingProvider $slotOutput A provider that can be used to gain access to
1575 * a ParserOutput of $content by calling $slotOutput->getSlotParserOutput( $role, false ).
1576 * @return DeferrableUpdate[] A list of DeferrableUpdate objects for putting information
1577 * about this content object somewhere. The default implementation returns an empty
1578 * array.
1579 * @since 1.32
1580 */
1581 public function getSecondaryDataUpdates(
1582 Title $title,
1583 Content $content,
1584 $role,
1585 SlotRenderingProvider $slotOutput
1586 ) {
1587 return [];
1588 }
1589
1590 /**
1591 * Returns a list of DeferrableUpdate objects for removing information about content
1592 * in some secondary data store. This is used when a page is deleted, and also when
1593 * a slot is removed from a page.
1594 *
1595 * Application logic should not call this method directly. Instead, it should call
1596 * WikiPage::getSecondaryDataUpdates().
1597 *
1598 * @note Implementations must not return a LinksDeletionUpdate instance. Instead, a
1599 * LinksDeletionUpdate is created by the calling code in WikiPage.
1600 * This is in contrast to the old getDeletionUpdates method defined by AbstractContent,
1601 * which returned a LinksUpdate.
1602 *
1603 * @note Implementations should not rely on the page's current content, but rather the current
1604 * state of the secondary data store.
1605 *
1606 * @stable to override
1607 *
1608 * @param Title $title The title of the page to supply the updates for
1609 * @param string $role The role (slot) in which the content is being used. Which updates
1610 * are performed should generally not depend on the role the content has, but the
1611 * DeferrableUpdates themselves may need to know the role, to track to which slot the
1612 * data refers, and to avoid overwriting data of the same kind from another slot.
1613 *
1614 * @return DeferrableUpdate[] A list of DeferrableUpdate objects for putting information
1615 * about this content object somewhere. The default implementation returns an empty
1616 * array.
1617 *
1618 * @since 1.32
1619 */
1620 public function getDeletionUpdates( Title $title, $role ) {
1621 return [];
1622 }
1623
1624 /**
1625 * Returns a $content object with pre-save transformations applied (or the same
1626 * object if no transformations apply).
1627 *
1628 * @note Not stable to call other then from ContentHandler hierarchy.
1629 * Callers need to use ContentTransformer::preSaveTransform.
1630 * @stable to override
1631 * @since 1.37
1632 *
1633 * @param Content $content
1634 * @param PreSaveTransformParams $pstParams
1635 *
1636 * @return Content
1637 */
1638 public function preSaveTransform(
1639 Content $content,
1640 PreSaveTransformParams $pstParams
1641 ): Content {
1642 return $content;
1643 }
1644
1645 /**
1646 * Returns a $content object with preload transformations applied (or the same
1647 * object if no transformations apply).
1648 *
1649 * @note Not stable to call other then from ContentHandler hierarchy.
1650 * Callers need to use ContentTransformer::preLoadTransform.
1651 * @stable to override
1652 * @since 1.37
1653 *
1654 * @param Content $content
1655 * @param PreloadTransformParams $pltParams
1656 *
1657 * @return Content
1658 */
1659 public function preloadTransform(
1660 Content $content,
1661 PreloadTransformParams $pltParams
1662 ): Content {
1663 return $content;
1664 }
1665
1666 /**
1667 * Validate content for saving it.
1668 *
1669 * This may be used to check the content's consistency with global state. This function should
1670 * NOT write any information to the database.
1671 *
1672 * Note that this method will usually be called inside the same transaction
1673 * bracket that will be used to save the new revision, so the revision passed
1674 * in is probably unsaved (has no id) and might belong to unsaved page.
1675 *
1676 * @since 1.38
1677 * @stable to override
1678 *
1679 * @param Content $content
1680 * @param ValidationParams $validationParams
1681 *
1682 * @return StatusValue A status object indicating if content can be saved in the given revision.
1683 */
1684 public function validateSave(
1685 Content $content,
1686 ValidationParams $validationParams
1687 ) {
1688 if ( $content->isValid() ) {
1689 return StatusValue::newGood();
1690 } else {
1691 return StatusValue::newFatal( "invalid-content-data" );
1692 }
1693 }
1694
1695 /**
1696 * Returns a ParserOutput object containing information derived from this content.
1697 * Most importantly, unless $cpoParams->getGenerateHtml was false, the return value contains an
1698 * HTML representation of the content.
1699 *
1700 * Subclasses that want to control the parser output may override
1701 * fillParserOutput() instead.
1702 *
1703 *
1704 *
1705 * @since 1.38
1706 *
1707 * @param Content $content
1708 * @param ContentParseParams $cpoParams
1709 * @return ParserOutput Containing information derived from this content.
1710 */
1711 public function getParserOutput(
1712 Content $content,
1713 ContentParseParams $cpoParams
1714 ) {
1715 $services = MediaWikiServices::getInstance();
1716 $title = $services->getTitleFactory()->newFromPageReference( $cpoParams->getPage() );
1717 $parserOptions = $cpoParams->getParserOptions();
1718
1719 if ( $parserOptions->getIsPreview() ) {
1720 $scopedCallback = $parserOptions->setupFakeRevision( $title, $content, $parserOptions->getUserIdentity() );
1721 }
1722
1723 $hookRunner = new HookRunner( $services->getHookContainer() );
1724
1725 $po = new ParserOutput();
1726
1727 // Initialize to the page language
1728 $po->setLanguage( $title->getPageLanguage() );
1729
1730 $parserOptions->registerWatcher( [ &$po, 'recordOption' ] );
1731 if ( $hookRunner->onContentGetParserOutput(
1732 // FIXME $cpoParams->getRevId() may be null here?
1733 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
1734 $content, $title, $cpoParams->getRevId(), $parserOptions, $cpoParams->getGenerateHtml(), $po )
1735 ) {
1736 // Save and restore the old value, just in case something is reusing
1737 // the ParserOptions object in some weird way.
1738 $oldRedir = $parserOptions->getRedirectTarget();
1739 $parserOptions->setRedirectTarget( $content->getRedirectTarget() );
1740
1741 $po->resetParseStartTime();
1742 $this->fillParserOutput(
1743 $content,
1744 $cpoParams,
1745 $po
1746 );
1747 $po->recordTimeProfile();
1748
1749 MediaWikiServices::getInstance()->get( '_ParserObserver' )->notifyParse(
1750 $title,
1751 $cpoParams->getRevId(),
1752 $parserOptions,
1753 $content,
1754 $po
1755 );
1756 $parserOptions->setRedirectTarget( $oldRedir );
1757 }
1758
1759 $hookRunner->onContentAlterParserOutput( $content, $title, $po );
1760 $parserOptions->registerWatcher( null );
1761 if ( isset( $scopedCallback ) ) {
1762 ScopedCallback::consume( $scopedCallback );
1763 }
1764
1765 return $po;
1766 }
1767
1768 /**
1769 * A temporary layer to move AbstractContent::fillParserOutput to ContentHandler::fillParserOutput
1770 *
1771 * @internal only core AbstractContent::fillParserOutput implementations need to call this.
1772 * @since 1.38
1773 * @param Content $content
1774 * @param ContentParseParams $cpoParams
1775 * @param ParserOutput &$output The output object to fill (reference).
1776 */
1777 public function fillParserOutputInternal(
1778 Content $content,
1779 ContentParseParams $cpoParams,
1780 ParserOutput &$output
1781 ) {
1782 $this->fillParserOutput( $content, $cpoParams, $output );
1783 }
1784
1785 /**
1786 * Fills the provided ParserOutput with information derived from the content.
1787 * Unless $cpoParams->getGenerateHtml() was false,
1788 * this includes an HTML representation of the content.
1789 *
1790 * If $cpoParams->getGenerateHtml() is false, and you chose not to generate
1791 * html, the ParserOutput must have a text of null. If the
1792 * text of the ParserOutput object is anything other than null (even if ''),
1793 * it is assumed that you don't support not generating html, and that it is
1794 * safe to reuse the parser output for calls expecting that html was generated.
1795 *
1796 * Subclasses are expected to override this method.
1797 *
1798 * This placeholder implementation always throws an exception.
1799 *
1800 * @stable to override
1801 *
1802 * @since 1.38
1803 * @param Content $content
1804 * @param ContentParseParams $cpoParams
1805 * @param ParserOutput &$output The output object to fill (reference).
1806 * Most implementations should modify the output object passed in here;
1807 * if you choose to replace it with a fresh object instead,
1808 * make sure you call {@link ParserOutput::resetParseStartTime()} on it.
1809 */
1810 protected function fillParserOutput(
1811 Content $content,
1812 ContentParseParams $cpoParams,
1813 ParserOutput &$output
1814 ) {
1815 // Subclasses must override fillParserOutput() to directly don't fail.
1816 throw new LogicException( 'Subclasses of ContentHandler must override fillParserOutput!' );
1817 }
1818
1819 }
1820
1821 /** @deprecated class alias since 1.43 */
1822 class_alias( ContentHandler::class, 'ContentHandler' );