Remove silly 'm' prefix from StubObject/DeprecatedGlobal members
[mediawiki.git] / includes / content / ContentHandler.php
blobdd7e27dcb9e915ae3b35a213dfecd926598b01e8
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 {
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.
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.
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.
53 * @ingroup Content
55 abstract class ContentHandler {
56 /**
57 * Switch for enabling deprecation warnings. Used by ContentHandler::deprecated()
58 * and ContentHandler::runLegacyHooks().
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.
63 protected static $enableDeprecationWarnings = false;
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!
70 * If $content is null, this method returns the empty string.
72 * If $content is an instance of TextContent, this method returns the flat
73 * text as returned by $content->getNativeData().
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.
86 * @since 1.21
88 * @param Content $content
90 * @throws MWException If the content is not an instance of TextContent and
91 * wgContentHandlerTextFallback was set to 'fail'.
92 * @return string|null Textual form of the content, if available.
94 public static function getContentText( Content $content = null ) {
95 global $wgContentHandlerTextFallback;
97 if ( is_null( $content ) ) {
98 return '';
101 if ( $content instanceof TextContent ) {
102 return $content->getNativeData();
105 wfDebugLog( 'ContentHandler', 'Accessing ' . $content->getModel() . ' content as text!' );
107 if ( $wgContentHandlerTextFallback == 'fail' ) {
108 throw new MWException(
109 "Attempt to get text from Content with model " .
110 $content->getModel()
114 if ( $wgContentHandlerTextFallback == 'serialize' ) {
115 return $content->serialize();
118 return null;
122 * Convenience function for creating a Content object from a given textual
123 * representation.
125 * $text will be deserialized into a Content object of the model specified
126 * by $modelId (or, if that is not given, $title->getContentModel()) using
127 * the given format.
129 * @since 1.21
131 * @param string $text The textual representation, will be
132 * unserialized to create the Content object
133 * @param Title $title The title of the page this text belongs to.
134 * Required if $modelId is not provided.
135 * @param string $modelId The model to deserialize to. If not provided,
136 * $title->getContentModel() is used.
137 * @param string $format The format to use for deserialization. If not
138 * given, the model's default format is used.
140 * @throws MWException If model ID or format is not supported or if the text can not be
141 * unserialized using the format.
142 * @return Content A Content object representing the text.
144 public static function makeContent( $text, Title $title = null,
145 $modelId = null, $format = null ) {
146 if ( is_null( $modelId ) ) {
147 if ( is_null( $title ) ) {
148 throw new MWException( "Must provide a Title object or a content model ID." );
151 $modelId = $title->getContentModel();
154 $handler = ContentHandler::getForModelID( $modelId );
156 return $handler->unserializeContent( $text, $format );
160 * Returns the name of the default content model to be used for the page
161 * with the given title.
163 * Note: There should rarely be need to call this method directly.
164 * To determine the actual content model for a given page, use
165 * Title::getContentModel().
167 * Which model is to be used by default for the page is determined based
168 * on several factors:
169 * - The global setting $wgNamespaceContentModels specifies a content model
170 * per namespace.
171 * - The hook ContentHandlerDefaultModelFor may be used to override the page's default
172 * model.
173 * - Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript
174 * model if they end in .js or .css, respectively.
175 * - Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
176 * - The hook TitleIsCssOrJsPage may be used to force a page to use the CSS
177 * or JavaScript model. This is a compatibility feature. The ContentHandlerDefaultModelFor
178 * hook should be used instead if possible.
179 * - The hook TitleIsWikitextPage may be used to force a page to use the
180 * wikitext model. This is a compatibility feature. The ContentHandlerDefaultModelFor
181 * hook should be used instead if possible.
183 * If none of the above applies, the wikitext model is used.
185 * Note: this is used by, and may thus not use, Title::getContentModel()
187 * @since 1.21
189 * @param Title $title
191 * @return string Default model name for the page given by $title
193 public static function getDefaultModelFor( Title $title ) {
194 // NOTE: this method must not rely on $title->getContentModel() directly or indirectly,
195 // because it is used to initialize the mContentModel member.
197 $ns = $title->getNamespace();
199 $ext = false;
200 $m = null;
201 $model = MWNamespace::getNamespaceContentModel( $ns );
203 // Hook can determine default model
204 if ( !wfRunHooks( 'ContentHandlerDefaultModelFor', array( $title, &$model ) ) ) {
205 if ( !is_null( $model ) ) {
206 return $model;
210 // Could this page contain custom CSS or JavaScript, based on the title?
211 $isCssOrJsPage = NS_MEDIAWIKI == $ns && preg_match( '!\.(css|js)$!u', $title->getText(), $m );
212 if ( $isCssOrJsPage ) {
213 $ext = $m[1];
216 // Hook can force JS/CSS
217 wfRunHooks( 'TitleIsCssOrJsPage', array( $title, &$isCssOrJsPage ) );
219 // Is this a .css subpage of a user page?
220 $isJsCssSubpage = NS_USER == $ns
221 && !$isCssOrJsPage
222 && preg_match( "/\\/.*\\.(js|css)$/", $title->getText(), $m );
223 if ( $isJsCssSubpage ) {
224 $ext = $m[1];
227 // Is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
228 $isWikitext = is_null( $model ) || $model == CONTENT_MODEL_WIKITEXT;
229 $isWikitext = $isWikitext && !$isCssOrJsPage && !$isJsCssSubpage;
231 // Hook can override $isWikitext
232 wfRunHooks( 'TitleIsWikitextPage', array( $title, &$isWikitext ) );
234 if ( !$isWikitext ) {
235 switch ( $ext ) {
236 case 'js':
237 return CONTENT_MODEL_JAVASCRIPT;
238 case 'css':
239 return CONTENT_MODEL_CSS;
240 default:
241 return is_null( $model ) ? CONTENT_MODEL_TEXT : $model;
245 // We established that it must be wikitext
247 return CONTENT_MODEL_WIKITEXT;
251 * Returns the appropriate ContentHandler singleton for the given title.
253 * @since 1.21
255 * @param Title $title
257 * @return ContentHandler
259 public static function getForTitle( Title $title ) {
260 $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
273 * @return ContentHandler
275 public static function getForContent( Content $content ) {
276 $modelId = $content->getModel();
278 return ContentHandler::getForModelID( $modelId );
282 * @var array A Cache of ContentHandler instances by model id
284 protected static $handlers;
287 * Returns the ContentHandler singleton for the given model ID. Use the
288 * CONTENT_MODEL_XXX constants to identify the desired content model.
290 * ContentHandler singletons are taken from the global $wgContentHandlers
291 * array. Keys in that array are model names, the values are either
292 * ContentHandler singleton objects, or strings specifying the appropriate
293 * subclass of ContentHandler.
295 * If a class name is encountered when looking up the singleton for a given
296 * model name, the class is instantiated and the class name is replaced by
297 * the resulting singleton in $wgContentHandlers.
299 * If no ContentHandler is defined for the desired $modelId, the
300 * ContentHandler may be provided by the ContentHandlerForModelID hook.
301 * If no ContentHandler can be determined, an MWException is raised.
303 * @since 1.21
305 * @param string $modelId The ID of the content model for which to get a
306 * handler. Use CONTENT_MODEL_XXX constants.
308 * @throws MWException If no handler is known for the model ID.
309 * @return ContentHandler The ContentHandler singleton for handling the model given by the ID.
311 public static function getForModelID( $modelId ) {
312 global $wgContentHandlers;
314 if ( isset( ContentHandler::$handlers[$modelId] ) ) {
315 return ContentHandler::$handlers[$modelId];
318 if ( empty( $wgContentHandlers[$modelId] ) ) {
319 $handler = null;
321 wfRunHooks( 'ContentHandlerForModelID', array( $modelId, &$handler ) );
323 if ( $handler === null ) {
324 throw new MWException( "No handler for model '$modelId' registered in \$wgContentHandlers" );
327 if ( !( $handler instanceof ContentHandler ) ) {
328 throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
330 } else {
331 $class = $wgContentHandlers[$modelId];
332 $handler = new $class( $modelId );
334 if ( !( $handler instanceof ContentHandler ) ) {
335 throw new MWException( "$class from \$wgContentHandlers is not " .
336 "compatible with ContentHandler" );
340 wfDebugLog( 'ContentHandler', 'Created handler for ' . $modelId
341 . ': ' . get_class( $handler ) );
343 ContentHandler::$handlers[$modelId] = $handler;
345 return ContentHandler::$handlers[$modelId];
349 * Returns the localized name for a given content model.
351 * Model names are localized using system messages. Message keys
352 * have the form content-model-$name, where $name is getContentModelName( $id ).
354 * @param string $name The content model ID, as given by a CONTENT_MODEL_XXX
355 * constant or returned by Revision::getContentModel().
357 * @throws MWException If the model ID isn't known.
358 * @return string The content model's localized name.
360 public static function getLocalizedName( $name ) {
361 // Messages: content-model-wikitext, content-model-text,
362 // content-model-javascript, content-model-css
363 $key = "content-model-$name";
365 $msg = wfMessage( $key );
367 return $msg->exists() ? $msg->plain() : $name;
370 public static function getContentModels() {
371 global $wgContentHandlers;
373 return array_keys( $wgContentHandlers );
376 public static function getAllContentFormats() {
377 global $wgContentHandlers;
379 $formats = array();
381 foreach ( $wgContentHandlers as $model => $class ) {
382 $handler = ContentHandler::getForModelID( $model );
383 $formats = array_merge( $formats, $handler->getSupportedFormats() );
386 $formats = array_unique( $formats );
388 return $formats;
391 // ------------------------------------------------------------------------
394 * @var string
396 protected $mModelID;
399 * @var string[]
401 protected $mSupportedFormats;
404 * Constructor, initializing the ContentHandler instance with its model ID
405 * and a list of supported formats. Values for the parameters are typically
406 * provided as literals by subclass's constructors.
408 * @param string $modelId (use CONTENT_MODEL_XXX constants).
409 * @param string[] $formats List for supported serialization formats
410 * (typically as MIME types)
412 public function __construct( $modelId, $formats ) {
413 $this->mModelID = $modelId;
414 $this->mSupportedFormats = $formats;
416 $this->mModelName = preg_replace( '/(Content)?Handler$/', '', get_class( $this ) );
417 $this->mModelName = preg_replace( '/[_\\\\]/', '', $this->mModelName );
418 $this->mModelName = strtolower( $this->mModelName );
422 * Serializes a Content object of the type supported by this ContentHandler.
424 * @since 1.21
426 * @param Content $content The Content object to serialize
427 * @param string $format The desired serialization format
429 * @return string Serialized form of the content
431 abstract public function serializeContent( Content $content, $format = null );
434 * Unserializes a Content object of the type supported by this ContentHandler.
436 * @since 1.21
438 * @param string $blob Serialized form of the content
439 * @param string $format The format used for serialization
441 * @return Content The Content object created by deserializing $blob
443 abstract public function unserializeContent( $blob, $format = null );
446 * Creates an empty Content object of the type supported by this
447 * ContentHandler.
449 * @since 1.21
451 * @return Content
453 abstract public function makeEmptyContent();
456 * Creates a new Content object that acts as a redirect to the given page,
457 * or null if redirects are not supported by this content model.
459 * This default implementation always returns null. Subclasses supporting redirects
460 * must override this method.
462 * Note that subclasses that override this method to return a Content object
463 * should also override supportsRedirects() to return true.
465 * @since 1.21
467 * @param Title $destination The page to redirect to.
468 * @param string $text Text to include in the redirect, if possible.
470 * @return Content Always null.
472 public function makeRedirectContent( Title $destination, $text = '' ) {
473 return null;
477 * Returns the model id that identifies the content model this
478 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
480 * @since 1.21
482 * @return string The model ID
484 public function getModelID() {
485 return $this->mModelID;
489 * @since 1.21
491 * @param string $model_id The model to check
493 * @throws MWException If the model ID is not the ID of the content model supported by this
494 * ContentHandler.
496 protected function checkModelID( $model_id ) {
497 if ( $model_id !== $this->mModelID ) {
498 throw new MWException( "Bad content model: " .
499 "expected {$this->mModelID} " .
500 "but got $model_id." );
505 * Returns a list of serialization formats supported by the
506 * serializeContent() and unserializeContent() methods of this
507 * ContentHandler.
509 * @since 1.21
511 * @return string[] List of serialization formats as MIME type like strings
513 public function getSupportedFormats() {
514 return $this->mSupportedFormats;
518 * The format used for serialization/deserialization by default by this
519 * ContentHandler.
521 * This default implementation will return the first element of the array
522 * of formats that was passed to the constructor.
524 * @since 1.21
526 * @return string The name of the default serialization format as a MIME type
528 public function getDefaultFormat() {
529 return $this->mSupportedFormats[0];
533 * Returns true if $format is a serialization format supported by this
534 * ContentHandler, and false otherwise.
536 * Note that if $format is null, this method always returns true, because
537 * null means "use the default format".
539 * @since 1.21
541 * @param string $format The serialization format to check
543 * @return bool
545 public function isSupportedFormat( $format ) {
546 if ( !$format ) {
547 return true; // this means "use the default"
550 return in_array( $format, $this->mSupportedFormats );
554 * Convenient for checking whether a format provided as a parameter is actually supported.
556 * @param string $format The serialization format to check
558 * @throws MWException If the format is not supported by this content handler.
560 protected function checkFormat( $format ) {
561 if ( !$this->isSupportedFormat( $format ) ) {
562 throw new MWException(
563 "Format $format is not supported for content model "
564 . $this->getModelID()
570 * Returns overrides for action handlers.
571 * Classes listed here will be used instead of the default one when
572 * (and only when) $wgActions[$action] === true. This allows subclasses
573 * to override the default action handlers.
575 * @since 1.21
577 * @return array Always an empty array.
579 public function getActionOverrides() {
580 return array();
584 * Factory for creating an appropriate DifferenceEngine for this content model.
586 * @since 1.21
588 * @param IContextSource $context Context to use, anything else will be ignored.
589 * @param int $old Revision ID we want to show and diff with.
590 * @param int|string $new Either a revision ID or one of the strings 'cur', 'prev' or 'next'.
591 * @param int $rcid FIXME: Deprecated, no longer used. Defaults to 0.
592 * @param bool $refreshCache If set, refreshes the diff cache. Defaults to false.
593 * @param bool $unhide If set, allow viewing deleted revs. Defaults to false.
595 * @return DifferenceEngine
597 public function createDifferenceEngine( IContextSource $context, $old = 0, $new = 0,
598 $rcid = 0, //FIXME: Deprecated, no longer used
599 $refreshCache = false, $unhide = false ) {
600 $diffEngineClass = $this->getDiffEngineClass();
602 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
606 * Get the language in which the content of the given page is written.
608 * This default implementation just returns $wgContLang (except for pages
609 * in the MediaWiki namespace)
611 * Note that the pages language is not cacheable, since it may in some
612 * cases depend on user settings.
614 * Also note that the page language may or may not depend on the actual content of the page,
615 * that is, this method may load the content in order to determine the language.
617 * @since 1.21
619 * @param Title $title The page to determine the language for.
620 * @param Content $content The page's content, if you have it handy, to avoid reloading it.
622 * @return Language The page's language
624 public function getPageLanguage( Title $title, Content $content = null ) {
625 global $wgContLang, $wgLang;
626 $pageLang = $wgContLang;
628 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
629 // Parse mediawiki messages with correct target language
630 list( /* $unused */, $lang ) = MessageCache::singleton()->figureMessage( $title->getText() );
631 $pageLang = wfGetLangObj( $lang );
634 wfRunHooks( 'PageContentLanguage', array( $title, &$pageLang, $wgLang ) );
636 return wfGetLangObj( $pageLang );
640 * Get the language in which the content of this page is written when
641 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
642 * specified a preferred variant, the variant will be used.
644 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
645 * the user specified a preferred variant.
647 * Note that the pages view language is not cacheable, since it depends on user settings.
649 * Also note that the page language may or may not depend on the actual content of the page,
650 * that is, this method may load the content in order to determine the language.
652 * @since 1.21
654 * @param Title $title The page to determine the language for.
655 * @param Content $content The page's content, if you have it handy, to avoid reloading it.
657 * @return Language The page's language for viewing
659 public function getPageViewLanguage( Title $title, Content $content = null ) {
660 $pageLang = $this->getPageLanguage( $title, $content );
662 if ( $title->getNamespace() !== NS_MEDIAWIKI ) {
663 // If the user chooses a variant, the content is actually
664 // in a language whose code is the variant code.
665 $variant = $pageLang->getPreferredVariant();
666 if ( $pageLang->getCode() !== $variant ) {
667 $pageLang = Language::factory( $variant );
671 return $pageLang;
675 * Determines whether the content type handled by this ContentHandler
676 * can be used on the given page.
678 * This default implementation always returns true.
679 * Subclasses may override this to restrict the use of this content model to specific locations,
680 * typically based on the namespace or some other aspect of the title, such as a special suffix
681 * (e.g. ".svg" for SVG content).
683 * @note: this calls the ContentHandlerCanBeUsedOn hook which may be used to override which
684 * content model can be used where.
686 * @param Title $title The page's title.
688 * @return bool True if content of this kind can be used on the given page, false otherwise.
690 public function canBeUsedOn( Title $title ) {
691 $ok = true;
693 wfRunHooks( 'ContentModelCanBeUsedOn', array( $this->getModelID(), $title, &$ok ) );
695 return $ok;
699 * Returns the name of the diff engine to use.
701 * @since 1.21
703 * @return string
705 protected function getDiffEngineClass() {
706 return 'DifferenceEngine';
710 * Attempts to merge differences between three versions. Returns a new
711 * Content object for a clean merge and false for failure or a conflict.
713 * This default implementation always returns false.
715 * @since 1.21
717 * @param Content|string $oldContent The page's previous content.
718 * @param Content|string $myContent One of the page's conflicting contents.
719 * @param Content|string $yourContent One of the page's conflicting contents.
721 * @return Content|bool Always false.
723 public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
724 return false;
728 * Return an applicable auto-summary if one exists for the given edit.
730 * @since 1.21
732 * @param Content $oldContent The previous text of the page.
733 * @param Content $newContent The submitted text of the page.
734 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
736 * @return string An appropriate auto-summary, or an empty string.
738 public function getAutosummary( Content $oldContent = null, Content $newContent = null,
739 $flags ) {
740 // Decide what kind of auto-summary is needed.
742 // Redirect auto-summaries
745 * @var $ot Title
746 * @var $rt Title
749 $ot = !is_null( $oldContent ) ? $oldContent->getRedirectTarget() : null;
750 $rt = !is_null( $newContent ) ? $newContent->getRedirectTarget() : null;
752 if ( is_object( $rt ) ) {
753 if ( !is_object( $ot )
754 || !$rt->equals( $ot )
755 || $ot->getFragment() != $rt->getFragment()
757 $truncatedtext = $newContent->getTextForSummary(
759 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
760 - strlen( $rt->getFullText() ) );
762 return wfMessage( 'autoredircomment', $rt->getFullText() )
763 ->rawParams( $truncatedtext )->inContentLanguage()->text();
767 // New page auto-summaries
768 if ( $flags & EDIT_NEW && $newContent->getSize() > 0 ) {
769 // If they're making a new article, give its text, truncated, in
770 // the summary.
772 $truncatedtext = $newContent->getTextForSummary(
773 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
775 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
776 ->inContentLanguage()->text();
779 // Blanking auto-summaries
780 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
781 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
782 } elseif ( !empty( $oldContent )
783 && $oldContent->getSize() > 10 * $newContent->getSize()
784 && $newContent->getSize() < 500
786 // Removing more than 90% of the article
788 $truncatedtext = $newContent->getTextForSummary(
789 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
791 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
792 ->inContentLanguage()->text();
795 // If we reach this point, there's no applicable auto-summary for our
796 // case, so our auto-summary is empty.
797 return '';
801 * Auto-generates a deletion reason
803 * @since 1.21
805 * @param Title $title The page's title
806 * @param bool &$hasHistory Whether the page has a history
808 * @return mixed String containing deletion reason or empty string, or
809 * boolean false if no revision occurred
811 * @XXX &$hasHistory is extremely ugly, it's here because
812 * WikiPage::getAutoDeleteReason() and Article::generateReason()
813 * have it / want it.
815 public function getAutoDeleteReason( Title $title, &$hasHistory ) {
816 $dbw = wfGetDB( DB_MASTER );
818 // Get the last revision
819 $rev = Revision::newFromTitle( $title );
821 if ( is_null( $rev ) ) {
822 return false;
825 // Get the article's contents
826 $content = $rev->getContent();
827 $blank = false;
829 // If the page is blank, use the text from the previous revision,
830 // which can only be blank if there's a move/import/protect dummy
831 // revision involved
832 if ( !$content || $content->isEmpty() ) {
833 $prev = $rev->getPrevious();
835 if ( $prev ) {
836 $rev = $prev;
837 $content = $rev->getContent();
838 $blank = true;
842 $this->checkModelID( $rev->getContentModel() );
844 // Find out if there was only one contributor
845 // Only scan the last 20 revisions
846 $res = $dbw->select( 'revision', 'rev_user_text',
847 array(
848 'rev_page' => $title->getArticleID(),
849 $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0'
851 __METHOD__,
852 array( 'LIMIT' => 20 )
855 if ( $res === false ) {
856 // This page has no revisions, which is very weird
857 return false;
860 $hasHistory = ( $res->numRows() > 1 );
861 $row = $dbw->fetchObject( $res );
863 if ( $row ) { // $row is false if the only contributor is hidden
864 $onlyAuthor = $row->rev_user_text;
865 // Try to find a second contributor
866 foreach ( $res as $row ) {
867 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
868 $onlyAuthor = false;
869 break;
872 } else {
873 $onlyAuthor = false;
876 // Generate the summary with a '$1' placeholder
877 if ( $blank ) {
878 // The current revision is blank and the one before is also
879 // blank. It's just not our lucky day
880 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
881 } else {
882 if ( $onlyAuthor ) {
883 $reason = wfMessage(
884 'excontentauthor',
885 '$1',
886 $onlyAuthor
887 )->inContentLanguage()->text();
888 } else {
889 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
893 if ( $reason == '-' ) {
894 // Allow these UI messages to be blanked out cleanly
895 return '';
898 // Max content length = max comment length - length of the comment (excl. $1)
899 $text = $content ? $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) : '';
901 // Now replace the '$1' placeholder
902 $reason = str_replace( '$1', $text, $reason );
904 return $reason;
908 * Get the Content object that needs to be saved in order to undo all revisions
909 * between $undo and $undoafter. Revisions must belong to the same page,
910 * must exist and must not be deleted.
912 * @since 1.21
914 * @param Revision $current The current text
915 * @param Revision $undo The revision to undo
916 * @param Revision $undoafter Must be an earlier revision than $undo
918 * @return mixed String on success, false on failure
920 public function getUndoContent( Revision $current, Revision $undo, Revision $undoafter ) {
921 $cur_content = $current->getContent();
923 if ( empty( $cur_content ) ) {
924 return false; // no page
927 $undo_content = $undo->getContent();
928 $undoafter_content = $undoafter->getContent();
930 if ( !$undo_content || !$undoafter_content ) {
931 return false; // no content to undo
934 $this->checkModelID( $cur_content->getModel() );
935 $this->checkModelID( $undo_content->getModel() );
936 $this->checkModelID( $undoafter_content->getModel() );
938 if ( $cur_content->equals( $undo_content ) ) {
939 // No use doing a merge if it's just a straight revert.
940 return $undoafter_content;
943 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
945 return $undone_content;
949 * Get parser options suitable for rendering and caching the article
951 * @param IContextSource|User|string $context One of the following:
952 * - IContextSource: Use the User and the Language of the provided
953 * context
954 * - User: Use the provided User object and $wgLang for the language,
955 * so use an IContextSource object if possible.
956 * - 'canonical': Canonical options (anonymous user with default
957 * preferences and content language).
959 * @throws MWException
960 * @return ParserOptions
962 public function makeParserOptions( $context ) {
963 global $wgContLang, $wgEnableParserLimitReporting;
965 if ( $context instanceof IContextSource ) {
966 $options = ParserOptions::newFromContext( $context );
967 } elseif ( $context instanceof User ) { // settings per user (even anons)
968 $options = ParserOptions::newFromUser( $context );
969 } elseif ( $context === 'canonical' ) { // canonical settings
970 $options = ParserOptions::newFromUserAndLang( new User, $wgContLang );
971 } else {
972 throw new MWException( "Bad context for parser options: $context" );
975 $options->enableLimitReport( $wgEnableParserLimitReporting ); // show inclusion/loop reports
976 $options->setTidy( true ); // fix bad HTML
978 return $options;
982 * Returns true for content models that support caching using the
983 * ParserCache mechanism. See WikiPage::isParserCacheUsed().
985 * @since 1.21
987 * @return bool Always false.
989 public function isParserCacheSupported() {
990 return false;
994 * Returns true if this content model supports sections.
995 * This default implementation returns false.
997 * Content models that return true here should also implement
998 * Content::getSection, Content::replaceSection, etc. to handle sections..
1000 * @return bool Always false.
1002 public function supportsSections() {
1003 return false;
1007 * Returns true if this content model supports redirects.
1008 * This default implementation returns false.
1010 * Content models that return true here should also implement
1011 * ContentHandler::makeRedirectContent to return a Content object.
1013 * @return bool Always false.
1015 public function supportsRedirects() {
1016 return false;
1020 * Logs a deprecation warning, visible if $wgDevelopmentWarnings, but only if
1021 * self::$enableDeprecationWarnings is set to true.
1023 * @param string $func The name of the deprecated function
1024 * @param string $version The version since the method is deprecated. Usually 1.21
1025 * for ContentHandler related stuff.
1026 * @param string|bool $component : Component to which the function belongs.
1027 * If false, it is assumed the function is in MediaWiki core.
1029 * @see ContentHandler::$enableDeprecationWarnings
1030 * @see wfDeprecated
1032 public static function deprecated( $func, $version, $component = false ) {
1033 if ( self::$enableDeprecationWarnings ) {
1034 wfDeprecated( $func, $version, $component, 3 );
1039 * Call a legacy hook that uses text instead of Content objects.
1040 * Will log a warning when a matching hook function is registered.
1041 * If the textual representation of the content is changed by the
1042 * hook function, a new Content object is constructed from the new
1043 * text.
1045 * @param string $event Event name
1046 * @param array $args Parameters passed to hook functions
1047 * @param bool $warn Whether to log a warning.
1048 * Default to self::$enableDeprecationWarnings.
1049 * May be set to false for testing.
1051 * @return bool True if no handler aborted the hook
1053 * @see ContentHandler::$enableDeprecationWarnings
1055 public static function runLegacyHooks( $event, $args = array(),
1056 $warn = null
1059 if ( $warn === null ) {
1060 $warn = self::$enableDeprecationWarnings;
1063 if ( !Hooks::isRegistered( $event ) ) {
1064 return true; // nothing to do here
1067 if ( $warn ) {
1068 // Log information about which handlers are registered for the legacy hook,
1069 // so we can find and fix them.
1071 $handlers = Hooks::getHandlers( $event );
1072 $handlerInfo = array();
1074 wfSuppressWarnings();
1076 foreach ( $handlers as $handler ) {
1077 if ( is_array( $handler ) ) {
1078 if ( is_object( $handler[0] ) ) {
1079 $info = get_class( $handler[0] );
1080 } else {
1081 $info = $handler[0];
1084 if ( isset( $handler[1] ) ) {
1085 $info .= '::' . $handler[1];
1087 } elseif ( is_object( $handler ) ) {
1088 $info = get_class( $handler[0] );
1089 $info .= '::on' . $event;
1090 } else {
1091 $info = $handler;
1094 $handlerInfo[] = $info;
1097 wfRestoreWarnings();
1099 wfWarn( "Using obsolete hook $event via ContentHandler::runLegacyHooks()! Handlers: " .
1100 implode( ', ', $handlerInfo ), 2 );
1103 // convert Content objects to text
1104 $contentObjects = array();
1105 $contentTexts = array();
1107 foreach ( $args as $k => $v ) {
1108 if ( $v instanceof Content ) {
1109 /* @var Content $v */
1111 $contentObjects[$k] = $v;
1113 $v = $v->serialize();
1114 $contentTexts[$k] = $v;
1115 $args[$k] = $v;
1119 // call the hook functions
1120 $ok = wfRunHooks( $event, $args );
1122 // see if the hook changed the text
1123 foreach ( $contentTexts as $k => $orig ) {
1124 /* @var Content $content */
1126 $modified = $args[$k];
1127 $content = $contentObjects[$k];
1129 if ( $modified !== $orig ) {
1130 // text was changed, create updated Content object
1131 $content = $content->getContentHandler()->unserializeContent( $modified );
1134 $args[$k] = $content;
1137 return $ok;