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