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