Merge "ParserOutput::addLanguageLink needs a string"
[lhc/web/wiklou.git] / includes / content / WikitextContent.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @since 1.21
19 *
20 * @file
21 * @ingroup Content
22 *
23 * @author Daniel Kinzler
24 */
25 class WikitextContent extends TextContent {
26
27 public function __construct( $text ) {
28 parent::__construct( $text, CONTENT_MODEL_WIKITEXT );
29 }
30
31 /**
32 * @see Content::getSection()
33 */
34 public function getSection( $section ) {
35 global $wgParser;
36
37 $text = $this->getNativeData();
38 $sect = $wgParser->getSection( $text, $section, false );
39
40 if ( $sect === false ) {
41 return false;
42 } else {
43 return new WikitextContent( $sect );
44 }
45 }
46
47 /**
48 * @see Content::replaceSection()
49 */
50 public function replaceSection( $section, Content $with, $sectionTitle = '' ) {
51 wfProfileIn( __METHOD__ );
52
53 $myModelId = $this->getModel();
54 $sectionModelId = $with->getModel();
55
56 if ( $sectionModelId != $myModelId ) {
57 throw new MWException( "Incompatible content model for section: " .
58 "document uses $myModelId but " .
59 "section uses $sectionModelId." );
60 }
61
62 $oldtext = $this->getNativeData();
63 $text = $with->getNativeData();
64
65 if ( $section === '' ) {
66 wfProfileOut( __METHOD__ );
67 return $with; # XXX: copy first?
68 } if ( $section == 'new' ) {
69 # Inserting a new section
70 $subject = $sectionTitle ? wfMessage( 'newsectionheaderdefaultlevel' )
71 ->rawParams( $sectionTitle )->inContentLanguage()->text() . "\n\n" : '';
72 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
73 $text = strlen( trim( $oldtext ) ) > 0
74 ? "{$oldtext}\n\n{$subject}{$text}"
75 : "{$subject}{$text}";
76 }
77 } else {
78 # Replacing an existing section; roll out the big guns
79 global $wgParser;
80
81 $text = $wgParser->replaceSection( $oldtext, $section, $text );
82 }
83
84 $newContent = new WikitextContent( $text );
85
86 wfProfileOut( __METHOD__ );
87 return $newContent;
88 }
89
90 /**
91 * Returns a new WikitextContent object with the given section heading
92 * prepended.
93 *
94 * @param $header string
95 * @return Content
96 */
97 public function addSectionHeader( $header ) {
98 $text = wfMessage( 'newsectionheaderdefaultlevel' )
99 ->rawParams( $header )->inContentLanguage()->text();
100 $text .= "\n\n";
101 $text .= $this->getNativeData();
102
103 return new WikitextContent( $text );
104 }
105
106 /**
107 * Returns a Content object with pre-save transformations applied using
108 * Parser::preSaveTransform().
109 *
110 * @param $title Title
111 * @param $user User
112 * @param $popts ParserOptions
113 * @return Content
114 */
115 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
116 global $wgParser;
117
118 $text = $this->getNativeData();
119 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
120 rtrim( $pst );
121
122 return ( $text === $pst ) ? $this : new WikitextContent( $pst );
123 }
124
125 /**
126 * Returns a Content object with preload transformations applied (or this
127 * object if no transformations apply).
128 *
129 * @param $title Title
130 * @param $popts ParserOptions
131 * @return Content
132 */
133 public function preloadTransform( Title $title, ParserOptions $popts ) {
134 global $wgParser;
135
136 $text = $this->getNativeData();
137 $plt = $wgParser->getPreloadText( $text, $title, $popts );
138
139 return new WikitextContent( $plt );
140 }
141
142 /**
143 * Implement redirect extraction for wikitext.
144 *
145 * @return null|Title
146 *
147 * @note: migrated here from Title::newFromRedirectInternal()
148 *
149 * @see Content::getRedirectTarget
150 * @see AbstractContent::getRedirectTarget
151 */
152 public function getRedirectTarget() {
153 global $wgMaxRedirects;
154 if ( $wgMaxRedirects < 1 ) {
155 // redirects are disabled, so quit early
156 return null;
157 }
158 $redir = MagicWord::get( 'redirect' );
159 $text = trim( $this->getNativeData() );
160 if ( $redir->matchStartAndRemove( $text ) ) {
161 // Extract the first link and see if it's usable
162 // Ensure that it really does come directly after #REDIRECT
163 // Some older redirects included a colon, so don't freak about that!
164 $m = array();
165 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
166 // Strip preceding colon used to "escape" categories, etc.
167 // and URL-decode links
168 if ( strpos( $m[1], '%' ) !== false ) {
169 // Match behavior of inline link parsing here;
170 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
171 }
172 $title = Title::newFromText( $m[1] );
173 // If the title is a redirect to bad special pages or is invalid, return null
174 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
175 return null;
176 }
177 return $title;
178 }
179 }
180 return null;
181 }
182
183 /**
184 * @see Content::updateRedirect()
185 *
186 * This implementation replaces the first link on the page with the given new target
187 * if this Content object is a redirect. Otherwise, this method returns $this.
188 *
189 * @since 1.21
190 *
191 * @param Title $target
192 *
193 * @return Content a new Content object with the updated redirect (or $this if this Content object isn't a redirect)
194 */
195 public function updateRedirect( Title $target ) {
196 if ( !$this->isRedirect() ) {
197 return $this;
198 }
199
200 # Fix the text
201 # Remember that redirect pages can have categories, templates, etc.,
202 # so the regex has to be fairly general
203 $newText = preg_replace( '/ \[ \[ [^\]]* \] \] /x',
204 '[[' . $target->getFullText() . ']]',
205 $this->getNativeData(), 1 );
206
207 return new WikitextContent( $newText );
208 }
209
210 /**
211 * Returns true if this content is not a redirect, and this content's text
212 * is countable according to the criteria defined by $wgArticleCountMethod.
213 *
214 * @param $hasLinks Bool if it is known whether this content contains
215 * links, provide this information here, to avoid redundant parsing to
216 * find out (default: null).
217 * @param $title Title: (default: null)
218 *
219 * @internal param \IContextSource $context context for parsing if necessary
220 *
221 * @return bool True if the content is countable
222 */
223 public function isCountable( $hasLinks = null, Title $title = null ) {
224 global $wgArticleCountMethod;
225
226 if ( $this->isRedirect( ) ) {
227 return false;
228 }
229
230 $text = $this->getNativeData();
231
232 switch ( $wgArticleCountMethod ) {
233 case 'any':
234 return true;
235 case 'comma':
236 return strpos( $text, ',' ) !== false;
237 case 'link':
238 if ( $hasLinks === null ) { # not known, find out
239 if ( !$title ) {
240 $context = RequestContext::getMain();
241 $title = $context->getTitle();
242 }
243
244 $po = $this->getParserOutput( $title, null, null, false );
245 $links = $po->getLinks();
246 $hasLinks = !empty( $links );
247 }
248
249 return $hasLinks;
250 }
251
252 return false;
253 }
254
255 public function getTextForSummary( $maxlength = 250 ) {
256 $truncatedtext = parent::getTextForSummary( $maxlength );
257
258 # clean up unfinished links
259 # XXX: make this optional? wasn't there in autosummary, but required for
260 # deletion summary.
261 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
262
263 return $truncatedtext;
264 }
265
266 /**
267 * Returns a ParserOutput object resulting from parsing the content's text
268 * using $wgParser.
269 *
270 * @since 1.21
271 *
272 * @param $title Title
273 * @param $revId int Revision to pass to the parser (default: null)
274 * @param $options ParserOptions (default: null)
275 * @param $generateHtml bool (default: false)
276 *
277 * @internal param \IContextSource|null $context
278 * @return ParserOutput representing the HTML form of the text
279 */
280 public function getParserOutput( Title $title,
281 $revId = null,
282 ParserOptions $options = null, $generateHtml = true
283 ) {
284 global $wgParser;
285
286 if ( !$options ) {
287 //NOTE: use canonical options per default to produce cacheable output
288 $options = $this->getContentHandler()->makeParserOptions( 'canonical' );
289 }
290
291 $po = $wgParser->parse( $this->getNativeData(), $title, $options, true, true, $revId );
292 return $po;
293 }
294
295 protected function getHtml() {
296 throw new MWException(
297 "getHtml() not implemented for wikitext. "
298 . "Use getParserOutput()->getText()."
299 );
300 }
301
302 /**
303 * @see Content::matchMagicWord()
304 *
305 * This implementation calls $word->match() on the this TextContent object's text.
306 *
307 * @param MagicWord $word
308 *
309 * @return bool whether this Content object matches the given magic word.
310 */
311 public function matchMagicWord( MagicWord $word ) {
312 return $word->match( $this->getNativeData() );
313 }
314 }