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