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
25 * @author Daniel Kinzler
29 * Exception representing a failure to serialize or unserialize a content object.
33 class MWContentSerializationException
extends MWException
{
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
55 abstract class ContentHandler
{
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;
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.
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'.
93 public static function getContentText( Content
$content = null ) {
94 global $wgContentHandlerTextFallback;
96 if ( is_null( $content ) ) {
100 if ( $content instanceof TextContent
) {
101 return $content->getNativeData();
104 wfDebugLog( 'ContentHandler', 'Accessing ' . $content->getModel() . ' content as text!' );
106 if ( $wgContentHandlerTextFallback == 'fail' ) {
107 throw new MWException(
108 "Attempt to get text from Content with model " .
113 if ( $wgContentHandlerTextFallback == 'serialize' ) {
114 return $content->serialize();
121 * Convenience function for creating a Content object from a given textual
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
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.
139 * @throws MWException
140 * @return Content a Content object representing $text
142 * @throws MWException if $model or $format is not supported or if $text can
143 * not be unserialized using $format.
145 public static function makeContent( $text, Title
$title = null,
146 $modelId = null, $format = null
148 if ( is_null( $modelId ) ) {
149 if ( is_null( $title ) ) {
150 throw new MWException( "Must provide a Title object or a content model ID." );
153 $modelId = $title->getContentModel();
156 $handler = ContentHandler
::getForModelID( $modelId );
158 return $handler->unserializeContent( $text, $format );
162 * Returns the name of the default content model to be used for the page
163 * with the given title.
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().
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
173 * - The hook ContentHandlerDefaultModelFor may be used to override the page's default
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.
185 * If none of the above applies, the wikitext model is used.
187 * Note: this is used by, and may thus not use, Title::getContentModel()
191 * @param $title Title
192 * @return null|string default model name for the page given by $title
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.
198 $ns = $title->getNamespace();
202 $model = MWNamespace
::getNamespaceContentModel( $ns );
204 // Hook can determine default model
205 if ( !wfRunHooks( 'ContentHandlerDefaultModelFor', array( $title, &$model ) ) ) {
206 if ( !is_null( $model ) ) {
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 ) {
217 // Hook can force JS/CSS
218 wfRunHooks( 'TitleIsCssOrJsPage', array( $title, &$isCssOrJsPage ) );
220 // Is this a .css subpage of a user page?
221 $isJsCssSubpage = NS_USER
== $ns
223 && preg_match( "/\\/.*\\.(js|css)$/", $title->getText(), $m );
224 if ( $isJsCssSubpage ) {
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;
232 // Hook can override $isWikitext
233 wfRunHooks( 'TitleIsWikitextPage', array( $title, &$isWikitext ) );
235 if ( !$isWikitext ) {
238 return CONTENT_MODEL_JAVASCRIPT
;
240 return CONTENT_MODEL_CSS
;
242 return is_null( $model ) ? CONTENT_MODEL_TEXT
: $model;
246 // We established that it must be wikitext
248 return CONTENT_MODEL_WIKITEXT
;
252 * Returns the appropriate ContentHandler singleton for the given title.
256 * @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
271 * @param $content Content
272 * @return ContentHandler
274 public static function getForContent( Content
$content ) {
275 $modelId = $content->getModel();
277 return ContentHandler
::getForModelID( $modelId );
281 * @var array A Cache of ContentHandler instances by model id
283 protected static $handlers;
286 * Returns the ContentHandler singleton for the given model ID. Use the
287 * CONTENT_MODEL_XXX constants to identify the desired content model.
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.
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.
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.
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.
310 public static function getForModelID( $modelId ) {
311 global $wgContentHandlers;
313 if ( isset( ContentHandler
::$handlers[$modelId] ) ) {
314 return ContentHandler
::$handlers[$modelId];
317 if ( empty( $wgContentHandlers[$modelId] ) ) {
320 wfRunHooks( 'ContentHandlerForModelID', array( $modelId, &$handler ) );
322 if ( $handler === null ) {
323 throw new MWException( "No handler for model '$modelId' registered in \$wgContentHandlers" );
326 if ( !( $handler instanceof ContentHandler
) ) {
327 throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
330 $class = $wgContentHandlers[$modelId];
331 $handler = new $class( $modelId );
333 if ( !( $handler instanceof ContentHandler
) ) {
334 throw new MWException( "$class from \$wgContentHandlers is not " .
335 "compatible with ContentHandler" );
339 wfDebugLog( 'ContentHandler', 'Created handler for ' . $modelId
340 . ': ' . get_class( $handler ) );
342 ContentHandler
::$handlers[$modelId] = $handler;
344 return ContentHandler
::$handlers[$modelId];
348 * Returns the localized name for a given content model.
350 * Model names are localized using system messages. Message keys
351 * have the form content-model-$name, where $name is getContentModelName( $id ).
353 * @param string $name The content model ID, as given by a CONTENT_MODEL_XXX
354 * constant or returned by Revision::getContentModel().
356 * @return string The content model's localized name.
357 * @throws MWException if the model id isn't known.
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";
364 $msg = wfMessage( $key );
366 return $msg->exists() ?
$msg->plain() : $name;
369 public static function getContentModels() {
370 global $wgContentHandlers;
372 return array_keys( $wgContentHandlers );
375 public static function getAllContentFormats() {
376 global $wgContentHandlers;
380 foreach ( $wgContentHandlers as $model => $class ) {
381 $handler = ContentHandler
::getForModelID( $model );
382 $formats = array_merge( $formats, $handler->getSupportedFormats() );
385 $formats = array_unique( $formats );
390 // ------------------------------------------------------------------------
393 protected $mSupportedFormats;
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.
400 * @param string $modelId (use CONTENT_MODEL_XXX constants).
401 * @param array $formats List for supported serialization formats
402 * (typically as MIME types)
404 public function __construct( $modelId, $formats ) {
405 $this->mModelID
= $modelId;
406 $this->mSupportedFormats
= $formats;
408 $this->mModelName
= preg_replace( '/(Content)?Handler$/', '', get_class( $this ) );
409 $this->mModelName
= preg_replace( '/[_\\\\]/', '', $this->mModelName
);
410 $this->mModelName
= strtolower( $this->mModelName
);
414 * Serializes a Content object of the type supported by this ContentHandler.
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
422 abstract public function serializeContent( Content
$content, $format = null );
425 * Unserializes a Content object of the type supported by this ContentHandler.
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
433 abstract public function unserializeContent( $blob, $format = null );
436 * Creates an empty Content object of the type supported by this
443 abstract public function makeEmptyContent();
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.
449 * This default implementation always returns null. Subclasses supporting redirects
450 * must override this method.
452 * Note that subclasses that override this method to return a Content object
453 * should also override supportsRedirects() to return true.
457 * @param Title $destination the page to redirect to.
458 * @param string $text text to include in the redirect, if possible.
462 public function makeRedirectContent( Title
$destination, $text = '' ) {
467 * Returns the model id that identifies the content model this
468 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
472 * @return String The model ID
474 public function getModelID() {
475 return $this->mModelID
;
479 * Throws an MWException if $model_id is not the ID of the content model
480 * supported by this ContentHandler.
484 * @param string $model_id The model to check
486 * @throws MWException
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." );
497 * Returns a list of serialization formats supported by the
498 * serializeContent() and unserializeContent() methods of this
503 * @return array of serialization formats as MIME type like strings
505 public function getSupportedFormats() {
506 return $this->mSupportedFormats
;
510 * The format used for serialization/deserialization by default by this
513 * This default implementation will return the first element of the array
514 * of formats that was passed to the constructor.
518 * @return string the name of the default serialization format as a MIME type
520 public function getDefaultFormat() {
521 return $this->mSupportedFormats
[0];
525 * Returns true if $format is a serialization format supported by this
526 * ContentHandler, and false otherwise.
528 * Note that if $format is null, this method always returns true, because
529 * null means "use the default format".
533 * @param string $format the serialization format to check
536 public function isSupportedFormat( $format ) {
539 return true; // this means "use the default"
542 return in_array( $format, $this->mSupportedFormats
);
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.
550 * @param string $format the serialization format to check
552 * @throws MWException
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()
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.
573 public function getActionOverrides() {
578 * Factory for creating an appropriate DifferenceEngine for this content model.
582 * @param $context IContextSource context to use, anything else will be
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
590 * @return DifferenceEngine
592 public function createDifferenceEngine( IContextSource
$context,
594 $rcid = 0, # FIXME: use everywhere!
595 $refreshCache = false, $unhide = false
597 $diffEngineClass = $this->getDiffEngineClass();
599 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
603 * Get the language in which the content of the given page is written.
605 * This default implementation just returns $wgContLang (except for pages
606 * in the MediaWiki namespace)
608 * Note that the pages language is not cacheable, since it may in some
609 * cases depend on user settings.
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.
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.
619 * @return Language the page's language
621 public function getPageLanguage( Title
$title, Content
$content = null ) {
622 global $wgContLang, $wgLang;
623 $pageLang = $wgContLang;
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 );
631 wfRunHooks( 'PageContentLanguage', array( $title, &$pageLang, $wgLang ) );
633 return wfGetLangObj( $pageLang );
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.
641 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
642 * the user specified a preferred variant.
644 * Note that the pages view language is not cacheable, since it depends on user settings.
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.
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.
654 * @return Language the page's language for viewing
656 public function getPageViewLanguage( Title
$title, Content
$content = null ) {
657 $pageLang = $this->getPageLanguage( $title, $content );
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 );
672 * Determines whether the content type handled by this ContentHandler
673 * can be used on the given page.
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).
680 * @note: this calls the ContentHandlerCanBeUsedOn hook which may be used to override which
681 * content model can be used where.
683 * @param Title $title the page's title.
685 * @return bool true if content of this kind can be used on the given page, false otherwise.
687 public function canBeUsedOn( Title
$title ) {
690 wfRunHooks( 'ContentModelCanBeUsedOn', array( $this->getModelID(), $title, &$ok ) );
696 * Returns the name of the diff engine to use.
702 protected function getDiffEngineClass() {
703 return 'DifferenceEngine';
707 * Attempts to merge differences between three versions.
708 * Returns a new Content object for a clean merge and false for failure or
711 * This default implementation always returns false.
715 * @param $oldContent Content|string String
716 * @param $myContent Content|string String
717 * @param $yourContent Content|string String
719 * @return Content|Bool
721 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
726 * Return an applicable auto-summary if one exists for the given edit.
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.
734 * @return string An appropriate auto-summary, or an empty string.
736 public function getAutosummary( Content
$oldContent = null, Content
$newContent = null, $flags ) {
737 // Decide what kind of auto-summary is needed.
739 // Redirect auto-summaries
746 $ot = !is_null( $oldContent ) ?
$oldContent->getRedirectTarget() : null;
747 $rt = !is_null( $newContent ) ?
$newContent->getRedirectTarget() : null;
749 if ( is_object( $rt ) ) {
750 if ( !is_object( $ot )
751 ||
!$rt->equals( $ot )
752 ||
$ot->getFragment() != $rt->getFragment()
754 $truncatedtext = $newContent->getTextForSummary(
756 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
757 - strlen( $rt->getFullText() ) );
759 return wfMessage( 'autoredircomment', $rt->getFullText() )
760 ->rawParams( $truncatedtext )->inContentLanguage()->text();
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
769 $truncatedtext = $newContent->getTextForSummary(
770 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
772 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
773 ->inContentLanguage()->text();
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
783 // Removing more than 90% of the article
785 $truncatedtext = $newContent->getTextForSummary(
786 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
788 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
789 ->inContentLanguage()->text();
792 // If we reach this point, there's no applicable auto-summary for our
793 // case, so our auto-summary is empty.
798 * Auto-generates a deletion reason
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
807 * @XXX &$hasHistory is extremely ugly, it's here because
808 * WikiPage::getAutoDeleteReason() and Article::generateReason()
811 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
812 $dbw = wfGetDB( DB_MASTER
);
814 // Get the last revision
815 $rev = Revision
::newFromTitle( $title );
817 if ( is_null( $rev ) ) {
821 // Get the article's contents
822 $content = $rev->getContent();
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
828 if ( !$content ||
$content->isEmpty() ) {
829 $prev = $rev->getPrevious();
833 $content = $rev->getContent();
838 $this->checkModelID( $rev->getContentModel() );
840 // Find out if there was only one contributor
841 // Only scan the last 20 revisions
842 $res = $dbw->select( 'revision', 'rev_user_text',
844 'rev_page' => $title->getArticleID(),
845 $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0'
848 array( 'LIMIT' => 20 )
851 if ( $res === false ) {
852 // This page has no revisions, which is very weird
856 $hasHistory = ( $res->numRows() > 1 );
857 $row = $dbw->fetchObject( $res );
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
872 // Generate the summary with a '$1' placeholder
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();
883 )->inContentLanguage()->text();
885 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
889 if ( $reason == '-' ) {
890 // Allow these UI messages to be blanked out cleanly
894 // Max content length = max comment length - length of the comment (excl. $1)
895 $text = $content ?
$content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) : '';
897 // Now replace the '$1' placeholder
898 $reason = str_replace( '$1', $text, $reason );
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.
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
914 * @return mixed String on success, false on failure
916 public function getUndoContent( Revision
$current, Revision
$undo, Revision
$undoafter ) {
917 $cur_content = $current->getContent();
919 if ( empty( $cur_content ) ) {
920 return false; // no page
923 $undo_content = $undo->getContent();
924 $undoafter_content = $undoafter->getContent();
926 if ( !$undo_content ||
!$undoafter_content ) {
927 return false; // no content to undo
930 $this->checkModelID( $cur_content->getModel() );
931 $this->checkModelID( $undo_content->getModel() );
932 $this->checkModelID( $undoafter_content->getModel() );
934 if ( $cur_content->equals( $undo_content ) ) {
935 // No use doing a merge if it's just a straight revert.
936 return $undoafter_content;
939 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
941 return $undone_content;
945 * Get parser options suitable for rendering and caching the article
947 * @param IContextSource|User|string $context One of the following:
948 * - IContextSource: Use the User and the Language of the provided
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).
955 * @throws MWException
956 * @return ParserOptions
958 public function makeParserOptions( $context ) {
959 global $wgContLang, $wgEnableParserLimitReporting;
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 );
968 throw new MWException( "Bad context for parser options: $context" );
971 $options->enableLimitReport( $wgEnableParserLimitReporting ); // show inclusion/loop reports
972 $options->setTidy( true ); // fix bad HTML
978 * Returns true for content models that support caching using the
979 * ParserCache mechanism. See WikiPage::isParserCacheUsed().
985 public function isParserCacheSupported() {
990 * Returns true if this content model supports sections.
991 * This default implementation returns false.
993 * Content models that return true here should also implement
994 * Content::getSection, Content::replaceSection, etc. to handle sections..
996 * @return boolean whether sections are supported.
998 public function supportsSections() {
1003 * Returns true if this content model supports redirects.
1004 * This default implementation returns false.
1006 * Content models that return true here should also implement
1007 * ContentHandler::makeRedirectContent to return a Content object.
1009 * @return boolean whether redirects are supported.
1011 public function supportsRedirects() {
1016 * Logs a deprecation warning, visible if $wgDevelopmentWarnings, but only if
1017 * self::$enableDeprecationWarnings is set to true.
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.
1025 * @see ContentHandler::$enableDeprecationWarnings
1028 public static function deprecated( $func, $version, $component = false ) {
1029 if ( self
::$enableDeprecationWarnings ) {
1030 wfDeprecated( $func, $version, $component, 3 );
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
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.
1047 * @return Boolean True if no handler aborted the hook
1049 * @see ContentHandler::$enableDeprecationWarnings
1051 public static function runLegacyHooks( $event, $args = array(),
1055 if ( $warn === null ) {
1056 $warn = self
::$enableDeprecationWarnings;
1059 if ( !Hooks
::isRegistered( $event ) ) {
1060 return true; // nothing to do here
1064 // Log information about which handlers are registered for the legacy hook,
1065 // so we can find and fix them.
1067 $handlers = Hooks
::getHandlers( $event );
1068 $handlerInfo = array();
1070 wfSuppressWarnings();
1072 foreach ( $handlers as $handler ) {
1073 if ( is_array( $handler ) ) {
1074 if ( is_object( $handler[0] ) ) {
1075 $info = get_class( $handler[0] );
1077 $info = $handler[0];
1080 if ( isset( $handler[1] ) ) {
1081 $info .= '::' . $handler[1];
1083 } elseif ( is_object( $handler ) ) {
1084 $info = get_class( $handler[0] );
1085 $info .= '::on' . $event;
1090 $handlerInfo[] = $info;
1093 wfRestoreWarnings();
1095 wfWarn( "Using obsolete hook $event via ContentHandler::runLegacyHooks()! Handlers: " .
1096 implode( ', ', $handlerInfo ), 2 );
1099 // convert Content objects to text
1100 $contentObjects = array();
1101 $contentTexts = array();
1103 foreach ( $args as $k => $v ) {
1104 if ( $v instanceof Content
) {
1105 /* @var Content $v */
1107 $contentObjects[$k] = $v;
1109 $v = $v->serialize();
1110 $contentTexts[$k] = $v;
1115 // call the hook functions
1116 $ok = wfRunHooks( $event, $args );
1118 // see if the hook changed the text
1119 foreach ( $contentTexts as $k => $orig ) {
1120 /* @var Content $content */
1122 $modified = $args[$k];
1123 $content = $contentObjects[$k];
1125 if ( $modified !== $orig ) {
1126 // text was changed, create updated Content object
1127 $content = $content->getContentHandler()->unserializeContent( $modified );
1130 $args[$k] = $content;