Merge "JavaScriptMinifier: Add test case for another line-break bug"
[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\MediaWikiServices;
29
30 /**
31 * Content object for wiki text pages.
32 *
33 * @ingroup Content
34 */
35 class WikitextContent extends TextContent {
36 private $redirectTargetAndText = null;
37
38 /**
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.
41 */
42 private $hadSignature = false;
43
44 public function __construct( $text ) {
45 parent::__construct( $text, CONTENT_MODEL_WIKITEXT );
46 }
47
48 /**
49 * @param string|int $sectionId
50 *
51 * @return Content|bool|null
52 *
53 * @see Content::getSection()
54 */
55 public function getSection( $sectionId ) {
56 global $wgParser;
57
58 $text = $this->getNativeData();
59 $sect = $wgParser->getSection( $text, $sectionId, false );
60
61 if ( $sect === false ) {
62 return false;
63 } else {
64 return new static( $sect );
65 }
66 }
67
68 /**
69 * @param string|int|null|bool $sectionId
70 * @param Content $with
71 * @param string $sectionTitle
72 *
73 * @throws MWException
74 * @return Content
75 *
76 * @see Content::replaceSection()
77 */
78 public function replaceSection( $sectionId, Content $with, $sectionTitle = '' ) {
79 $myModelId = $this->getModel();
80 $sectionModelId = $with->getModel();
81
82 if ( $sectionModelId != $myModelId ) {
83 throw new MWException( "Incompatible content model for section: " .
84 "document uses $myModelId but " .
85 "section uses $sectionModelId." );
86 }
87
88 $oldtext = $this->getNativeData();
89 $text = $with->getNativeData();
90
91 if ( strval( $sectionId ) === '' ) {
92 return $with; # XXX: copy first?
93 }
94
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}";
103 }
104 } else {
105 # Replacing an existing section; roll out the big guns
106 global $wgParser;
107
108 $text = $wgParser->replaceSection( $oldtext, $sectionId, $text );
109 }
110
111 $newContent = new static( $text );
112
113 return $newContent;
114 }
115
116 /**
117 * Returns a new WikitextContent object with the given section heading
118 * prepended.
119 *
120 * @param string $header
121 *
122 * @return Content
123 */
124 public function addSectionHeader( $header ) {
125 $text = wfMessage( 'newsectionheaderdefaultlevel' )
126 ->rawParams( $header )->inContentLanguage()->text();
127 $text .= "\n\n";
128 $text .= $this->getNativeData();
129
130 return new static( $text );
131 }
132
133 /**
134 * Returns a Content object with pre-save transformations applied using
135 * Parser::preSaveTransform().
136 *
137 * @param Title $title
138 * @param User $user
139 * @param ParserOptions $popts
140 *
141 * @return Content
142 */
143 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
144 global $wgParser;
145
146 $text = $this->getNativeData();
147 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
148
149 if ( $text === $pst ) {
150 return $this;
151 }
152
153 $ret = new static( $pst );
154
155 if ( $wgParser->getOutput()->getFlag( 'user-signature' ) ) {
156 $ret->hadSignature = true;
157 }
158
159 return $ret;
160 }
161
162 /**
163 * Returns a Content object with preload transformations applied (or this
164 * object if no transformations apply).
165 *
166 * @param Title $title
167 * @param ParserOptions $popts
168 * @param array $params
169 *
170 * @return Content
171 */
172 public function preloadTransform( Title $title, ParserOptions $popts, $params = [] ) {
173 global $wgParser;
174
175 $text = $this->getNativeData();
176 $plt = $wgParser->getPreloadText( $text, $title, $popts, $params );
177
178 return new static( $plt );
179 }
180
181 /**
182 * Extract the redirect target and the remaining text on the page.
183 *
184 * @note migrated here from Title::newFromRedirectInternal()
185 *
186 * @since 1.23
187 *
188 * @return array List of two elements: Title|null and string.
189 */
190 protected function getRedirectTargetAndText() {
191 global $wgMaxRedirects;
192
193 if ( $this->redirectTargetAndText !== null ) {
194 return $this->redirectTargetAndText;
195 }
196
197 if ( $wgMaxRedirects < 1 ) {
198 // redirects are disabled, so quit early
199 $this->redirectTargetAndText = [ null, $this->getNativeData() ];
200 return $this->redirectTargetAndText;
201 }
202
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!
209 $m = [];
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], ':' ) );
216 }
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;
222 }
223
224 $this->redirectTargetAndText = [ $title, substr( $text, strlen( $m[0] ) ) ];
225 return $this->redirectTargetAndText;
226 }
227 }
228
229 $this->redirectTargetAndText = [ null, $this->getNativeData() ];
230 return $this->redirectTargetAndText;
231 }
232
233 /**
234 * Implement redirect extraction for wikitext.
235 *
236 * @return Title|null
237 *
238 * @see Content::getRedirectTarget
239 */
240 public function getRedirectTarget() {
241 list( $title, ) = $this->getRedirectTargetAndText();
242
243 return $title;
244 }
245
246 /**
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.
249 *
250 * @since 1.21
251 *
252 * @param Title $target
253 *
254 * @return Content
255 *
256 * @see Content::updateRedirect()
257 */
258 public function updateRedirect( Title $target ) {
259 if ( !$this->isRedirect() ) {
260 return $this;
261 }
262
263 # Fix the text
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 );
269
270 return new static( $newText );
271 }
272
273 /**
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.
276 *
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.
281 *
282 * @return bool
283 */
284 public function isCountable( $hasLinks = null, Title $title = null ) {
285 global $wgArticleCountMethod;
286
287 if ( $this->isRedirect() ) {
288 return false;
289 }
290
291 if ( $wgArticleCountMethod === 'link' ) {
292 if ( $hasLinks === null ) { # not known, find out
293 if ( !$title ) {
294 $context = RequestContext::getMain();
295 $title = $context->getTitle();
296 }
297
298 $po = $this->getParserOutput( $title, null, null, false );
299 $links = $po->getLinks();
300 $hasLinks = !empty( $links );
301 }
302
303 return $hasLinks;
304 }
305
306 return true;
307 }
308
309 /**
310 * @param int $maxlength
311 * @return string
312 */
313 public function getTextForSummary( $maxlength = 250 ) {
314 $truncatedtext = parent::getTextForSummary( $maxlength );
315
316 # clean up unfinished links
317 # XXX: make this optional? wasn't there in autosummary, but required for
318 # deletion summary.
319 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
320
321 return $truncatedtext;
322 }
323
324 /**
325 * Returns a ParserOutput object resulting from parsing the content's text
326 * using $wgParser.
327 *
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.
334 */
335 protected function fillParserOutput( Title $title, $revId,
336 ParserOptions $options, $generateHtml, ParserOutput &$output
337 ) {
338 global $wgParser;
339
340 list( $redir, $text ) = $this->getRedirectTargetAndText();
341 $output = $wgParser->parse( $text, $title, $options, true, true, $revId );
342
343 // Add redirect indicator at the top
344 if ( $redir ) {
345 // Make sure to include the redirect link in pagelinks
346 $output->addLink( $redir );
347 if ( $generateHtml ) {
348 $chain = $this->getRedirectChain();
349 $output->setText(
350 Article::getRedirectHeaderHtml( $title->getPageLanguage(), $chain, false ) .
351 $output->getRawText()
352 );
353 $output->addModuleStyles( 'mediawiki.action.view.redirectPage' );
354 }
355 }
356
357 // Pass along user-signature flag
358 if ( $this->hadSignature ) {
359 $output->setFlag( 'user-signature' );
360 }
361 }
362
363 /**
364 * @throws MWException
365 */
366 protected function getHtml() {
367 throw new MWException(
368 "getHtml() not implemented for wikitext. "
369 . "Use getParserOutput()->getText()."
370 );
371 }
372
373 /**
374 * This implementation calls $word->match() on the this TextContent object's text.
375 *
376 * @param MagicWord $word
377 *
378 * @return bool
379 *
380 * @see Content::matchMagicWord()
381 */
382 public function matchMagicWord( MagicWord $word ) {
383 return $word->match( $this->getNativeData() );
384 }
385
386 }