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