3 * Content object for wiki text pages.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @author Daniel Kinzler
28 use MediaWiki\Logger\LoggerFactory
;
29 use MediaWiki\MediaWikiServices
;
32 * Content object for wiki text pages.
36 class WikitextContent
extends TextContent
{
37 private $redirectTargetAndText = null;
40 * @var bool Tracks if the parser set the user-signature flag when creating this content, which
41 * would make it expire faster in ApiStashEdit.
43 private $hadSignature = false;
46 * @var array|null Stack trace of the previous parse
48 private $previousParseStackTrace = null;
50 public function __construct( $text ) {
51 parent
::__construct( $text, CONTENT_MODEL_WIKITEXT
);
55 * @param string|int $sectionId
57 * @return Content|bool|null
59 * @see Content::getSection()
61 public function getSection( $sectionId ) {
62 $text = $this->getText();
63 $sect = MediaWikiServices
::getInstance()->getParser()
64 ->getSection( $text, $sectionId, false );
66 if ( $sect === false ) {
69 return new static( $sect );
74 * @param string|int|null|bool $sectionId
75 * @param Content $with
76 * @param string $sectionTitle
81 * @see Content::replaceSection()
83 public function replaceSection( $sectionId, Content
$with, $sectionTitle = '' ) {
84 $myModelId = $this->getModel();
85 $sectionModelId = $with->getModel();
87 if ( $sectionModelId != $myModelId ) {
88 throw new MWException( "Incompatible content model for section: " .
89 "document uses $myModelId but " .
90 "section uses $sectionModelId." );
93 $oldtext = $this->getText();
94 $text = $with->getText();
96 if ( strval( $sectionId ) === '' ) {
97 return $with; # XXX: copy first?
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}";
110 # Replacing an existing section; roll out the big guns
111 $text = MediaWikiServices
::getInstance()->getParser()
112 ->replaceSection( $oldtext, $sectionId, $text );
115 $newContent = new static( $text );
121 * Returns a new WikitextContent object with the given section heading
124 * @param string $header
128 public function addSectionHeader( $header ) {
129 $text = wfMessage( 'newsectionheaderdefaultlevel' )
130 ->rawParams( $header )->inContentLanguage()->text();
132 $text .= $this->getText();
134 return new static( $text );
138 * Returns a Content object with pre-save transformations applied using
139 * Parser::preSaveTransform().
141 * @param Title $title
143 * @param ParserOptions $popts
147 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
148 $text = $this->getText();
150 $parser = MediaWikiServices
::getInstance()->getParser();
151 $pst = $parser->preSaveTransform( $text, $title, $user, $popts );
153 if ( $text === $pst ) {
157 $ret = new static( $pst );
159 if ( $parser->getOutput()->getFlag( 'user-signature' ) ) {
160 $ret->hadSignature
= true;
167 * Returns a Content object with preload transformations applied (or this
168 * object if no transformations apply).
170 * @param Title $title
171 * @param ParserOptions $popts
172 * @param array $params
176 public function preloadTransform( Title
$title, ParserOptions
$popts, $params = [] ) {
177 $text = $this->getText();
178 $plt = MediaWikiServices
::getInstance()->getParser()
179 ->getPreloadText( $text, $title, $popts, $params );
181 return new static( $plt );
185 * Extract the redirect target and the remaining text on the page.
187 * @note migrated here from Title::newFromRedirectInternal()
191 * @return array List of two elements: Title|null and string.
193 protected function getRedirectTargetAndText() {
194 global $wgMaxRedirects;
196 if ( $this->redirectTargetAndText
!== null ) {
197 return $this->redirectTargetAndText
;
200 if ( $wgMaxRedirects < 1 ) {
201 // redirects are disabled, so quit early
202 $this->redirectTargetAndText
= [ null, $this->getText() ];
203 return $this->redirectTargetAndText
;
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!
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], ':' ) );
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() ];
224 return $this->redirectTargetAndText
;
227 $this->redirectTargetAndText
= [ $title, substr( $text, strlen( $m[0] ) ) ];
228 return $this->redirectTargetAndText
;
232 $this->redirectTargetAndText
= [ null, $this->getText() ];
233 return $this->redirectTargetAndText
;
237 * Implement redirect extraction for wikitext.
241 * @see Content::getRedirectTarget
243 public function getRedirectTarget() {
244 list( $title, ) = $this->getRedirectTargetAndText();
250 * This implementation replaces the first link on the page with the given new target
251 * if this Content object is a redirect. Otherwise, this method returns $this.
255 * @param Title $target
259 * @see Content::updateRedirect()
261 public function updateRedirect( Title
$target ) {
262 if ( !$this->isRedirect() ) {
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 );
273 return new static( $newText );
277 * Returns true if this content is not a redirect, and this content's text
278 * is countable according to the criteria defined by $wgArticleCountMethod.
280 * @param bool|null $hasLinks If it is known whether this content contains
281 * links, provide this information here, to avoid redundant parsing to
282 * find out (default: null).
283 * @param Title|null $title Optional title, defaults to the title from the current main request.
287 public function isCountable( $hasLinks = null, Title
$title = null ) {
288 global $wgArticleCountMethod;
290 if ( $this->isRedirect() ) {
294 if ( $wgArticleCountMethod === 'link' ) {
295 if ( $hasLinks === null ) { # not known, find out
297 $context = RequestContext
::getMain();
298 $title = $context->getTitle();
301 $po = $this->getParserOutput( $title, null, null, false );
302 $links = $po->getLinks();
303 $hasLinks = !empty( $links );
313 * @param int $maxlength
316 public function getTextForSummary( $maxlength = 250 ) {
317 $truncatedtext = parent
::getTextForSummary( $maxlength );
319 # clean up unfinished links
320 # XXX: make this optional? wasn't there in autosummary, but required for
322 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
324 return $truncatedtext;
328 * Returns a ParserOutput object resulting from parsing the content's text
329 * using the global Parser service.
331 * @param Title $title
332 * @param int|null $revId Revision to pass to the parser (default: null)
333 * @param ParserOptions $options (default: null)
334 * @param bool $generateHtml (default: true)
335 * @param ParserOutput &$output ParserOutput representing the HTML form of the text,
336 * may be manipulated or replaced.
338 protected function fillParserOutput( Title
$title, $revId,
339 ParserOptions
$options, $generateHtml, ParserOutput
&$output
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' );
348 __METHOD__
. ': Possibly redundant parse!',
350 'title' => $title->getPrefixedDBkey(),
352 'options-hash' => $options->optionsHash(
353 ParserOptions
::allCacheVaryingOptions(),
356 'trace' => $stackTrace,
357 'previous-trace' => $this->previousParseStackTrace
,
361 $this->previousParseStackTrace
= $stackTrace;
363 list( $redir, $text ) = $this->getRedirectTargetAndText();
364 $output = MediaWikiServices
::getInstance()->getParser()
365 ->parse( $text, $title, $options, true, true, $revId );
367 // Add redirect indicator at the top
369 // Make sure to include the redirect link in pagelinks
370 $output->addLink( $redir );
371 if ( $generateHtml ) {
372 $chain = $this->getRedirectChain();
374 Article
::getRedirectHeaderHtml( $title->getPageLanguage(), $chain, false ) .
375 $output->getRawText()
377 $output->addModuleStyles( 'mediawiki.action.view.redirectPage' );
381 // Pass along user-signature flag
382 if ( $this->hadSignature
) {
383 $output->setFlag( 'user-signature' );
388 * @throws MWException
390 protected function getHtml() {
391 throw new MWException(
392 "getHtml() not implemented for wikitext. "
393 . "Use getParserOutput()->getText()."
398 * This implementation calls $word->match() on the this TextContent object's text.
400 * @param MagicWord $word
404 * @see Content::matchMagicWord()
406 public function matchMagicWord( MagicWord
$word ) {
407 return $word->match( $this->getText() );