28use Wikimedia\Assert\Assert;
94 wfDebugLog(
'ContentHandler',
'Accessing ' .
$content->getModel() .
' content as text!' );
98 "Attempt to get text from Content with model " .
134 $modelId =
null, $format =
null ) {
135 if ( is_null( $modelId ) ) {
136 if ( is_null(
$title ) ) {
137 throw new MWException(
"Must provide a Title object or a content model ID." );
140 $modelId =
$title->getContentModel();
143 $handler = self::getForModelID( $modelId );
145 return $handler->unserializeContent( $text, $format );
186 $ns =
$title->getNamespace();
190 $model = MWNamespace::getNamespaceContentModel( $ns );
193 if ( !Hooks::run(
'ContentHandlerDefaultModelFor', [
$title, &$model ] ) ) {
194 if ( !is_null( $model ) ) {
200 $isCodePage =
NS_MEDIAWIKI == $ns && preg_match(
'!\.(css|js|json)$!u',
$title->getText(), $m );
206 $isCodeSubpage =
NS_USER == $ns
208 && preg_match(
"/\\/.*\\.(js|css|json)$/",
$title->getText(), $m );
209 if ( $isCodeSubpage ) {
215 $isWikitext = $isWikitext && !$isCodePage && !$isCodeSubpage;
217 if ( !$isWikitext ) {
245 $modelId =
$title->getContentModel();
247 return self::getForModelID( $modelId );
263 return self::getForModelID( $modelId );
300 if ( isset( self::$handlers[$modelId] ) ) {
301 return self::$handlers[$modelId];
307 Hooks::run(
'ContentHandlerForModelID', [ $modelId, &
$handler ] );
314 throw new MWException(
"ContentHandlerForModelID must supply a ContentHandler instance" );
319 if ( is_callable( $classOrCallback ) ) {
320 $handler = call_user_func( $classOrCallback, $modelId );
322 $handler =
new $classOrCallback( $modelId );
326 throw new MWException(
"$classOrCallback from \$wgContentHandlers is not " .
327 "compatible with ContentHandler" );
331 wfDebugLog(
'ContentHandler',
'Created handler for ' . $modelId
334 self::$handlers[$modelId] =
$handler;
336 return self::$handlers[$modelId];
343 self::$handlers = [];
362 $key =
"content-model-$name";
366 $msg->inLanguage(
$lang );
369 return $msg->exists() ? $msg->plain() :
$name;
376 Hooks::run(
'GetContentModels', [ &$models ] );
386 $handler = self::getForModelID( $model );
387 $formats = array_merge( $formats,
$handler->getSupportedFormats() );
390 $formats = array_unique( $formats );
417 $this->mModelID = $modelId;
418 $this->mSupportedFormats = $formats;
514 return $this->mModelID;
526 if ( $model_id !== $this->mModelID ) {
528 "expected {$this->mModelID} " .
529 "but got $model_id." );
543 return $this->mSupportedFormats;
558 return $this->mSupportedFormats[0];
579 return in_array( $format, $this->mSupportedFormats );
592 "Format $format is not supported for content model "
663 if ( get_class( $slotDiffRenderer ) === TextSlotDiffRenderer::class ) {
669 LoggerFactory::getInstance(
'diff' )->info(
670 'Falling back to DifferenceEngineSlotDiffRenderer', [
677 Hooks::run(
'GetSlotDiffRenderer', [ $this, &$slotDiffRenderer,
$context ] );
678 return $slotDiffRenderer;
687 $contentLanguage = MediaWikiServices::getInstance()->getContentLanguage();
688 $statsdDataFactory = MediaWikiServices::getInstance()->getStatsdDataFactory();
690 $slotDiffRenderer->setStatsdDataFactory( $statsdDataFactory );
692 $slotDiffRenderer->setLanguage( $contentLanguage );
693 $slotDiffRenderer->setWikiDiff2MovedParagraphDetectionCutoff(
694 $context->getConfig()->get(
'WikiDiff2MovedParagraphDetectionCutoff' )
700 } elseif (
$engine ===
'wikidiff2' ) {
706 return $slotDiffRenderer;
730 $pageLang = MediaWikiServices::getInstance()->getContentLanguage();
734 list( ,
$lang ) = MessageCache::singleton()->figureMessage(
$title->getText() );
735 $pageLang = Language::factory(
$lang );
738 Hooks::run(
'PageContentLanguage', [
$title, &$pageLang,
$wgLang ] );
769 $variant = $pageLang->getPreferredVariant();
770 if ( $pageLang->getCode() !== $variant ) {
771 $pageLang = Language::factory( $variant );
797 Hooks::run(
'ContentModelCanBeUsedOn', [ $this->
getModelID(),
$title, &$ok ] );
810 return DifferenceEngine::class;
847 $oldTarget = $oldContent !==
null ? $oldContent->getRedirectTarget() :
null;
848 $newTarget = $newContent !==
null ? $newContent->getRedirectTarget() :
null;
853 if ( $oldContent && $oldContent->getSize() > 0 &&
854 $newContent && $newContent->getSize() === 0
863 return 'new-redirect';
864 } elseif ( !$newTarget->equals( $oldTarget ) ||
865 $oldTarget->getFragment() !== $newTarget->getFragment()
868 return 'changed-redirect-target';
870 } elseif ( $oldTarget ) {
872 return 'removed-redirect';
876 if ( $flags &
EDIT_NEW && $newContent ) {
877 if ( $newContent->getSize() === 0 ) {
886 if ( $oldContent && $newContent && $oldContent->getSize() > 10 * $newContent->getSize() ) {
891 if ( $oldContent && $newContent && $oldContent->getModel() !== $newContent->getModel() ) {
892 return 'contentmodelchange';
914 $changeType = $this->
getChangeType( $oldContent, $newContent, $flags );
917 if ( !$changeType ) {
922 switch ( $changeType ) {
924 $newTarget = $newContent->getRedirectTarget();
925 $truncatedtext = $newContent->getTextForSummary(
927 - strlen(
wfMessage(
'autoredircomment' )->inContentLanguage()->
text() )
928 - strlen( $newTarget->getFullText() )
931 return wfMessage(
'autoredircomment', $newTarget->getFullText() )
932 ->plaintextParams( $truncatedtext )->inContentLanguage()->text();
933 case 'changed-redirect-target':
934 $oldTarget = $oldContent->getRedirectTarget();
935 $newTarget = $newContent->getRedirectTarget();
937 $truncatedtext = $newContent->getTextForSummary(
939 - strlen(
wfMessage(
'autosumm-changed-redirect-target' )
940 ->inContentLanguage()->
text() )
941 - strlen( $oldTarget->getFullText() )
942 - strlen( $newTarget->getFullText() )
945 return wfMessage(
'autosumm-changed-redirect-target',
946 $oldTarget->getFullText(),
947 $newTarget->getFullText() )
948 ->rawParams( $truncatedtext )->inContentLanguage()->text();
949 case 'removed-redirect':
950 $oldTarget = $oldContent->getRedirectTarget();
951 $truncatedtext = $newContent->getTextForSummary(
953 - strlen(
wfMessage(
'autosumm-removed-redirect' )
954 ->inContentLanguage()->
text() )
955 - strlen( $oldTarget->getFullText() ) );
957 return wfMessage(
'autosumm-removed-redirect', $oldTarget->getFullText() )
958 ->rawParams( $truncatedtext )->inContentLanguage()->text();
961 $truncatedtext = $newContent->getTextForSummary(
962 200 - strlen(
wfMessage(
'autosumm-new' )->inContentLanguage()->
text() ) );
964 return wfMessage(
'autosumm-new' )->rawParams( $truncatedtext )
965 ->inContentLanguage()->text();
967 return wfMessage(
'autosumm-blank' )->inContentLanguage()->text();
969 $truncatedtext = $newContent->getTextForSummary(
970 200 - strlen(
wfMessage(
'autosumm-replace' )->inContentLanguage()->
text() ) );
972 return wfMessage(
'autosumm-replace' )->rawParams( $truncatedtext )
973 ->inContentLanguage()->text();
975 return wfMessage(
'autosumm-newblank' )->inContentLanguage()->text();
997 $changeType = $this->
getChangeType( $oldContent, $newContent, $flags );
1000 if ( !$changeType ) {
1007 $tag =
'mw-' . $changeType;
1010 if ( in_array( $tag, ChangeTags::getSoftwareTags() ) ) {
1038 if ( is_null(
$rev ) ) {
1050 $prev =
$rev->getPrevious();
1066 [
'rev_user_text' =>
$revQuery[
'fields'][
'rev_user_text'] ],
1068 'rev_page' =>
$title->getArticleID(),
1076 if (
$res ===
false ) {
1081 $hasHistory = (
$res->numRows() > 1 );
1085 $onlyAuthor = $row->rev_user_text;
1087 foreach (
$res as $row ) {
1088 if ( $row->rev_user_text != $onlyAuthor ) {
1089 $onlyAuthor =
false;
1094 $onlyAuthor =
false;
1101 $reason =
wfMessage(
'exbeforeblank',
'$1' )->inContentLanguage()->text();
1103 if ( $onlyAuthor ) {
1108 )->inContentLanguage()->text();
1110 $reason =
wfMessage(
'excontent',
'$1' )->inContentLanguage()->text();
1114 if ( $reason ==
'-' ) {
1120 $text =
$content ?
$content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) :
'';
1123 $reason = str_replace(
'$1', $text, $reason );
1144 public function getUndoContent( $current, $undo, $undoafter, $undoIsLatest =
false ) {
1145 Assert::parameterType( Revision::class .
'|' . Content::class, $current,
'$current' );
1146 if ( $current instanceof
Content ) {
1147 Assert::parameter( $undo instanceof
Content,
'$undo',
1148 'Must be Content when $current is Content' );
1149 Assert::parameter( $undoafter instanceof
Content,
'$undoafter',
1150 'Must be Content when $current is Content' );
1151 $cur_content = $current;
1152 $undo_content = $undo;
1153 $undoafter_content = $undoafter;
1155 Assert::parameter( $undo instanceof
Revision,
'$undo',
1156 'Must be Revision when $current is Revision' );
1157 Assert::parameter( $undoafter instanceof
Revision,
'$undoafter',
1158 'Must be Revision when $current is Revision' );
1160 $cur_content = $current->getContent();
1162 if ( empty( $cur_content ) ) {
1166 $undo_content = $undo->getContent();
1167 $undoafter_content = $undoafter->getContent();
1169 if ( !$undo_content || !$undoafter_content ) {
1173 $undoIsLatest = $current->getId() === $undo->getId();
1179 if ( !$undoIsLatest ) {
1192 if ( $cur_content->equals( $undo_content ) ) {
1194 return $undoafter_content;
1197 $undone_content = $this->
merge3( $undo_content, $undoafter_content, $cur_content );
1199 return $undone_content;
1220 return ParserOptions::newCanonical(
$context );
1300 $fields[
'category'] =
$engine->makeSearchFieldMapping(
1306 $fields[
'external_link'] =
$engine->makeSearchFieldMapping(
1311 $fields[
'outgoing_link'] =
$engine->makeSearchFieldMapping(
1316 $fields[
'template'] =
$engine->makeSearchFieldMapping(
1322 $fields[
'content_model'] =
$engine->makeSearchFieldMapping(
1366 $fieldData[
'category'] = $searchDataExtractor->getCategories(
$output );
1367 $fieldData[
'external_link'] = $searchDataExtractor->getExternalLinks(
$output );
1368 $fieldData[
'outgoing_link'] = $searchDataExtractor->getOutgoingLinks(
$output );
1369 $fieldData[
'template'] = $searchDataExtractor->getTemplates(
$output );
1371 $text =
$content->getTextForSearchIndex();
1373 $fieldData[
'text'] = $text;
1374 $fieldData[
'source_text'] = $text;
1375 $fieldData[
'text_bytes'] =
$content->getSize();
1376 $fieldData[
'content_model'] =
$content->getModel();
1379 Hooks::run(
'SearchDataForIndex', [ &$fieldData, $this, $page,
$output,
$engine ] );
1397 $parserOutput =
$cache->get( $page, $parserOptions );
1400 if ( empty( $parserOutput ) ) {
1401 $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
1403 $renderer->getRenderedRevision(
1406 )->getRevisionParserOutput();
1408 $cache->save( $parserOutput, $page, $parserOptions );
1411 return $parserOutput;
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
$wgContentHandlerTextFallback
How to react if a plain text version of a non-text Content object is requested using ContentHandler::...
$wgContentHandlers
Plugins for page content model handling.
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
A content handler knows how do deal with a specific type of content on a wiki page.
getParserOutputForIndexing(WikiPage $page, ParserCache $cache=null)
Produce page output suitable for indexing.
getModelID()
Returns the model id that identifies the content model this ContentHandler can handle.
makeRedirectContent(Title $destination, $text='')
Creates a new Content object that acts as a redirect to the given page, or null if redirects are not ...
__construct( $modelId, $formats)
Constructor, initializing the ContentHandler instance with its model ID and a list of supported forma...
static getAllContentFormats()
string[] $mSupportedFormats
getChangeType(Content $oldContent=null, Content $newContent=null, $flags=0)
Return type of change if one exists for the given edit.
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
importTransform( $blob, $format=null)
Apply import transformation (per default, returns $blob unchanged).
isParserCacheSupported()
Returns true for content models that support caching using the ParserCache mechanism.
static getForModelID( $modelId)
Returns the ContentHandler singleton for the given model ID.
supportsDirectApiEditing()
Whether or not this content model supports direct editing via ApiEditPage.
getAutoDeleteReason(Title $title, &$hasHistory)
Auto-generates a deletion reason.
getChangeTag(Content $oldContent=null, Content $newContent=null, $flags=0)
Return an applicable tag if one exists for the given edit or return null.
getDiffEngineClass()
Returns the name of the diff engine to use.
static getForTitle(Title $title)
Returns the appropriate ContentHandler singleton for the given title.
exportTransform( $blob, $format=null)
Applies transformations on export (returns the blob unchanged per default).
merge3(Content $oldContent, Content $myContent, Content $yourContent)
Attempts to merge differences between three versions.
getAutosummary(Content $oldContent=null, Content $newContent=null, $flags=0)
Return an applicable auto-summary if one exists for the given edit.
checkFormat( $format)
Convenient for checking whether a format provided as a parameter is actually supported.
addSearchField(&$fields, SearchEngine $engine, $name, $type)
Add new field definition to array.
getActionOverrides()
Returns overrides for action handlers.
createDifferenceEngine(IContextSource $context, $old=0, $new=0, $rcid=0, $refreshCache=false, $unhide=false)
Factory for creating an appropriate DifferenceEngine for this content model.
getSecondaryDataUpdates(Title $title, Content $content, $role, SlotRenderingProvider $slotOutput)
Returns a list of DeferrableUpdate objects for recording information about the given Content in some ...
static getContentModels()
getPageLanguage(Title $title, Content $content=null)
Get the language in which the content of the given page is written.
getDefaultFormat()
The format used for serialization/deserialization by default by this ContentHandler.
getSlotDiffRendererInternal(IContextSource $context)
Return the SlotDiffRenderer appropriate for this content handler.
static getDefaultModelFor(Title $title)
Returns the name of the default content model to be used for the page with the given title.
unserializeContent( $blob, $format=null)
Unserializes a Content object of the type supported by this ContentHandler.
static getLocalizedName( $name, Language $lang=null)
Returns the localized name for a given content model.
supportsDirectEditing()
Return true if this content model supports direct editing, such as via EditPage.
getDeletionUpdates(Title $title, $role)
Returns a list of DeferrableUpdate objects for removing information about content in some secondary d...
isSupportedFormat( $format)
Returns true if $format is a serialization format supported by this ContentHandler,...
getSupportedFormats()
Returns a list of serialization formats supported by the serializeContent() and unserializeContent() ...
supportsSections()
Returns true if this content model supports sections.
getSlotDiffRenderer(IContextSource $context)
Get an appropriate SlotDiffRenderer for this content model.
static cleanupHandlersCache()
Clean up handlers cache.
static getContentText(Content $content=null)
Convenience function for getting flat text from a Content object.
getDataForSearchIndex(WikiPage $page, ParserOutput $output, SearchEngine $engine)
Return fields to be indexed by search engine as representation of this document.
supportsCategories()
Returns true if this content model supports categories.
static getForContent(Content $content)
Returns the appropriate ContentHandler singleton for the given Content object.
supportsRedirects()
Returns true if this content model supports redirects.
canBeUsedOn(Title $title)
Determines whether the content type handled by this ContentHandler can be used on the given page.
serializeContent(Content $content, $format=null)
Serializes a Content object of the type supported by this ContentHandler.
makeEmptyContent()
Creates an empty Content object of the type supported by this ContentHandler.
static array $handlers
A Cache of ContentHandler instances by model id.
makeParserOptions( $context)
Get parser options suitable for rendering and caching the article.
getFieldsForSearchIndex(SearchEngine $engine)
Get fields definition for search index.
getUndoContent( $current, $undo, $undoafter, $undoIsLatest=false)
Get the Content object that needs to be saved in order to undo all revisions between $undo and $undoa...
getPageViewLanguage(Title $title, Content $content=null)
Get the language in which the content of this page is written when viewed by user.
B/C adapter for turning a DifferenceEngine into a SlotDiffRenderer.
static getEngine()
Process $wgExternalDiffEngine and get a sane, usable engine.
Internationalisation code.
Exception thrown when an unregistered content model is requested.
static getQueryInfo( $options=[])
Return the tables, fields, and join conditions to be selected to create a new revision object.
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target.
Contain a class for special pages.
Content object implementation for representing flat text.
Renders a slot diff by doing a text diff on the native representation.
const ENGINE_PHP
Use the PHP diff implementation (DiffEngine).
const ENGINE_EXTERNAL
Use an external executable.
const ENGINE_WIKIDIFF2
Use the wikidiff2 PHP module.
Represents a title within MediaWiki.
Class representing a MediaWiki article and history.
getRevision()
Get the latest revision.
makeParserOptions( $context)
Get parser options suitable for rendering the primary article wikitext.
getContent( $audience=Revision::FOR_PUBLIC, User $user=null)
Get the content of the current revision.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
const CONTENT_MODEL_WIKITEXT
const CONTENT_MODEL_JAVASCRIPT
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify as strings Extensions should add to this list prev or next $refreshCache
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify as strings Extensions should add to this list prev or next refreshes the diff cache $unhide
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
namespace and then decline to actually register it file or subcat img or subcat $title
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify as strings Extensions should add to this list prev or next refreshes the diff cache allow viewing deleted revs & $differenceEngine
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "<div ...>$1</div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
Allows to change the fields on the form that will be generated $name
the value to return A Title object or null for latest all implement SearchIndexField $engine
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
returning false will NOT prevent logging $e
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Base interface for content objects.
Interface for objects which can provide a MediaWiki context on request.
const INDEX_TYPE_TEXT
Field types.
const FLAG_CASEFOLD
Generic field flags.
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
if(!is_readable( $file)) $ext
if(!isset( $args[0])) $lang