MediaWiki  1.33.0
WikitextContent.php
Go to the documentation of this file.
1 <?php
30 
37  private $redirectTargetAndText = null;
38 
43  private $hadSignature = false;
44 
48  private $previousParseStackTrace = null;
49 
50  public function __construct( $text ) {
51  parent::__construct( $text, CONTENT_MODEL_WIKITEXT );
52  }
53 
61  public function getSection( $sectionId ) {
62  global $wgParser;
63 
64  $text = $this->getText();
65  $sect = $wgParser->getSection( $text, $sectionId, false );
66 
67  if ( $sect === false ) {
68  return false;
69  } else {
70  return new static( $sect );
71  }
72  }
73 
84  public function replaceSection( $sectionId, Content $with, $sectionTitle = '' ) {
85  $myModelId = $this->getModel();
86  $sectionModelId = $with->getModel();
87 
88  if ( $sectionModelId != $myModelId ) {
89  throw new MWException( "Incompatible content model for section: " .
90  "document uses $myModelId but " .
91  "section uses $sectionModelId." );
92  }
93 
94  $oldtext = $this->getText();
95  $text = $with->getText();
96 
97  if ( strval( $sectionId ) === '' ) {
98  return $with; # XXX: copy first?
99  }
100 
101  if ( $sectionId === 'new' ) {
102  # Inserting a new section
103  $subject = $sectionTitle ? wfMessage( 'newsectionheaderdefaultlevel' )
104  ->plaintextParams( $sectionTitle )->inContentLanguage()->text() . "\n\n" : '';
105  if ( Hooks::run( 'PlaceNewSection', [ $this, $oldtext, $subject, &$text ] ) ) {
106  $text = strlen( trim( $oldtext ) ) > 0
107  ? "{$oldtext}\n\n{$subject}{$text}"
108  : "{$subject}{$text}";
109  }
110  } else {
111  # Replacing an existing section; roll out the big guns
112  global $wgParser;
113 
114  $text = $wgParser->replaceSection( $oldtext, $sectionId, $text );
115  }
116 
117  $newContent = new static( $text );
118 
119  return $newContent;
120  }
121 
130  public function addSectionHeader( $header ) {
131  $text = wfMessage( 'newsectionheaderdefaultlevel' )
132  ->rawParams( $header )->inContentLanguage()->text();
133  $text .= "\n\n";
134  $text .= $this->getText();
135 
136  return new static( $text );
137  }
138 
149  public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
150  global $wgParser;
151 
152  $text = $this->getText();
153  $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
154 
155  if ( $text === $pst ) {
156  return $this;
157  }
158 
159  $ret = new static( $pst );
160 
161  if ( $wgParser->getOutput()->getFlag( 'user-signature' ) ) {
162  $ret->hadSignature = true;
163  }
164 
165  return $ret;
166  }
167 
178  public function preloadTransform( Title $title, ParserOptions $popts, $params = [] ) {
179  global $wgParser;
180 
181  $text = $this->getText();
182  $plt = $wgParser->getPreloadText( $text, $title, $popts, $params );
183 
184  return new static( $plt );
185  }
186 
196  protected function getRedirectTargetAndText() {
197  global $wgMaxRedirects;
198 
199  if ( $this->redirectTargetAndText !== null ) {
201  }
202 
203  if ( $wgMaxRedirects < 1 ) {
204  // redirects are disabled, so quit early
205  $this->redirectTargetAndText = [ null, $this->getText() ];
207  }
208 
209  $redir = MediaWikiServices::getInstance()->getMagicWordFactory()->get( 'redirect' );
210  $text = ltrim( $this->getText() );
211  if ( $redir->matchStartAndRemove( $text ) ) {
212  // Extract the first link and see if it's usable
213  // Ensure that it really does come directly after #REDIRECT
214  // Some older redirects included a colon, so don't freak about that!
215  $m = [];
216  if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}\s*!', $text, $m ) ) {
217  // Strip preceding colon used to "escape" categories, etc.
218  // and URL-decode links
219  if ( strpos( $m[1], '%' ) !== false ) {
220  // Match behavior of inline link parsing here;
221  $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
222  }
223  $title = Title::newFromText( $m[1] );
224  // If the title is a redirect to bad special pages or is invalid, return null
225  if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
226  $this->redirectTargetAndText = [ null, $this->getText() ];
228  }
229 
230  $this->redirectTargetAndText = [ $title, substr( $text, strlen( $m[0] ) ) ];
232  }
233  }
234 
235  $this->redirectTargetAndText = [ null, $this->getText() ];
237  }
238 
246  public function getRedirectTarget() {
247  list( $title, ) = $this->getRedirectTargetAndText();
248 
249  return $title;
250  }
251 
264  public function updateRedirect( Title $target ) {
265  if ( !$this->isRedirect() ) {
266  return $this;
267  }
268 
269  # Fix the text
270  # Remember that redirect pages can have categories, templates, etc.,
271  # so the regex has to be fairly general
272  $newText = preg_replace( '/ \[ \[ [^\]]* \] \] /x',
273  '[[' . $target->getFullText() . ']]',
274  $this->getText(), 1 );
275 
276  return new static( $newText );
277  }
278 
290  public function isCountable( $hasLinks = null, Title $title = null ) {
291  global $wgArticleCountMethod;
292 
293  if ( $this->isRedirect() ) {
294  return false;
295  }
296 
297  if ( $wgArticleCountMethod === 'link' ) {
298  if ( $hasLinks === null ) { # not known, find out
299  if ( !$title ) {
301  $title = $context->getTitle();
302  }
303 
304  $po = $this->getParserOutput( $title, null, null, false );
305  $links = $po->getLinks();
306  $hasLinks = !empty( $links );
307  }
308 
309  return $hasLinks;
310  }
311 
312  return true;
313  }
314 
319  public function getTextForSummary( $maxlength = 250 ) {
320  $truncatedtext = parent::getTextForSummary( $maxlength );
321 
322  # clean up unfinished links
323  # XXX: make this optional? wasn't there in autosummary, but required for
324  # deletion summary.
325  $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
326 
327  return $truncatedtext;
328  }
329 
341  protected function fillParserOutput( Title $title, $revId,
342  ParserOptions $options, $generateHtml, ParserOutput &$output
343  ) {
344  global $wgParser;
345 
346  $stackTrace = ( new RuntimeException() )->getTraceAsString();
347  if ( $this->previousParseStackTrace ) {
348  // NOTE: there may be legitimate changes to re-parse the same WikiText content,
349  // e.g. if predicted revision ID for the REVISIONID magic word mismatched.
350  // But that should be rare.
351  $logger = LoggerFactory::getInstance( 'DuplicateParse' );
352  $logger->debug(
353  __METHOD__ . ': Possibly redundant parse!',
354  [
355  'title' => $title->getPrefixedDBkey(),
356  'rev' => $revId,
357  'options-hash' => $options->optionsHash(
359  $title
360  ),
361  'trace' => $stackTrace,
362  'previous-trace' => $this->previousParseStackTrace,
363  ]
364  );
365  }
366  $this->previousParseStackTrace = $stackTrace;
367 
368  list( $redir, $text ) = $this->getRedirectTargetAndText();
369  $output = $wgParser->parse( $text, $title, $options, true, true, $revId );
370 
371  // Add redirect indicator at the top
372  if ( $redir ) {
373  // Make sure to include the redirect link in pagelinks
374  $output->addLink( $redir );
375  if ( $generateHtml ) {
376  $chain = $this->getRedirectChain();
377  $output->setText(
378  Article::getRedirectHeaderHtml( $title->getPageLanguage(), $chain, false ) .
379  $output->getRawText()
380  );
381  $output->addModuleStyles( 'mediawiki.action.view.redirectPage' );
382  }
383  }
384 
385  // Pass along user-signature flag
386  if ( $this->hadSignature ) {
387  $output->setFlag( 'user-signature' );
388  }
389  }
390 
394  protected function getHtml() {
395  throw new MWException(
396  "getHtml() not implemented for wikitext. "
397  . "Use getParserOutput()->getText()."
398  );
399  }
400 
410  public function matchMagicWord( MagicWord $word ) {
411  return $word->match( $this->getText() );
412  }
413 
414 }
ParserOptions
Set options of the Parser.
Definition: ParserOptions.php:42
$user
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1476
WikitextContent\$redirectTargetAndText
$redirectTargetAndText
Definition: WikitextContent.php:37
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:306
ParserOutput
Definition: ParserOutput.php:25
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
AbstractContent\isRedirect
isRedirect()
Definition: AbstractContent.php:356
WikitextContent\getRedirectTarget
getRedirectTarget()
Implement redirect extraction for wikitext.
Definition: WikitextContent.php:246
$context
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:2636
$wgParser
$wgParser
Definition: Setup.php:886
AbstractContent\getParserOutput
getParserOutput(Title $title, $revId=null, ParserOptions $options=null, $generateHtml=true)
Returns a ParserOutput object containing information derived from this content.
Definition: AbstractContent.php:538
MediaWiki\getTitle
getTitle()
Get the Title object that we'll be acting on, as specified in the WebRequest.
Definition: MediaWiki.php:137
WikitextContent\updateRedirect
updateRedirect(Title $target)
This implementation replaces the first link on the page with the given new target if this Content obj...
Definition: WikitextContent.php:264
$params
$params
Definition: styleTest.css.php:44
AbstractContent\getRedirectChain
getRedirectChain()
Definition: AbstractContent.php:291
WikitextContent\getRedirectTargetAndText
getRedirectTargetAndText()
Extract the redirect target and the remaining text on the page.
Definition: WikitextContent.php:196
CONTENT_MODEL_WIKITEXT
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:235
WikitextContent\$previousParseStackTrace
array null $previousParseStackTrace
Stack trace of the previous parse.
Definition: WikitextContent.php:48
TextContent\getText
getText()
Returns the text represented by this Content object, as a string.
Definition: TextContent.php:136
php
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
WikitextContent\$hadSignature
bool $hadSignature
Tracks if the parser set the user-signature flag when creating this content, which would make it expi...
Definition: WikitextContent.php:43
MWException
MediaWiki exception.
Definition: MWException.php:26
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
not
if not
Definition: COPYING.txt:307
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
Title\getFullText
getFullText()
Get the prefixed title with spaces, plus any fragment (part beginning with '#')
Definition: Title.php:1684
TextContent\copy
copy()
Definition: TextContent.php:71
WikitextContent\isCountable
isCountable( $hasLinks=null, Title $title=null)
Returns true if this content is not a redirect, and this content's text is countable according to the...
Definition: WikitextContent.php:290
$output
$output
Definition: SyntaxHighlight.php:334
WikitextContent\__construct
__construct( $text)
Definition: WikitextContent.php:50
ParserOutput\setText
setText( $text)
Definition: ParserOutput.php:581
MagicWord
This class encapsulates "magic words" such as "#redirect", NOTOC, etc.
Definition: MagicWord.php:57
WikitextContent
Content object for wiki text pages.
Definition: WikitextContent.php:36
array
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))
WikitextContent\preSaveTransform
preSaveTransform(Title $title, User $user, ParserOptions $popts)
Returns a Content object with pre-save transformations applied using Parser::preSaveTransform().
Definition: WikitextContent.php:149
list
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
WikitextContent\getSection
getSection( $sectionId)
Definition: WikitextContent.php:61
WikitextContent\fillParserOutput
fillParserOutput(Title $title, $revId, ParserOptions $options, $generateHtml, ParserOutput &$output)
Returns a ParserOutput object resulting from parsing the content's text using $wgParser.
Definition: WikitextContent.php:341
$header
$header
Definition: updateCredits.php:41
WikitextContent\matchMagicWord
matchMagicWord(MagicWord $word)
This implementation calls $word->match() on the this TextContent object's text.
Definition: WikitextContent.php:410
WikitextContent\preloadTransform
preloadTransform(Title $title, ParserOptions $popts, $params=[])
Returns a Content object with preload transformations applied (or this object if no transformations a...
Definition: WikitextContent.php:178
$ret
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:1985
WikitextContent\getTextForSummary
getTextForSummary( $maxlength=250)
Definition: WikitextContent.php:319
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:430
TextContent
Content object implementation for representing flat text.
Definition: TextContent.php:37
Content
Base interface for content objects.
Definition: Content.php:34
AbstractContent\getModel
getModel()
Definition: AbstractContent.php:60
Title
Represents a title within MediaWiki.
Definition: Title.php:40
WikitextContent\addSectionHeader
addSectionHeader( $header)
Returns a new WikitextContent object with the given section heading prepended.
Definition: WikitextContent.php:130
$options
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:1985
ParserOptions\allCacheVaryingOptions
static allCacheVaryingOptions()
Return all option keys that vary the options hash.
Definition: ParserOptions.php:1269
LoggerFactory
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
Content\getModel
getModel()
Returns the ID of the content model used by this Content object.
WikitextContent\replaceSection
replaceSection( $sectionId, Content $with, $sectionTitle='')
Definition: WikitextContent.php:84
$wgMaxRedirects
$wgMaxRedirects
Max number of redirects to follow when resolving redirects.
Definition: DefaultSettings.php:4077
$wgArticleCountMethod
$wgArticleCountMethod
Method used to determine if a page in a content namespace should be counted as a valid article.
Definition: DefaultSettings.php:4362
WikitextContent\getHtml
getHtml()
Definition: WikitextContent.php:394
MediaWikiServices
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
wfMessage
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
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:48
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
MagicWord\match
match( $text)
Returns true if the text contains the word.
Definition: MagicWord.php:304
Article\getRedirectHeaderHtml
static getRedirectHeaderHtml(Language $lang, $target, $forceKnown=false)
Return the HTML for the top of a redirect page.
Definition: Article.php:1684