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\MediaWikiServices
;
31 * Content object for wiki text pages.
35 class WikitextContent
extends TextContent
{
36 private $redirectTargetAndText = null;
39 * @var bool Tracks if the parser set the user-signature flag when creating this content, which
40 * would make it expire faster in ApiStashEdit.
42 private $hadSignature = false;
44 public function __construct( $text ) {
45 parent
::__construct( $text, CONTENT_MODEL_WIKITEXT
);
49 * @param string|int $sectionId
51 * @return Content|bool|null
53 * @see Content::getSection()
55 public function getSection( $sectionId ) {
58 $text = $this->getNativeData();
59 $sect = $wgParser->getSection( $text, $sectionId, false );
61 if ( $sect === false ) {
64 return new static( $sect );
69 * @param string|int|null|bool $sectionId
70 * @param Content $with
71 * @param string $sectionTitle
76 * @see Content::replaceSection()
78 public function replaceSection( $sectionId, Content
$with, $sectionTitle = '' ) {
79 $myModelId = $this->getModel();
80 $sectionModelId = $with->getModel();
82 if ( $sectionModelId != $myModelId ) {
83 throw new MWException( "Incompatible content model for section: " .
84 "document uses $myModelId but " .
85 "section uses $sectionModelId." );
88 $oldtext = $this->getNativeData();
89 $text = $with->getNativeData();
91 if ( strval( $sectionId ) === '' ) {
92 return $with; # XXX: copy first?
95 if ( $sectionId === 'new' ) {
96 # Inserting a new section
97 $subject = $sectionTitle ?
wfMessage( 'newsectionheaderdefaultlevel' )
98 ->plaintextParams( $sectionTitle )->inContentLanguage()->text() . "\n\n" : '';
99 if ( Hooks
::run( 'PlaceNewSection', [ $this, $oldtext, $subject, &$text ] ) ) {
100 $text = strlen( trim( $oldtext ) ) > 0
101 ?
"{$oldtext}\n\n{$subject}{$text}"
102 : "{$subject}{$text}";
105 # Replacing an existing section; roll out the big guns
108 $text = $wgParser->replaceSection( $oldtext, $sectionId, $text );
111 $newContent = new static( $text );
117 * Returns a new WikitextContent object with the given section heading
120 * @param string $header
124 public function addSectionHeader( $header ) {
125 $text = wfMessage( 'newsectionheaderdefaultlevel' )
126 ->rawParams( $header )->inContentLanguage()->text();
128 $text .= $this->getNativeData();
130 return new static( $text );
134 * Returns a Content object with pre-save transformations applied using
135 * Parser::preSaveTransform().
137 * @param Title $title
139 * @param ParserOptions $popts
143 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
146 $text = $this->getNativeData();
147 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
149 if ( $text === $pst ) {
153 $ret = new static( $pst );
155 if ( $wgParser->getOutput()->getFlag( 'user-signature' ) ) {
156 $ret->hadSignature
= true;
163 * Returns a Content object with preload transformations applied (or this
164 * object if no transformations apply).
166 * @param Title $title
167 * @param ParserOptions $popts
168 * @param array $params
172 public function preloadTransform( Title
$title, ParserOptions
$popts, $params = [] ) {
175 $text = $this->getNativeData();
176 $plt = $wgParser->getPreloadText( $text, $title, $popts, $params );
178 return new static( $plt );
182 * Extract the redirect target and the remaining text on the page.
184 * @note migrated here from Title::newFromRedirectInternal()
188 * @return array List of two elements: Title|null and string.
190 protected function getRedirectTargetAndText() {
191 global $wgMaxRedirects;
193 if ( $this->redirectTargetAndText
!== null ) {
194 return $this->redirectTargetAndText
;
197 if ( $wgMaxRedirects < 1 ) {
198 // redirects are disabled, so quit early
199 $this->redirectTargetAndText
= [ null, $this->getNativeData() ];
200 return $this->redirectTargetAndText
;
203 $redir = MediaWikiServices
::getInstance()->getMagicWordFactory()->get( 'redirect' );
204 $text = ltrim( $this->getNativeData() );
205 if ( $redir->matchStartAndRemove( $text ) ) {
206 // Extract the first link and see if it's usable
207 // Ensure that it really does come directly after #REDIRECT
208 // Some older redirects included a colon, so don't freak about that!
210 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}\s*!', $text, $m ) ) {
211 // Strip preceding colon used to "escape" categories, etc.
212 // and URL-decode links
213 if ( strpos( $m[1], '%' ) !== false ) {
214 // Match behavior of inline link parsing here;
215 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
217 $title = Title
::newFromText( $m[1] );
218 // If the title is a redirect to bad special pages or is invalid, return null
219 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
220 $this->redirectTargetAndText
= [ null, $this->getNativeData() ];
221 return $this->redirectTargetAndText
;
224 $this->redirectTargetAndText
= [ $title, substr( $text, strlen( $m[0] ) ) ];
225 return $this->redirectTargetAndText
;
229 $this->redirectTargetAndText
= [ null, $this->getNativeData() ];
230 return $this->redirectTargetAndText
;
234 * Implement redirect extraction for wikitext.
238 * @see Content::getRedirectTarget
240 public function getRedirectTarget() {
241 list( $title, ) = $this->getRedirectTargetAndText();
247 * This implementation replaces the first link on the page with the given new target
248 * if this Content object is a redirect. Otherwise, this method returns $this.
252 * @param Title $target
256 * @see Content::updateRedirect()
258 public function updateRedirect( Title
$target ) {
259 if ( !$this->isRedirect() ) {
264 # Remember that redirect pages can have categories, templates, etc.,
265 # so the regex has to be fairly general
266 $newText = preg_replace( '/ \[ \[ [^\]]* \] \] /x',
267 '[[' . $target->getFullText() . ']]',
268 $this->getNativeData(), 1 );
270 return new static( $newText );
274 * Returns true if this content is not a redirect, and this content's text
275 * is countable according to the criteria defined by $wgArticleCountMethod.
277 * @param bool|null $hasLinks If it is known whether this content contains
278 * links, provide this information here, to avoid redundant parsing to
279 * find out (default: null).
280 * @param Title|null $title Optional title, defaults to the title from the current main request.
284 public function isCountable( $hasLinks = null, Title
$title = null ) {
285 global $wgArticleCountMethod;
287 if ( $this->isRedirect() ) {
291 if ( $wgArticleCountMethod === 'link' ) {
292 if ( $hasLinks === null ) { # not known, find out
294 $context = RequestContext
::getMain();
295 $title = $context->getTitle();
298 $po = $this->getParserOutput( $title, null, null, false );
299 $links = $po->getLinks();
300 $hasLinks = !empty( $links );
310 * @param int $maxlength
313 public function getTextForSummary( $maxlength = 250 ) {
314 $truncatedtext = parent
::getTextForSummary( $maxlength );
316 # clean up unfinished links
317 # XXX: make this optional? wasn't there in autosummary, but required for
319 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
321 return $truncatedtext;
325 * Returns a ParserOutput object resulting from parsing the content's text
328 * @param Title $title
329 * @param int $revId Revision to pass to the parser (default: null)
330 * @param ParserOptions $options (default: null)
331 * @param bool $generateHtml (default: true)
332 * @param ParserOutput &$output ParserOutput representing the HTML form of the text,
333 * may be manipulated or replaced.
335 protected function fillParserOutput( Title
$title, $revId,
336 ParserOptions
$options, $generateHtml, ParserOutput
&$output
340 list( $redir, $text ) = $this->getRedirectTargetAndText();
341 $output = $wgParser->parse( $text, $title, $options, true, true, $revId );
343 // Add redirect indicator at the top
345 // Make sure to include the redirect link in pagelinks
346 $output->addLink( $redir );
347 if ( $generateHtml ) {
348 $chain = $this->getRedirectChain();
350 Article
::getRedirectHeaderHtml( $title->getPageLanguage(), $chain, false ) .
351 $output->getRawText()
353 $output->addModuleStyles( 'mediawiki.action.view.redirectPage' );
357 // Pass along user-signature flag
358 if ( $this->hadSignature
) {
359 $output->setFlag( 'user-signature' );
364 * @throws MWException
366 protected function getHtml() {
367 throw new MWException(
368 "getHtml() not implemented for wikitext. "
369 . "Use getParserOutput()->getText()."
374 * This implementation calls $word->match() on the this TextContent object's text.
376 * @param MagicWord $word
380 * @see Content::matchMagicWord()
382 public function matchMagicWord( MagicWord
$word ) {
383 return $word->match( $this->getNativeData() );