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." );
92 /** @var self $with $oldtext */
93 '@phan-var self $with';
95 $oldtext = $this->getText();
96 $text = $with->getText();
98 if ( strval( $sectionId ) === '' ) {
99 return $with; # XXX: copy first?
102 if ( $sectionId === 'new' ) {
103 # Inserting a new section
104 $subject = $sectionTitle ?
wfMessage( 'newsectionheaderdefaultlevel' )
105 ->plaintextParams( $sectionTitle )->inContentLanguage()->text() . "\n\n" : '';
106 if ( Hooks
::run( 'PlaceNewSection', [ $this, $oldtext, $subject, &$text ] ) ) {
107 $text = strlen( trim( $oldtext ) ) > 0
108 ?
"{$oldtext}\n\n{$subject}{$text}"
109 : "{$subject}{$text}";
112 # Replacing an existing section; roll out the big guns
113 $text = MediaWikiServices
::getInstance()->getParser()
114 ->replaceSection( $oldtext, $sectionId, $text );
117 $newContent = new static( $text );
123 * Returns a new WikitextContent object with the given section heading
126 * @param string $header
130 public function addSectionHeader( $header ) {
131 $text = wfMessage( 'newsectionheaderdefaultlevel' )
132 ->rawParams( $header )->inContentLanguage()->text();
134 $text .= $this->getText();
136 return new static( $text );
140 * Returns a Content object with pre-save transformations applied using
141 * Parser::preSaveTransform().
143 * @param Title $title
145 * @param ParserOptions $popts
149 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
150 $text = $this->getText();
152 $parser = MediaWikiServices
::getInstance()->getParser();
153 $pst = $parser->preSaveTransform( $text, $title, $user, $popts );
155 if ( $text === $pst ) {
159 $ret = new static( $pst );
161 if ( $parser->getOutput()->getFlag( 'user-signature' ) ) {
162 $ret->hadSignature
= true;
169 * Returns a Content object with preload transformations applied (or this
170 * object if no transformations apply).
172 * @param Title $title
173 * @param ParserOptions $popts
174 * @param array $params
178 public function preloadTransform( Title
$title, ParserOptions
$popts, $params = [] ) {
179 $text = $this->getText();
180 $plt = MediaWikiServices
::getInstance()->getParser()
181 ->getPreloadText( $text, $title, $popts, $params );
183 return new static( $plt );
187 * Extract the redirect target and the remaining text on the page.
189 * @note migrated here from Title::newFromRedirectInternal()
193 * @return array List of two elements: Title|null and string.
195 protected function getRedirectTargetAndText() {
196 global $wgMaxRedirects;
198 if ( $this->redirectTargetAndText
!== null ) {
199 return $this->redirectTargetAndText
;
202 if ( $wgMaxRedirects < 1 ) {
203 // redirects are disabled, so quit early
204 $this->redirectTargetAndText
= [ null, $this->getText() ];
205 return $this->redirectTargetAndText
;
208 $redir = MediaWikiServices
::getInstance()->getMagicWordFactory()->get( 'redirect' );
209 $text = ltrim( $this->getText() );
210 if ( $redir->matchStartAndRemove( $text ) ) {
211 // Extract the first link and see if it's usable
212 // Ensure that it really does come directly after #REDIRECT
213 // Some older redirects included a colon, so don't freak about that!
215 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}\s*!', $text, $m ) ) {
216 // Strip preceding colon used to "escape" categories, etc.
217 // and URL-decode links
218 if ( strpos( $m[1], '%' ) !== false ) {
219 // Match behavior of inline link parsing here;
220 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
222 $title = Title
::newFromText( $m[1] );
223 // If the title is a redirect to bad special pages or is invalid, return null
224 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
225 $this->redirectTargetAndText
= [ null, $this->getText() ];
226 return $this->redirectTargetAndText
;
229 $this->redirectTargetAndText
= [ $title, substr( $text, strlen( $m[0] ) ) ];
230 return $this->redirectTargetAndText
;
234 $this->redirectTargetAndText
= [ null, $this->getText() ];
235 return $this->redirectTargetAndText
;
239 * Implement redirect extraction for wikitext.
243 * @see Content::getRedirectTarget
245 public function getRedirectTarget() {
246 list( $title, ) = $this->getRedirectTargetAndText();
252 * This implementation replaces the first link on the page with the given new target
253 * if this Content object is a redirect. Otherwise, this method returns $this.
257 * @param Title $target
261 * @see Content::updateRedirect()
263 public function updateRedirect( Title
$target ) {
264 if ( !$this->isRedirect() ) {
269 # Remember that redirect pages can have categories, templates, etc.,
270 # so the regex has to be fairly general
271 $newText = preg_replace( '/ \[ \[ [^\]]* \] \] /x',
272 '[[' . $target->getFullText() . ']]',
273 $this->getText(), 1 );
275 return new static( $newText );
279 * Returns true if this content is not a redirect, and this content's text
280 * is countable according to the criteria defined by $wgArticleCountMethod.
282 * @param bool|null $hasLinks If it is known whether this content contains
283 * links, provide this information here, to avoid redundant parsing to
284 * find out (default: null).
285 * @param Title|null $title Optional title, defaults to the title from the current main request.
289 public function isCountable( $hasLinks = null, Title
$title = null ) {
290 global $wgArticleCountMethod;
292 if ( $this->isRedirect() ) {
296 if ( $wgArticleCountMethod === 'link' ) {
297 if ( $hasLinks === null ) { # not known, find out
299 $context = RequestContext
::getMain();
300 $title = $context->getTitle();
303 $po = $this->getParserOutput( $title, null, null, false );
304 $links = $po->getLinks();
305 $hasLinks = !empty( $links );
315 * @param int $maxlength
318 public function getTextForSummary( $maxlength = 250 ) {
319 $truncatedtext = parent
::getTextForSummary( $maxlength );
321 # clean up unfinished links
322 # XXX: make this optional? wasn't there in autosummary, but required for
324 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
326 return $truncatedtext;
330 * Returns a ParserOutput object resulting from parsing the content's text
331 * using the global Parser service.
333 * @param Title $title
334 * @param int|null $revId ID of the revision being rendered.
335 * See Parser::parse() for the ramifications. (default: null)
336 * @param ParserOptions $options (default: null)
337 * @param bool $generateHtml (default: true)
338 * @param ParserOutput &$output ParserOutput representing the HTML form of the text,
339 * may be manipulated or replaced.
341 protected function fillParserOutput( Title
$title, $revId,
342 ParserOptions
$options, $generateHtml, ParserOutput
&$output
344 $stackTrace = ( new RuntimeException() )->getTraceAsString();
345 if ( $this->previousParseStackTrace
) {
346 // NOTE: there may be legitimate changes to re-parse the same WikiText content,
347 // e.g. if predicted revision ID for the REVISIONID magic word mismatched.
348 // But that should be rare.
349 $logger = LoggerFactory
::getInstance( 'DuplicateParse' );
351 __METHOD__
. ': Possibly redundant parse!',
353 'title' => $title->getPrefixedDBkey(),
355 'options-hash' => $options->optionsHash(
356 ParserOptions
::allCacheVaryingOptions(),
359 'trace' => $stackTrace,
360 'previous-trace' => $this->previousParseStackTrace
,
364 $this->previousParseStackTrace
= $stackTrace;
366 list( $redir, $text ) = $this->getRedirectTargetAndText();
367 $output = MediaWikiServices
::getInstance()->getParser()
368 ->parse( $text, $title, $options, true, true, $revId );
370 // Add redirect indicator at the top
372 // Make sure to include the redirect link in pagelinks
373 $output->addLink( $redir );
374 if ( $generateHtml ) {
375 $chain = $this->getRedirectChain();
377 Article
::getRedirectHeaderHtml( $title->getPageLanguage(), $chain, false ) .
378 $output->getRawText()
380 $output->addModuleStyles( 'mediawiki.action.view.redirectPage' );
384 // Pass along user-signature flag
385 if ( $this->hadSignature
) {
386 $output->setFlag( 'user-signature' );
391 * @throws MWException
393 protected function getHtml() {
394 throw new MWException(
395 "getHtml() not implemented for wikitext. "
396 . "Use getParserOutput()->getText()."
401 * This implementation calls $word->match() on the this TextContent object's text.
403 * @param MagicWord $word
407 * @see Content::matchMagicWord()
409 public function matchMagicWord( MagicWord
$word ) {
410 return $word->match( $this->getText() );