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