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