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