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