Merge "Update MagicWord to use ContentLanguage"
[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 public function __construct( $text ) {
39 parent::__construct( $text, CONTENT_MODEL_WIKITEXT );
40 }
41
42 /**
43 * @param string|int $sectionId
44 *
45 * @return Content|bool|null
46 *
47 * @see Content::getSection()
48 */
49 public function getSection( $sectionId ) {
50 global $wgParser;
51
52 $text = $this->getNativeData();
53 $sect = $wgParser->getSection( $text, $sectionId, false );
54
55 if ( $sect === false ) {
56 return false;
57 } else {
58 return new static( $sect );
59 }
60 }
61
62 /**
63 * @param string|int|null|bool $sectionId
64 * @param Content $with
65 * @param string $sectionTitle
66 *
67 * @throws MWException
68 * @return Content
69 *
70 * @see Content::replaceSection()
71 */
72 public function replaceSection( $sectionId, Content $with, $sectionTitle = '' ) {
73 $myModelId = $this->getModel();
74 $sectionModelId = $with->getModel();
75
76 if ( $sectionModelId != $myModelId ) {
77 throw new MWException( "Incompatible content model for section: " .
78 "document uses $myModelId but " .
79 "section uses $sectionModelId." );
80 }
81
82 $oldtext = $this->getNativeData();
83 $text = $with->getNativeData();
84
85 if ( strval( $sectionId ) === '' ) {
86 return $with; # XXX: copy first?
87 }
88
89 if ( $sectionId === 'new' ) {
90 # Inserting a new section
91 $subject = $sectionTitle ? wfMessage( 'newsectionheaderdefaultlevel' )
92 ->plaintextParams( $sectionTitle )->inContentLanguage()->text() . "\n\n" : '';
93 if ( Hooks::run( 'PlaceNewSection', [ $this, $oldtext, $subject, &$text ] ) ) {
94 $text = strlen( trim( $oldtext ) ) > 0
95 ? "{$oldtext}\n\n{$subject}{$text}"
96 : "{$subject}{$text}";
97 }
98 } else {
99 # Replacing an existing section; roll out the big guns
100 global $wgParser;
101
102 $text = $wgParser->replaceSection( $oldtext, $sectionId, $text );
103 }
104
105 $newContent = new static( $text );
106
107 return $newContent;
108 }
109
110 /**
111 * Returns a new WikitextContent object with the given section heading
112 * prepended.
113 *
114 * @param string $header
115 *
116 * @return Content
117 */
118 public function addSectionHeader( $header ) {
119 $text = wfMessage( 'newsectionheaderdefaultlevel' )
120 ->rawParams( $header )->inContentLanguage()->text();
121 $text .= "\n\n";
122 $text .= $this->getNativeData();
123
124 return new static( $text );
125 }
126
127 /**
128 * Returns a Content object with pre-save transformations applied using
129 * Parser::preSaveTransform().
130 *
131 * @param Title $title
132 * @param User $user
133 * @param ParserOptions $popts
134 *
135 * @return Content
136 */
137 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
138 global $wgParser;
139
140 $text = $this->getNativeData();
141 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
142
143 return ( $text === $pst ) ? $this : new static( $pst );
144 }
145
146 /**
147 * Returns a Content object with preload transformations applied (or this
148 * object if no transformations apply).
149 *
150 * @param Title $title
151 * @param ParserOptions $popts
152 * @param array $params
153 *
154 * @return Content
155 */
156 public function preloadTransform( Title $title, ParserOptions $popts, $params = [] ) {
157 global $wgParser;
158
159 $text = $this->getNativeData();
160 $plt = $wgParser->getPreloadText( $text, $title, $popts, $params );
161
162 return new static( $plt );
163 }
164
165 /**
166 * Extract the redirect target and the remaining text on the page.
167 *
168 * @note migrated here from Title::newFromRedirectInternal()
169 *
170 * @since 1.23
171 *
172 * @return array List of two elements: Title|null and string.
173 */
174 protected function getRedirectTargetAndText() {
175 global $wgMaxRedirects;
176
177 if ( $this->redirectTargetAndText !== null ) {
178 return $this->redirectTargetAndText;
179 }
180
181 if ( $wgMaxRedirects < 1 ) {
182 // redirects are disabled, so quit early
183 $this->redirectTargetAndText = [ null, $this->getNativeData() ];
184 return $this->redirectTargetAndText;
185 }
186
187 $redir = MediaWikiServices::getInstance()->getMagicWordFactory()->get( 'redirect' );
188 $text = ltrim( $this->getNativeData() );
189 if ( $redir->matchStartAndRemove( $text ) ) {
190 // Extract the first link and see if it's usable
191 // Ensure that it really does come directly after #REDIRECT
192 // Some older redirects included a colon, so don't freak about that!
193 $m = [];
194 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}\s*!', $text, $m ) ) {
195 // Strip preceding colon used to "escape" categories, etc.
196 // and URL-decode links
197 if ( strpos( $m[1], '%' ) !== false ) {
198 // Match behavior of inline link parsing here;
199 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
200 }
201 $title = Title::newFromText( $m[1] );
202 // If the title is a redirect to bad special pages or is invalid, return null
203 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
204 $this->redirectTargetAndText = [ null, $this->getNativeData() ];
205 return $this->redirectTargetAndText;
206 }
207
208 $this->redirectTargetAndText = [ $title, substr( $text, strlen( $m[0] ) ) ];
209 return $this->redirectTargetAndText;
210 }
211 }
212
213 $this->redirectTargetAndText = [ null, $this->getNativeData() ];
214 return $this->redirectTargetAndText;
215 }
216
217 /**
218 * Implement redirect extraction for wikitext.
219 *
220 * @return Title|null
221 *
222 * @see Content::getRedirectTarget
223 */
224 public function getRedirectTarget() {
225 list( $title, ) = $this->getRedirectTargetAndText();
226
227 return $title;
228 }
229
230 /**
231 * This implementation replaces the first link on the page with the given new target
232 * if this Content object is a redirect. Otherwise, this method returns $this.
233 *
234 * @since 1.21
235 *
236 * @param Title $target
237 *
238 * @return Content
239 *
240 * @see Content::updateRedirect()
241 */
242 public function updateRedirect( Title $target ) {
243 if ( !$this->isRedirect() ) {
244 return $this;
245 }
246
247 # Fix the text
248 # Remember that redirect pages can have categories, templates, etc.,
249 # so the regex has to be fairly general
250 $newText = preg_replace( '/ \[ \[ [^\]]* \] \] /x',
251 '[[' . $target->getFullText() . ']]',
252 $this->getNativeData(), 1 );
253
254 return new static( $newText );
255 }
256
257 /**
258 * Returns true if this content is not a redirect, and this content's text
259 * is countable according to the criteria defined by $wgArticleCountMethod.
260 *
261 * @param bool|null $hasLinks If it is known whether this content contains
262 * links, provide this information here, to avoid redundant parsing to
263 * find out (default: null).
264 * @param Title|null $title Optional title, defaults to the title from the current main request.
265 *
266 * @return bool
267 */
268 public function isCountable( $hasLinks = null, Title $title = null ) {
269 global $wgArticleCountMethod;
270
271 if ( $this->isRedirect() ) {
272 return false;
273 }
274
275 if ( $wgArticleCountMethod === 'link' ) {
276 if ( $hasLinks === null ) { # not known, find out
277 if ( !$title ) {
278 $context = RequestContext::getMain();
279 $title = $context->getTitle();
280 }
281
282 $po = $this->getParserOutput( $title, null, null, false );
283 $links = $po->getLinks();
284 $hasLinks = !empty( $links );
285 }
286
287 return $hasLinks;
288 }
289
290 return true;
291 }
292
293 /**
294 * @param int $maxlength
295 * @return string
296 */
297 public function getTextForSummary( $maxlength = 250 ) {
298 $truncatedtext = parent::getTextForSummary( $maxlength );
299
300 # clean up unfinished links
301 # XXX: make this optional? wasn't there in autosummary, but required for
302 # deletion summary.
303 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
304
305 return $truncatedtext;
306 }
307
308 /**
309 * Returns a ParserOutput object resulting from parsing the content's text
310 * using $wgParser.
311 *
312 * @param Title $title
313 * @param int $revId Revision to pass to the parser (default: null)
314 * @param ParserOptions $options (default: null)
315 * @param bool $generateHtml (default: true)
316 * @param ParserOutput &$output ParserOutput representing the HTML form of the text,
317 * may be manipulated or replaced.
318 */
319 protected function fillParserOutput( Title $title, $revId,
320 ParserOptions $options, $generateHtml, ParserOutput &$output
321 ) {
322 global $wgParser;
323
324 list( $redir, $text ) = $this->getRedirectTargetAndText();
325 $output = $wgParser->parse( $text, $title, $options, true, true, $revId );
326
327 // Add redirect indicator at the top
328 if ( $redir ) {
329 // Make sure to include the redirect link in pagelinks
330 $output->addLink( $redir );
331 if ( $generateHtml ) {
332 $chain = $this->getRedirectChain();
333 $output->setText(
334 Article::getRedirectHeaderHtml( $title->getPageLanguage(), $chain, false ) .
335 $output->getRawText()
336 );
337 $output->addModuleStyles( 'mediawiki.action.view.redirectPage' );
338 }
339 }
340 }
341
342 /**
343 * @throws MWException
344 */
345 protected function getHtml() {
346 throw new MWException(
347 "getHtml() not implemented for wikitext. "
348 . "Use getParserOutput()->getText()."
349 );
350 }
351
352 /**
353 * This implementation calls $word->match() on the this TextContent object's text.
354 *
355 * @param MagicWord $word
356 *
357 * @return bool
358 *
359 * @see Content::matchMagicWord()
360 */
361 public function matchMagicWord( MagicWord $word ) {
362 return $word->match( $this->getNativeData() );
363 }
364
365 }