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 ) {
64 $text = $this->getNativeData();
65 $sect = $wgParser->getSection( $text, $sectionId, false );
67 if ( $sect === false ) {
70 return new static( $sect );
75 * @param string|int|null|bool $sectionId
76 * @param Content $with
77 * @param string $sectionTitle
82 * @see Content::replaceSection()
84 public function replaceSection( $sectionId, Content
$with, $sectionTitle = '' ) {
85 $myModelId = $this->getModel();
86 $sectionModelId = $with->getModel();
88 if ( $sectionModelId != $myModelId ) {
89 throw new MWException( "Incompatible content model for section: " .
90 "document uses $myModelId but " .
91 "section uses $sectionModelId." );
94 $oldtext = $this->getNativeData();
95 $text = $with->getNativeData();
97 if ( strval( $sectionId ) === '' ) {
98 return $with; # XXX: copy first?
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}";
111 # Replacing an existing section; roll out the big guns
114 $text = $wgParser->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->getNativeData();
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 ) {
152 $text = $this->getNativeData();
153 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
155 if ( $text === $pst ) {
159 $ret = new static( $pst );
161 if ( $wgParser->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 = [] ) {
181 $text = $this->getNativeData();
182 $plt = $wgParser->getPreloadText( $text, $title, $popts, $params );
184 return new static( $plt );
188 * Extract the redirect target and the remaining text on the page.
190 * @note migrated here from Title::newFromRedirectInternal()
194 * @return array List of two elements: Title|null and string.
196 protected function getRedirectTargetAndText() {
197 global $wgMaxRedirects;
199 if ( $this->redirectTargetAndText
!== null ) {
200 return $this->redirectTargetAndText
;
203 if ( $wgMaxRedirects < 1 ) {
204 // redirects are disabled, so quit early
205 $this->redirectTargetAndText
= [ null, $this->getNativeData() ];
206 return $this->redirectTargetAndText
;
209 $redir = MediaWikiServices
::getInstance()->getMagicWordFactory()->get( 'redirect' );
210 $text = ltrim( $this->getNativeData() );
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!
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], ':' ) );
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->getNativeData() ];
227 return $this->redirectTargetAndText
;
230 $this->redirectTargetAndText
= [ $title, substr( $text, strlen( $m[0] ) ) ];
231 return $this->redirectTargetAndText
;
235 $this->redirectTargetAndText
= [ null, $this->getNativeData() ];
236 return $this->redirectTargetAndText
;
240 * Implement redirect extraction for wikitext.
244 * @see Content::getRedirectTarget
246 public function getRedirectTarget() {
247 list( $title, ) = $this->getRedirectTargetAndText();
253 * This implementation replaces the first link on the page with the given new target
254 * if this Content object is a redirect. Otherwise, this method returns $this.
258 * @param Title $target
262 * @see Content::updateRedirect()
264 public function updateRedirect( Title
$target ) {
265 if ( !$this->isRedirect() ) {
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->getNativeData(), 1 );
276 return new static( $newText );
280 * Returns true if this content is not a redirect, and this content's text
281 * is countable according to the criteria defined by $wgArticleCountMethod.
283 * @param bool|null $hasLinks If it is known whether this content contains
284 * links, provide this information here, to avoid redundant parsing to
285 * find out (default: null).
286 * @param Title|null $title Optional title, defaults to the title from the current main request.
290 public function isCountable( $hasLinks = null, Title
$title = null ) {
291 global $wgArticleCountMethod;
293 if ( $this->isRedirect() ) {
297 if ( $wgArticleCountMethod === 'link' ) {
298 if ( $hasLinks === null ) { # not known, find out
300 $context = RequestContext
::getMain();
301 $title = $context->getTitle();
304 $po = $this->getParserOutput( $title, null, null, false );
305 $links = $po->getLinks();
306 $hasLinks = !empty( $links );
316 * @param int $maxlength
319 public function getTextForSummary( $maxlength = 250 ) {
320 $truncatedtext = parent
::getTextForSummary( $maxlength );
322 # clean up unfinished links
323 # XXX: make this optional? wasn't there in autosummary, but required for
325 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
327 return $truncatedtext;
331 * Returns a ParserOutput object resulting from parsing the content's text
334 * @param Title $title
335 * @param int $revId Revision to pass to the parser (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
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' );
353 __METHOD__
. ': Possibly redundant parse!',
355 'title' => $title->getPrefixedDBkey(),
357 'options-hash' => $options->optionsHash(
358 ParserOptions
::allCacheVaryingOptions(),
361 'trace' => $stackTrace,
362 'previous-trace' => $this->previousParseStackTrace
,
366 $this->previousParseStackTrace
= $stackTrace;
368 list( $redir, $text ) = $this->getRedirectTargetAndText();
369 $output = $wgParser->parse( $text, $title, $options, true, true, $revId );
371 // Add redirect indicator at the top
373 // Make sure to include the redirect link in pagelinks
374 $output->addLink( $redir );
375 if ( $generateHtml ) {
376 $chain = $this->getRedirectChain();
378 Article
::getRedirectHeaderHtml( $title->getPageLanguage(), $chain, false ) .
379 $output->getRawText()
381 $output->addModuleStyles( 'mediawiki.action.view.redirectPage' );
385 // Pass along user-signature flag
386 if ( $this->hadSignature
) {
387 $output->setFlag( 'user-signature' );
392 * @throws MWException
394 protected function getHtml() {
395 throw new MWException(
396 "getHtml() not implemented for wikitext. "
397 . "Use getParserOutput()->getText()."
402 * This implementation calls $word->match() on the this TextContent object's text.
404 * @param MagicWord $word
408 * @see Content::matchMagicWord()
410 public function matchMagicWord( MagicWord
$word ) {
411 return $word->match( $this->getNativeData() );