Merge "objectcache: Fixes WinCache increment losing TTL."
[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 $wikitext = $this->convert( CONTENT_MODEL_WIKITEXT, 'lossy' );
159
160 if ( $wikitext ) {
161 return $wikitext->getText();
162 } else {
163 return false;
164 }
165 }
166
167 /**
168 * Do a "\r\n" -> "\n" and "\r" -> "\n" transformation
169 * as well as trim trailing whitespace
170 *
171 * This was formerly part of Parser::preSaveTransform, but
172 * for non-wikitext content models they probably still want
173 * to normalize line endings without all of the other PST
174 * changes.
175 *
176 * @since 1.28
177 * @param string $text
178 * @return string
179 */
180 public static function normalizeLineEndings( $text ) {
181 return str_replace( [ "\r\n", "\r" ], "\n", rtrim( $text ) );
182 }
183
184 /**
185 * Returns a Content object with pre-save transformations applied.
186 *
187 * At a minimum, subclasses should make sure to call TextContent::normalizeLineEndings()
188 * either directly or part of Parser::preSaveTransform().
189 *
190 * @param Title $title
191 * @param User $user
192 * @param ParserOptions $popts
193 *
194 * @return Content
195 */
196 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
197 $text = $this->getText();
198 $pst = self::normalizeLineEndings( $text );
199
200 return ( $text === $pst ) ? $this : new static( $pst, $this->getModel() );
201 }
202
203 /**
204 * Diff this content object with another content object.
205 *
206 * @since 1.21
207 *
208 * @param Content $that The other content object to compare this content object to.
209 * @param Language|null $lang The language object to use for text segmentation.
210 * If not given, the content language is used.
211 *
212 * @return Diff A diff representing the changes that would have to be
213 * made to this content object to make it equal to $that.
214 */
215 public function diff( Content $that, Language $lang = null ) {
216 $this->checkModelID( $that->getModel() );
217
218 // @todo could implement this in DifferenceEngine and just delegate here?
219
220 if ( !$lang ) {
221 $lang = MediaWikiServices::getInstance()->getContentLanguage();
222 }
223
224 $otext = $this->getText();
225 $ntext = $that->getText();
226
227 # Note: Use native PHP diff, external engines don't give us abstract output
228 $ota = explode( "\n", $lang->segmentForDiff( $otext ) );
229 $nta = explode( "\n", $lang->segmentForDiff( $ntext ) );
230
231 $diff = new Diff( $ota, $nta );
232
233 return $diff;
234 }
235
236 /**
237 * Fills the provided ParserOutput object with information derived from the content.
238 * Unless $generateHtml was false, this includes an HTML representation of the content
239 * provided by getHtml().
240 *
241 * For content models listed in $wgTextModelsToParse, this method will call the MediaWiki
242 * wikitext parser on the text to extract any (wikitext) links, magic words, etc.
243 *
244 * Subclasses may override this to provide custom content processing.
245 * For custom HTML generation alone, it is sufficient to override getHtml().
246 *
247 * @param Title $title Context title for parsing
248 * @param int $revId Revision ID (for {{REVISIONID}})
249 * @param ParserOptions $options
250 * @param bool $generateHtml Whether or not to generate HTML
251 * @param ParserOutput &$output The output object to fill (reference).
252 */
253 protected function fillParserOutput( Title $title, $revId,
254 ParserOptions $options, $generateHtml, ParserOutput &$output
255 ) {
256 global $wgParser, $wgTextModelsToParse;
257
258 if ( in_array( $this->getModel(), $wgTextModelsToParse ) ) {
259 // parse just to get links etc into the database, HTML is replaced below.
260 $output = $wgParser->parse( $this->getText(), $title, $options, true, true, $revId );
261 }
262
263 if ( $generateHtml ) {
264 $html = $this->getHtml();
265 } else {
266 $html = '';
267 }
268
269 $output->clearWrapperDivClass();
270 $output->setText( $html );
271 }
272
273 /**
274 * Generates an HTML version of the content, for display. Used by
275 * fillParserOutput() to provide HTML for the ParserOutput object.
276 *
277 * Subclasses may override this to provide a custom HTML rendering.
278 * If further information is to be derived from the content (such as
279 * categories), the fillParserOutput() method can be overridden instead.
280 *
281 * For backwards-compatibility, this default implementation just calls
282 * getHighlightHtml().
283 *
284 * @return string An HTML representation of the content
285 */
286 protected function getHtml() {
287 return $this->getHighlightHtml();
288 }
289
290 /**
291 * Generates an HTML version of the content, for display.
292 *
293 * This default implementation returns an HTML-escaped version
294 * of the raw text content.
295 *
296 * @note The functionality of this method should really be implemented
297 * in getHtml(), and subclasses should override getHtml() if needed.
298 * getHighlightHtml() is kept around for backward compatibility with
299 * extensions that already override it.
300 *
301 * @deprecated since 1.24. Use getHtml() instead. In particular, subclasses overriding
302 * getHighlightHtml() should override getHtml() instead.
303 *
304 * @return string An HTML representation of the content
305 */
306 protected function getHighlightHtml() {
307 return htmlspecialchars( $this->getText() );
308 }
309
310 /**
311 * This implementation provides lossless conversion between content models based
312 * on TextContent.
313 *
314 * @param string $toModel The desired content model, use the CONTENT_MODEL_XXX flags.
315 * @param string $lossy Flag, set to "lossy" to allow lossy conversion. If lossy conversion is not
316 * allowed, full round-trip conversion is expected to work without losing information.
317 *
318 * @return Content|bool A content object with the content model $toModel, or false if that
319 * conversion is not supported.
320 *
321 * @see Content::convert()
322 */
323 public function convert( $toModel, $lossy = '' ) {
324 $converted = parent::convert( $toModel, $lossy );
325
326 if ( $converted !== false ) {
327 return $converted;
328 }
329
330 $toHandler = ContentHandler::getForModelID( $toModel );
331
332 if ( $toHandler instanceof TextContentHandler ) {
333 // NOTE: ignore content serialization format - it's just text anyway.
334 $text = $this->getText();
335 $converted = $toHandler->unserializeContent( $text );
336 }
337
338 return $converted;
339 }
340
341 }