MediaWiki  1.28.1
AbstractContent.php
Go to the documentation of this file.
1 <?php
34 abstract class AbstractContent implements Content {
43  protected $model_id;
44 
50  public function __construct( $modelId = null ) {
51  $this->model_id = $modelId;
52  }
53 
59  public function getModel() {
60  return $this->model_id;
61  }
62 
71  protected function checkModelID( $modelId ) {
72  if ( $modelId !== $this->model_id ) {
73  throw new MWException(
74  "Bad content model: " .
75  "expected {$this->model_id} " .
76  "but got $modelId."
77  );
78  }
79  }
80 
86  public function getContentHandler() {
87  return ContentHandler::getForContent( $this );
88  }
89 
95  public function getDefaultFormat() {
96  return $this->getContentHandler()->getDefaultFormat();
97  }
98 
104  public function getSupportedFormats() {
105  return $this->getContentHandler()->getSupportedFormats();
106  }
107 
117  public function isSupportedFormat( $format ) {
118  if ( !$format ) {
119  return true; // this means "use the default"
120  }
121 
122  return $this->getContentHandler()->isSupportedFormat( $format );
123  }
124 
132  protected function checkFormat( $format ) {
133  if ( !$this->isSupportedFormat( $format ) ) {
134  throw new MWException(
135  "Format $format is not supported for content model " .
136  $this->getModel()
137  );
138  }
139  }
140 
150  public function serialize( $format = null ) {
151  return $this->getContentHandler()->serializeContent( $this, $format );
152  }
153 
161  public function isEmpty() {
162  return $this->getSize() === 0;
163  }
164 
174  public function isValid() {
175  return true;
176  }
177 
187  public function equals( Content $that = null ) {
188  if ( is_null( $that ) ) {
189  return false;
190  }
191 
192  if ( $that === $this ) {
193  return true;
194  }
195 
196  if ( $that->getModel() !== $this->getModel() ) {
197  return false;
198  }
199 
200  return $this->getNativeData() === $that->getNativeData();
201  }
202 
226  public function getSecondaryDataUpdates( Title $title, Content $old = null,
227  $recursive = true, ParserOutput $parserOutput = null
228  ) {
229  if ( $parserOutput === null ) {
230  $parserOutput = $this->getParserOutput( $title, null, null, false );
231  }
232 
233  $updates = [
234  new LinksUpdate( $title, $parserOutput, $recursive )
235  ];
236 
237  Hooks::run( 'SecondaryDataUpdates', [ $title, $old, $recursive, $parserOutput, &$updates ] );
238 
239  return $updates;
240  }
241 
249  public function getRedirectChain() {
250  global $wgMaxRedirects;
251  $title = $this->getRedirectTarget();
252  if ( is_null( $title ) ) {
253  return null;
254  }
255  // recursive check to follow double redirects
256  $recurse = $wgMaxRedirects;
257  $titles = [ $title ];
258  while ( --$recurse > 0 ) {
259  if ( $title->isRedirect() ) {
261  $newtitle = $page->getRedirectTarget();
262  } else {
263  break;
264  }
265  // Redirects to some special pages are not permitted
266  if ( $newtitle instanceof Title && $newtitle->isValidRedirectTarget() ) {
267  // The new title passes the checks, so make that our current
268  // title so that further recursion can be checked
269  $title = $newtitle;
270  $titles[] = $newtitle;
271  } else {
272  break;
273  }
274  }
275 
276  return $titles;
277  }
278 
288  public function getRedirectTarget() {
289  return null;
290  }
291 
301  public function getUltimateRedirectTarget() {
302  $titles = $this->getRedirectChain();
303 
304  return $titles ? array_pop( $titles ) : null;
305  }
306 
314  public function isRedirect() {
315  return $this->getRedirectTarget() !== null;
316  }
317 
330  public function updateRedirect( Title $target ) {
331  return $this;
332  }
333 
341  public function getSection( $sectionId ) {
342  return null;
343  }
344 
352  public function replaceSection( $sectionId, Content $with, $sectionTitle = '' ) {
353  return null;
354  }
355 
363  public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
364  return $this;
365  }
366 
374  public function addSectionHeader( $header ) {
375  return $this;
376  }
377 
385  public function preloadTransform( Title $title, ParserOptions $popts, $params = [] ) {
386  return $this;
387  }
388 
396  public function prepareSave( WikiPage $page, $flags, $parentRevId, User $user ) {
397  if ( $this->isValid() ) {
398  return Status::newGood();
399  } else {
400  return Status::newFatal( "invalid-content-data" );
401  }
402  }
403 
415  return [
416  new LinksDeletionUpdate( $page ),
417  ];
418  }
419 
432  public function matchMagicWord( MagicWord $word ) {
433  return false;
434  }
435 
447  public function convert( $toModel, $lossy = '' ) {
448  if ( $this->getModel() === $toModel ) {
449  // nothing to do, shorten out.
450  return $this;
451  }
452 
453  $lossy = ( $lossy === 'lossy' ); // string flag, convert to boolean for convenience
454  $result = false;
455 
456  Hooks::run( 'ConvertContent', [ $this, $toModel, $lossy, &$result ] );
457 
458  return $result;
459  }
460 
481  public function getParserOutput( Title $title, $revId = null,
482  ParserOptions $options = null, $generateHtml = true
483  ) {
484  if ( $options === null ) {
485  $options = $this->getContentHandler()->makeParserOptions( 'canonical' );
486  }
487 
488  $po = new ParserOutput();
489 
490  if ( Hooks::run( 'ContentGetParserOutput',
491  [ $this, $title, $revId, $options, $generateHtml, &$po ] ) ) {
492 
493  // Save and restore the old value, just in case something is reusing
494  // the ParserOptions object in some weird way.
495  $oldRedir = $options->getRedirectTarget();
496  $options->setRedirectTarget( $this->getRedirectTarget() );
497  $this->fillParserOutput( $title, $revId, $options, $generateHtml, $po );
498  $options->setRedirectTarget( $oldRedir );
499  }
500 
501  Hooks::run( 'ContentAlterParserOutput', [ $this, $title, $po ] );
502 
503  return $po;
504  }
505 
526  protected function fillParserOutput( Title $title, $revId,
528  ) {
529  // Don't make abstract, so subclasses that override getParserOutput() directly don't fail.
530  throw new MWException( 'Subclasses of AbstractContent must override fillParserOutput!' );
531  }
532 }
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:115
isValid()
Subclasses may override this to implement (light weight) validation.
preSaveTransform(Title $title, User $user, ParserOptions $popts)
replaceSection($sectionId, Content $with, $sectionTitle= '')
$model_id
Name of the content model this Content object represents.
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 $generateHtml
Definition: hooks.txt:1046
Class the manages updates of *_link tables as well as similar extension-managed tables.
Definition: LinksUpdate.php:33
static newFatal($message)
Factory function for fatal errors.
Definition: StatusValue.php:63
Set options of the Parser.
getDeletionUpdates(WikiPage $page, ParserOutput $parserOutput=null)
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
Definition: hooks.txt:1046
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2703
checkModelID($modelId)
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
addSectionHeader($header)
serialize($format=null)
__construct($modelId=null)
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED!Use HtmlPageLinkRendererBegin instead.Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1934
getSize()
Returns the content's nominal size in "bogo-bytes".
preloadTransform(Title $title, ParserOptions $popts, $params=[])
getSecondaryDataUpdates(Title $title, Content $old=null, $recursive=true, ParserOutput $parserOutput=null)
Returns a list of DataUpdate objects for recording information about this Content in some secondary d...
convert($toModel, $lossy= '')
This base implementation calls the hook ConvertContent to enable custom conversions.
isSupportedFormat($format)
updateRedirect(Title $target)
This default implementation always returns $this.
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
Definition: hooks.txt:1046
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
Definition: hooks.txt:1046
static getForContent(Content $content)
Returns the appropriate ContentHandler singleton for the given Content object.
equals(Content $that=null)
Base implementation for content objects.
Base interface for content objects.
Definition: Content.php:34
$params
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:953
static newGood($value=null)
Factory function for good results.
Definition: StatusValue.php:76
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
$header
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
getNativeData()
Returns native representation of the data.
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
Definition: hooks.txt:1046
Class representing a MediaWiki article and history.
Definition: WikiPage.php:32
prepareSave(WikiPage $page, $flags, $parentRevId, User $user)
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
Definition: injection.txt:35
linkcache txt The LinkCache class maintains a list of article titles and the information about whether or not the article exists in the database This is used to mark up links when displaying a page If the same link appears more than once on any page then it only has to be looked up once In most cases link lookups are done in batches with the LinkBatch class or the equivalent in so the link cache is mostly useful for short snippets of parsed and for links in the navigation areas of the skin The link cache was formerly used to track links used in a document for the purposes of updating the link tables This application is now deprecated To create a you can use the following $titles
Definition: linkcache.txt:17
fillParserOutput(Title $title, $revId, ParserOptions $options, $generateHtml, ParserOutput &$output)
Fills the provided ParserOutput with information derived from the content.
getSection($sectionId)
getParserOutput(Title $title, $revId=null, ParserOptions $options=null, $generateHtml=true)
Returns a ParserOutput object containing information derived from this content.
matchMagicWord(MagicWord $word)
This default implementation always returns false.
getRedirectTarget()
Subclasses that implement redirects should override this.
Update object handling the cleanup of links tables after a page was deleted.
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
Definition: hooks.txt:2491
This class encapsulates "magic words" such as "#redirect", NOTOC, etc.
Definition: MagicWord.php:59