Remove PathRouter.php from Generic.Files.OneObjectStructurePerFile.MultipleFound
[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 global $wgParser;
63
64 $text = $this->getText();
65 $sect = $wgParser->getSection( $text, $sectionId, false );
66
67 if ( $sect === false ) {
68 return false;
69 } else {
70 return new static( $sect );
71 }
72 }
73
74 /**
75 * @param string|int|null|bool $sectionId
76 * @param Content $with
77 * @param string $sectionTitle
78 *
79 * @throws MWException
80 * @return Content
81 *
82 * @see Content::replaceSection()
83 */
84 public function replaceSection( $sectionId, Content $with, $sectionTitle = '' ) {
85 $myModelId = $this->getModel();
86 $sectionModelId = $with->getModel();
87
88 if ( $sectionModelId != $myModelId ) {
89 throw new MWException( "Incompatible content model for section: " .
90 "document uses $myModelId but " .
91 "section uses $sectionModelId." );
92 }
93
94 $oldtext = $this->getText();
95 $text = $with->getText();
96
97 if ( strval( $sectionId ) === '' ) {
98 return $with; # XXX: copy first?
99 }
100
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}";
109 }
110 } else {
111 # Replacing an existing section; roll out the big guns
112 global $wgParser;
113
114 $text = $wgParser->replaceSection( $oldtext, $sectionId, $text );
115 }
116
117 $newContent = new static( $text );
118
119 return $newContent;
120 }
121
122 /**
123 * Returns a new WikitextContent object with the given section heading
124 * prepended.
125 *
126 * @param string $header
127 *
128 * @return Content
129 */
130 public function addSectionHeader( $header ) {
131 $text = wfMessage( 'newsectionheaderdefaultlevel' )
132 ->rawParams( $header )->inContentLanguage()->text();
133 $text .= "\n\n";
134 $text .= $this->getText();
135
136 return new static( $text );
137 }
138
139 /**
140 * Returns a Content object with pre-save transformations applied using
141 * Parser::preSaveTransform().
142 *
143 * @param Title $title
144 * @param User $user
145 * @param ParserOptions $popts
146 *
147 * @return Content
148 */
149 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
150 global $wgParser;
151
152 $text = $this->getText();
153 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
154
155 if ( $text === $pst ) {
156 return $this;
157 }
158
159 $ret = new static( $pst );
160
161 if ( $wgParser->getOutput()->getFlag( 'user-signature' ) ) {
162 $ret->hadSignature = true;
163 }
164
165 return $ret;
166 }
167
168 /**
169 * Returns a Content object with preload transformations applied (or this
170 * object if no transformations apply).
171 *
172 * @param Title $title
173 * @param ParserOptions $popts
174 * @param array $params
175 *
176 * @return Content
177 */
178 public function preloadTransform( Title $title, ParserOptions $popts, $params = [] ) {
179 global $wgParser;
180
181 $text = $this->getText();
182 $plt = $wgParser->getPreloadText( $text, $title, $popts, $params );
183
184 return new static( $plt );
185 }
186
187 /**
188 * Extract the redirect target and the remaining text on the page.
189 *
190 * @note migrated here from Title::newFromRedirectInternal()
191 *
192 * @since 1.23
193 *
194 * @return array List of two elements: Title|null and string.
195 */
196 protected function getRedirectTargetAndText() {
197 global $wgMaxRedirects;
198
199 if ( $this->redirectTargetAndText !== null ) {
200 return $this->redirectTargetAndText;
201 }
202
203 if ( $wgMaxRedirects < 1 ) {
204 // redirects are disabled, so quit early
205 $this->redirectTargetAndText = [ null, $this->getText() ];
206 return $this->redirectTargetAndText;
207 }
208
209 $redir = MediaWikiServices::getInstance()->getMagicWordFactory()->get( 'redirect' );
210 $text = ltrim( $this->getText() );
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!
215 $m = [];
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], ':' ) );
222 }
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->getText() ];
227 return $this->redirectTargetAndText;
228 }
229
230 $this->redirectTargetAndText = [ $title, substr( $text, strlen( $m[0] ) ) ];
231 return $this->redirectTargetAndText;
232 }
233 }
234
235 $this->redirectTargetAndText = [ null, $this->getText() ];
236 return $this->redirectTargetAndText;
237 }
238
239 /**
240 * Implement redirect extraction for wikitext.
241 *
242 * @return Title|null
243 *
244 * @see Content::getRedirectTarget
245 */
246 public function getRedirectTarget() {
247 list( $title, ) = $this->getRedirectTargetAndText();
248
249 return $title;
250 }
251
252 /**
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.
255 *
256 * @since 1.21
257 *
258 * @param Title $target
259 *
260 * @return Content
261 *
262 * @see Content::updateRedirect()
263 */
264 public function updateRedirect( Title $target ) {
265 if ( !$this->isRedirect() ) {
266 return $this;
267 }
268
269 # Fix the text
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->getText(), 1 );
275
276 return new static( $newText );
277 }
278
279 /**
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.
282 *
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.
287 *
288 * @return bool
289 */
290 public function isCountable( $hasLinks = null, Title $title = null ) {
291 global $wgArticleCountMethod;
292
293 if ( $this->isRedirect() ) {
294 return false;
295 }
296
297 if ( $wgArticleCountMethod === 'link' ) {
298 if ( $hasLinks === null ) { # not known, find out
299 if ( !$title ) {
300 $context = RequestContext::getMain();
301 $title = $context->getTitle();
302 }
303
304 $po = $this->getParserOutput( $title, null, null, false );
305 $links = $po->getLinks();
306 $hasLinks = !empty( $links );
307 }
308
309 return $hasLinks;
310 }
311
312 return true;
313 }
314
315 /**
316 * @param int $maxlength
317 * @return string
318 */
319 public function getTextForSummary( $maxlength = 250 ) {
320 $truncatedtext = parent::getTextForSummary( $maxlength );
321
322 # clean up unfinished links
323 # XXX: make this optional? wasn't there in autosummary, but required for
324 # deletion summary.
325 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
326
327 return $truncatedtext;
328 }
329
330 /**
331 * Returns a ParserOutput object resulting from parsing the content's text
332 * using $wgParser.
333 *
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.
340 */
341 protected function fillParserOutput( Title $title, $revId,
342 ParserOptions $options, $generateHtml, ParserOutput &$output
343 ) {
344 global $wgParser;
345
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' );
352 $logger->debug(
353 __METHOD__ . ': Possibly redundant parse!',
354 [
355 'title' => $title->getPrefixedDBkey(),
356 'rev' => $revId,
357 'options-hash' => $options->optionsHash(
358 ParserOptions::allCacheVaryingOptions(),
359 $title
360 ),
361 'trace' => $stackTrace,
362 'previous-trace' => $this->previousParseStackTrace,
363 ]
364 );
365 }
366 $this->previousParseStackTrace = $stackTrace;
367
368 list( $redir, $text ) = $this->getRedirectTargetAndText();
369 $output = $wgParser->parse( $text, $title, $options, true, true, $revId );
370
371 // Add redirect indicator at the top
372 if ( $redir ) {
373 // Make sure to include the redirect link in pagelinks
374 $output->addLink( $redir );
375 if ( $generateHtml ) {
376 $chain = $this->getRedirectChain();
377 $output->setText(
378 Article::getRedirectHeaderHtml( $title->getPageLanguage(), $chain, false ) .
379 $output->getRawText()
380 );
381 $output->addModuleStyles( 'mediawiki.action.view.redirectPage' );
382 }
383 }
384
385 // Pass along user-signature flag
386 if ( $this->hadSignature ) {
387 $output->setFlag( 'user-signature' );
388 }
389 }
390
391 /**
392 * @throws MWException
393 */
394 protected function getHtml() {
395 throw new MWException(
396 "getHtml() not implemented for wikitext. "
397 . "Use getParserOutput()->getText()."
398 );
399 }
400
401 /**
402 * This implementation calls $word->match() on the this TextContent object's text.
403 *
404 * @param MagicWord $word
405 *
406 * @return bool
407 *
408 * @see Content::matchMagicWord()
409 */
410 public function matchMagicWord( MagicWord $word ) {
411 return $word->match( $this->getText() );
412 }
413
414 }