53 parent::__construct(
"The content model '$modelId' is not registered on this wiki.\n" .
54 'See https://www.mediawiki.org/wiki/Content_handlers to find out which extensions ' .
55 'handle this content model.' );
125 wfDebugLog(
'ContentHandler',
'Accessing ' .
$content->getModel() .
' content as text!' );
129 "Attempt to get text from Content with model " .
165 $modelId =
null, $format =
null ) {
166 if ( is_null( $modelId ) ) {
167 if ( is_null(
$title ) ) {
168 throw new MWException(
"Must provide a Title object or a content model ID." );
171 $modelId =
$title->getContentModel();
176 return $handler->unserializeContent( $text, $format );
217 $ns =
$title->getNamespace();
221 $model = MWNamespace::getNamespaceContentModel( $ns );
224 if ( !Hooks::run(
'ContentHandlerDefaultModelFor', [
$title, &$model ] ) ) {
225 if ( !is_null( $model ) ) {
231 $isCodePage =
NS_MEDIAWIKI == $ns && preg_match(
'!\.(css|js|json)$!u',
$title->getText(), $m );
237 Hooks::run(
'TitleIsCssOrJsPage', [
$title, &$isCodePage ],
'1.21' );
240 $isCodeSubpage =
NS_USER == $ns
242 && preg_match(
"/\\/.*\\.(js|css|json)$/",
$title->getText(), $m );
243 if ( $isCodeSubpage ) {
249 $isWikitext = $isWikitext && !$isCodePage && !$isCodeSubpage;
252 Hooks::run(
'TitleIsWikitextPage', [
$title, &$isWikitext ],
'1.21' );
254 if ( !$isWikitext ) {
282 $modelId =
$title->getContentModel();
344 Hooks::run(
'ContentHandlerForModelID', [ $modelId, &
$handler ] );
351 throw new MWException(
"ContentHandlerForModelID must supply a ContentHandler instance" );
356 if ( is_callable( $classOrCallback ) ) {
357 $handler = call_user_func( $classOrCallback, $modelId );
359 $handler =
new $classOrCallback( $modelId );
363 throw new MWException(
"$classOrCallback from \$wgContentHandlers is not " .
364 "compatible with ContentHandler" );
368 wfDebugLog(
'ContentHandler',
'Created handler for ' . $modelId
392 $key =
"content-model-$name";
396 $msg->inLanguage(
$lang );
399 return $msg->exists() ? $msg->plain() :
$name;
415 $formats = array_merge( $formats,
$handler->getSupportedFormats() );
418 $formats = array_unique( $formats );
445 $this->mModelID = $modelId;
446 $this->mSupportedFormats = $formats;
554 if ( $model_id !== $this->mModelID ) {
556 "expected {$this->mModelID} " .
557 "but got $model_id." );
586 return $this->mSupportedFormats[0];
607 return in_array( $format, $this->mSupportedFormats );
620 "Format $format is not supported for content model "
665 if ( !Hooks::run(
'GetDifferenceEngine',
700 $pageLang = Language::factory(
$lang );
703 Hooks::run(
'PageContentLanguage', [
$title, &$pageLang,
$wgLang ] );
734 $variant = $pageLang->getPreferredVariant();
735 if ( $pageLang->getCode() !== $variant ) {
736 $pageLang = Language::factory( $variant );
762 Hooks::run(
'ContentModelCanBeUsedOn', [ $this->
getModelID(), $title, &$ok ] );
775 return DifferenceEngine::class;
818 $ot = !is_null( $oldContent ) ? $oldContent->getRedirectTarget() :
null;
819 $rt = !is_null( $newContent ) ? $newContent->getRedirectTarget() :
null;
821 if ( is_object( $rt ) ) {
822 if ( !is_object( $ot )
823 || !$rt->equals( $ot )
824 || $ot->getFragment() != $rt->getFragment()
826 $truncatedtext = $newContent->getTextForSummary(
828 - strlen(
wfMessage(
'autoredircomment' )->inContentLanguage()->
text() )
829 - strlen( $rt->getFullText() ) );
831 return wfMessage(
'autoredircomment', $rt->getFullText() )
832 ->rawParams( $truncatedtext )->inContentLanguage()->text();
841 $truncatedtext = $newContent->getTextForSummary(
842 200 - strlen(
wfMessage(
'autosumm-new' )->inContentLanguage()->
text() ) );
844 return wfMessage(
'autosumm-new' )->rawParams( $truncatedtext )
845 ->inContentLanguage()->text();
849 if ( !empty( $oldContent ) && $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
850 return wfMessage(
'autosumm-blank' )->inContentLanguage()->text();
851 } elseif ( !empty( $oldContent )
852 && $oldContent->getSize() > 10 * $newContent->getSize()
853 && $newContent->getSize() < 500
857 $truncatedtext = $newContent->getTextForSummary(
858 200 - strlen(
wfMessage(
'autosumm-replace' )->inContentLanguage()->
text() ) );
860 return wfMessage(
'autosumm-replace' )->rawParams( $truncatedtext )
861 ->inContentLanguage()->text();
866 return wfMessage(
'autosumm-newblank' )->inContentLanguage()->text();
895 if ( is_null(
$rev ) ) {
907 $prev =
$rev->getPrevious();
920 $res =
$dbr->select(
'revision',
'rev_user_text',
929 if (
$res ===
false ) {
934 $hasHistory = (
$res->numRows() > 1 );
938 $onlyAuthor = $row->rev_user_text;
940 foreach (
$res as $row ) {
941 if ( $row->rev_user_text != $onlyAuthor ) {
954 $reason =
wfMessage(
'exbeforeblank',
'$1' )->inContentLanguage()->text();
961 )->inContentLanguage()->text();
963 $reason =
wfMessage(
'excontent',
'$1' )->inContentLanguage()->text();
967 if ( $reason ==
'-' ) {
973 $text =
$content ?
$content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) :
'';
976 $reason = str_replace(
'$1', $text, $reason );
997 if ( empty( $cur_content ) ) {
1002 $undoafter_content = $undoafter->
getContent();
1004 if ( !$undo_content || !$undoafter_content ) {
1011 if ( $current->
getId() !== $undo->
getId() ) {
1024 if ( $cur_content->equals( $undo_content ) ) {
1026 return $undoafter_content;
1029 $undone_content = $this->
merge3( $undo_content, $undoafter_content, $cur_content );
1031 return $undone_content;
1055 } elseif (
$context ===
'canonical' ) {
1058 throw new MWException(
"Bad context for parser options: $context" );
1148 $deprecatedVersion =
null
1151 if ( !Hooks::isRegistered( $event ) ) {
1156 $contentObjects = [];
1159 foreach (
$args as $k => $v ) {
1160 if ( $v instanceof
Content ) {
1163 $contentObjects[$k] = $v;
1165 $v = $v->serialize();
1166 $contentTexts[$k] = $v;
1172 $ok = Hooks::run( $event,
$args, $deprecatedVersion );
1175 foreach ( $contentTexts
as $k => $orig ) {
1178 $modified =
$args[$k];
1181 if ( $modified !== $orig ) {
1203 $fields[
'category'] =
$engine->makeSearchFieldMapping(
1210 $fields[
'external_link'] =
$engine->makeSearchFieldMapping(
1215 $fields[
'outgoing_link'] =
$engine->makeSearchFieldMapping(
1220 $fields[
'template'] =
$engine->makeSearchFieldMapping(
1263 $fieldData[
'category'] = $searchDataExtractor->getCategories(
$output );
1264 $fieldData[
'external_link'] = $searchDataExtractor->getExternalLinks(
$output );
1265 $fieldData[
'outgoing_link'] = $searchDataExtractor->getOutgoingLinks(
$output );
1266 $fieldData[
'template'] = $searchDataExtractor->getTemplates(
$output );
1268 $text =
$content->getTextForSearchIndex();
1270 $fieldData[
'text'] = $text;
1271 $fieldData[
'source_text'] = $text;
1272 $fieldData[
'text_bytes'] =
$content->getSize();
1289 $parserOptions =
$page->makeParserOptions(
'canonical' );
1296 $page->getContent()->getParserOutput(
$page->getTitle(),
$revId, $parserOptions );
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgEnableParserLimitReporting
Whether to include the NewPP limit report as a HTML comment.
$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.
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.
getAutosummary(Content $oldContent=null, Content $newContent=null, $flags)
Return an applicable auto-summary if one exists for the given edit.
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
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.
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.
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.
getUndoContent(Revision $current, Revision $undo, Revision $undoafter)
Get the Content object that needs to be saved in order to undo all revisions between $undo and $undoa...
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.
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.
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.
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.
static runLegacyHooks( $event, $args=[], $deprecatedVersion=null)
Call a legacy hook that uses text instead of Content objects.
getPageViewLanguage(Title $title, Content $content=null)
Get the language in which the content of this page is written when viewed by user.
Internationalisation code.
Exception representing a failure to serialize or unserialize a content object.
Exception thrown when an unregistered content model is requested.
string $modelId
The name of the unknown content model.
static singleton()
Get the signleton instance of this class.
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
static newFromUser( $user)
Get a ParserOptions object from a given user.
static newFromUserAndLang(User $user, Language $lang)
Get a ParserOptions object from a given user and language.
getContent( $audience=self::FOR_PUBLIC, User $user=null)
Fetch revision content if it's available to the specified audience.
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.
Represents a title within MediaWiki.
getArticleID( $flags=0)
Get the article ID for this Title from the link cache, adding it if necessary.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Class representing a MediaWiki article and history.
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 class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
when a variable name is used in a it is silently declared as a new local masking the global
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
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
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context $revId
the array() calling protocol came about after MediaWiki 1.4rc1.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context $parserOutput
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
namespace and then decline to actually register it file or subcat img or subcat $title
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
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 prev or next $refreshCache
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
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 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
it s the revision text itself In either if gzip is the revision text is gzipped $flags
the value to return A Title object or null for latest all implement SearchIndexField $engine
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 prev or next refreshes the diff cache $unhide
Allows to change the fields on the form that will be generated $name
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
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
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
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive false for true for descending in case the handler function wants to provide a converted Content object Note that $result getContentModel() must return $toModel. 'CustomEditor' $rcid is used in generating this variable which contains information about the new such as the revision s whether the revision was marked as a minor edit or etc $differenceEngine
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.
if(!isset( $args[0])) $lang