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