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 * @param Title $title the page's title.
682 * @return bool true if content of this kind can be used on the given page, false otherwise.
684 public function canBeUsedOn( Title
$title ) {
689 * Returns the name of the diff engine to use.
695 protected function getDiffEngineClass() {
696 return 'DifferenceEngine';
700 * Attempts to merge differences between three versions.
701 * Returns a new Content object for a clean merge and false for failure or
704 * This default implementation always returns false.
708 * @param $oldContent Content|string String
709 * @param $myContent Content|string String
710 * @param $yourContent Content|string String
712 * @return Content|Bool
714 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
719 * Return an applicable auto-summary if one exists for the given edit.
723 * @param $oldContent Content|null: the previous text of the page.
724 * @param $newContent Content|null: The submitted text of the page.
725 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
727 * @return string An appropriate auto-summary, or an empty string.
729 public function getAutosummary( Content
$oldContent = null, Content
$newContent = null, $flags ) {
730 // Decide what kind of auto-summary is needed.
732 // Redirect auto-summaries
739 $ot = !is_null( $oldContent ) ?
$oldContent->getRedirectTarget() : null;
740 $rt = !is_null( $newContent ) ?
$newContent->getRedirectTarget() : null;
742 if ( is_object( $rt ) ) {
743 if ( !is_object( $ot )
744 ||
!$rt->equals( $ot )
745 ||
$ot->getFragment() != $rt->getFragment()
747 $truncatedtext = $newContent->getTextForSummary(
749 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
750 - strlen( $rt->getFullText() ) );
752 return wfMessage( 'autoredircomment', $rt->getFullText() )
753 ->rawParams( $truncatedtext )->inContentLanguage()->text();
757 // New page auto-summaries
758 if ( $flags & EDIT_NEW
&& $newContent->getSize() > 0 ) {
759 // If they're making a new article, give its text, truncated, in
762 $truncatedtext = $newContent->getTextForSummary(
763 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
765 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
766 ->inContentLanguage()->text();
769 // Blanking auto-summaries
770 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
771 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
772 } elseif ( !empty( $oldContent )
773 && $oldContent->getSize() > 10 * $newContent->getSize()
774 && $newContent->getSize() < 500
776 // Removing more than 90% of the article
778 $truncatedtext = $newContent->getTextForSummary(
779 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
781 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
782 ->inContentLanguage()->text();
785 // If we reach this point, there's no applicable auto-summary for our
786 // case, so our auto-summary is empty.
791 * Auto-generates a deletion reason
795 * @param $title Title: the page's title
796 * @param &$hasHistory Boolean: whether the page has a history
797 * @return mixed String containing deletion reason or empty string, or
798 * boolean false if no revision occurred
800 * @XXX &$hasHistory is extremely ugly, it's here because
801 * WikiPage::getAutoDeleteReason() and Article::generateReason()
804 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
805 $dbw = wfGetDB( DB_MASTER
);
807 // Get the last revision
808 $rev = Revision
::newFromTitle( $title );
810 if ( is_null( $rev ) ) {
814 // Get the article's contents
815 $content = $rev->getContent();
818 // If the page is blank, use the text from the previous revision,
819 // which can only be blank if there's a move/import/protect dummy
821 if ( !$content ||
$content->isEmpty() ) {
822 $prev = $rev->getPrevious();
826 $content = $rev->getContent();
831 $this->checkModelID( $rev->getContentModel() );
833 // Find out if there was only one contributor
834 // Only scan the last 20 revisions
835 $res = $dbw->select( 'revision', 'rev_user_text',
837 'rev_page' => $title->getArticleID(),
838 $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0'
841 array( 'LIMIT' => 20 )
844 if ( $res === false ) {
845 // This page has no revisions, which is very weird
849 $hasHistory = ( $res->numRows() > 1 );
850 $row = $dbw->fetchObject( $res );
852 if ( $row ) { // $row is false if the only contributor is hidden
853 $onlyAuthor = $row->rev_user_text
;
854 // Try to find a second contributor
855 foreach ( $res as $row ) {
856 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
865 // Generate the summary with a '$1' placeholder
867 // The current revision is blank and the one before is also
868 // blank. It's just not our lucky day
869 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
876 )->inContentLanguage()->text();
878 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
882 if ( $reason == '-' ) {
883 // Allow these UI messages to be blanked out cleanly
887 // Max content length = max comment length - length of the comment (excl. $1)
888 $text = $content ?
$content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) : '';
890 // Now replace the '$1' placeholder
891 $reason = str_replace( '$1', $text, $reason );
897 * Get the Content object that needs to be saved in order to undo all revisions
898 * between $undo and $undoafter. Revisions must belong to the same page,
899 * must exist and must not be deleted.
903 * @param $current Revision The current text
904 * @param $undo Revision The revision to undo
905 * @param $undoafter Revision Must be an earlier revision than $undo
907 * @return mixed String on success, false on failure
909 public function getUndoContent( Revision
$current, Revision
$undo, Revision
$undoafter ) {
910 $cur_content = $current->getContent();
912 if ( empty( $cur_content ) ) {
913 return false; // no page
916 $undo_content = $undo->getContent();
917 $undoafter_content = $undoafter->getContent();
919 if ( !$undo_content ||
!$undoafter_content ) {
920 return false; // no content to undo
923 $this->checkModelID( $cur_content->getModel() );
924 $this->checkModelID( $undo_content->getModel() );
925 $this->checkModelID( $undoafter_content->getModel() );
927 if ( $cur_content->equals( $undo_content ) ) {
928 // No use doing a merge if it's just a straight revert.
929 return $undoafter_content;
932 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
934 return $undone_content;
938 * Get parser options suitable for rendering the primary article wikitext
940 * @param IContextSource|User|string $context One of the following:
941 * - IContextSource: Use the User and the Language of the provided
943 * - User: Use the provided User object and $wgLang for the language,
944 * so use an IContextSource object if possible.
945 * - 'canonical': Canonical options (anonymous user with default
946 * preferences and content language).
948 * @param IContextSource|User|string $context
950 * @throws MWException
951 * @return ParserOptions
953 public function makeParserOptions( $context ) {
954 global $wgContLang, $wgEnableParserLimitReporting;
956 if ( $context instanceof IContextSource
) {
957 $options = ParserOptions
::newFromContext( $context );
958 } elseif ( $context instanceof User
) { // settings per user (even anons)
959 $options = ParserOptions
::newFromUser( $context );
960 } elseif ( $context === 'canonical' ) { // canonical settings
961 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
963 throw new MWException( "Bad context for parser options: $context" );
966 $options->enableLimitReport( $wgEnableParserLimitReporting ); // show inclusion/loop reports
967 $options->setTidy( true ); // fix bad HTML
973 * Returns true for content models that support caching using the
974 * ParserCache mechanism. See WikiPage::isParserCacheUsed().
980 public function isParserCacheSupported() {
985 * Returns true if this content model supports sections.
986 * This default implementation returns false.
988 * Content models that return true here should also implement
989 * Content::getSection, Content::replaceSection, etc. to handle sections..
991 * @return boolean whether sections are supported.
993 public function supportsSections() {
998 * Returns true if this content model supports redirects.
999 * This default implementation returns false.
1001 * Content models that return true here should also implement
1002 * ContentHandler::makeRedirectContent to return a Content object.
1004 * @return boolean whether redirects are supported.
1006 public function supportsRedirects() {
1011 * Logs a deprecation warning, visible if $wgDevelopmentWarnings, but only if
1012 * self::$enableDeprecationWarnings is set to true.
1014 * @param string $func The name of the deprecated function
1015 * @param string $version The version since the method is deprecated. Usually 1.21
1016 * for ContentHandler related stuff.
1017 * @param string|bool $component : Component to which the function belongs.
1018 * If false, it is assumed the function is in MediaWiki core.
1020 * @see ContentHandler::$enableDeprecationWarnings
1023 public static function deprecated( $func, $version, $component = false ) {
1024 if ( self
::$enableDeprecationWarnings ) {
1025 wfDeprecated( $func, $version, $component, 3 );
1030 * Call a legacy hook that uses text instead of Content objects.
1031 * Will log a warning when a matching hook function is registered.
1032 * If the textual representation of the content is changed by the
1033 * hook function, a new Content object is constructed from the new
1036 * @param string $event event name
1037 * @param array $args parameters passed to hook functions
1038 * @param bool $warn whether to log a warning.
1039 * Default to self::$enableDeprecationWarnings.
1040 * May be set to false for testing.
1042 * @return Boolean True if no handler aborted the hook
1044 * @see ContentHandler::$enableDeprecationWarnings
1046 public static function runLegacyHooks( $event, $args = array(),
1050 if ( $warn === null ) {
1051 $warn = self
::$enableDeprecationWarnings;
1054 if ( !Hooks
::isRegistered( $event ) ) {
1055 return true; // nothing to do here
1059 // Log information about which handlers are registered for the legacy hook,
1060 // so we can find and fix them.
1062 $handlers = Hooks
::getHandlers( $event );
1063 $handlerInfo = array();
1065 wfSuppressWarnings();
1067 foreach ( $handlers as $handler ) {
1068 if ( is_array( $handler ) ) {
1069 if ( is_object( $handler[0] ) ) {
1070 $info = get_class( $handler[0] );
1072 $info = $handler[0];
1075 if ( isset( $handler[1] ) ) {
1076 $info .= '::' . $handler[1];
1078 } elseif ( is_object( $handler ) ) {
1079 $info = get_class( $handler[0] );
1080 $info .= '::on' . $event;
1085 $handlerInfo[] = $info;
1088 wfRestoreWarnings();
1090 wfWarn( "Using obsolete hook $event via ContentHandler::runLegacyHooks()! Handlers: " .
1091 implode( ', ', $handlerInfo ), 2 );
1094 // convert Content objects to text
1095 $contentObjects = array();
1096 $contentTexts = array();
1098 foreach ( $args as $k => $v ) {
1099 if ( $v instanceof Content
) {
1100 /* @var Content $v */
1102 $contentObjects[$k] = $v;
1104 $v = $v->serialize();
1105 $contentTexts[$k] = $v;
1110 // call the hook functions
1111 $ok = wfRunHooks( $event, $args );
1113 // see if the hook changed the text
1114 foreach ( $contentTexts as $k => $orig ) {
1115 /* @var Content $content */
1117 $modified = $args[$k];
1118 $content = $contentObjects[$k];
1120 if ( $modified !== $orig ) {
1121 // text was changed, create updated Content object
1122 $content = $content->getContentHandler()->unserializeContent( $modified );
1125 $args[$k] = $content;