Merge "Add .pipeline/ with dev image variant"
[lhc/web/wiklou.git] / includes / content / TextContent.php
1 <?php
2 /**
3 * Content object implementation for representing flat text.
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 use MediaWiki\MediaWikiServices;
29
30 /**
31 * Content object implementation for representing flat text.
32 *
33 * TextContent instances are immutable
34 *
35 * @ingroup Content
36 */
37 class TextContent extends AbstractContent {
38
39 /**
40 * @var string
41 */
42 protected $mText;
43
44 /**
45 * @param string $text
46 * @param string $model_id
47 * @throws MWException
48 */
49 public function __construct( $text, $model_id = CONTENT_MODEL_TEXT ) {
50 parent::__construct( $model_id );
51
52 if ( $text === null || $text === false ) {
53 wfWarn( "TextContent constructed with \$text = " . var_export( $text, true ) . "! "
54 . "This may indicate an error in the caller's scope.", 2 );
55
56 $text = '';
57 }
58
59 if ( !is_string( $text ) ) {
60 throw new MWException( "TextContent expects a string in the constructor." );
61 }
62
63 $this->mText = $text;
64 }
65
66 /**
67 * @note Mutable subclasses MUST override this to return a copy!
68 *
69 * @return Content $this
70 */
71 public function copy() {
72 return $this; # NOTE: this is ok since TextContent are immutable.
73 }
74
75 public function getTextForSummary( $maxlength = 250 ) {
76 $text = $this->getText();
77
78 $truncatedtext = MediaWikiServices::getInstance()->getContentLanguage()->
79 truncateForDatabase( preg_replace( "/[\n\r]/", ' ', $text ), max( 0, $maxlength ) );
80
81 return $truncatedtext;
82 }
83
84 /**
85 * Returns the text's size in bytes.
86 *
87 * @return int
88 */
89 public function getSize() {
90 $text = $this->getText();
91
92 return strlen( $text );
93 }
94
95 /**
96 * Returns true if this content is not a redirect, and $wgArticleCountMethod
97 * is "any".
98 *
99 * @param bool|null $hasLinks If it is known whether this content contains links,
100 * provide this information here, to avoid redundant parsing to find out.
101 *
102 * @return bool
103 */
104 public function isCountable( $hasLinks = null ) {
105 global $wgArticleCountMethod;
106
107 if ( $this->isRedirect() ) {
108 return false;
109 }
110
111 if ( $wgArticleCountMethod === 'any' ) {
112 return true;
113 }
114
115 return false;
116 }
117
118 /**
119 * Returns the text represented by this Content object, as a string.
120 *
121 * @deprecated since 1.33 use getText() instead.
122 *
123 * @return string The raw text. Subclasses may guarantee a specific syntax here.
124 */
125 public function getNativeData() {
126 return $this->getText();
127 }
128
129 /**
130 * Returns the text represented by this Content object, as a string.
131 *
132 * @since 1.33
133 *
134 * @return string The raw text.
135 */
136 public function getText() {
137 return $this->mText;
138 }
139
140 /**
141 * Returns the text represented by this Content object, as a string.
142 *
143 * @return string The raw text.
144 */
145 public function getTextForSearchIndex() {
146 return $this->getText();
147 }
148
149 /**
150 * Returns attempts to convert this content object to wikitext,
151 * and then returns the text string. The conversion may be lossy.
152 *
153 * @note this allows any text-based content to be transcluded as if it was wikitext.
154 *
155 * @return string|bool The raw text, or false if the conversion failed.
156 */
157 public function getWikitextForTransclusion() {
158 /** @var WikitextContent $wikitext */
159 $wikitext = $this->convert( CONTENT_MODEL_WIKITEXT, 'lossy' );
160 '@phan-var WikitextContent $wikitext';
161
162 if ( $wikitext ) {
163 return $wikitext->getText();
164 } else {
165 return false;
166 }
167 }
168
169 /**
170 * Do a "\r\n" -> "\n" and "\r" -> "\n" transformation
171 * as well as trim trailing whitespace
172 *
173 * This was formerly part of Parser::preSaveTransform, but
174 * for non-wikitext content models they probably still want
175 * to normalize line endings without all of the other PST
176 * changes.
177 *
178 * @since 1.28
179 * @param string $text
180 * @return string
181 */
182 public static function normalizeLineEndings( $text ) {
183 return str_replace( [ "\r\n", "\r" ], "\n", rtrim( $text ) );
184 }
185
186 /**
187 * Returns a Content object with pre-save transformations applied.
188 *
189 * At a minimum, subclasses should make sure to call TextContent::normalizeLineEndings()
190 * either directly or part of Parser::preSaveTransform().
191 *
192 * @param Title $title
193 * @param User $user
194 * @param ParserOptions $popts
195 *
196 * @return Content
197 */
198 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
199 $text = $this->getText();
200 $pst = self::normalizeLineEndings( $text );
201
202 return ( $text === $pst ) ? $this : new static( $pst, $this->getModel() );
203 }
204
205 /**
206 * Diff this content object with another content object.
207 *
208 * @since 1.21
209 *
210 * @param Content $that The other content object to compare this content object to.
211 * @param Language|null $lang The language object to use for text segmentation.
212 * If not given, the content language is used.
213 *
214 * @return Diff A diff representing the changes that would have to be
215 * made to this content object to make it equal to $that.
216 */
217 public function diff( Content $that, Language $lang = null ) {
218 $this->checkModelID( $that->getModel() );
219 /** @var self $that */
220 '@phan-var self $that';
221 // @todo could implement this in DifferenceEngine and just delegate here?
222
223 if ( !$lang ) {
224 $lang = MediaWikiServices::getInstance()->getContentLanguage();
225 }
226
227 $otext = $this->getText();
228 $ntext = $that->getText();
229
230 # Note: Use native PHP diff, external engines don't give us abstract output
231 $ota = explode( "\n", $lang->segmentForDiff( $otext ) );
232 $nta = explode( "\n", $lang->segmentForDiff( $ntext ) );
233
234 $diff = new Diff( $ota, $nta );
235
236 return $diff;
237 }
238
239 /**
240 * Fills the provided ParserOutput object with information derived from the content.
241 * Unless $generateHtml was false, this includes an HTML representation of the content
242 * provided by getHtml().
243 *
244 * For content models listed in $wgTextModelsToParse, this method will call the MediaWiki
245 * wikitext parser on the text to extract any (wikitext) links, magic words, etc.
246 *
247 * Subclasses may override this to provide custom content processing.
248 * For custom HTML generation alone, it is sufficient to override getHtml().
249 *
250 * @param Title $title Context title for parsing
251 * @param int $revId Revision ID (for {{REVISIONID}})
252 * @param ParserOptions $options
253 * @param bool $generateHtml Whether or not to generate HTML
254 * @param ParserOutput &$output The output object to fill (reference).
255 */
256 protected function fillParserOutput( Title $title, $revId,
257 ParserOptions $options, $generateHtml, ParserOutput &$output
258 ) {
259 global $wgTextModelsToParse;
260
261 if ( in_array( $this->getModel(), $wgTextModelsToParse ) ) {
262 // parse just to get links etc into the database, HTML is replaced below.
263 $output = MediaWikiServices::getInstance()->getParser()
264 ->parse( $this->getText(), $title, $options, true, true, $revId );
265 }
266
267 if ( $generateHtml ) {
268 $html = $this->getHtml();
269 } else {
270 $html = '';
271 }
272
273 $output->clearWrapperDivClass();
274 $output->setText( $html );
275 }
276
277 /**
278 * Generates an HTML version of the content, for display. Used by
279 * fillParserOutput() to provide HTML for the ParserOutput object.
280 *
281 * Subclasses may override this to provide a custom HTML rendering.
282 * If further information is to be derived from the content (such as
283 * categories), the fillParserOutput() method can be overridden instead.
284 *
285 * For backwards-compatibility, this default implementation just calls
286 * getHighlightHtml().
287 *
288 * @return string An HTML representation of the content
289 */
290 protected function getHtml() {
291 return $this->getHighlightHtml();
292 }
293
294 /**
295 * Generates an HTML version of the content, for display.
296 *
297 * This default implementation returns an HTML-escaped version
298 * of the raw text content.
299 *
300 * @note The functionality of this method should really be implemented
301 * in getHtml(), and subclasses should override getHtml() if needed.
302 * getHighlightHtml() is kept around for backward compatibility with
303 * extensions that already override it.
304 *
305 * @deprecated since 1.24. Use getHtml() instead. In particular, subclasses overriding
306 * getHighlightHtml() should override getHtml() instead.
307 *
308 * @return string An HTML representation of the content
309 */
310 protected function getHighlightHtml() {
311 return htmlspecialchars( $this->getText() );
312 }
313
314 /**
315 * This implementation provides lossless conversion between content models based
316 * on TextContent.
317 *
318 * @param string $toModel The desired content model, use the CONTENT_MODEL_XXX flags.
319 * @param string $lossy Flag, set to "lossy" to allow lossy conversion. If lossy conversion is not
320 * allowed, full round-trip conversion is expected to work without losing information.
321 *
322 * @return Content|bool A content object with the content model $toModel, or false if that
323 * conversion is not supported.
324 *
325 * @see Content::convert()
326 */
327 public function convert( $toModel, $lossy = '' ) {
328 $converted = parent::convert( $toModel, $lossy );
329
330 if ( $converted !== false ) {
331 return $converted;
332 }
333
334 $toHandler = ContentHandler::getForModelID( $toModel );
335
336 if ( $toHandler instanceof TextContentHandler ) {
337 // NOTE: ignore content serialization format - it's just text anyway.
338 $text = $this->getText();
339 $converted = $toHandler->unserializeContent( $text );
340 }
341
342 return $converted;
343 }
344
345 }