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