Merge "Document the wikipage.content hook"
[mediawiki.git] / includes / content / WikitextContent.php
blob1f96bdca1373f733423819f6750669049e740a2f
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 {
34 public function __construct( $text ) {
35 parent::__construct( $text, CONTENT_MODEL_WIKITEXT );
38 /**
39 * @see Content::getSection()
41 public function getSection( $section ) {
42 global $wgParser;
44 $text = $this->getNativeData();
45 $sect = $wgParser->getSection( $text, $section, false );
47 if ( $sect === false ) {
48 return false;
49 } else {
50 return new WikitextContent( $sect );
54 /**
55 * @see Content::replaceSection()
57 public function replaceSection( $section, Content $with, $sectionTitle = '' ) {
58 wfProfileIn( __METHOD__ );
60 $myModelId = $this->getModel();
61 $sectionModelId = $with->getModel();
63 if ( $sectionModelId != $myModelId ) {
64 wfProfileOut( __METHOD__ );
65 throw new MWException( "Incompatible content model for section: " .
66 "document uses $myModelId but " .
67 "section uses $sectionModelId." );
70 $oldtext = $this->getNativeData();
71 $text = $with->getNativeData();
73 if ( $section === '' ) {
74 wfProfileOut( __METHOD__ );
76 return $with; # XXX: copy first?
79 if ( $section == 'new' ) {
80 # Inserting a new section
81 $subject = $sectionTitle ? wfMessage( 'newsectionheaderdefaultlevel' )
82 ->rawParams( $sectionTitle )->inContentLanguage()->text() . "\n\n" : '';
83 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
84 $text = strlen( trim( $oldtext ) ) > 0
85 ? "{$oldtext}\n\n{$subject}{$text}"
86 : "{$subject}{$text}";
88 } else {
89 # Replacing an existing section; roll out the big guns
90 global $wgParser;
92 $text = $wgParser->replaceSection( $oldtext, $section, $text );
95 $newContent = new WikitextContent( $text );
97 wfProfileOut( __METHOD__ );
99 return $newContent;
103 * Returns a new WikitextContent object with the given section heading
104 * prepended.
106 * @param $header string
107 * @return Content
109 public function addSectionHeader( $header ) {
110 $text = wfMessage( 'newsectionheaderdefaultlevel' )
111 ->rawParams( $header )->inContentLanguage()->text();
112 $text .= "\n\n";
113 $text .= $this->getNativeData();
115 return new WikitextContent( $text );
119 * Returns a Content object with pre-save transformations applied using
120 * Parser::preSaveTransform().
122 * @param $title Title
123 * @param $user User
124 * @param $popts ParserOptions
125 * @return Content
127 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
128 global $wgParser;
130 $text = $this->getNativeData();
131 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
132 rtrim( $pst );
134 return ( $text === $pst ) ? $this : new WikitextContent( $pst );
138 * Returns a Content object with preload transformations applied (or this
139 * object if no transformations apply).
141 * @param $title Title
142 * @param $popts ParserOptions
143 * @return Content
145 public function preloadTransform( Title $title, ParserOptions $popts ) {
146 global $wgParser;
148 $text = $this->getNativeData();
149 $plt = $wgParser->getPreloadText( $text, $title, $popts );
151 return new WikitextContent( $plt );
155 * Implement redirect extraction for wikitext.
157 * @return null|Title
159 * @note: migrated here from Title::newFromRedirectInternal()
161 * @see Content::getRedirectTarget
162 * @see AbstractContent::getRedirectTarget
164 public function getRedirectTarget() {
165 global $wgMaxRedirects;
166 if ( $wgMaxRedirects < 1 ) {
167 // redirects are disabled, so quit early
168 return null;
170 $redir = MagicWord::get( 'redirect' );
171 $text = trim( $this->getNativeData() );
172 if ( $redir->matchStartAndRemove( $text ) ) {
173 // Extract the first link and see if it's usable
174 // Ensure that it really does come directly after #REDIRECT
175 // Some older redirects included a colon, so don't freak about that!
176 $m = array();
177 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
178 // Strip preceding colon used to "escape" categories, etc.
179 // and URL-decode links
180 if ( strpos( $m[1], '%' ) !== false ) {
181 // Match behavior of inline link parsing here;
182 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
184 $title = Title::newFromText( $m[1] );
185 // If the title is a redirect to bad special pages or is invalid, return null
186 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
187 return null;
190 return $title;
194 return null;
198 * @see Content::updateRedirect()
200 * This implementation replaces the first link on the page with the given new target
201 * if this Content object is a redirect. Otherwise, this method returns $this.
203 * @since 1.21
205 * @param Title $target
207 * @return Content a new Content object with the updated redirect (or $this
208 * if this Content object isn't a redirect)
210 public function updateRedirect( Title $target ) {
211 if ( !$this->isRedirect() ) {
212 return $this;
215 # Fix the text
216 # Remember that redirect pages can have categories, templates, etc.,
217 # so the regex has to be fairly general
218 $newText = preg_replace( '/ \[ \[ [^\]]* \] \] /x',
219 '[[' . $target->getFullText() . ']]',
220 $this->getNativeData(), 1 );
222 return new WikitextContent( $newText );
226 * Returns true if this content is not a redirect, and this content's text
227 * is countable according to the criteria defined by $wgArticleCountMethod.
229 * @param bool $hasLinks if it is known whether this content contains
230 * links, provide this information here, to avoid redundant parsing to
231 * find out (default: null).
232 * @param $title Title: (default: null)
234 * @internal param \IContextSource $context context for parsing if necessary
236 * @return bool True if the content is countable
238 public function isCountable( $hasLinks = null, Title $title = null ) {
239 global $wgArticleCountMethod;
241 if ( $this->isRedirect() ) {
242 return false;
245 $text = $this->getNativeData();
247 switch ( $wgArticleCountMethod ) {
248 case 'any':
249 return true;
250 case 'comma':
251 return strpos( $text, ',' ) !== false;
252 case 'link':
253 if ( $hasLinks === null ) { # not known, find out
254 if ( !$title ) {
255 $context = RequestContext::getMain();
256 $title = $context->getTitle();
259 $po = $this->getParserOutput( $title, null, null, false );
260 $links = $po->getLinks();
261 $hasLinks = !empty( $links );
264 return $hasLinks;
267 return false;
270 public function getTextForSummary( $maxlength = 250 ) {
271 $truncatedtext = parent::getTextForSummary( $maxlength );
273 # clean up unfinished links
274 # XXX: make this optional? wasn't there in autosummary, but required for
275 # deletion summary.
276 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
278 return $truncatedtext;
282 * Returns a ParserOutput object resulting from parsing the content's text
283 * using $wgParser.
285 * @since 1.21
287 * @param $title Title
288 * @param int $revId Revision to pass to the parser (default: null)
289 * @param $options ParserOptions (default: null)
290 * @param bool $generateHtml (default: false)
292 * @internal param \IContextSource|null $context
293 * @return ParserOutput representing the HTML form of the text
295 public function getParserOutput( Title $title,
296 $revId = null,
297 ParserOptions $options = null, $generateHtml = true
299 global $wgParser;
301 if ( !$options ) {
302 //NOTE: use canonical options per default to produce cacheable output
303 $options = $this->getContentHandler()->makeParserOptions( 'canonical' );
306 $po = $wgParser->parse( $this->getNativeData(), $title, $options, true, true, $revId );
308 return $po;
311 protected function getHtml() {
312 throw new MWException(
313 "getHtml() not implemented for wikitext. "
314 . "Use getParserOutput()->getText()."
319 * @see Content::matchMagicWord()
321 * This implementation calls $word->match() on the this TextContent object's text.
323 * @param MagicWord $word
325 * @return bool whether this Content object matches the given magic word.
327 public function matchMagicWord( MagicWord $word ) {
328 return $word->match( $this->getNativeData() );