Merge "Tweaked WikiPage::clear() comment a bit"
[mediawiki.git] / includes / content / ContentHandler.php
blobede43063b771dc2274914504e64ce9fc5bbf7b55
1 <?php
2 /**
3 * Base class for content handling.
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.
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.
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
20 * @since 1.21
22 * @file
23 * @ingroup Content
25 * @author Daniel Kinzler
28 /**
29 * Exception representing a failure to serialize or unserialize a content object.
31 * @ingroup Content
33 class MWContentSerializationException extends MWException {
37 /**
38 * A content handler knows how do deal with a specific type of content on a wiki
39 * page. Content is stored in the database in a serialized form (using a
40 * serialization format a.k.a. MIME type) and is unserialized into its native
41 * PHP representation (the content model), which is wrapped in an instance of
42 * the appropriate subclass of Content.
44 * ContentHandler instances are stateless singletons that serve, among other
45 * things, as a factory for Content objects. Generally, there is one subclass
46 * of ContentHandler and one subclass of Content for every type of content model.
48 * Some content types have a flat model, that is, their native representation
49 * is the same as their serialized form. Examples would be JavaScript and CSS
50 * code. As of now, this also applies to wikitext (MediaWiki's default content
51 * type), but wikitext content may be represented by a DOM or AST structure in
52 * the future.
54 * @ingroup Content
56 abstract class ContentHandler {
58 /**
59 * Switch for enabling deprecation warnings. Used by ContentHandler::deprecated()
60 * and ContentHandler::runLegacyHooks().
62 * Once the ContentHandler code has settled in a bit, this should be set to true to
63 * make extensions etc. show warnings when using deprecated functions and hooks.
65 protected static $enableDeprecationWarnings = false;
67 /**
68 * Convenience function for getting flat text from a Content object. This
69 * should only be used in the context of backwards compatibility with code
70 * that is not yet able to handle Content objects!
72 * If $content is null, this method returns the empty string.
74 * If $content is an instance of TextContent, this method returns the flat
75 * text as returned by $content->getNativeData().
77 * If $content is not a TextContent object, the behavior of this method
78 * depends on the global $wgContentHandlerTextFallback:
79 * - If $wgContentHandlerTextFallback is 'fail' and $content is not a
80 * TextContent object, an MWException is thrown.
81 * - If $wgContentHandlerTextFallback is 'serialize' and $content is not a
82 * TextContent object, $content->serialize() is called to get a string
83 * form of the content.
84 * - If $wgContentHandlerTextFallback is 'ignore' and $content is not a
85 * TextContent object, this method returns null.
86 * - otherwise, the behavior is undefined.
88 * @since 1.21
90 * @param $content Content|null
91 * @return null|string the textual form of $content, if available
92 * @throws MWException if $content is not an instance of TextContent and
93 * $wgContentHandlerTextFallback was set to 'fail'.
95 public static function getContentText( Content $content = null ) {
96 global $wgContentHandlerTextFallback;
98 if ( is_null( $content ) ) {
99 return '';
102 if ( $content instanceof TextContent ) {
103 return $content->getNativeData();
106 wfDebugLog( 'ContentHandler', 'Accessing ' . $content->getModel() . ' content as text!' );
108 if ( $wgContentHandlerTextFallback == 'fail' ) {
109 throw new MWException(
110 "Attempt to get text from Content with model " .
111 $content->getModel()
115 if ( $wgContentHandlerTextFallback == 'serialize' ) {
116 return $content->serialize();
119 return null;
123 * Convenience function for creating a Content object from a given textual
124 * representation.
126 * $text will be deserialized into a Content object of the model specified
127 * by $modelId (or, if that is not given, $title->getContentModel()) using
128 * the given format.
130 * @since 1.21
132 * @param string $text the textual representation, will be
133 * unserialized to create the Content object
134 * @param $title null|Title the title of the page this text belongs to.
135 * Required if $modelId is not provided.
136 * @param $modelId null|string the model to deserialize to. If not provided,
137 * $title->getContentModel() is used.
138 * @param $format null|string the format to use for deserialization. If not
139 * given, the model's default format is used.
141 * @throws MWException
142 * @return Content a Content object representing $text
144 * @throws MWException if $model or $format is not supported or if $text can
145 * not be unserialized using $format.
147 public static function makeContent( $text, Title $title = null,
148 $modelId = null, $format = null )
150 if ( is_null( $modelId ) ) {
151 if ( is_null( $title ) ) {
152 throw new MWException( "Must provide a Title object or a content model ID." );
155 $modelId = $title->getContentModel();
158 $handler = ContentHandler::getForModelID( $modelId );
159 return $handler->unserializeContent( $text, $format );
163 * Returns the name of the default content model to be used for the page
164 * with the given title.
166 * Note: There should rarely be need to call this method directly.
167 * To determine the actual content model for a given page, use
168 * Title::getContentModel().
170 * Which model is to be used by default for the page is determined based
171 * on several factors:
172 * - The global setting $wgNamespaceContentModels specifies a content model
173 * per namespace.
174 * - The hook ContentHandlerDefaultModelFor may be used to override the page's default
175 * model.
176 * - Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript
177 * model if they end in .js or .css, respectively.
178 * - Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
179 * - The hook TitleIsCssOrJsPage may be used to force a page to use the CSS
180 * or JavaScript model. This is a compatibility feature. The ContentHandlerDefaultModelFor
181 * hook should be used instead if possible.
182 * - The hook TitleIsWikitextPage may be used to force a page to use the
183 * wikitext model. This is a compatibility feature. The ContentHandlerDefaultModelFor
184 * hook should be used instead if possible.
186 * If none of the above applies, the wikitext model is used.
188 * Note: this is used by, and may thus not use, Title::getContentModel()
190 * @since 1.21
192 * @param $title Title
193 * @return null|string default model name for the page given by $title
195 public static function getDefaultModelFor( Title $title ) {
196 // NOTE: this method must not rely on $title->getContentModel() directly or indirectly,
197 // because it is used to initialize the mContentModel member.
199 $ns = $title->getNamespace();
201 $ext = false;
202 $m = null;
203 $model = MWNamespace::getNamespaceContentModel( $ns );
205 // Hook can determine default model
206 if ( !wfRunHooks( 'ContentHandlerDefaultModelFor', array( $title, &$model ) ) ) {
207 if ( !is_null( $model ) ) {
208 return $model;
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];
218 // Hook can force JS/CSS
219 wfRunHooks( 'TitleIsCssOrJsPage', array( $title, &$isCssOrJsPage ) );
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];
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;
233 // Hook can override $isWikitext
234 wfRunHooks( 'TitleIsWikitextPage', array( $title, &$isWikitext ) );
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;
247 // We established that it must be wikitext
249 return CONTENT_MODEL_WIKITEXT;
253 * Returns the appropriate ContentHandler singleton for the given title.
255 * @since 1.21
257 * @param $title Title
258 * @return ContentHandler
260 public static function getForTitle( Title $title ) {
261 $modelId = $title->getContentModel();
262 return ContentHandler::getForModelID( $modelId );
266 * Returns the appropriate ContentHandler singleton for the given Content
267 * object.
269 * @since 1.21
271 * @param $content Content
272 * @return ContentHandler
274 public static function getForContent( Content $content ) {
275 $modelId = $content->getModel();
276 return ContentHandler::getForModelID( $modelId );
280 * @var Array A Cache of ContentHandler instances by model id
282 static $handlers;
285 * Returns the ContentHandler singleton for the given model ID. Use the
286 * CONTENT_MODEL_XXX constants to identify the desired content model.
288 * ContentHandler singletons are taken from the global $wgContentHandlers
289 * array. Keys in that array are model names, the values are either
290 * ContentHandler singleton objects, or strings specifying the appropriate
291 * subclass of ContentHandler.
293 * If a class name is encountered when looking up the singleton for a given
294 * model name, the class is instantiated and the class name is replaced by
295 * the resulting singleton in $wgContentHandlers.
297 * If no ContentHandler is defined for the desired $modelId, the
298 * ContentHandler may be provided by the ContentHandlerForModelID hook.
299 * If no ContentHandler can be determined, an MWException is raised.
301 * @since 1.21
303 * @param string $modelId The ID of the content model for which to get a
304 * handler. Use CONTENT_MODEL_XXX constants.
305 * @return ContentHandler The ContentHandler singleton for handling the
306 * model given by $modelId
307 * @throws MWException if no handler is known for $modelId.
309 public static function getForModelID( $modelId ) {
310 global $wgContentHandlers;
312 if ( isset( ContentHandler::$handlers[$modelId] ) ) {
313 return ContentHandler::$handlers[$modelId];
316 if ( empty( $wgContentHandlers[$modelId] ) ) {
317 $handler = null;
319 wfRunHooks( 'ContentHandlerForModelID', array( $modelId, &$handler ) );
321 if ( $handler === null ) {
322 throw new MWException( "No handler for model '$modelId' registered in \$wgContentHandlers" );
325 if ( !( $handler instanceof ContentHandler ) ) {
326 throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
328 } else {
329 $class = $wgContentHandlers[$modelId];
330 $handler = new $class( $modelId );
332 if ( !( $handler instanceof ContentHandler ) ) {
333 throw new MWException( "$class from \$wgContentHandlers is not compatible with ContentHandler" );
337 wfDebugLog( 'ContentHandler', 'Created handler for ' . $modelId
338 . ': ' . get_class( $handler ) );
340 ContentHandler::$handlers[$modelId] = $handler;
341 return ContentHandler::$handlers[$modelId];
345 * Returns the localized name for a given content model.
347 * Model names are localized using system messages. Message keys
348 * have the form content-model-$name, where $name is getContentModelName( $id ).
350 * @param string $name The content model ID, as given by a CONTENT_MODEL_XXX
351 * constant or returned by Revision::getContentModel().
353 * @return string The content model's localized name.
354 * @throws MWException if the model id isn't known.
356 public static function getLocalizedName( $name ) {
357 // Messages: content-model-wikitext, content-model-text,
358 // content-model-javascript, content-model-css
359 $key = "content-model-$name";
361 $msg = wfMessage( $key );
363 return $msg->exists() ? $msg->plain() : $name;
366 public static function getContentModels() {
367 global $wgContentHandlers;
369 return array_keys( $wgContentHandlers );
372 public static function getAllContentFormats() {
373 global $wgContentHandlers;
375 $formats = array();
377 foreach ( $wgContentHandlers as $model => $class ) {
378 $handler = ContentHandler::getForModelID( $model );
379 $formats = array_merge( $formats, $handler->getSupportedFormats() );
382 $formats = array_unique( $formats );
383 return $formats;
386 // ------------------------------------------------------------------------
388 protected $mModelID;
389 protected $mSupportedFormats;
392 * Constructor, initializing the ContentHandler instance with its model ID
393 * and a list of supported formats. Values for the parameters are typically
394 * provided as literals by subclass's constructors.
396 * @param string $modelId (use CONTENT_MODEL_XXX constants).
397 * @param array $formats List for supported serialization formats
398 * (typically as MIME types)
400 public function __construct( $modelId, $formats ) {
401 $this->mModelID = $modelId;
402 $this->mSupportedFormats = $formats;
404 $this->mModelName = preg_replace( '/(Content)?Handler$/', '', get_class( $this ) );
405 $this->mModelName = preg_replace( '/[_\\\\]/', '', $this->mModelName );
406 $this->mModelName = strtolower( $this->mModelName );
410 * Serializes a Content object of the type supported by this ContentHandler.
412 * @since 1.21
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
418 abstract public function serializeContent( Content $content, $format = null );
421 * Unserializes a Content object of the type supported by this ContentHandler.
423 * @since 1.21
425 * @param string $blob serialized form of the content
426 * @param $format null|String the format used for serialization
427 * @return Content the Content object created by deserializing $blob
429 abstract public function unserializeContent( $blob, $format = null );
432 * Creates an empty Content object of the type supported by this
433 * ContentHandler.
435 * @since 1.21
437 * @return Content
439 abstract public function makeEmptyContent();
442 * Creates a new Content object that acts as a redirect to the given page,
443 * or null of redirects are not supported by this content model.
445 * This default implementation always returns null. Subclasses supporting redirects
446 * must override this method.
448 * Note that subclasses that override this method to return a Content object
449 * should also override supportsRedirects() to return true.
451 * @since 1.21
453 * @param Title $destination the page to redirect to.
454 * @param string $text text to include in the redirect, if possible.
456 * @return Content
458 public function makeRedirectContent( Title $destination, $text = '' ) {
459 return null;
463 * Returns the model id that identifies the content model this
464 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
466 * @since 1.21
468 * @return String The model ID
470 public function getModelID() {
471 return $this->mModelID;
475 * Throws an MWException if $model_id is not the ID of the content model
476 * supported by this ContentHandler.
478 * @since 1.21
480 * @param string $model_id The model to check
482 * @throws MWException
484 protected function checkModelID( $model_id ) {
485 if ( $model_id !== $this->mModelID ) {
486 throw new MWException( "Bad content model: " .
487 "expected {$this->mModelID} " .
488 "but got $model_id." );
493 * Returns a list of serialization formats supported by the
494 * serializeContent() and unserializeContent() methods of this
495 * ContentHandler.
497 * @since 1.21
499 * @return array of serialization formats as MIME type like strings
501 public function getSupportedFormats() {
502 return $this->mSupportedFormats;
506 * The format used for serialization/deserialization by default by this
507 * ContentHandler.
509 * This default implementation will return the first element of the array
510 * of formats that was passed to the constructor.
512 * @since 1.21
514 * @return string the name of the default serialization format as a MIME type
516 public function getDefaultFormat() {
517 return $this->mSupportedFormats[0];
521 * Returns true if $format is a serialization format supported by this
522 * ContentHandler, and false otherwise.
524 * Note that if $format is null, this method always returns true, because
525 * null means "use the default format".
527 * @since 1.21
529 * @param string $format the serialization format to check
530 * @return bool
532 public function isSupportedFormat( $format ) {
534 if ( !$format ) {
535 return true; // this means "use the default"
538 return in_array( $format, $this->mSupportedFormats );
542 * Throws an MWException if isSupportedFormat( $format ) is not true.
543 * Convenient for checking whether a format provided as a parameter is
544 * actually supported.
546 * @param string $format the serialization format to check
548 * @throws MWException
550 protected function checkFormat( $format ) {
551 if ( !$this->isSupportedFormat( $format ) ) {
552 throw new MWException(
553 "Format $format is not supported for content model "
554 . $this->getModelID()
560 * Returns overrides for action handlers.
561 * Classes listed here will be used instead of the default one when
562 * (and only when) $wgActions[$action] === true. This allows subclasses
563 * to override the default action handlers.
565 * @since 1.21
567 * @return Array
569 public function getActionOverrides() {
570 return array();
574 * Factory for creating an appropriate DifferenceEngine for this content model.
576 * @since 1.21
578 * @param $context IContextSource context to use, anything else will be
579 * ignored
580 * @param $old Integer Old ID we want to show and diff with.
581 * @param int|string $new String either 'prev' or 'next'.
582 * @param $rcid Integer ??? FIXME (default 0)
583 * @param $refreshCache boolean If set, refreshes the diff cache
584 * @param $unhide boolean If set, allow viewing deleted revs
586 * @return DifferenceEngine
588 public function createDifferenceEngine( IContextSource $context,
589 $old = 0, $new = 0,
590 $rcid = 0, # FIXME: use everywhere!
591 $refreshCache = false, $unhide = false
593 $diffEngineClass = $this->getDiffEngineClass();
595 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
599 * Get the language in which the content of the given page is written.
601 * This default implementation just returns $wgContLang (except for pages in the MediaWiki namespace)
603 * Note that the pages language is not cacheable, since it may in some cases depend on user settings.
605 * Also note that the page language may or may not depend on the actual content of the page,
606 * that is, this method may load the content in order to determine the language.
608 * @since 1.21
610 * @param Title $title the page to determine the language for.
611 * @param Content|null $content the page's content, if you have it handy, to avoid reloading it.
613 * @return Language the page's language
615 public function getPageLanguage( Title $title, Content $content = null ) {
616 global $wgContLang, $wgLang;
617 $pageLang = $wgContLang;
619 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
620 // Parse mediawiki messages with correct target language
621 list( /* $unused */, $lang ) = MessageCache::singleton()->figureMessage( $title->getText() );
622 $pageLang = wfGetLangObj( $lang );
625 wfRunHooks( 'PageContentLanguage', array( $title, &$pageLang, $wgLang ) );
626 return wfGetLangObj( $pageLang );
630 * Get the language in which the content of this page is written when
631 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
632 * specified a preferred variant, the variant will be used.
634 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
635 * the user specified a preferred variant.
637 * Note that the pages view language is not cacheable, since it depends on user settings.
639 * Also note that the page language may or may not depend on the actual content of the page,
640 * that is, this method may load the content in order to determine the language.
642 * @since 1.21
644 * @param Title $title the page to determine the language for.
645 * @param Content|null $content the page's content, if you have it handy, to avoid reloading it.
647 * @return Language the page's language for viewing
649 public function getPageViewLanguage( Title $title, Content $content = null ) {
650 $pageLang = $this->getPageLanguage( $title, $content );
652 if ( $title->getNamespace() !== NS_MEDIAWIKI ) {
653 // If the user chooses a variant, the content is actually
654 // in a language whose code is the variant code.
655 $variant = $pageLang->getPreferredVariant();
656 if ( $pageLang->getCode() !== $variant ) {
657 $pageLang = Language::factory( $variant );
661 return $pageLang;
665 * Determines whether the content type handled by this ContentHandler
666 * can be used on the given page.
668 * This default implementation always returns true.
669 * Subclasses may override this to restrict the use of this content model to specific locations,
670 * typically based on the namespace or some other aspect of the title, such as a special suffix
671 * (e.g. ".svg" for SVG content).
673 * @param Title $title the page's title.
675 * @return bool true if content of this kind can be used on the given page, false otherwise.
677 public function canBeUsedOn( Title $title ) {
678 return true;
682 * Returns the name of the diff engine to use.
684 * @since 1.21
686 * @return string
688 protected function getDiffEngineClass() {
689 return 'DifferenceEngine';
693 * Attempts to merge differences between three versions.
694 * Returns a new Content object for a clean merge and false for failure or
695 * a conflict.
697 * This default implementation always returns false.
699 * @since 1.21
701 * @param $oldContent Content|string String
702 * @param $myContent Content|string String
703 * @param $yourContent Content|string String
705 * @return Content|Bool
707 public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
708 return false;
712 * Return an applicable auto-summary if one exists for the given edit.
714 * @since 1.21
716 * @param $oldContent Content|null: the previous text of the page.
717 * @param $newContent Content|null: The submitted text of the page.
718 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
720 * @return string An appropriate auto-summary, or an empty string.
722 public function getAutosummary( Content $oldContent = null, Content $newContent = null, $flags ) {
723 // Decide what kind of auto-summary is needed.
725 // Redirect auto-summaries
728 * @var $ot Title
729 * @var $rt Title
732 $ot = !is_null( $oldContent ) ? $oldContent->getRedirectTarget() : null;
733 $rt = !is_null( $newContent ) ? $newContent->getRedirectTarget() : null;
735 if ( is_object( $rt ) ) {
736 if ( !is_object( $ot )
737 || !$rt->equals( $ot )
738 || $ot->getFragment() != $rt->getFragment() )
740 $truncatedtext = $newContent->getTextForSummary(
742 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
743 - strlen( $rt->getFullText() ) );
745 return wfMessage( 'autoredircomment', $rt->getFullText() )
746 ->rawParams( $truncatedtext )->inContentLanguage()->text();
750 // New page auto-summaries
751 if ( $flags & EDIT_NEW && $newContent->getSize() > 0 ) {
752 // If they're making a new article, give its text, truncated, in
753 // the summary.
755 $truncatedtext = $newContent->getTextForSummary(
756 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
758 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
759 ->inContentLanguage()->text();
762 // Blanking auto-summaries
763 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
764 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
765 } elseif ( !empty( $oldContent )
766 && $oldContent->getSize() > 10 * $newContent->getSize()
767 && $newContent->getSize() < 500 )
769 // Removing more than 90% of the article
771 $truncatedtext = $newContent->getTextForSummary(
772 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
774 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
775 ->inContentLanguage()->text();
778 // If we reach this point, there's no applicable auto-summary for our
779 // case, so our auto-summary is empty.
780 return '';
784 * Auto-generates a deletion reason
786 * @since 1.21
788 * @param $title Title: the page's title
789 * @param &$hasHistory Boolean: whether the page has a history
790 * @return mixed String containing deletion reason or empty string, or
791 * boolean false if no revision occurred
793 * @XXX &$hasHistory is extremely ugly, it's here because
794 * WikiPage::getAutoDeleteReason() and Article::generateReason()
795 * have it / want it.
797 public function getAutoDeleteReason( Title $title, &$hasHistory ) {
798 $dbw = wfGetDB( DB_MASTER );
800 // Get the last revision
801 $rev = Revision::newFromTitle( $title );
803 if ( is_null( $rev ) ) {
804 return false;
807 // Get the article's contents
808 $content = $rev->getContent();
809 $blank = false;
811 // If the page is blank, use the text from the previous revision,
812 // which can only be blank if there's a move/import/protect dummy
813 // revision involved
814 if ( !$content || $content->isEmpty() ) {
815 $prev = $rev->getPrevious();
817 if ( $prev ) {
818 $rev = $prev;
819 $content = $rev->getContent();
820 $blank = true;
824 $this->checkModelID( $rev->getContentModel() );
826 // Find out if there was only one contributor
827 // Only scan the last 20 revisions
828 $res = $dbw->select( 'revision', 'rev_user_text',
829 array(
830 'rev_page' => $title->getArticleID(),
831 $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0'
833 __METHOD__,
834 array( 'LIMIT' => 20 )
837 if ( $res === false ) {
838 // This page has no revisions, which is very weird
839 return false;
842 $hasHistory = ( $res->numRows() > 1 );
843 $row = $dbw->fetchObject( $res );
845 if ( $row ) { // $row is false if the only contributor is hidden
846 $onlyAuthor = $row->rev_user_text;
847 // Try to find a second contributor
848 foreach ( $res as $row ) {
849 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
850 $onlyAuthor = false;
851 break;
854 } else {
855 $onlyAuthor = false;
858 // Generate the summary with a '$1' placeholder
859 if ( $blank ) {
860 // The current revision is blank and the one before is also
861 // blank. It's just not our lucky day
862 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
863 } else {
864 if ( $onlyAuthor ) {
865 $reason = wfMessage(
866 'excontentauthor',
867 '$1',
868 $onlyAuthor
869 )->inContentLanguage()->text();
870 } else {
871 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
875 if ( $reason == '-' ) {
876 // Allow these UI messages to be blanked out cleanly
877 return '';
880 // Max content length = max comment length - length of the comment (excl. $1)
881 $text = $content ? $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) : '';
883 // Now replace the '$1' placeholder
884 $reason = str_replace( '$1', $text, $reason );
886 return $reason;
890 * Get the Content object that needs to be saved in order to undo all revisions
891 * between $undo and $undoafter. Revisions must belong to the same page,
892 * must exist and must not be deleted.
894 * @since 1.21
896 * @param $current Revision The current text
897 * @param $undo Revision The revision to undo
898 * @param $undoafter Revision Must be an earlier revision than $undo
900 * @return mixed String on success, false on failure
902 public function getUndoContent( Revision $current, Revision $undo, Revision $undoafter ) {
903 $cur_content = $current->getContent();
905 if ( empty( $cur_content ) ) {
906 return false; // no page
909 $undo_content = $undo->getContent();
910 $undoafter_content = $undoafter->getContent();
912 if ( !$undo_content || !$undoafter_content ) {
913 return false; // no content to undo
916 $this->checkModelID( $cur_content->getModel() );
917 $this->checkModelID( $undo_content->getModel() );
918 $this->checkModelID( $undoafter_content->getModel() );
920 if ( $cur_content->equals( $undo_content ) ) {
921 // No use doing a merge if it's just a straight revert.
922 return $undoafter_content;
925 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
927 return $undone_content;
931 * Get parser options suitable for rendering the primary article wikitext
933 * @param IContextSource|User|string $context One of the following:
934 * - IContextSource: Use the User and the Language of the provided
935 * context
936 * - User: Use the provided User object and $wgLang for the language,
937 * so use an IContextSource object if possible.
938 * - 'canonical': Canonical options (anonymous user with default
939 * preferences and content language).
941 * @param IContextSource|User|string $context
943 * @throws MWException
944 * @return ParserOptions
946 public function makeParserOptions( $context ) {
947 global $wgContLang, $wgEnableParserLimitReporting;
949 if ( $context instanceof IContextSource ) {
950 $options = ParserOptions::newFromContext( $context );
951 } elseif ( $context instanceof User ) { // settings per user (even anons)
952 $options = ParserOptions::newFromUser( $context );
953 } elseif ( $context === 'canonical' ) { // canonical settings
954 $options = ParserOptions::newFromUserAndLang( new User, $wgContLang );
955 } else {
956 throw new MWException( "Bad context for parser options: $context" );
959 $options->enableLimitReport( $wgEnableParserLimitReporting ); // show inclusion/loop reports
960 $options->setTidy( true ); // fix bad HTML
962 return $options;
966 * Returns true for content models that support caching using the
967 * ParserCache mechanism. See WikiPage::isParserCacheUsed().
969 * @since 1.21
971 * @return bool
973 public function isParserCacheSupported() {
974 return false;
978 * Returns true if this content model supports sections.
979 * This default implementation returns false.
981 * Content models that return true here should also implement
982 * Content::getSection, Content::replaceSection, etc. to handle sections..
984 * @return boolean whether sections are supported.
986 public function supportsSections() {
987 return false;
991 * Returns true if this content model supports redirects.
992 * This default implementation returns false.
994 * Content models that return true here should also implement
995 * ContentHandler::makeRedirectContent to return a Content object.
997 * @return boolean whether redirects are supported.
999 public function supportsRedirects() {
1000 return false;
1004 * Logs a deprecation warning, visible if $wgDevelopmentWarnings, but only if
1005 * self::$enableDeprecationWarnings is set to true.
1007 * @param string $func The name of the deprecated function
1008 * @param string $version The version since the method is deprecated. Usually 1.21
1009 * for ContentHandler related stuff.
1010 * @param string|bool $component: Component to which the function belongs.
1011 * If false, it is assumed the function is in MediaWiki core.
1013 * @see ContentHandler::$enableDeprecationWarnings
1014 * @see wfDeprecated
1016 public static function deprecated( $func, $version, $component = false ) {
1017 if ( self::$enableDeprecationWarnings ) {
1018 wfDeprecated( $func, $version, $component, 3 );
1023 * Call a legacy hook that uses text instead of Content objects.
1024 * Will log a warning when a matching hook function is registered.
1025 * If the textual representation of the content is changed by the
1026 * hook function, a new Content object is constructed from the new
1027 * text.
1029 * @param string $event event name
1030 * @param array $args parameters passed to hook functions
1031 * @param bool $warn whether to log a warning.
1032 * Default to self::$enableDeprecationWarnings.
1033 * May be set to false for testing.
1035 * @return Boolean True if no handler aborted the hook
1037 * @see ContentHandler::$enableDeprecationWarnings
1039 public static function runLegacyHooks( $event, $args = array(),
1040 $warn = null ) {
1042 if ( $warn === null ) {
1043 $warn = self::$enableDeprecationWarnings;
1046 if ( !Hooks::isRegistered( $event ) ) {
1047 return true; // nothing to do here
1050 if ( $warn ) {
1051 // Log information about which handlers are registered for the legacy hook,
1052 // so we can find and fix them.
1054 $handlers = Hooks::getHandlers( $event );
1055 $handlerInfo = array();
1057 wfSuppressWarnings();
1059 foreach ( $handlers as $handler ) {
1060 if ( is_array( $handler ) ) {
1061 if ( is_object( $handler[0] ) ) {
1062 $info = get_class( $handler[0] );
1063 } else {
1064 $info = $handler[0];
1067 if ( isset( $handler[1] ) ) {
1068 $info .= '::' . $handler[1];
1070 } elseif ( is_object( $handler ) ) {
1071 $info = get_class( $handler[0] );
1072 $info .= '::on' . $event;
1073 } else {
1074 $info = $handler;
1077 $handlerInfo[] = $info;
1080 wfRestoreWarnings();
1082 wfWarn( "Using obsolete hook $event via ContentHandler::runLegacyHooks()! Handlers: " . implode( ', ', $handlerInfo ), 2 );
1085 // convert Content objects to text
1086 $contentObjects = array();
1087 $contentTexts = array();
1089 foreach ( $args as $k => $v ) {
1090 if ( $v instanceof Content ) {
1091 /* @var Content $v */
1093 $contentObjects[$k] = $v;
1095 $v = $v->serialize();
1096 $contentTexts[$k] = $v;
1097 $args[$k] = $v;
1101 // call the hook functions
1102 $ok = wfRunHooks( $event, $args );
1104 // see if the hook changed the text
1105 foreach ( $contentTexts as $k => $orig ) {
1106 /* @var Content $content */
1108 $modified = $args[$k];
1109 $content = $contentObjects[$k];
1111 if ( $modified !== $orig ) {
1112 // text was changed, create updated Content object
1113 $content = $content->getContentHandler()->unserializeContent( $modified );
1116 $args[$k] = $content;
1119 return $ok;