MediaWiki  1.27.2
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 
72  $myModelId = $this->getModel();
73  $sectionModelId = $with->getModel();
74 
75  if ( $sectionModelId != $myModelId ) {
76  throw new MWException( "Incompatible content model for section: " .
77  "document uses $myModelId but " .
78  "section uses $sectionModelId." );
79  }
80 
81  $oldtext = $this->getNativeData();
82  $text = $with->getNativeData();
83 
84  if ( strval( $sectionId ) === '' ) {
85  return $with; # XXX: copy first?
86  }
87 
88  if ( $sectionId === 'new' ) {
89  # Inserting a new section
90  $subject = $sectionTitle ? wfMessage( 'newsectionheaderdefaultlevel' )
91  ->rawParams( $sectionTitle )->inContentLanguage()->text() . "\n\n" : '';
92  if ( Hooks::run( 'PlaceNewSection', [ $this, $oldtext, $subject, &$text ] ) ) {
93  $text = strlen( trim( $oldtext ) ) > 0
94  ? "{$oldtext}\n\n{$subject}{$text}"
95  : "{$subject}{$text}";
96  }
97  } else {
98  # Replacing an existing section; roll out the big guns
100 
101  $text = $wgParser->replaceSection( $oldtext, $sectionId, $text );
102  }
103 
104  $newContent = new static( $text );
105 
106  return $newContent;
107  }
108 
117  public function addSectionHeader( $header ) {
118  $text = wfMessage( 'newsectionheaderdefaultlevel' )
119  ->rawParams( $header )->inContentLanguage()->text();
120  $text .= "\n\n";
121  $text .= $this->getNativeData();
122 
123  return new static( $text );
124  }
125 
136  public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
138 
139  $text = $this->getNativeData();
140  $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
141  rtrim( $pst );
142 
143  return ( $text === $pst ) ? $this : new static( $pst );
144  }
145 
156  public function preloadTransform( Title $title, ParserOptions $popts, $params = [] ) {
158 
159  $text = $this->getNativeData();
160  $plt = $wgParser->getPreloadText( $text, $title, $popts, $params );
161 
162  return new static( $plt );
163  }
164 
174  protected function getRedirectTargetAndText() {
175  global $wgMaxRedirects;
176 
177  if ( $this->redirectTargetAndText !== null ) {
179  }
180 
181  if ( $wgMaxRedirects < 1 ) {
182  // redirects are disabled, so quit early
183  $this->redirectTargetAndText = [ null, $this->getNativeData() ];
185  }
186 
187  $redir = MagicWord::get( 'redirect' );
188  $text = ltrim( $this->getNativeData() );
189  if ( $redir->matchStartAndRemove( $text ) ) {
190  // Extract the first link and see if it's usable
191  // Ensure that it really does come directly after #REDIRECT
192  // Some older redirects included a colon, so don't freak about that!
193  $m = [];
194  if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}\s*!', $text, $m ) ) {
195  // Strip preceding colon used to "escape" categories, etc.
196  // and URL-decode links
197  if ( strpos( $m[1], '%' ) !== false ) {
198  // Match behavior of inline link parsing here;
199  $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
200  }
201  $title = Title::newFromText( $m[1] );
202  // If the title is a redirect to bad special pages or is invalid, return null
203  if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
204  $this->redirectTargetAndText = [ null, $this->getNativeData() ];
206  }
207 
208  $this->redirectTargetAndText = [ $title, substr( $text, strlen( $m[0] ) ) ];
210  }
211  }
212 
213  $this->redirectTargetAndText = [ null, $this->getNativeData() ];
215  }
216 
224  public function getRedirectTarget() {
225  list( $title, ) = $this->getRedirectTargetAndText();
226 
227  return $title;
228  }
229 
242  public function updateRedirect( Title $target ) {
243  if ( !$this->isRedirect() ) {
244  return $this;
245  }
246 
247  # Fix the text
248  # Remember that redirect pages can have categories, templates, etc.,
249  # so the regex has to be fairly general
250  $newText = preg_replace( '/ \[ \[ [^\]]* \] \] /x',
251  '[[' . $target->getFullText() . ']]',
252  $this->getNativeData(), 1 );
253 
254  return new static( $newText );
255  }
256 
268  public function isCountable( $hasLinks = null, Title $title = null ) {
269  global $wgArticleCountMethod;
270 
271  if ( $this->isRedirect() ) {
272  return false;
273  }
274 
275  switch ( $wgArticleCountMethod ) {
276  case 'any':
277  return true;
278  case 'comma':
279  $text = $this->getNativeData();
280  return strpos( $text, ',' ) !== false;
281  case 'link':
282  if ( $hasLinks === null ) { # not known, find out
283  if ( !$title ) {
285  $title = $context->getTitle();
286  }
287 
288  $po = $this->getParserOutput( $title, null, null, false );
289  $links = $po->getLinks();
290  $hasLinks = !empty( $links );
291  }
292 
293  return $hasLinks;
294  }
295 
296  return false;
297  }
298 
303  public function getTextForSummary( $maxlength = 250 ) {
304  $truncatedtext = parent::getTextForSummary( $maxlength );
305 
306  # clean up unfinished links
307  # XXX: make this optional? wasn't there in autosummary, but required for
308  # deletion summary.
309  $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
310 
311  return $truncatedtext;
312  }
313 
325  protected function fillParserOutput( Title $title, $revId,
327  ) {
329 
330  list( $redir, $text ) = $this->getRedirectTargetAndText();
331  $output = $wgParser->parse( $text, $title, $options, true, true, $revId );
332 
333  // Add redirect indicator at the top
334  if ( $redir ) {
335  // Make sure to include the redirect link in pagelinks
336  $output->addLink( $redir );
337  if ( $generateHtml ) {
338  $chain = $this->getRedirectChain();
339  $output->setText(
341  $output->getRawText()
342  );
343  $output->addModuleStyles( 'mediawiki.action.view.redirectPage' );
344  }
345  }
346  }
347 
351  protected function getHtml() {
352  throw new MWException(
353  "getHtml() not implemented for wikitext. "
354  . "Use getParserOutput()->getText()."
355  );
356  }
357 
367  public function matchMagicWord( MagicWord $word ) {
368  return $word->match( $this->getNativeData() );
369  }
370 
371 }
getNativeData()
Returns the text represented by this Content object, as a string.
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
replaceSection($sectionId, Content $with, $sectionTitle= '')
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:277
$context
Definition: load.php:44
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:1004
getRedirectTargetAndText()
Extract the redirect target and the remaining text on the page.
Set options of the Parser.
$wgParser
Definition: Setup.php:809
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
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:1004
addModuleStyles($modules)
match($text)
Returns true if the text contains the word.
Definition: MagicWord.php:458
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:277
Represents a title within MediaWiki.
Definition: Title.php:34
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
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...
Content object implementation for representing flat text.
Definition: TextContent.php:35
static getMain()
Static methods.
addSectionHeader($header)
Returns a new WikitextContent object with the given section heading prepended.
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:1004
getSection($sectionId)
static getRedirectHeaderHtml(Language $lang, $target, $forceKnown=false)
Return the HTML for the top of a redirect page.
Definition: Article.php:1563
Base interface for content objects.
Definition: Content.php:34
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 just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing 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 unsetoffset-wrap String Wrap the message in html(usually something like"&lt
$params
matchMagicWord(MagicWord $word)
This implementation calls $word->match() on the this TextContent object's text.
getFullText()
Get the prefixed title with spaces, plus any fragment (part beginning with '#')
Definition: Title.php:1473
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
Content object for wiki text pages.
getRawText()
Get the cacheable text with markers still in it.
static & get($id)
Factory: creates an object representing an ID.
Definition: MagicWord.php:257
getTextForSummary($maxlength=250)
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:1004
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().
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...
getPageLanguage()
Get the language in which the content of this page is written in wikitext.
Definition: Title.php:4669
addLink(Title $title, $id=null)
Record a local or interwiki inline link for saving in future link tables.
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's text using $wgParser.
This class encapsulates "magic words" such as "#redirect", NOTOC, etc.
Definition: MagicWord.php:59