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