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