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