MediaWiki  1.30.0
WikitextContent.php
Go to the documentation of this file.
1 <?php
34  private $redirectTargetAndText = null;
35 
36  public function __construct( $text ) {
37  parent::__construct( $text, CONTENT_MODEL_WIKITEXT );
38  }
39 
47  public function getSection( $sectionId ) {
49 
50  $text = $this->getNativeData();
51  $sect = $wgParser->getSection( $text, $sectionId, false );
52 
53  if ( $sect === false ) {
54  return false;
55  } else {
56  return new static( $sect );
57  }
58  }
59 
70  public function replaceSection( $sectionId, Content $with, $sectionTitle = '' ) {
71  $myModelId = $this->getModel();
72  $sectionModelId = $with->getModel();
73 
74  if ( $sectionModelId != $myModelId ) {
75  throw new MWException( "Incompatible content model for section: " .
76  "document uses $myModelId but " .
77  "section uses $sectionModelId." );
78  }
79 
80  $oldtext = $this->getNativeData();
81  $text = $with->getNativeData();
82 
83  if ( strval( $sectionId ) === '' ) {
84  return $with; # XXX: copy first?
85  }
86 
87  if ( $sectionId === 'new' ) {
88  # Inserting a new section
89  $subject = $sectionTitle ? wfMessage( 'newsectionheaderdefaultlevel' )
90  ->rawParams( $sectionTitle )->inContentLanguage()->text() . "\n\n" : '';
91  if ( Hooks::run( 'PlaceNewSection', [ $this, $oldtext, $subject, &$text ] ) ) {
92  $text = strlen( trim( $oldtext ) ) > 0
93  ? "{$oldtext}\n\n{$subject}{$text}"
94  : "{$subject}{$text}";
95  }
96  } else {
97  # Replacing an existing section; roll out the big guns
99 
100  $text = $wgParser->replaceSection( $oldtext, $sectionId, $text );
101  }
102 
103  $newContent = new static( $text );
104 
105  return $newContent;
106  }
107 
116  public function addSectionHeader( $header ) {
117  $text = wfMessage( 'newsectionheaderdefaultlevel' )
118  ->rawParams( $header )->inContentLanguage()->text();
119  $text .= "\n\n";
120  $text .= $this->getNativeData();
121 
122  return new static( $text );
123  }
124 
135  public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
137 
138  $text = $this->getNativeData();
139  $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
140 
141  return ( $text === $pst ) ? $this : new static( $pst );
142  }
143 
154  public function preloadTransform( Title $title, ParserOptions $popts, $params = [] ) {
156 
157  $text = $this->getNativeData();
158  $plt = $wgParser->getPreloadText( $text, $title, $popts, $params );
159 
160  return new static( $plt );
161  }
162 
172  protected function getRedirectTargetAndText() {
174 
175  if ( $this->redirectTargetAndText !== null ) {
177  }
178 
179  if ( $wgMaxRedirects < 1 ) {
180  // redirects are disabled, so quit early
181  $this->redirectTargetAndText = [ null, $this->getNativeData() ];
183  }
184 
185  $redir = MagicWord::get( 'redirect' );
186  $text = ltrim( $this->getNativeData() );
187  if ( $redir->matchStartAndRemove( $text ) ) {
188  // Extract the first link and see if it's usable
189  // Ensure that it really does come directly after #REDIRECT
190  // Some older redirects included a colon, so don't freak about that!
191  $m = [];
192  if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}\s*!', $text, $m ) ) {
193  // Strip preceding colon used to "escape" categories, etc.
194  // and URL-decode links
195  if ( strpos( $m[1], '%' ) !== false ) {
196  // Match behavior of inline link parsing here;
197  $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
198  }
199  $title = Title::newFromText( $m[1] );
200  // If the title is a redirect to bad special pages or is invalid, return null
201  if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
202  $this->redirectTargetAndText = [ null, $this->getNativeData() ];
204  }
205 
206  $this->redirectTargetAndText = [ $title, substr( $text, strlen( $m[0] ) ) ];
208  }
209  }
210 
211  $this->redirectTargetAndText = [ null, $this->getNativeData() ];
213  }
214 
222  public function getRedirectTarget() {
223  list( $title, ) = $this->getRedirectTargetAndText();
224 
225  return $title;
226  }
227 
240  public function updateRedirect( Title $target ) {
241  if ( !$this->isRedirect() ) {
242  return $this;
243  }
244 
245  # Fix the text
246  # Remember that redirect pages can have categories, templates, etc.,
247  # so the regex has to be fairly general
248  $newText = preg_replace( '/ \[ \[ [^\]]* \] \] /x',
249  '[[' . $target->getFullText() . ']]',
250  $this->getNativeData(), 1 );
251 
252  return new static( $newText );
253  }
254 
266  public function isCountable( $hasLinks = null, Title $title = null ) {
268 
269  if ( $this->isRedirect() ) {
270  return false;
271  }
272 
273  switch ( $wgArticleCountMethod ) {
274  case 'any':
275  return true;
276  case 'comma':
277  $text = $this->getNativeData();
278  return strpos( $text, ',' ) !== false;
279  case 'link':
280  if ( $hasLinks === null ) { # not known, find out
281  if ( !$title ) {
283  $title = $context->getTitle();
284  }
285 
286  $po = $this->getParserOutput( $title, null, null, false );
287  $links = $po->getLinks();
288  $hasLinks = !empty( $links );
289  }
290 
291  return $hasLinks;
292  }
293 
294  return false;
295  }
296 
301  public function getTextForSummary( $maxlength = 250 ) {
302  $truncatedtext = parent::getTextForSummary( $maxlength );
303 
304  # clean up unfinished links
305  # XXX: make this optional? wasn't there in autosummary, but required for
306  # deletion summary.
307  $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
308 
309  return $truncatedtext;
310  }
311 
323  protected function fillParserOutput( Title $title, $revId,
324  ParserOptions $options, $generateHtml, ParserOutput &$output
325  ) {
327 
328  list( $redir, $text ) = $this->getRedirectTargetAndText();
329  $output = $wgParser->parse( $text, $title, $options, true, true, $revId );
330 
331  // Add redirect indicator at the top
332  if ( $redir ) {
333  // Make sure to include the redirect link in pagelinks
334  $output->addLink( $redir );
335  if ( $generateHtml ) {
336  $chain = $this->getRedirectChain();
337  $output->setText(
338  Article::getRedirectHeaderHtml( $title->getPageLanguage(), $chain, false ) .
339  $output->getRawText()
340  );
341  $output->addModuleStyles( 'mediawiki.action.view.redirectPage' );
342  }
343  }
344  }
345 
349  protected function getHtml() {
350  throw new MWException(
351  "getHtml() not implemented for wikitext. "
352  . "Use getParserOutput()->getText()."
353  );
354  }
355 
365  public function matchMagicWord( MagicWord $word ) {
366  return $word->match( $this->getNativeData() );
367  }
368 
369 }
ParserOptions
Set options of the Parser.
Definition: ParserOptions.php:40
$user
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 account $user
Definition: hooks.txt:244
WikitextContent\$redirectTargetAndText
$redirectTargetAndText
Definition: WikitextContent.php:34
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:268
ParserOutput
Definition: ParserOutput.php:24
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
AbstractContent\isRedirect
isRedirect()
Definition: AbstractContent.php:318
WikitextContent\getRedirectTarget
getRedirectTarget()
Implement redirect extraction for wikitext.
Definition: WikitextContent.php:222
$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:2581
$wgParser
$wgParser
Definition: Setup.php:824
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:500
MediaWiki\getTitle
getTitle()
Get the Title object that we'll be acting on, as specified in the WebRequest.
Definition: MediaWiki.php:137
MagicWord\get
static & get( $id)
Factory: creates an object representing an ID.
Definition: MagicWord.php:258
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:240
$params
$params
Definition: styleTest.css.php:40
AbstractContent\getRedirectChain
getRedirectChain()
Definition: AbstractContent.php:253
WikitextContent\getRedirectTargetAndText
getRedirectTargetAndText()
Extract the redirect target and the remaining text on the page.
Definition: WikitextContent.php:172
CONTENT_MODEL_WIKITEXT
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:236
$output
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place $output
Definition: hooks.txt:2198
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
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:932
not
if not
Definition: COPYING.txt:307
Title\getFullText
getFullText()
Get the prefixed title with spaces, plus any fragment (part beginning with '#')
Definition: Title.php:1574
TextContent\copy
copy()
Definition: TextContent.php:64
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:266
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
WikitextContent\__construct
__construct( $text)
Definition: WikitextContent.php:36
ParserOutput\setText
setText( $text)
Definition: ParserOutput.php:437
MagicWord
This class encapsulates "magic words" such as "#redirect", NOTOC, etc.
Definition: MagicWord.php:59
WikitextContent
Content object for wiki text pages.
Definition: WikitextContent.php:33
WikitextContent\preSaveTransform
preSaveTransform(Title $title, User $user, ParserOptions $popts)
Returns a Content object with pre-save transformations applied using Parser::preSaveTransform().
Definition: WikitextContent.php:135
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:47
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:323
$header
$header
Definition: updateCredits.php:35
WikitextContent\matchMagicWord
matchMagicWord(MagicWord $word)
This implementation calls $word->match() on the this TextContent object's text.
Definition: WikitextContent.php:365
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:154
Content\getNativeData
getNativeData()
Returns native representation of the data.
WikitextContent\getTextForSummary
getTextForSummary( $maxlength=250)
Definition: WikitextContent.php:301
RequestContext\getMain
static getMain()
Static methods.
Definition: RequestContext.php:470
TextContent
Content object implementation for representing flat text.
Definition: TextContent.php:35
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:39
WikitextContent\addSectionHeader
addSectionHeader( $header)
Returns a new WikitextContent object with the given section heading prepended.
Definition: WikitextContent.php:116
$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:1965
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:70
$wgMaxRedirects
$wgMaxRedirects
Max number of redirects to follow when resolving redirects.
Definition: DefaultSettings.php:4135
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 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
$wgArticleCountMethod
$wgArticleCountMethod
Method used to determine if a page in a content namespace should be counted as a valid article.
Definition: DefaultSettings.php:4460
WikitextContent\getHtml
getHtml()
Definition: WikitextContent.php:349
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:51
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:203
MagicWord\match
match( $text)
Returns true if the text contains the word.
Definition: MagicWord.php:459
Article\getRedirectHeaderHtml
static getRedirectHeaderHtml(Language $lang, $target, $forceKnown=false)
Return the HTML for the top of a redirect page.
Definition: Article.php:1461
TextContent\getNativeData
getNativeData()
Returns the text represented by this Content object, as a string.
Definition: TextContent.php:119