Merge "Actually assign suppression-related rights to 'suppress' group"
[lhc/web/wiklou.git] / includes / content / WikitextContent.php
1 <?php
2 /**
3 * Content object for wiki text pages.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @since 1.21
21 *
22 * @file
23 * @ingroup Content
24 *
25 * @author Daniel Kinzler
26 */
27
28 use MediaWiki\Logger\LoggerFactory;
29 use MediaWiki\MediaWikiServices;
30
31 /**
32 * Content object for wiki text pages.
33 *
34 * @ingroup Content
35 */
36 class WikitextContent extends TextContent {
37 private $redirectTargetAndText = null;
38
39 /**
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.
42 */
43 private $hadSignature = false;
44
45 /**
46 * @var array|null Stack trace of the previous parse
47 */
48 private $previousParseStackTrace = null;
49
50 public function __construct( $text ) {
51 parent::__construct( $text, CONTENT_MODEL_WIKITEXT );
52 }
53
54 /**
55 * @param string|int $sectionId
56 *
57 * @return Content|bool|null
58 *
59 * @see Content::getSection()
60 */
61 public function getSection( $sectionId ) {
62 $text = $this->getText();
63 $sect = MediaWikiServices::getInstance()->getParser()
64 ->getSection( $text, $sectionId, false );
65
66 if ( $sect === false ) {
67 return false;
68 } else {
69 return new static( $sect );
70 }
71 }
72
73 /**
74 * @param string|int|null|bool $sectionId
75 * @param Content $with
76 * @param string $sectionTitle
77 *
78 * @throws MWException
79 * @return Content
80 *
81 * @see Content::replaceSection()
82 */
83 public function replaceSection( $sectionId, Content $with, $sectionTitle = '' ) {
84 $myModelId = $this->getModel();
85 $sectionModelId = $with->getModel();
86
87 if ( $sectionModelId != $myModelId ) {
88 throw new MWException( "Incompatible content model for section: " .
89 "document uses $myModelId but " .
90 "section uses $sectionModelId." );
91 }
92
93 $oldtext = $this->getText();
94 $text = $with->getText();
95
96 if ( strval( $sectionId ) === '' ) {
97 return $with; # XXX: copy first?
98 }
99
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}";
108 }
109 } else {
110 # Replacing an existing section; roll out the big guns
111 $text = MediaWikiServices::getInstance()->getParser()
112 ->replaceSection( $oldtext, $sectionId, $text );
113 }
114
115 $newContent = new static( $text );
116
117 return $newContent;
118 }
119
120 /**
121 * Returns a new WikitextContent object with the given section heading
122 * prepended.
123 *
124 * @param string $header
125 *
126 * @return Content
127 */
128 public function addSectionHeader( $header ) {
129 $text = wfMessage( 'newsectionheaderdefaultlevel' )
130 ->rawParams( $header )->inContentLanguage()->text();
131 $text .= "\n\n";
132 $text .= $this->getText();
133
134 return new static( $text );
135 }
136
137 /**
138 * Returns a Content object with pre-save transformations applied using
139 * Parser::preSaveTransform().
140 *
141 * @param Title $title
142 * @param User $user
143 * @param ParserOptions $popts
144 *
145 * @return Content
146 */
147 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
148 $text = $this->getText();
149
150 $parser = MediaWikiServices::getInstance()->getParser();
151 $pst = $parser->preSaveTransform( $text, $title, $user, $popts );
152
153 if ( $text === $pst ) {
154 return $this;
155 }
156
157 $ret = new static( $pst );
158
159 if ( $parser->getOutput()->getFlag( 'user-signature' ) ) {
160 $ret->hadSignature = true;
161 }
162
163 return $ret;
164 }
165
166 /**
167 * Returns a Content object with preload transformations applied (or this
168 * object if no transformations apply).
169 *
170 * @param Title $title
171 * @param ParserOptions $popts
172 * @param array $params
173 *
174 * @return Content
175 */
176 public function preloadTransform( Title $title, ParserOptions $popts, $params = [] ) {
177 $text = $this->getText();
178 $plt = MediaWikiServices::getInstance()->getParser()
179 ->getPreloadText( $text, $title, $popts, $params );
180
181 return new static( $plt );
182 }
183
184 /**
185 * Extract the redirect target and the remaining text on the page.
186 *
187 * @note migrated here from Title::newFromRedirectInternal()
188 *
189 * @since 1.23
190 *
191 * @return array List of two elements: Title|null and string.
192 */
193 protected function getRedirectTargetAndText() {
194 global $wgMaxRedirects;
195
196 if ( $this->redirectTargetAndText !== null ) {
197 return $this->redirectTargetAndText;
198 }
199
200 if ( $wgMaxRedirects < 1 ) {
201 // redirects are disabled, so quit early
202 $this->redirectTargetAndText = [ null, $this->getText() ];
203 return $this->redirectTargetAndText;
204 }
205
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!
212 $m = [];
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], ':' ) );
219 }
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;
225 }
226
227 $this->redirectTargetAndText = [ $title, substr( $text, strlen( $m[0] ) ) ];
228 return $this->redirectTargetAndText;
229 }
230 }
231
232 $this->redirectTargetAndText = [ null, $this->getText() ];
233 return $this->redirectTargetAndText;
234 }
235
236 /**
237 * Implement redirect extraction for wikitext.
238 *
239 * @return Title|null
240 *
241 * @see Content::getRedirectTarget
242 */
243 public function getRedirectTarget() {
244 list( $title, ) = $this->getRedirectTargetAndText();
245
246 return $title;
247 }
248
249 /**
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.
252 *
253 * @since 1.21
254 *
255 * @param Title $target
256 *
257 * @return Content
258 *
259 * @see Content::updateRedirect()
260 */
261 public function updateRedirect( Title $target ) {
262 if ( !$this->isRedirect() ) {
263 return $this;
264 }
265
266 # Fix the text
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 );
272
273 return new static( $newText );
274 }
275
276 /**
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.
279 *
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.
284 *
285 * @return bool
286 */
287 public function isCountable( $hasLinks = null, Title $title = null ) {
288 global $wgArticleCountMethod;
289
290 if ( $this->isRedirect() ) {
291 return false;
292 }
293
294 if ( $wgArticleCountMethod === 'link' ) {
295 if ( $hasLinks === null ) { # not known, find out
296 if ( !$title ) {
297 $context = RequestContext::getMain();
298 $title = $context->getTitle();
299 }
300
301 $po = $this->getParserOutput( $title, null, null, false );
302 $links = $po->getLinks();
303 $hasLinks = !empty( $links );
304 }
305
306 return $hasLinks;
307 }
308
309 return true;
310 }
311
312 /**
313 * @param int $maxlength
314 * @return string
315 */
316 public function getTextForSummary( $maxlength = 250 ) {
317 $truncatedtext = parent::getTextForSummary( $maxlength );
318
319 # clean up unfinished links
320 # XXX: make this optional? wasn't there in autosummary, but required for
321 # deletion summary.
322 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
323
324 return $truncatedtext;
325 }
326
327 /**
328 * Returns a ParserOutput object resulting from parsing the content's text
329 * using the global Parser service.
330 *
331 * @param Title $title
332 * @param int|null $revId ID of the revision being rendered.
333 * See Parser::parse() for the ramifications. (default: null)
334 * @param ParserOptions $options (default: null)
335 * @param bool $generateHtml (default: true)
336 * @param ParserOutput &$output ParserOutput representing the HTML form of the text,
337 * may be manipulated or replaced.
338 */
339 protected function fillParserOutput( Title $title, $revId,
340 ParserOptions $options, $generateHtml, ParserOutput &$output
341 ) {
342 $stackTrace = ( new RuntimeException() )->getTraceAsString();
343 if ( $this->previousParseStackTrace ) {
344 // NOTE: there may be legitimate changes to re-parse the same WikiText content,
345 // e.g. if predicted revision ID for the REVISIONID magic word mismatched.
346 // But that should be rare.
347 $logger = LoggerFactory::getInstance( 'DuplicateParse' );
348 $logger->debug(
349 __METHOD__ . ': Possibly redundant parse!',
350 [
351 'title' => $title->getPrefixedDBkey(),
352 'rev' => $revId,
353 'options-hash' => $options->optionsHash(
354 ParserOptions::allCacheVaryingOptions(),
355 $title
356 ),
357 'trace' => $stackTrace,
358 'previous-trace' => $this->previousParseStackTrace,
359 ]
360 );
361 }
362 $this->previousParseStackTrace = $stackTrace;
363
364 list( $redir, $text ) = $this->getRedirectTargetAndText();
365 $output = MediaWikiServices::getInstance()->getParser()
366 ->parse( $text, $title, $options, true, true, $revId );
367
368 // Add redirect indicator at the top
369 if ( $redir ) {
370 // Make sure to include the redirect link in pagelinks
371 $output->addLink( $redir );
372 if ( $generateHtml ) {
373 $chain = $this->getRedirectChain();
374 $output->setText(
375 Article::getRedirectHeaderHtml( $title->getPageLanguage(), $chain, false ) .
376 $output->getRawText()
377 );
378 $output->addModuleStyles( 'mediawiki.action.view.redirectPage' );
379 }
380 }
381
382 // Pass along user-signature flag
383 if ( $this->hadSignature ) {
384 $output->setFlag( 'user-signature' );
385 }
386 }
387
388 /**
389 * @throws MWException
390 */
391 protected function getHtml() {
392 throw new MWException(
393 "getHtml() not implemented for wikitext. "
394 . "Use getParserOutput()->getText()."
395 );
396 }
397
398 /**
399 * This implementation calls $word->match() on the this TextContent object's text.
400 *
401 * @param MagicWord $word
402 *
403 * @return bool
404 *
405 * @see Content::matchMagicWord()
406 */
407 public function matchMagicWord( MagicWord $word ) {
408 return $word->match( $this->getText() );
409 }
410
411 }