Added docu headers to content(handler) files
[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 * @static
84 * @param $content Content|null
85 * @return null|string the textual form of $content, if available
86 * @throws MWException if $content is not an instance of TextContent and
87 * $wgContentHandlerTextFallback was set to 'fail'.
88 */
89 public static function getContentText( Content $content = null ) {
90 global $wgContentHandlerTextFallback;
91
92 if ( is_null( $content ) ) {
93 return '';
94 }
95
96 if ( $content instanceof TextContent ) {
97 return $content->getNativeData();
98 }
99
100 if ( $wgContentHandlerTextFallback == 'fail' ) {
101 throw new MWException(
102 "Attempt to get text from Content with model " .
103 $content->getModel()
104 );
105 }
106
107 if ( $wgContentHandlerTextFallback == 'serialize' ) {
108 return $content->serialize();
109 }
110
111 return null;
112 }
113
114 /**
115 * Convenience function for creating a Content object from a given textual
116 * representation.
117 *
118 * $text will be deserialized into a Content object of the model specified
119 * by $modelId (or, if that is not given, $title->getContentModel()) using
120 * the given format.
121 *
122 * @since 1.21
123 *
124 * @static
125 *
126 * @param $text string the textual representation, will be
127 * unserialized to create the Content object
128 * @param $title null|Title the title of the page this text belongs to.
129 * Required if $modelId is not provided.
130 * @param $modelId null|string the model to deserialize to. If not provided,
131 * $title->getContentModel() is used.
132 * @param $format null|string the format to use for deserialization. If not
133 * given, the model's default format is used.
134 *
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 * @static
186 * @param $title Title
187 * @return null|string default model name for the page given by $title
188 */
189 public static function getDefaultModelFor( Title $title ) {
190 global $wgNamespaceContentModels;
191
192 // NOTE: this method must not rely on $title->getContentModel() directly or indirectly,
193 // because it is used to initialize the mContentModel member.
194
195 $ns = $title->getNamespace();
196
197 $ext = false;
198 $m = null;
199 $model = null;
200
201 if ( !empty( $wgNamespaceContentModels[ $ns ] ) ) {
202 $model = $wgNamespaceContentModels[ $ns ];
203 }
204
205 // Hook can determine default model
206 if ( !wfRunHooks( 'ContentHandlerDefaultModelFor', array( $title, &$model ) ) ) {
207 if ( !is_null( $model ) ) {
208 return $model;
209 }
210 }
211
212 // Could this page contain custom CSS or JavaScript, based on the title?
213 $isCssOrJsPage = NS_MEDIAWIKI == $ns && preg_match( '!\.(css|js)$!u', $title->getText(), $m );
214 if ( $isCssOrJsPage ) {
215 $ext = $m[1];
216 }
217
218 // Hook can force JS/CSS
219 wfRunHooks( 'TitleIsCssOrJsPage', array( $title, &$isCssOrJsPage ) );
220
221 // Is this a .css subpage of a user page?
222 $isJsCssSubpage = NS_USER == $ns
223 && !$isCssOrJsPage
224 && preg_match( "/\\/.*\\.(js|css)$/", $title->getText(), $m );
225 if ( $isJsCssSubpage ) {
226 $ext = $m[1];
227 }
228
229 // Is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
230 $isWikitext = is_null( $model ) || $model == CONTENT_MODEL_WIKITEXT;
231 $isWikitext = $isWikitext && !$isCssOrJsPage && !$isJsCssSubpage;
232
233 // Hook can override $isWikitext
234 wfRunHooks( 'TitleIsWikitextPage', array( $title, &$isWikitext ) );
235
236 if ( !$isWikitext ) {
237 switch ( $ext ) {
238 case 'js':
239 return CONTENT_MODEL_JAVASCRIPT;
240 case 'css':
241 return CONTENT_MODEL_CSS;
242 default:
243 return is_null( $model ) ? CONTENT_MODEL_TEXT : $model;
244 }
245 }
246
247 // We established that it must be wikitext
248
249 return CONTENT_MODEL_WIKITEXT;
250 }
251
252 /**
253 * Returns the appropriate ContentHandler singleton for the given title.
254 *
255 * @since 1.21
256 *
257 * @static
258 * @param $title Title
259 * @return ContentHandler
260 */
261 public static function getForTitle( Title $title ) {
262 $modelId = $title->getContentModel();
263 return ContentHandler::getForModelID( $modelId );
264 }
265
266 /**
267 * Returns the appropriate ContentHandler singleton for the given Content
268 * object.
269 *
270 * @since 1.21
271 *
272 * @static
273 * @param $content Content
274 * @return ContentHandler
275 */
276 public static function getForContent( Content $content ) {
277 $modelId = $content->getModel();
278 return ContentHandler::getForModelID( $modelId );
279 }
280
281 /**
282 * @var Array A Cache of ContentHandler instances by model id
283 */
284 static $handlers;
285
286 /**
287 * Returns the ContentHandler singleton for the given model ID. Use the
288 * CONTENT_MODEL_XXX constants to identify the desired content model.
289 *
290 * ContentHandler singletons are taken from the global $wgContentHandlers
291 * array. Keys in that array are model names, the values are either
292 * ContentHandler singleton objects, or strings specifying the appropriate
293 * subclass of ContentHandler.
294 *
295 * If a class name is encountered when looking up the singleton for a given
296 * model name, the class is instantiated and the class name is replaced by
297 * the resulting singleton in $wgContentHandlers.
298 *
299 * If no ContentHandler is defined for the desired $modelId, the
300 * ContentHandler may be provided by the ContentHandlerForModelID hook.
301 * If no ContentHandler can be determined, an MWException is raised.
302 *
303 * @since 1.21
304 *
305 * @static
306 * @param $modelId String 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 ContentHandler::$handlers[$modelId] = $handler;
341 return ContentHandler::$handlers[$modelId];
342 }
343
344 /**
345 * Returns the localized name for a given content model.
346 *
347 * Model names are localized using system messages. Message keys
348 * have the form content-model-$name, where $name is getContentModelName( $id ).
349 *
350 * @static
351 * @param $name String The content model ID, as given by a CONTENT_MODEL_XXX
352 * constant or returned by Revision::getContentModel().
353 *
354 * @return string The content format's localized name.
355 * @throws MWException if the model id isn't known.
356 */
357 public static function getLocalizedName( $name ) {
358 $key = "content-model-$name";
359
360 $msg = wfMessage( $key );
361
362 return $msg->exists() ? $msg->plain() : $name;
363 }
364
365 public static function getContentModels() {
366 global $wgContentHandlers;
367
368 return array_keys( $wgContentHandlers );
369 }
370
371 public static function getAllContentFormats() {
372 global $wgContentHandlers;
373
374 $formats = array();
375
376 foreach ( $wgContentHandlers as $model => $class ) {
377 $handler = ContentHandler::getForModelID( $model );
378 $formats = array_merge( $formats, $handler->getSupportedFormats() );
379 }
380
381 $formats = array_unique( $formats );
382 return $formats;
383 }
384
385 // ------------------------------------------------------------------------
386
387 protected $mModelID;
388 protected $mSupportedFormats;
389
390 /**
391 * Constructor, initializing the ContentHandler instance with its model ID
392 * and a list of supported formats. Values for the parameters are typically
393 * provided as literals by subclass's constructors.
394 *
395 * @param $modelId String (use CONTENT_MODEL_XXX constants).
396 * @param $formats array List for supported serialization formats
397 * (typically as MIME types)
398 */
399 public function __construct( $modelId, $formats ) {
400 $this->mModelID = $modelId;
401 $this->mSupportedFormats = $formats;
402
403 $this->mModelName = preg_replace( '/(Content)?Handler$/', '', get_class( $this ) );
404 $this->mModelName = preg_replace( '/[_\\\\]/', '', $this->mModelName );
405 $this->mModelName = strtolower( $this->mModelName );
406 }
407
408 /**
409 * Serializes a Content object of the type supported by this ContentHandler.
410 *
411 * @since 1.21
412 *
413 * @abstract
414 * @param $content Content The Content object to serialize
415 * @param $format null|String The desired serialization format
416 * @return string Serialized form of the content
417 */
418 public abstract function serializeContent( Content $content, $format = null );
419
420 /**
421 * Unserializes a Content object of the type supported by this ContentHandler.
422 *
423 * @since 1.21
424 *
425 * @abstract
426 * @param $blob string serialized form of the content
427 * @param $format null|String the format used for serialization
428 * @return Content the Content object created by deserializing $blob
429 */
430 public abstract function unserializeContent( $blob, $format = null );
431
432 /**
433 * Creates an empty Content object of the type supported by this
434 * ContentHandler.
435 *
436 * @since 1.21
437 *
438 * @return Content
439 */
440 public abstract function makeEmptyContent();
441
442 /**
443 * Creates a new Content object that acts as a redirect to the given page,
444 * or null of redirects are not supported by this content model.
445 *
446 * This default implementation always returns null. Subclasses supporting redirects
447 * must override this method.
448 *
449 * @since 1.21
450 *
451 * @param Title $destination the page to redirect to.
452 *
453 * @return Content
454 */
455 public function makeRedirectContent( Title $destination ) {
456 return null;
457 }
458
459 /**
460 * Returns the model id that identifies the content model this
461 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
462 *
463 * @since 1.21
464 *
465 * @return String The model ID
466 */
467 public function getModelID() {
468 return $this->mModelID;
469 }
470
471 /**
472 * Throws an MWException if $model_id is not the ID of the content model
473 * supported by this ContentHandler.
474 *
475 * @since 1.21
476 *
477 * @param String $model_id The model to check
478 *
479 * @throws MWException
480 */
481 protected function checkModelID( $model_id ) {
482 if ( $model_id !== $this->mModelID ) {
483 throw new MWException( "Bad content model: " .
484 "expected {$this->mModelID} " .
485 "but got $model_id." );
486 }
487 }
488
489 /**
490 * Returns a list of serialization formats supported by the
491 * serializeContent() and unserializeContent() methods of this
492 * ContentHandler.
493 *
494 * @since 1.21
495 *
496 * @return array of serialization formats as MIME type like strings
497 */
498 public function getSupportedFormats() {
499 return $this->mSupportedFormats;
500 }
501
502 /**
503 * The format used for serialization/deserialization by default by this
504 * ContentHandler.
505 *
506 * This default implementation will return the first element of the array
507 * of formats that was passed to the constructor.
508 *
509 * @since 1.21
510 *
511 * @return string the name of the default serialization format as a MIME type
512 */
513 public function getDefaultFormat() {
514 return $this->mSupportedFormats[0];
515 }
516
517 /**
518 * Returns true if $format is a serialization format supported by this
519 * ContentHandler, and false otherwise.
520 *
521 * Note that if $format is null, this method always returns true, because
522 * null means "use the default format".
523 *
524 * @since 1.21
525 *
526 * @param $format string the serialization format to check
527 * @return bool
528 */
529 public function isSupportedFormat( $format ) {
530
531 if ( !$format ) {
532 return true; // this means "use the default"
533 }
534
535 return in_array( $format, $this->mSupportedFormats );
536 }
537
538 /**
539 * Throws an MWException if isSupportedFormat( $format ) is not true.
540 * Convenient for checking whether a format provided as a parameter is
541 * actually supported.
542 *
543 * @param $format string the serialization format to check
544 *
545 * @throws MWException
546 */
547 protected function checkFormat( $format ) {
548 if ( !$this->isSupportedFormat( $format ) ) {
549 throw new MWException(
550 "Format $format is not supported for content model "
551 . $this->getModelID()
552 );
553 }
554 }
555
556 /**
557 * Returns overrides for action handlers.
558 * Classes listed here will be used instead of the default one when
559 * (and only when) $wgActions[$action] === true. This allows subclasses
560 * to override the default action handlers.
561 *
562 * @since 1.21
563 *
564 * @return Array
565 */
566 public function getActionOverrides() {
567 return array();
568 }
569
570 /**
571 * Factory for creating an appropriate DifferenceEngine for this content model.
572 *
573 * @since 1.21
574 *
575 * @param $context IContextSource context to use, anything else will be
576 * ignored
577 * @param $old Integer Old ID we want to show and diff with.
578 * @param $new int|string String either 'prev' or 'next'.
579 * @param $rcid Integer ??? FIXME (default 0)
580 * @param $refreshCache boolean If set, refreshes the diff cache
581 * @param $unhide boolean If set, allow viewing deleted revs
582 *
583 * @return DifferenceEngine
584 */
585 public function createDifferenceEngine( IContextSource $context,
586 $old = 0, $new = 0,
587 $rcid = 0, # FIXME: use everywhere!
588 $refreshCache = false, $unhide = false
589 ) {
590 $this->checkModelID( $context->getTitle()->getContentModel() );
591
592 $diffEngineClass = $this->getDiffEngineClass();
593
594 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
595 }
596
597 /**
598 * Get the language in which the content of the given page is written.
599 *
600 * This default implementation just returns $wgContLang (except for pages in the MediaWiki namespace)
601 *
602 * Note that the pages language is not cacheable, since it may in some cases depend on user settings.
603 *
604 * Also note that the page language may or may not depend on the actual content of the page,
605 * that is, this method may load the content in order to determine the language.
606 *
607 * @since 1.21
608 *
609 * @param Title $title the page to determine the language for.
610 * @param Content|null $content the page's content, if you have it handy, to avoid reloading it.
611 *
612 * @return Language the page's language
613 */
614 public function getPageLanguage( Title $title, Content $content = null ) {
615 global $wgContLang;
616
617 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
618 // Parse mediawiki messages with correct target language
619 list( /* $unused */, $lang ) = MessageCache::singleton()->figureMessage( $title->getText() );
620 return wfGetLangObj( $lang );
621 }
622
623 return $wgContLang;
624 }
625
626 /**
627 * Get the language in which the content of this page is written when
628 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
629 * specified a preferred variant, the variant will be used.
630 *
631 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
632 * the user specified a preferred variant.
633 *
634 * Note that the pages view language is not cacheable, since it depends on user settings.
635 *
636 * Also note that the page language may or may not depend on the actual content of the page,
637 * that is, this method may load the content in order to determine the language.
638 *
639 * @since 1.21
640 *
641 * @param Title $title the page to determine the language for.
642 * @param Content|null $content the page's content, if you have it handy, to avoid reloading it.
643 *
644 * @return Language the page's language for viewing
645 */
646 public function getPageViewLanguage( Title $title, Content $content = null ) {
647 $pageLang = $this->getPageLanguage( $title, $content );
648
649 if ( $title->getNamespace() !== NS_MEDIAWIKI ) {
650 // If the user chooses a variant, the content is actually
651 // in a language whose code is the variant code.
652 $variant = $pageLang->getPreferredVariant();
653 if ( $pageLang->getCode() !== $variant ) {
654 $pageLang = Language::factory( $variant );
655 }
656 }
657
658 return $pageLang;
659 }
660
661 /**
662 * Determines whether the content type handled by this ContentHandler
663 * can be used on the given page.
664 *
665 * This default implementation always returns true.
666 * Subclasses may override this to restrict the use of this content model to specific locations,
667 * typically based on the namespace or some other aspect of the title, such as a special suffix
668 * (e.g. ".svg" for SVG content).
669 *
670 * @param Title $title the page's title.
671 *
672 * @return bool true if content of this kind can be used on the given page, false otherwise.
673 */
674 public function canBeUsedOn( Title $title ) {
675 return true;
676 }
677
678 /**
679 * Returns the name of the diff engine to use.
680 *
681 * @since 1.21
682 *
683 * @return string
684 */
685 protected function getDiffEngineClass() {
686 return 'DifferenceEngine';
687 }
688
689 /**
690 * Attempts to merge differences between three versions.
691 * Returns a new Content object for a clean merge and false for failure or
692 * a conflict.
693 *
694 * This default implementation always returns false.
695 *
696 * @since 1.21
697 *
698 * @param $oldContent Content|string String
699 * @param $myContent Content|string String
700 * @param $yourContent Content|string String
701 *
702 * @return Content|Bool
703 */
704 public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
705 return false;
706 }
707
708 /**
709 * Return an applicable auto-summary if one exists for the given edit.
710 *
711 * @since 1.21
712 *
713 * @param $oldContent Content|null: the previous text of the page.
714 * @param $newContent Content|null: The submitted text of the page.
715 * @param $flags int Bit mask: a bit mask of flags submitted for the edit.
716 *
717 * @return string An appropriate auto-summary, or an empty string.
718 */
719 public function getAutosummary( Content $oldContent = null, Content $newContent = null, $flags ) {
720 global $wgContLang;
721
722 // Decide what kind of auto-summary is needed.
723
724 // Redirect auto-summaries
725
726 /**
727 * @var $ot Title
728 * @var $rt Title
729 */
730
731 $ot = !is_null( $oldContent ) ? $oldContent->getRedirectTarget() : null;
732 $rt = !is_null( $newContent ) ? $newContent->getRedirectTarget() : null;
733
734 if ( is_object( $rt ) ) {
735 if ( !is_object( $ot )
736 || !$rt->equals( $ot )
737 || $ot->getFragment() != $rt->getFragment() )
738 {
739 $truncatedtext = $newContent->getTextForSummary(
740 250
741 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
742 - strlen( $rt->getFullText() ) );
743
744 return wfMessage( 'autoredircomment', $rt->getFullText() )
745 ->rawParams( $truncatedtext )->inContentLanguage()->text();
746 }
747 }
748
749 // New page auto-summaries
750 if ( $flags & EDIT_NEW && $newContent->getSize() > 0 ) {
751 // If they're making a new article, give its text, truncated, in
752 // the summary.
753
754 $truncatedtext = $newContent->getTextForSummary(
755 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
756
757 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
758 ->inContentLanguage()->text();
759 }
760
761 // Blanking auto-summaries
762 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
763 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
764 } elseif ( !empty( $oldContent )
765 && $oldContent->getSize() > 10 * $newContent->getSize()
766 && $newContent->getSize() < 500 )
767 {
768 // Removing more than 90% of the article
769
770 $truncatedtext = $newContent->getTextForSummary(
771 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
772
773 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
774 ->inContentLanguage()->text();
775 }
776
777 // If we reach this point, there's no applicable auto-summary for our
778 // case, so our auto-summary is empty.
779 return '';
780 }
781
782 /**
783 * Auto-generates a deletion reason
784 *
785 * @since 1.21
786 *
787 * @param $title Title: the page's title
788 * @param &$hasHistory Boolean: whether the page has a history
789 * @return mixed String containing deletion reason or empty string, or
790 * boolean false if no revision occurred
791 *
792 * @XXX &$hasHistory is extremely ugly, it's here because
793 * WikiPage::getAutoDeleteReason() and Article::getReason()
794 * have it / want it.
795 */
796 public function getAutoDeleteReason( Title $title, &$hasHistory ) {
797 $dbw = wfGetDB( DB_MASTER );
798
799 // Get the last revision
800 $rev = Revision::newFromTitle( $title );
801
802 if ( is_null( $rev ) ) {
803 return false;
804 }
805
806 // Get the article's contents
807 $content = $rev->getContent();
808 $blank = false;
809
810 $this->checkModelID( $content->getModel() );
811
812 // If the page is blank, use the text from the previous revision,
813 // which can only be blank if there's a move/import/protect dummy
814 // revision involved
815 if ( $content->getSize() == 0 ) {
816 $prev = $rev->getPrevious();
817
818 if ( $prev ) {
819 $content = $prev->getContent();
820 $blank = true;
821 }
822 }
823
824 // Find out if there was only one contributor
825 // Only scan the last 20 revisions
826 $res = $dbw->select( 'revision', 'rev_user_text',
827 array(
828 'rev_page' => $title->getArticleID(),
829 $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0'
830 ),
831 __METHOD__,
832 array( 'LIMIT' => 20 )
833 );
834
835 if ( $res === false ) {
836 // This page has no revisions, which is very weird
837 return false;
838 }
839
840 $hasHistory = ( $res->numRows() > 1 );
841 $row = $dbw->fetchObject( $res );
842
843 if ( $row ) { // $row is false if the only contributor is hidden
844 $onlyAuthor = $row->rev_user_text;
845 // Try to find a second contributor
846 foreach ( $res as $row ) {
847 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
848 $onlyAuthor = false;
849 break;
850 }
851 }
852 } else {
853 $onlyAuthor = false;
854 }
855
856 // Generate the summary with a '$1' placeholder
857 if ( $blank ) {
858 // The current revision is blank and the one before is also
859 // blank. It's just not our lucky day
860 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
861 } else {
862 if ( $onlyAuthor ) {
863 $reason = wfMessage(
864 'excontentauthor',
865 '$1',
866 $onlyAuthor
867 )->inContentLanguage()->text();
868 } else {
869 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
870 }
871 }
872
873 if ( $reason == '-' ) {
874 // Allow these UI messages to be blanked out cleanly
875 return '';
876 }
877
878 // Max content length = max comment length - length of the comment (excl. $1)
879 $text = $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) );
880
881 // Now replace the '$1' placeholder
882 $reason = str_replace( '$1', $text, $reason );
883
884 return $reason;
885 }
886
887 /**
888 * Get the Content object that needs to be saved in order to undo all revisions
889 * between $undo and $undoafter. Revisions must belong to the same page,
890 * must exist and must not be deleted.
891 *
892 * @since 1.21
893 *
894 * @param $current Revision The current text
895 * @param $undo Revision The revision to undo
896 * @param $undoafter Revision Must be an earlier revision than $undo
897 *
898 * @return mixed String on success, false on failure
899 */
900 public function getUndoContent( Revision $current, Revision $undo, Revision $undoafter ) {
901 $cur_content = $current->getContent();
902
903 if ( empty( $cur_content ) ) {
904 return false; // no page
905 }
906
907 $undo_content = $undo->getContent();
908 $undoafter_content = $undoafter->getContent();
909
910 $this->checkModelID( $cur_content->getModel() );
911 $this->checkModelID( $undo_content->getModel() );
912 $this->checkModelID( $undoafter_content->getModel() );
913
914 if ( $cur_content->equals( $undo_content ) ) {
915 // No use doing a merge if it's just a straight revert.
916 return $undoafter_content;
917 }
918
919 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
920
921 return $undone_content;
922 }
923
924 /**
925 * Get parser options suitable for rendering the primary article wikitext
926 *
927 * @param IContextSource|User|string $context One of the following:
928 * - IContextSource: Use the User and the Language of the provided
929 * context
930 * - User: Use the provided User object and $wgLang for the language,
931 * so use an IContextSource object if possible.
932 * - 'canonical': Canonical options (anonymous user with default
933 * preferences and content language).
934 *
935 * @param IContextSource|User|string $context
936 *
937 * @throws MWException
938 * @return ParserOptions
939 */
940 public function makeParserOptions( $context ) {
941 global $wgContLang;
942
943 if ( $context instanceof IContextSource ) {
944 $options = ParserOptions::newFromContext( $context );
945 } elseif ( $context instanceof User ) { // settings per user (even anons)
946 $options = ParserOptions::newFromUser( $context );
947 } elseif ( $context === 'canonical' ) { // canonical settings
948 $options = ParserOptions::newFromUserAndLang( new User, $wgContLang );
949 } else {
950 throw new MWException( "Bad context for parser options: $context" );
951 }
952
953 $options->enableLimitReport(); // show inclusion/loop reports
954 $options->setTidy( true ); // fix bad HTML
955
956 return $options;
957 }
958
959 /**
960 * Returns true for content models that support caching using the
961 * ParserCache mechanism. See WikiPage::isParserCacheUsed().
962 *
963 * @since 1.21
964 *
965 * @return bool
966 */
967 public function isParserCacheSupported() {
968 return false;
969 }
970
971 /**
972 * Returns true if this content model supports sections.
973 *
974 * This default implementation returns false.
975 *
976 * @return boolean whether sections are supported.
977 */
978 public function supportsSections() {
979 return false;
980 }
981
982 /**
983 * Logs a deprecation warning, visible if $wgDevelopmentWarnings, but only if
984 * self::$enableDeprecationWarnings is set to true.
985 *
986 * @param String $func The name of the deprecated function
987 * @param string $version The version since the method is deprecated. Usually 1.21
988 * for ContentHandler related stuff.
989 * @param String|bool $component: Component to which the function belongs.
990 * If false, it is assumed the function is in MediaWiki core.
991 *
992 * @see ContentHandler::$enableDeprecationWarnings
993 * @see wfDeprecated
994 */
995 public static function deprecated( $func, $version, $component = false ) {
996 if ( self::$enableDeprecationWarnings ) {
997 wfDeprecated( $func, $version, $component, 3 );
998 }
999 }
1000
1001 /**
1002 * Call a legacy hook that uses text instead of Content objects.
1003 * Will log a warning when a matching hook function is registered.
1004 * If the textual representation of the content is changed by the
1005 * hook function, a new Content object is constructed from the new
1006 * text.
1007 *
1008 * @param $event String: event name
1009 * @param $args Array: parameters passed to hook functions
1010 * @param $warn bool: whether to log a warning.
1011 * Default to self::$enableDeprecationWarnings.
1012 * May be set to false for testing.
1013 *
1014 * @return Boolean True if no handler aborted the hook
1015 *
1016 * @see ContentHandler::$enableDeprecationWarnings
1017 */
1018 public static function runLegacyHooks( $event, $args = array(),
1019 $warn = null ) {
1020
1021 if ( $warn === null ) {
1022 $warn = self::$enableDeprecationWarnings;
1023 }
1024
1025 if ( !Hooks::isRegistered( $event ) ) {
1026 return true; // nothing to do here
1027 }
1028
1029 if ( $warn ) {
1030 // Log information about which handlers are registered for the legacy hook,
1031 // so we can find and fix them.
1032
1033 $handlers = Hooks::getHandlers( $event );
1034 $handlerInfo = array();
1035
1036 wfSuppressWarnings();
1037
1038 foreach ( $handlers as $handler ) {
1039 $info = '';
1040
1041 if ( is_array( $handler ) ) {
1042 if ( is_object( $handler[0] ) ) {
1043 $info = get_class( $handler[0] );
1044 } else {
1045 $info = $handler[0];
1046 }
1047
1048 if ( isset( $handler[1] ) ) {
1049 $info .= '::' . $handler[1];
1050 }
1051 } else if ( is_object( $handler ) ) {
1052 $info = get_class( $handler[0] );
1053 $info .= '::on' . $event;
1054 } else {
1055 $info = $handler;
1056 }
1057
1058 $handlerInfo[] = $info;
1059 }
1060
1061 wfRestoreWarnings();
1062
1063 wfWarn( "Using obsolete hook $event via ContentHandler::runLegacyHooks()! Handlers: " . implode(', ', $handlerInfo), 2 );
1064 }
1065
1066 // convert Content objects to text
1067 $contentObjects = array();
1068 $contentTexts = array();
1069
1070 foreach ( $args as $k => $v ) {
1071 if ( $v instanceof Content ) {
1072 /* @var Content $v */
1073
1074 $contentObjects[$k] = $v;
1075
1076 $v = $v->serialize();
1077 $contentTexts[ $k ] = $v;
1078 $args[ $k ] = $v;
1079 }
1080 }
1081
1082 // call the hook functions
1083 $ok = wfRunHooks( $event, $args );
1084
1085 // see if the hook changed the text
1086 foreach ( $contentTexts as $k => $orig ) {
1087 /* @var Content $content */
1088
1089 $modified = $args[ $k ];
1090 $content = $contentObjects[$k];
1091
1092 if ( $modified !== $orig ) {
1093 // text was changed, create updated Content object
1094 $content = $content->getContentHandler()->unserializeContent( $modified );
1095 }
1096
1097 $args[ $k ] = $content;
1098 }
1099
1100 return $ok;
1101 }
1102 }
1103
1104 /**
1105 * @since 1.21
1106 */
1107 class TextContentHandler extends ContentHandler {
1108
1109 public function __construct( $modelId = CONTENT_MODEL_TEXT, $formats = array( CONTENT_FORMAT_TEXT ) ) {
1110 parent::__construct( $modelId, $formats );
1111 }
1112
1113 /**
1114 * Returns the content's text as-is.
1115 *
1116 * @param $content Content
1117 * @param $format string|null
1118 * @return mixed
1119 */
1120 public function serializeContent( Content $content, $format = null ) {
1121 $this->checkFormat( $format );
1122 return $content->getNativeData();
1123 }
1124
1125 /**
1126 * Attempts to merge differences between three versions. Returns a new
1127 * Content object for a clean merge and false for failure or a conflict.
1128 *
1129 * All three Content objects passed as parameters must have the same
1130 * content model.
1131 *
1132 * This text-based implementation uses wfMerge().
1133 *
1134 * @param $oldContent \Content|string String
1135 * @param $myContent \Content|string String
1136 * @param $yourContent \Content|string String
1137 *
1138 * @return Content|Bool
1139 */
1140 public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
1141 $this->checkModelID( $oldContent->getModel() );
1142 $this->checkModelID( $myContent->getModel() );
1143 $this->checkModelID( $yourContent->getModel() );
1144
1145 $format = $this->getDefaultFormat();
1146
1147 $old = $this->serializeContent( $oldContent, $format );
1148 $mine = $this->serializeContent( $myContent, $format );
1149 $yours = $this->serializeContent( $yourContent, $format );
1150
1151 $ok = wfMerge( $old, $mine, $yours, $result );
1152
1153 if ( !$ok ) {
1154 return false;
1155 }
1156
1157 if ( !$result ) {
1158 return $this->makeEmptyContent();
1159 }
1160
1161 $mergedContent = $this->unserializeContent( $result, $format );
1162 return $mergedContent;
1163 }
1164
1165 /**
1166 * Unserializes a Content object of the type supported by this ContentHandler.
1167 *
1168 * @since 1.21
1169 *
1170 * @param $text string serialized form of the content
1171 * @param $format null|String the format used for serialization
1172 *
1173 * @return Content the TextContent object wrapping $text
1174 */
1175 public function unserializeContent( $text, $format = null ) {
1176 $this->checkFormat( $format );
1177
1178 return new TextContent( $text );
1179 }
1180
1181 /**
1182 * Creates an empty TextContent object.
1183 *
1184 * @since 1.21
1185 *
1186 * @return Content
1187 */
1188 public function makeEmptyContent() {
1189 return new TextContent( '' );
1190 }
1191 }
1192
1193 /**
1194 * @since 1.21
1195 */
1196 class WikitextContentHandler extends TextContentHandler {
1197
1198 public function __construct( $modelId = CONTENT_MODEL_WIKITEXT ) {
1199 parent::__construct( $modelId, array( CONTENT_FORMAT_WIKITEXT ) );
1200 }
1201
1202 public function unserializeContent( $text, $format = null ) {
1203 $this->checkFormat( $format );
1204
1205 return new WikitextContent( $text );
1206 }
1207
1208 /**
1209 * @see ContentHandler::makeEmptyContent
1210 *
1211 * @return Content
1212 */
1213 public function makeEmptyContent() {
1214 return new WikitextContent( '' );
1215 }
1216
1217
1218 /**
1219 * Returns a WikitextContent object representing a redirect to the given destination page.
1220 *
1221 * @see ContentHandler::makeRedirectContent
1222 *
1223 * @param Title $destination the page to redirect to.
1224 *
1225 * @return Content
1226 */
1227 public function makeRedirectContent( Title $destination ) {
1228 $mwRedir = MagicWord::get( 'redirect' );
1229 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $destination->getPrefixedText() . "]]\n";
1230
1231 return new WikitextContent( $redirectText );
1232 }
1233
1234 /**
1235 * Returns true because wikitext supports sections.
1236 *
1237 * @return boolean whether sections are supported.
1238 */
1239 public function supportsSections() {
1240 return true;
1241 }
1242
1243 /**
1244 * Returns true, because wikitext supports caching using the
1245 * ParserCache mechanism.
1246 *
1247 * @since 1.21
1248 * @return bool
1249 */
1250 public function isParserCacheSupported() {
1251 return true;
1252 }
1253 }
1254
1255 # XXX: make ScriptContentHandler base class, do highlighting stuff there?
1256
1257 /**
1258 * @since 1.21
1259 */
1260 class JavaScriptContentHandler extends TextContentHandler {
1261
1262 public function __construct( $modelId = CONTENT_MODEL_JAVASCRIPT ) {
1263 parent::__construct( $modelId, array( CONTENT_FORMAT_JAVASCRIPT ) );
1264 }
1265
1266 public function unserializeContent( $text, $format = null ) {
1267 $this->checkFormat( $format );
1268
1269 return new JavaScriptContent( $text );
1270 }
1271
1272 public function makeEmptyContent() {
1273 return new JavaScriptContent( '' );
1274 }
1275
1276 /**
1277 * Returns the english language, because JS is english, and should be handled as such.
1278 *
1279 * @return Language wfGetLangObj( 'en' )
1280 *
1281 * @see ContentHandler::getPageLanguage()
1282 */
1283 public function getPageLanguage( Title $title, Content $content = null ) {
1284 return wfGetLangObj( 'en' );
1285 }
1286
1287 /**
1288 * Returns the english language, because CSS is english, and should be handled as such.
1289 *
1290 * @return Language wfGetLangObj( 'en' )
1291 *
1292 * @see ContentHandler::getPageViewLanguage()
1293 */
1294 public function getPageViewLanguage( Title $title, Content $content = null ) {
1295 return wfGetLangObj( 'en' );
1296 }
1297 }
1298
1299 /**
1300 * @since 1.21
1301 */
1302 class CssContentHandler extends TextContentHandler {
1303
1304 public function __construct( $modelId = CONTENT_MODEL_CSS ) {
1305 parent::__construct( $modelId, array( CONTENT_FORMAT_CSS ) );
1306 }
1307
1308 public function unserializeContent( $text, $format = null ) {
1309 $this->checkFormat( $format );
1310
1311 return new CssContent( $text );
1312 }
1313
1314 public function makeEmptyContent() {
1315 return new CssContent( '' );
1316 }
1317
1318 /**
1319 * Returns the english language, because CSS is english, and should be handled as such.
1320 *
1321 * @return Language wfGetLangObj( 'en' )
1322 *
1323 * @see ContentHandler::getPageLanguage()
1324 */
1325 public function getPageLanguage( Title $title, Content $content = null ) {
1326 return wfGetLangObj( 'en' );
1327 }
1328
1329 /**
1330 * Returns the english language, because CSS is english, and should be handled as such.
1331 *
1332 * @return Language wfGetLangObj( 'en' )
1333 *
1334 * @see ContentHandler::getPageViewLanguage()
1335 */
1336 public function getPageViewLanguage( Title $title, Content $content = null ) {
1337 return wfGetLangObj( 'en' );
1338 }
1339 }