MWException: Don't send headers multiple times
[mediawiki.git] / includes / content / WikitextContent.php
blobccea91655cb2b30fcb68e75ae3e7e133fdf5cf27
1 <?php
2 /**
3 * Content object for wiki text pages.
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.
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.
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
20 * @since 1.21
22 * @file
23 * @ingroup Content
25 * @author Daniel Kinzler
28 /**
29 * Content object for wiki text pages.
31 * @ingroup Content
33 class WikitextContent extends TextContent {
35 public function __construct( $text ) {
36 parent::__construct( $text, CONTENT_MODEL_WIKITEXT );
39 /**
40 * @param string $section
42 * @return Content|bool|null
44 * @see Content::getSection()
46 public function getSection( $section ) {
47 global $wgParser;
49 $text = $this->getNativeData();
50 $sect = $wgParser->getSection( $text, $section, false );
52 if ( $sect === false ) {
53 return false;
54 } else {
55 return new WikitextContent( $sect );
59 /**
60 * @param string $section
61 * @param Content $with
62 * @param string $sectionTitle
64 * @throws MWException
65 * @return Content
67 * @see Content::replaceSection()
69 public function replaceSection( $section, Content $with, $sectionTitle = '' ) {
70 wfProfileIn( __METHOD__ );
72 $myModelId = $this->getModel();
73 $sectionModelId = $with->getModel();
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." );
82 $oldtext = $this->getNativeData();
83 $text = $with->getNativeData();
85 if ( $section === '' ) {
86 wfProfileOut( __METHOD__ );
88 return $with; # XXX: copy first?
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}";
100 } else {
101 # Replacing an existing section; roll out the big guns
102 global $wgParser;
104 $text = $wgParser->replaceSection( $oldtext, $section, $text );
107 $newContent = new WikitextContent( $text );
109 wfProfileOut( __METHOD__ );
111 return $newContent;
115 * Returns a new WikitextContent object with the given section heading
116 * prepended.
118 * @param string $header
120 * @return Content
122 public function addSectionHeader( $header ) {
123 $text = wfMessage( 'newsectionheaderdefaultlevel' )
124 ->rawParams( $header )->inContentLanguage()->text();
125 $text .= "\n\n";
126 $text .= $this->getNativeData();
128 return new WikitextContent( $text );
132 * Returns a Content object with pre-save transformations applied using
133 * Parser::preSaveTransform().
135 * @param Title $title
136 * @param User $user
137 * @param ParserOptions $popts
139 * @return Content
141 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
142 global $wgParser;
144 $text = $this->getNativeData();
145 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
146 rtrim( $pst );
148 return ( $text === $pst ) ? $this : new WikitextContent( $pst );
152 * Returns a Content object with preload transformations applied (or this
153 * object if no transformations apply).
155 * @param Title $title
156 * @param ParserOptions $popts
157 * @param array $params
159 * @return Content
161 public function preloadTransform( Title $title, ParserOptions $popts, $params = array() ) {
162 global $wgParser;
164 $text = $this->getNativeData();
165 $plt = $wgParser->getPreloadText( $text, $title, $popts, $params );
167 return new WikitextContent( $plt );
171 * Extract the redirect target and the remaining text on the page.
173 * @note: migrated here from Title::newFromRedirectInternal()
175 * @since 1.23
177 * @return array List of two elements: Title|null and string.
179 protected function getRedirectTargetAndText() {
180 global $wgMaxRedirects;
181 if ( $wgMaxRedirects < 1 ) {
182 // redirects are disabled, so quit early
183 return array( null, $this->getNativeData() );
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], ':' ) );
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() );
205 return array( $title, substr( $text, strlen( $m[0] ) ) );
209 return array( null, $this->getNativeData() );
213 * Implement redirect extraction for wikitext.
215 * @return Title|null
217 * @see Content::getRedirectTarget
219 public function getRedirectTarget() {
220 list( $title, ) = $this->getRedirectTargetAndText();
222 return $title;
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.
229 * @since 1.21
231 * @param Title $target
233 * @return Content
235 * @see Content::updateRedirect()
237 public function updateRedirect( Title $target ) {
238 if ( !$this->isRedirect() ) {
239 return $this;
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 );
249 return new WikitextContent( $newText );
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.
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.
261 * @return bool
263 public function isCountable( $hasLinks = null, Title $title = null ) {
264 global $wgArticleCountMethod;
266 if ( $this->isRedirect() ) {
267 return false;
270 $text = $this->getNativeData();
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();
284 $po = $this->getParserOutput( $title, null, null, false );
285 $links = $po->getLinks();
286 $hasLinks = !empty( $links );
289 return $hasLinks;
292 return false;
296 * @param int $maxlength
297 * @return string
299 public function getTextForSummary( $maxlength = 250 ) {
300 $truncatedtext = parent::getTextForSummary( $maxlength );
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 );
307 return $truncatedtext;
311 * Returns a ParserOutput object resulting from parsing the content's text
312 * using $wgParser.
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 &$output ParserOutput representing the HTML form of the text,
319 * may be manipulated or replaced.
321 protected function fillParserOutput( Title $title, $revId,
322 ParserOptions $options, $generateHtml, ParserOutput &$output
324 global $wgParser;
326 list( $redir, $text ) = $this->getRedirectTargetAndText();
327 $output = $wgParser->parse( $text, $title, $options, true, true, $revId );
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()
344 * @throws MWException
346 protected function getHtml() {
347 throw new MWException(
348 "getHtml() not implemented for wikitext. "
349 . "Use getParserOutput()->getText()."
354 * This implementation calls $word->match() on the this TextContent object's text.
356 * @param MagicWord $word
358 * @return bool
360 * @see Content::matchMagicWord()
362 public function matchMagicWord( MagicWord $word ) {
363 return $word->match( $this->getNativeData() );