Merge "Apply vform styling to HTMLForm buttons"
[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|number $sectionId
41 *
42 * @return Content|bool|null
43 *
44 * @see Content::getSection()
45 */
46 public function getSection( $sectionId ) {
47 global $wgParser;
48
49 $text = $this->getNativeData();
50 $sect = $wgParser->getSection( $text, $sectionId, false );
51
52 if ( $sect === false ) {
53 return false;
54 } else {
55 return new static( $sect );
56 }
57 }
58
59 /**
60 * @param string|number|null|bool $sectionId
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( $sectionId, 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 ( strval( $sectionId ) === '' ) {
86 wfProfileOut( __METHOD__ );
87
88 return $with; # XXX: copy first?
89 }
90
91 if ( $sectionId === '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, $sectionId, $text );
105 }
106
107 $newContent = new static( $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 static( $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 static( $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 static( $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 static( $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 * @return bool
262 */
263 public function isCountable( $hasLinks = null, Title $title = null ) {
264 global $wgArticleCountMethod;
265
266 if ( $this->isRedirect() ) {
267 return false;
268 }
269
270 $text = $this->getNativeData();
271
272 switch ( $wgArticleCountMethod ) {
273 case 'any':
274 return true;
275 case 'comma':
276 return strpos( $text, ',' ) !== false;
277 case 'link':
278 if ( $hasLinks === null ) { # not known, find out
279 if ( !$title ) {
280 $context = RequestContext::getMain();
281 $title = $context->getTitle();
282 }
283
284 $po = $this->getParserOutput( $title, null, null, false );
285 $links = $po->getLinks();
286 $hasLinks = !empty( $links );
287 }
288
289 return $hasLinks;
290 }
291
292 return false;
293 }
294
295 /**
296 * @param int $maxlength
297 * @return string
298 */
299 public function getTextForSummary( $maxlength = 250 ) {
300 $truncatedtext = parent::getTextForSummary( $maxlength );
301
302 # clean up unfinished links
303 # XXX: make this optional? wasn't there in autosummary, but required for
304 # deletion summary.
305 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
306
307 return $truncatedtext;
308 }
309
310 /**
311 * Returns a ParserOutput object resulting from parsing the content's text
312 * using $wgParser.
313 *
314 * @param Title $title
315 * @param int $revId Revision to pass to the parser (default: null)
316 * @param ParserOptions $options (default: null)
317 * @param bool $generateHtml (default: true)
318 * @param ParserOutput &$output ParserOutput representing the HTML form of the text,
319 * may be manipulated or replaced.
320 */
321 protected function fillParserOutput( Title $title, $revId,
322 ParserOptions $options, $generateHtml, ParserOutput &$output
323 ) {
324 global $wgParser;
325
326 list( $redir, $text ) = $this->getRedirectTargetAndText();
327 $output = $wgParser->parse( $text, $title, $options, true, true, $revId );
328
329 // Add redirect indicator at the top
330 if ( $redir ) {
331 // Make sure to include the redirect link in pagelinks
332 $output->addLink( $redir );
333 if ( $generateHtml ) {
334 $chain = $this->getRedirectChain();
335 $output->setText(
336 Article::getRedirectHeaderHtml( $title->getPageLanguage(), $chain, false ) .
337 $output->getText()
338 );
339 $output->addModuleStyles( 'mediawiki.action.view.redirectPage' );
340 }
341 }
342 }
343
344 /**
345 * @throws MWException
346 */
347 protected function getHtml() {
348 throw new MWException(
349 "getHtml() not implemented for wikitext. "
350 . "Use getParserOutput()->getText()."
351 );
352 }
353
354 /**
355 * This implementation calls $word->match() on the this TextContent object's text.
356 *
357 * @param MagicWord $word
358 *
359 * @return bool
360 *
361 * @see Content::matchMagicWord()
362 */
363 public function matchMagicWord( MagicWord $word ) {
364 return $word->match( $this->getNativeData() );
365 }
366
367 }