MediaWiki  master
WikitextContent.php
Go to the documentation of this file.
1 <?php
30 
38 
43  private $hadSignature = false;
44 
49 
50  public function __construct( $text ) {
51  parent::__construct( $text, CONTENT_MODEL_WIKITEXT );
52  }
53 
61  public function getSection( $sectionId ) {
62  $text = $this->getText();
63  $sect = MediaWikiServices::getInstance()->getParser()
64  ->getSection( $text, $sectionId, false );
65 
66  if ( $sect === false ) {
67  return false;
68  } else {
69  return new static( $sect );
70  }
71  }
72 
83  public function replaceSection( $sectionId, Content $with, $sectionTitle = '' ) {
84  $myModelId = $this->getModel();
85  $sectionModelId = $with->getModel();
86 
87  if ( $sectionModelId != $myModelId ) {
88  throw new MWException( "Incompatible content model for section: " .
89  "document uses $myModelId but " .
90  "section uses $sectionModelId." );
91  }
92 
93  $oldtext = $this->getText();
94  $text = $with->getText();
95 
96  if ( strval( $sectionId ) === '' ) {
97  return $with; # XXX: copy first?
98  }
99 
100  if ( $sectionId === 'new' ) {
101  # Inserting a new section
102  $subject = $sectionTitle ? wfMessage( 'newsectionheaderdefaultlevel' )
103  ->plaintextParams( $sectionTitle )->inContentLanguage()->text() . "\n\n" : '';
104  if ( Hooks::run( 'PlaceNewSection', [ $this, $oldtext, $subject, &$text ] ) ) {
105  $text = strlen( trim( $oldtext ) ) > 0
106  ? "{$oldtext}\n\n{$subject}{$text}"
107  : "{$subject}{$text}";
108  }
109  } else {
110  # Replacing an existing section; roll out the big guns
111  $text = MediaWikiServices::getInstance()->getParser()
112  ->replaceSection( $oldtext, $sectionId, $text );
113  }
114 
115  $newContent = new static( $text );
116 
117  return $newContent;
118  }
119 
128  public function addSectionHeader( $header ) {
129  $text = wfMessage( 'newsectionheaderdefaultlevel' )
130  ->rawParams( $header )->inContentLanguage()->text();
131  $text .= "\n\n";
132  $text .= $this->getText();
133 
134  return new static( $text );
135  }
136 
147  public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
148  $text = $this->getText();
149 
150  $parser = MediaWikiServices::getInstance()->getParser();
151  $pst = $parser->preSaveTransform( $text, $title, $user, $popts );
152 
153  if ( $text === $pst ) {
154  return $this;
155  }
156 
157  $ret = new static( $pst );
158 
159  if ( $parser->getOutput()->getFlag( 'user-signature' ) ) {
160  $ret->hadSignature = true;
161  }
162 
163  return $ret;
164  }
165 
176  public function preloadTransform( Title $title, ParserOptions $popts, $params = [] ) {
177  $text = $this->getText();
178  $plt = MediaWikiServices::getInstance()->getParser()
179  ->getPreloadText( $text, $title, $popts, $params );
180 
181  return new static( $plt );
182  }
183 
193  protected function getRedirectTargetAndText() {
194  global $wgMaxRedirects;
195 
196  if ( $this->redirectTargetAndText !== null ) {
198  }
199 
200  if ( $wgMaxRedirects < 1 ) {
201  // redirects are disabled, so quit early
202  $this->redirectTargetAndText = [ null, $this->getText() ];
204  }
205 
206  $redir = MediaWikiServices::getInstance()->getMagicWordFactory()->get( 'redirect' );
207  $text = ltrim( $this->getText() );
208  if ( $redir->matchStartAndRemove( $text ) ) {
209  // Extract the first link and see if it's usable
210  // Ensure that it really does come directly after #REDIRECT
211  // Some older redirects included a colon, so don't freak about that!
212  $m = [];
213  if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}\s*!', $text, $m ) ) {
214  // Strip preceding colon used to "escape" categories, etc.
215  // and URL-decode links
216  if ( strpos( $m[1], '%' ) !== false ) {
217  // Match behavior of inline link parsing here;
218  $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
219  }
220  $title = Title::newFromText( $m[1] );
221  // If the title is a redirect to bad special pages or is invalid, return null
222  if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
223  $this->redirectTargetAndText = [ null, $this->getText() ];
225  }
226 
227  $this->redirectTargetAndText = [ $title, substr( $text, strlen( $m[0] ) ) ];
229  }
230  }
231 
232  $this->redirectTargetAndText = [ null, $this->getText() ];
234  }
235 
243  public function getRedirectTarget() {
244  list( $title, ) = $this->getRedirectTargetAndText();
245 
246  return $title;
247  }
248 
261  public function updateRedirect( Title $target ) {
262  if ( !$this->isRedirect() ) {
263  return $this;
264  }
265 
266  # Fix the text
267  # Remember that redirect pages can have categories, templates, etc.,
268  # so the regex has to be fairly general
269  $newText = preg_replace( '/ \[ \[ [^\]]* \] \] /x',
270  '[[' . $target->getFullText() . ']]',
271  $this->getText(), 1 );
272 
273  return new static( $newText );
274  }
275 
287  public function isCountable( $hasLinks = null, Title $title = null ) {
288  global $wgArticleCountMethod;
289 
290  if ( $this->isRedirect() ) {
291  return false;
292  }
293 
294  if ( $wgArticleCountMethod === 'link' ) {
295  if ( $hasLinks === null ) { # not known, find out
296  if ( !$title ) {
298  $title = $context->getTitle();
299  }
300 
301  $po = $this->getParserOutput( $title, null, null, false );
302  $links = $po->getLinks();
303  $hasLinks = !empty( $links );
304  }
305 
306  return $hasLinks;
307  }
308 
309  return true;
310  }
311 
316  public function getTextForSummary( $maxlength = 250 ) {
317  $truncatedtext = parent::getTextForSummary( $maxlength );
318 
319  # clean up unfinished links
320  # XXX: make this optional? wasn't there in autosummary, but required for
321  # deletion summary.
322  $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
323 
324  return $truncatedtext;
325  }
326 
338  protected function fillParserOutput( Title $title, $revId,
339  ParserOptions $options, $generateHtml, ParserOutput &$output
340  ) {
341  $stackTrace = ( new RuntimeException() )->getTraceAsString();
342  if ( $this->previousParseStackTrace ) {
343  // NOTE: there may be legitimate changes to re-parse the same WikiText content,
344  // e.g. if predicted revision ID for the REVISIONID magic word mismatched.
345  // But that should be rare.
346  $logger = LoggerFactory::getInstance( 'DuplicateParse' );
347  $logger->debug(
348  __METHOD__ . ': Possibly redundant parse!',
349  [
350  'title' => $title->getPrefixedDBkey(),
351  'rev' => $revId,
352  'options-hash' => $options->optionsHash(
354  $title
355  ),
356  'trace' => $stackTrace,
357  'previous-trace' => $this->previousParseStackTrace,
358  ]
359  );
360  }
361  $this->previousParseStackTrace = $stackTrace;
362 
363  list( $redir, $text ) = $this->getRedirectTargetAndText();
364  $output = MediaWikiServices::getInstance()->getParser()
365  ->parse( $text, $title, $options, true, true, $revId );
366 
367  // Add redirect indicator at the top
368  if ( $redir ) {
369  // Make sure to include the redirect link in pagelinks
370  $output->addLink( $redir );
371  if ( $generateHtml ) {
372  $chain = $this->getRedirectChain();
373  $output->setText(
375  $output->getRawText()
376  );
377  $output->addModuleStyles( 'mediawiki.action.view.redirectPage' );
378  }
379  }
380 
381  // Pass along user-signature flag
382  if ( $this->hadSignature ) {
383  $output->setFlag( 'user-signature' );
384  }
385  }
386 
390  protected function getHtml() {
391  throw new MWException(
392  "getHtml() not implemented for wikitext. "
393  . "Use getParserOutput()->getText()."
394  );
395  }
396 
406  public function matchMagicWord( MagicWord $word ) {
407  return $word->match( $this->getText() );
408  }
409 
410 }
$wgArticleCountMethod
Method used to determine if a page in a content namespace should be counted as a valid article...
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
Definition: deferred.txt:11
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:215
addModuleStyles( $modules)
setText( $text)
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1972
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getRedirectTargetAndText()
Extract the redirect target and the remaining text on the page.
optionsHash( $forOptions, $title=null)
Generate a hash string with the values set on these ParserOptions for the keys given in the array...
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 MediaWikiServices
Definition: injection.txt:23
bool $hadSignature
Tracks if the parser set the user-signature flag when creating this content, which would make it expi...
getText()
Returns the text represented by this Content object, as a string.
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
Definition: hooks.txt:1781
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
Definition: hooks.txt:2205
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:51
updateRedirect(Title $target)
This implementation replaces the first link on the page with the given new target if this Content obj...
getRedirectTarget()
Implement redirect extraction for wikitext.
preloadTransform(Title $title, ParserOptions $popts, $params=[])
Returns a Content object with preload transformations applied (or this object if no transformations a...
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 "&lt
static getMain()
Get the RequestContext object associated with the main request.
$wgMaxRedirects
Max number of redirects to follow when resolving redirects.
setFlag( $flag)
Attach a flag to the output so that it can be checked later to handle special cases.
addSectionHeader( $header)
Returns a new WikitextContent object with the given section heading prepended.
array null $previousParseStackTrace
Stack trace of the previous parse.
static getRedirectHeaderHtml(Language $lang, $target, $forceKnown=false)
Return the HTML for the top of a redirect page.
Definition: Article.php:1690
match( $text)
Returns true if the text contains the word.
Definition: MagicWord.php:300
$params
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1972
matchMagicWord(MagicWord $word)
This implementation calls $word->match() on the this TextContent object&#39;s text.
getFullText()
Get the prefixed title with spaces, plus any fragment (part beginning with &#39;#&#39;)
Definition: Title.php:1748
getTextForSummary( $maxlength=250)
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
$header
replaceSection( $sectionId, Content $with, $sectionTitle='')
getRawText()
Get the cacheable text with <mw:editsection> markers still in it.
getTitle()
Get the Title object that we&#39;ll be acting on, as specified in the WebRequest.
Definition: MediaWiki.php:137
static allCacheVaryingOptions()
Return all option keys that vary the options hash.
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
preSaveTransform(Title $title, User $user, ParserOptions $popts)
Returns a Content object with pre-save transformations applied using Parser::preSaveTransform().
getSection( $sectionId)
getPageLanguage()
Get the language in which the content of this page is written in wikitext.
Definition: Title.php:4479
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
Definition: hooks.txt:2621
addLink(Title $title, $id=null)
Record a local or interwiki inline link for saving in future link tables.
MediaWiki Logger LoggerFactory implements a PSR [0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
isCountable( $hasLinks=null, Title $title=null)
Returns true if this content is not a redirect, and this content&#39;s text is countable according to the...
getModel()
Returns the ID of the content model used by this Content object.
getParserOutput(Title $title, $revId=null, ParserOptions $options=null, $generateHtml=true)
Returns a ParserOutput object containing information derived from this content.
fillParserOutput(Title $title, $revId, ParserOptions $options, $generateHtml, ParserOutput &$output)
Returns a ParserOutput object resulting from parsing the content&#39;s text using the global Parser servi...
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1454
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
getPrefixedDBkey()
Get the prefixed database key form.
Definition: Title.php:1712
This class encapsulates "magic words" such as "#redirect", NOTOC, etc.
Definition: MagicWord.php:57
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:322