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
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 ) ) {
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 " .
114 if ( $wgContentHandlerTextFallback == 'serialize' ) {
115 return $content->serialize();
122 * Convenience function for creating a Content object from a given textual
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
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
171 * - The hook ContentHandlerDefaultModelFor may be used to override the page's default
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()
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();
201 $model = MWNamespace
::getNamespaceContentModel( $ns );
203 // Hook can determine default model
204 if ( !Hooks
::run( 'ContentHandlerDefaultModelFor', array( $title, &$model ) ) ) {
205 if ( !is_null( $model ) ) {
210 // Could this page contain code based on the title?
211 $isCodePage = NS_MEDIAWIKI
== $ns && preg_match( '!\.(css|js|json)$!u', $title->getText(), $m );
216 // Hook can force JS/CSS
217 Hooks
::run( 'TitleIsCssOrJsPage', array( $title, &$isCodePage ), '1.25' );
219 // Is this a user subpage containing code?
220 $isCodeSubpage = NS_USER
== $ns
222 && preg_match( "/\\/.*\\.(js|css|json)$/", $title->getText(), $m );
223 if ( $isCodeSubpage ) {
227 // Is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
228 $isWikitext = is_null( $model ) ||
$model == CONTENT_MODEL_WIKITEXT
;
229 $isWikitext = $isWikitext && !$isCodePage && !$isCodeSubpage;
231 // Hook can override $isWikitext
232 Hooks
::run( 'TitleIsWikitextPage', array( $title, &$isWikitext ), '1.25' );
234 if ( !$isWikitext ) {
237 return CONTENT_MODEL_JAVASCRIPT
;
239 return CONTENT_MODEL_CSS
;
241 return CONTENT_MODEL_JSON
;
243 return is_null( $model ) ? CONTENT_MODEL_TEXT
: $model;
247 // We established that it must be wikitext
249 return CONTENT_MODEL_WIKITEXT
;
253 * Returns the appropriate ContentHandler singleton for the given title.
257 * @param Title $title
259 * @return ContentHandler
261 public static function getForTitle( Title
$title ) {
262 $modelId = $title->getContentModel();
264 return ContentHandler
::getForModelID( $modelId );
268 * Returns the appropriate ContentHandler singleton for the given Content
273 * @param Content $content
275 * @return ContentHandler
277 public static function getForContent( Content
$content ) {
278 $modelId = $content->getModel();
280 return ContentHandler
::getForModelID( $modelId );
284 * @var array A Cache of ContentHandler instances by model id
286 protected static $handlers;
289 * Returns the ContentHandler singleton for the given model ID. Use the
290 * CONTENT_MODEL_XXX constants to identify the desired content model.
292 * ContentHandler singletons are taken from the global $wgContentHandlers
293 * array. Keys in that array are model names, the values are either
294 * ContentHandler singleton objects, or strings specifying the appropriate
295 * subclass of ContentHandler.
297 * If a class name is encountered when looking up the singleton for a given
298 * model name, the class is instantiated and the class name is replaced by
299 * the resulting singleton in $wgContentHandlers.
301 * If no ContentHandler is defined for the desired $modelId, the
302 * ContentHandler may be provided by the ContentHandlerForModelID hook.
303 * If no ContentHandler can be determined, an MWException is raised.
307 * @param string $modelId The ID of the content model for which to get a
308 * handler. Use CONTENT_MODEL_XXX constants.
310 * @throws MWException If no handler is known for the model ID.
311 * @return ContentHandler The ContentHandler singleton for handling the model given by the ID.
313 public static function getForModelID( $modelId ) {
314 global $wgContentHandlers;
316 if ( isset( ContentHandler
::$handlers[$modelId] ) ) {
317 return ContentHandler
::$handlers[$modelId];
320 if ( empty( $wgContentHandlers[$modelId] ) ) {
323 Hooks
::run( 'ContentHandlerForModelID', array( $modelId, &$handler ) );
325 if ( $handler === null ) {
326 throw new MWException( "No handler for model '$modelId' registered in \$wgContentHandlers" );
329 if ( !( $handler instanceof ContentHandler
) ) {
330 throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
333 $class = $wgContentHandlers[$modelId];
334 $handler = new $class( $modelId );
336 if ( !( $handler instanceof ContentHandler
) ) {
337 throw new MWException( "$class from \$wgContentHandlers is not " .
338 "compatible with ContentHandler" );
342 wfDebugLog( 'ContentHandler', 'Created handler for ' . $modelId
343 . ': ' . get_class( $handler ) );
345 ContentHandler
::$handlers[$modelId] = $handler;
347 return ContentHandler
::$handlers[$modelId];
351 * Returns the localized name for a given content model.
353 * Model names are localized using system messages. Message keys
354 * have the form content-model-$name, where $name is getContentModelName( $id ).
356 * @param string $name The content model ID, as given by a CONTENT_MODEL_XXX
357 * constant or returned by Revision::getContentModel().
358 * @param Language|null $lang The language to parse the message in (since 1.26)
360 * @throws MWException If the model ID isn't known.
361 * @return string The content model's localized name.
363 public static function getLocalizedName( $name, Language
$lang = null ) {
364 // Messages: content-model-wikitext, content-model-text,
365 // content-model-javascript, content-model-css
366 $key = "content-model-$name";
368 $msg = wfMessage( $key );
370 $msg->inLanguage( $lang );
373 return $msg->exists() ?
$msg->plain() : $name;
376 public static function getContentModels() {
377 global $wgContentHandlers;
379 return array_keys( $wgContentHandlers );
382 public static function getAllContentFormats() {
383 global $wgContentHandlers;
387 foreach ( $wgContentHandlers as $model => $class ) {
388 $handler = ContentHandler
::getForModelID( $model );
389 $formats = array_merge( $formats, $handler->getSupportedFormats() );
392 $formats = array_unique( $formats );
397 // ------------------------------------------------------------------------
407 protected $mSupportedFormats;
410 * Constructor, initializing the ContentHandler instance with its model ID
411 * and a list of supported formats. Values for the parameters are typically
412 * provided as literals by subclass's constructors.
414 * @param string $modelId (use CONTENT_MODEL_XXX constants).
415 * @param string[] $formats List for supported serialization formats
416 * (typically as MIME types)
418 public function __construct( $modelId, $formats ) {
419 $this->mModelID
= $modelId;
420 $this->mSupportedFormats
= $formats;
422 $this->mModelName
= preg_replace( '/(Content)?Handler$/', '', get_class( $this ) );
423 $this->mModelName
= preg_replace( '/[_\\\\]/', '', $this->mModelName
);
424 $this->mModelName
= strtolower( $this->mModelName
);
428 * Serializes a Content object of the type supported by this ContentHandler.
432 * @param Content $content The Content object to serialize
433 * @param string $format The desired serialization format
435 * @return string Serialized form of the content
437 abstract public function serializeContent( Content
$content, $format = null );
440 * Applies transformations on export (returns the blob unchanged per default).
441 * Subclasses may override this to perform transformations such as conversion
442 * of legacy formats or filtering of internal meta-data.
444 * @param string $blob The blob to be exported
445 * @param string|null $format The blob's serialization format
449 public function exportTransform( $blob, $format = null ) {
454 * Unserializes a Content object of the type supported by this ContentHandler.
458 * @param string $blob Serialized form of the content
459 * @param string $format The format used for serialization
461 * @return Content The Content object created by deserializing $blob
463 abstract public function unserializeContent( $blob, $format = null );
466 * Apply import transformation (per default, returns $blob unchanged).
467 * This gives subclasses an opportunity to transform data blobs on import.
471 * @param string $blob
472 * @param string|null $format
476 public function importTransform( $blob, $format = null ) {
481 * Creates an empty Content object of the type supported by this
488 abstract public function makeEmptyContent();
491 * Creates a new Content object that acts as a redirect to the given page,
492 * or null if redirects are not supported by this content model.
494 * This default implementation always returns null. Subclasses supporting redirects
495 * must override this method.
497 * Note that subclasses that override this method to return a Content object
498 * should also override supportsRedirects() to return true.
502 * @param Title $destination The page to redirect to.
503 * @param string $text Text to include in the redirect, if possible.
505 * @return Content Always null.
507 public function makeRedirectContent( Title
$destination, $text = '' ) {
512 * Returns the model id that identifies the content model this
513 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
517 * @return string The model ID
519 public function getModelID() {
520 return $this->mModelID
;
526 * @param string $model_id The model to check
528 * @throws MWException If the model ID is not the ID of the content model supported by this
531 protected function checkModelID( $model_id ) {
532 if ( $model_id !== $this->mModelID
) {
533 throw new MWException( "Bad content model: " .
534 "expected {$this->mModelID} " .
535 "but got $model_id." );
540 * Returns a list of serialization formats supported by the
541 * serializeContent() and unserializeContent() methods of this
546 * @return string[] List of serialization formats as MIME type like strings
548 public function getSupportedFormats() {
549 return $this->mSupportedFormats
;
553 * The format used for serialization/deserialization by default by this
556 * This default implementation will return the first element of the array
557 * of formats that was passed to the constructor.
561 * @return string The name of the default serialization format as a MIME type
563 public function getDefaultFormat() {
564 return $this->mSupportedFormats
[0];
568 * Returns true if $format is a serialization format supported by this
569 * ContentHandler, and false otherwise.
571 * Note that if $format is null, this method always returns true, because
572 * null means "use the default format".
576 * @param string $format The serialization format to check
580 public function isSupportedFormat( $format ) {
582 return true; // this means "use the default"
585 return in_array( $format, $this->mSupportedFormats
);
589 * Convenient for checking whether a format provided as a parameter is actually supported.
591 * @param string $format The serialization format to check
593 * @throws MWException If the format is not supported by this content handler.
595 protected function checkFormat( $format ) {
596 if ( !$this->isSupportedFormat( $format ) ) {
597 throw new MWException(
598 "Format $format is not supported for content model "
599 . $this->getModelID()
605 * Returns overrides for action handlers.
606 * Classes listed here will be used instead of the default one when
607 * (and only when) $wgActions[$action] === true. This allows subclasses
608 * to override the default action handlers.
612 * @return array Always an empty array.
614 public function getActionOverrides() {
619 * Factory for creating an appropriate DifferenceEngine for this content model.
623 * @param IContextSource $context Context to use, anything else will be ignored.
624 * @param int $old Revision ID we want to show and diff with.
625 * @param int|string $new Either a revision ID or one of the strings 'cur', 'prev' or 'next'.
626 * @param int $rcid FIXME: Deprecated, no longer used. Defaults to 0.
627 * @param bool $refreshCache If set, refreshes the diff cache. Defaults to false.
628 * @param bool $unhide If set, allow viewing deleted revs. Defaults to false.
630 * @return DifferenceEngine
632 public function createDifferenceEngine( IContextSource
$context, $old = 0, $new = 0,
633 $rcid = 0, //FIXME: Deprecated, no longer used
634 $refreshCache = false, $unhide = false ) {
636 // hook: get difference engine
637 $differenceEngine = null;
638 if ( !Hooks
::run( 'GetDifferenceEngine',
639 array( $context, $old, $new, $refreshCache, $unhide, &$differenceEngine )
641 return $differenceEngine;
643 $diffEngineClass = $this->getDiffEngineClass();
644 return new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
648 * Get the language in which the content of the given page is written.
650 * This default implementation just returns $wgContLang (except for pages
651 * in the MediaWiki namespace)
653 * Note that the pages language is not cacheable, since it may in some
654 * cases depend on user settings.
656 * Also note that the page language may or may not depend on the actual content of the page,
657 * that is, this method may load the content in order to determine the language.
661 * @param Title $title The page to determine the language for.
662 * @param Content $content The page's content, if you have it handy, to avoid reloading it.
664 * @return Language The page's language
666 public function getPageLanguage( Title
$title, Content
$content = null ) {
667 global $wgContLang, $wgLang;
668 $pageLang = $wgContLang;
670 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
671 // Parse mediawiki messages with correct target language
672 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $title->getText() );
673 $pageLang = wfGetLangObj( $lang );
676 Hooks
::run( 'PageContentLanguage', array( $title, &$pageLang, $wgLang ) );
678 return wfGetLangObj( $pageLang );
682 * Get the language in which the content of this page is written when
683 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
684 * specified a preferred variant, the variant will be used.
686 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
687 * the user specified a preferred variant.
689 * Note that the pages view language is not cacheable, since it depends on user settings.
691 * Also note that the page language may or may not depend on the actual content of the page,
692 * that is, this method may load the content in order to determine the language.
696 * @param Title $title The page to determine the language for.
697 * @param Content $content The page's content, if you have it handy, to avoid reloading it.
699 * @return Language The page's language for viewing
701 public function getPageViewLanguage( Title
$title, Content
$content = null ) {
702 $pageLang = $this->getPageLanguage( $title, $content );
704 if ( $title->getNamespace() !== NS_MEDIAWIKI
) {
705 // If the user chooses a variant, the content is actually
706 // in a language whose code is the variant code.
707 $variant = $pageLang->getPreferredVariant();
708 if ( $pageLang->getCode() !== $variant ) {
709 $pageLang = Language
::factory( $variant );
717 * Determines whether the content type handled by this ContentHandler
718 * can be used on the given page.
720 * This default implementation always returns true.
721 * Subclasses may override this to restrict the use of this content model to specific locations,
722 * typically based on the namespace or some other aspect of the title, such as a special suffix
723 * (e.g. ".svg" for SVG content).
725 * @note this calls the ContentHandlerCanBeUsedOn hook which may be used to override which
726 * content model can be used where.
728 * @param Title $title The page's title.
730 * @return bool True if content of this kind can be used on the given page, false otherwise.
732 public function canBeUsedOn( Title
$title ) {
735 Hooks
::run( 'ContentModelCanBeUsedOn', array( $this->getModelID(), $title, &$ok ) );
741 * Returns the name of the diff engine to use.
747 protected function getDiffEngineClass() {
748 return 'DifferenceEngine';
752 * Attempts to merge differences between three versions. Returns a new
753 * Content object for a clean merge and false for failure or a conflict.
755 * This default implementation always returns false.
759 * @param Content $oldContent The page's previous content.
760 * @param Content $myContent One of the page's conflicting contents.
761 * @param Content $yourContent One of the page's conflicting contents.
763 * @return Content|bool Always false.
765 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
770 * Return an applicable auto-summary if one exists for the given edit.
774 * @param Content $oldContent The previous text of the page.
775 * @param Content $newContent The submitted text of the page.
776 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
778 * @return string An appropriate auto-summary, or an empty string.
780 public function getAutosummary( Content
$oldContent = null, Content
$newContent = null,
782 // Decide what kind of auto-summary is needed.
784 // Redirect auto-summaries
791 $ot = !is_null( $oldContent ) ?
$oldContent->getRedirectTarget() : null;
792 $rt = !is_null( $newContent ) ?
$newContent->getRedirectTarget() : null;
794 if ( is_object( $rt ) ) {
795 if ( !is_object( $ot )
796 ||
!$rt->equals( $ot )
797 ||
$ot->getFragment() != $rt->getFragment()
799 $truncatedtext = $newContent->getTextForSummary(
801 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
802 - strlen( $rt->getFullText() ) );
804 return wfMessage( 'autoredircomment', $rt->getFullText() )
805 ->rawParams( $truncatedtext )->inContentLanguage()->text();
809 // New page auto-summaries
810 if ( $flags & EDIT_NEW
&& $newContent->getSize() > 0 ) {
811 // If they're making a new article, give its text, truncated, in
814 $truncatedtext = $newContent->getTextForSummary(
815 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
817 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
818 ->inContentLanguage()->text();
821 // Blanking auto-summaries
822 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
823 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
824 } elseif ( !empty( $oldContent )
825 && $oldContent->getSize() > 10 * $newContent->getSize()
826 && $newContent->getSize() < 500
828 // Removing more than 90% of the article
830 $truncatedtext = $newContent->getTextForSummary(
831 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
833 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
834 ->inContentLanguage()->text();
837 // New blank article auto-summary
838 if ( $flags & EDIT_NEW
&& $newContent->isEmpty() ) {
839 return wfMessage( 'autosumm-newblank' )->inContentLanguage()->text();
842 // If we reach this point, there's no applicable auto-summary for our
843 // case, so our auto-summary is empty.
848 * Auto-generates a deletion reason
852 * @param Title $title The page's title
853 * @param bool &$hasHistory Whether the page has a history
855 * @return mixed String containing deletion reason or empty string, or
856 * boolean false if no revision occurred
858 * @todo &$hasHistory is extremely ugly, it's here because
859 * WikiPage::getAutoDeleteReason() and Article::generateReason()
862 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
863 $dbw = wfGetDB( DB_MASTER
);
865 // Get the last revision
866 $rev = Revision
::newFromTitle( $title );
868 if ( is_null( $rev ) ) {
872 // Get the article's contents
873 $content = $rev->getContent();
876 // If the page is blank, use the text from the previous revision,
877 // which can only be blank if there's a move/import/protect dummy
879 if ( !$content ||
$content->isEmpty() ) {
880 $prev = $rev->getPrevious();
884 $content = $rev->getContent();
889 $this->checkModelID( $rev->getContentModel() );
891 // Find out if there was only one contributor
892 // Only scan the last 20 revisions
893 $res = $dbw->select( 'revision', 'rev_user_text',
895 'rev_page' => $title->getArticleID(),
896 $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0'
899 array( 'LIMIT' => 20 )
902 if ( $res === false ) {
903 // This page has no revisions, which is very weird
907 $hasHistory = ( $res->numRows() > 1 );
908 $row = $dbw->fetchObject( $res );
910 if ( $row ) { // $row is false if the only contributor is hidden
911 $onlyAuthor = $row->rev_user_text
;
912 // Try to find a second contributor
913 foreach ( $res as $row ) {
914 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
923 // Generate the summary with a '$1' placeholder
925 // The current revision is blank and the one before is also
926 // blank. It's just not our lucky day
927 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
934 )->inContentLanguage()->text();
936 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
940 if ( $reason == '-' ) {
941 // Allow these UI messages to be blanked out cleanly
945 // Max content length = max comment length - length of the comment (excl. $1)
946 $text = $content ?
$content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) : '';
948 // Now replace the '$1' placeholder
949 $reason = str_replace( '$1', $text, $reason );
955 * Get the Content object that needs to be saved in order to undo all revisions
956 * between $undo and $undoafter. Revisions must belong to the same page,
957 * must exist and must not be deleted.
961 * @param Revision $current The current text
962 * @param Revision $undo The revision to undo
963 * @param Revision $undoafter Must be an earlier revision than $undo
965 * @return mixed String on success, false on failure
967 public function getUndoContent( Revision
$current, Revision
$undo, Revision
$undoafter ) {
968 $cur_content = $current->getContent();
970 if ( empty( $cur_content ) ) {
971 return false; // no page
974 $undo_content = $undo->getContent();
975 $undoafter_content = $undoafter->getContent();
977 if ( !$undo_content ||
!$undoafter_content ) {
978 return false; // no content to undo
981 $this->checkModelID( $cur_content->getModel() );
982 $this->checkModelID( $undo_content->getModel() );
983 $this->checkModelID( $undoafter_content->getModel() );
985 if ( $cur_content->equals( $undo_content ) ) {
986 // No use doing a merge if it's just a straight revert.
987 return $undoafter_content;
990 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
992 return $undone_content;
996 * Get parser options suitable for rendering and caching the article
998 * @param IContextSource|User|string $context One of the following:
999 * - IContextSource: Use the User and the Language of the provided
1001 * - User: Use the provided User object and $wgLang for the language,
1002 * so use an IContextSource object if possible.
1003 * - 'canonical': Canonical options (anonymous user with default
1004 * preferences and content language).
1006 * @throws MWException
1007 * @return ParserOptions
1009 public function makeParserOptions( $context ) {
1010 global $wgContLang, $wgEnableParserLimitReporting;
1012 if ( $context instanceof IContextSource
) {
1013 $options = ParserOptions
::newFromContext( $context );
1014 } elseif ( $context instanceof User
) { // settings per user (even anons)
1015 $options = ParserOptions
::newFromUser( $context );
1016 } elseif ( $context === 'canonical' ) { // canonical settings
1017 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1019 throw new MWException( "Bad context for parser options: $context" );
1022 $options->enableLimitReport( $wgEnableParserLimitReporting ); // show inclusion/loop reports
1023 $options->setTidy( true ); // fix bad HTML
1029 * Returns true for content models that support caching using the
1030 * ParserCache mechanism. See WikiPage::shouldCheckParserCache().
1034 * @return bool Always false.
1036 public function isParserCacheSupported() {
1041 * Returns true if this content model supports sections.
1042 * This default implementation returns false.
1044 * Content models that return true here should also implement
1045 * Content::getSection, Content::replaceSection, etc. to handle sections..
1047 * @return bool Always false.
1049 public function supportsSections() {
1054 * Returns true if this content model supports redirects.
1055 * This default implementation returns false.
1057 * Content models that return true here should also implement
1058 * ContentHandler::makeRedirectContent to return a Content object.
1060 * @return bool Always false.
1062 public function supportsRedirects() {
1067 * Return true if this content model supports direct editing, such as via EditPage.
1069 * @return bool Default is false, and true for TextContent and it's derivatives.
1071 public function supportsDirectEditing() {
1076 * Whether or not this content model supports direct editing via ApiEditPage
1078 * @return bool Default is false, and true for TextContent and derivatives.
1080 public function supportsDirectApiEditing() {
1081 return $this->supportsDirectEditing();
1085 * Logs a deprecation warning, visible if $wgDevelopmentWarnings, but only if
1086 * self::$enableDeprecationWarnings is set to true.
1088 * @param string $func The name of the deprecated function
1089 * @param string $version The version since the method is deprecated. Usually 1.21
1090 * for ContentHandler related stuff.
1091 * @param string|bool $component : Component to which the function belongs.
1092 * If false, it is assumed the function is in MediaWiki core.
1094 * @see ContentHandler::$enableDeprecationWarnings
1097 public static function deprecated( $func, $version, $component = false ) {
1098 if ( self
::$enableDeprecationWarnings ) {
1099 wfDeprecated( $func, $version, $component, 3 );
1104 * Call a legacy hook that uses text instead of Content objects.
1105 * Will log a warning when a matching hook function is registered.
1106 * If the textual representation of the content is changed by the
1107 * hook function, a new Content object is constructed from the new
1110 * @param string $event Event name
1111 * @param array $args Parameters passed to hook functions
1112 * @param bool $warn Whether to log a warning.
1113 * Default to self::$enableDeprecationWarnings.
1114 * May be set to false for testing.
1116 * @return bool True if no handler aborted the hook
1118 * @see ContentHandler::$enableDeprecationWarnings
1120 public static function runLegacyHooks( $event, $args = array(),
1124 if ( $warn === null ) {
1125 $warn = self
::$enableDeprecationWarnings;
1128 if ( !Hooks
::isRegistered( $event ) ) {
1129 return true; // nothing to do here
1133 // Log information about which handlers are registered for the legacy hook,
1134 // so we can find and fix them.
1136 $handlers = Hooks
::getHandlers( $event );
1137 $handlerInfo = array();
1139 MediaWiki\
suppressWarnings();
1141 foreach ( $handlers as $handler ) {
1142 if ( is_array( $handler ) ) {
1143 if ( is_object( $handler[0] ) ) {
1144 $info = get_class( $handler[0] );
1146 $info = $handler[0];
1149 if ( isset( $handler[1] ) ) {
1150 $info .= '::' . $handler[1];
1152 } elseif ( is_object( $handler ) ) {
1153 $info = get_class( $handler[0] );
1154 $info .= '::on' . $event;
1159 $handlerInfo[] = $info;
1162 MediaWiki\restoreWarnings
();
1164 wfWarn( "Using obsolete hook $event via ContentHandler::runLegacyHooks()! Handlers: " .
1165 implode( ', ', $handlerInfo ), 2 );
1168 // convert Content objects to text
1169 $contentObjects = array();
1170 $contentTexts = array();
1172 foreach ( $args as $k => $v ) {
1173 if ( $v instanceof Content
) {
1174 /* @var Content $v */
1176 $contentObjects[$k] = $v;
1178 $v = $v->serialize();
1179 $contentTexts[$k] = $v;
1184 // call the hook functions
1185 $ok = Hooks
::run( $event, $args );
1187 // see if the hook changed the text
1188 foreach ( $contentTexts as $k => $orig ) {
1189 /* @var Content $content */
1191 $modified = $args[$k];
1192 $content = $contentObjects[$k];
1194 if ( $modified !== $orig ) {
1195 // text was changed, create updated Content object
1196 $content = $content->getContentHandler()->unserializeContent( $modified );
1199 $args[$k] = $content;