1ec4b0c569c88d53ece10c09119b489f9788c241
[lhc/web/wiklou.git] / includes / Content.php
1 <?php
2
3 /**
4 * A content object represents page content, e.g. the text to show on a page.
5 * Content objects have no knowledge about how they relate to Wiki pages.
6 * Content objects are imutable.
7 *
8 */
9 abstract class Content {
10
11 public function __construct( $modelName = null ) {
12 $this->mModelName = $modelName;
13 }
14
15 public function getModelName() {
16 return $this->mModelName;
17 }
18
19 protected function checkModelName( $modelName ) {
20 if ( $modelName !== $this->mModelName ) {
21 throw new MWException( "Bad content model: expected " . $this->mModelName . " but got found " . $modelName );
22 }
23 }
24
25 public function getContentHandler() {
26 return ContentHandler::getForContent( $this );
27 }
28
29 public function getDefaultFormat() {
30 return $this->getContentHandler()->getDefaultFormat();
31 }
32
33 public function getSupportedFormats() {
34 return $this->getContentHandler()->getSupportedFormats();
35 }
36
37 public function isSupportedFormat( $format ) {
38 if ( !$format ) return true; # this means "use the default"
39
40 return $this->getContentHandler()->isSupportedFormat( $format );
41 }
42
43 protected function checkFormat( $format ) {
44 if ( !$this->isSupportedFormat( $format ) ) {
45 throw new MWException( "Format $format is not supported for content model " . $this->getModelName() );
46 }
47 }
48
49 public function serialize( $format = null ) {
50 return $this->getContentHandler()->serialize( $this, $format );
51 }
52
53 /**
54 * @return String a string representing the content in a way useful for building a full text search index.
55 * If no useful representation exists, this method returns an empty string.
56 */
57 public abstract function getTextForSearchIndex( );
58
59 /**
60 * @return String the wikitext to include when another page includes this content, or false if the content is not
61 * includable in a wikitext page.
62 */
63 #TODO: allow native handling, bypassing wikitext representation, like for includable special pages.
64 public abstract function getWikitextForTransclusion( ); #FIXME: use in parser, etc!
65
66 /**
67 * Returns a textual representation of the content suitable for use in edit summaries and log messages.
68 *
69 * @param int $maxlength maximum length of the summary text
70 * @return String the summary text
71 */
72 public abstract function getTextForSummary( $maxlength = 250 );
73
74 /**
75 * Returns native represenation of the data. Interpretation depends on the data model used,
76 * as given by getDataModel().
77 *
78 * @return mixed the native representation of the content. Could be a string, a nested array
79 * structure, an object, a binary blob... anything, really.
80 */
81 public abstract function getNativeData( ); #FIXME: review all calls carefully, caller must be aware of content model!
82
83 /**
84 * returns the content's nominal size in bogo-bytes.
85 *
86 * @return int
87 */
88 public abstract function getSize( );
89
90 public function isEmpty() {
91 return $this->getSize() == 0;
92 }
93
94 public function equals( Content $that ) {
95 if ( empty( $that ) ) return false;
96 if ( $that === $this ) return true;
97 if ( $that->getModelName() !== $this->getModelName() ) return false;
98
99 return $this->getNativeData() == $that->getNativeData();
100 }
101
102 /**
103 * Returns true if this content is countable as a "real" wiki page, provided
104 * that it's also in a countable location (e.g. a current revision in the main namespace).
105 *
106 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
107 * to avoid redundant parsing to find out.
108 */
109 public abstract function isCountable( $hasLinks = null ) ;
110
111 /**
112 * @param null|Title $title
113 * @param null $revId
114 * @param null|ParserOptions $options
115 * @return ParserOutput
116 */
117 public abstract function getParserOutput( Title $title = null, $revId = null, ParserOptions $options = NULL );
118
119 /**
120 * Construct the redirect destination from this content and return an
121 * array of Titles, or null if this content doesn't represent a redirect.
122 * The last element in the array is the final destination after all redirects
123 * have been resolved (up to $wgMaxRedirects times).
124 *
125 * @return Array of Titles, with the destination last
126 */
127 public function getRedirectChain() {
128 return null;
129 }
130
131 /**
132 * Construct the redirect destination from this content and return an
133 * array of Titles, or null if this content doesn't represent a redirect.
134 * This will only return the immediate redirect target, useful for
135 * the redirect table and other checks that don't need full recursion.
136 *
137 * @return Title: The corresponding Title
138 */
139 public function getRedirectTarget() {
140 return null;
141 }
142
143 /**
144 * Construct the redirect destination from this content and return the
145 * Title, or null if this content doesn't represent a redirect.
146 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
147 * in order to provide (hopefully) the Title of the final destination instead of another redirect.
148 *
149 * @return Title
150 */
151 public function getUltimateRedirectTarget() {
152 return null;
153 }
154
155 public function isRedirect() {
156 return $this->getRedirectTarget() != null;
157 }
158
159 /**
160 * Returns the section with the given id.
161 *
162 * The default implementation returns null.
163 *
164 * @param String $sectionId the section's id
165 * @return Content|Boolean|null the section, or false if no such section exist, or null if sections are not supported
166 */
167 public function getSection( $sectionId ) {
168 return null;
169 }
170
171 /**
172 * Replaces a section of the content and returns a Content object with the section replaced.
173 *
174 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
175 * @param $with Content: new content of the section
176 * @param $sectionTitle String: new section's subject, only if $section is 'new'
177 * @return string Complete article text, or null if error
178 */
179 public function replaceSection( $section, Content $with, $sectionTitle = '' ) {
180 return $this;
181 }
182
183 /**
184 * Returns a Content object with pre-save transformations applied (or this object if no transformations apply).
185 *
186 * @param Title $title
187 * @param User $user
188 * @param null|ParserOptions $popts
189 * @return Content
190 */
191 public function preSaveTransform( Title $title, User $user, ParserOptions $popts = null ) {
192 return $this;
193 }
194
195 /**
196 * Returns a new WikitextContent object with the given section heading prepended, if supported.
197 * The default implementation just returns this Content object unmodified, ignoring the section header.
198 *
199 * @param $header String
200 * @return Content
201 */
202 public function addSectionHeader( $header ) {
203 return $this;
204 }
205
206 /**
207 * Returns a Content object with preload transformations applied (or this object if no transformations apply).
208 *
209 * @param Title $title
210 * @param null|ParserOptions $popts
211 * @return Content
212 */
213 public function preloadTransform( Title $title, ParserOptions $popts = null ) {
214 return $this;
215 }
216
217 #TODO: implement specialized ParserOutput for Wikidata model
218 #TODO: provide "combined" ParserOutput for Multipart... somehow.
219
220 # XXX: isCacheable( ) # can/should we do this here?
221
222 # TODO: EditPage::getPreloadedText( $preload ) // $wgParser->getPreloadText
223 # TODO: tie into EditPage, make it use Content-objects throughout, make edit form aware of content model and format
224 # TODO: make model-aware diff view!
225 # TODO: handle ImagePage and CategoryPage
226
227 # TODO: Title::newFromRedirectRecurse( $this->getRawText() );
228
229 # TODO: tie into API to provide contentModel for Revisions
230 # TODO: tie into API to provide serialized version and contentFormat for Revisions
231 # TODO: tie into API edit interface
232
233 }
234
235 /**
236 * Content object implementation for representing flat text. The
237 */
238 abstract class TextContent extends Content {
239 public function __construct( $text, $modelName = null ) {
240 parent::__construct($modelName);
241
242 $this->mText = $text;
243 }
244
245 public function getTextForSummary( $maxlength = 250 ) {
246 global $wgContLang;
247
248 $text = $this->getNativeData();
249
250 $truncatedtext = $wgContLang->truncate(
251 preg_replace( "/[\n\r]/", ' ', $text ),
252 max( 0, $maxlength ) );
253
254 return $truncatedtext;
255 }
256
257 /**
258 * returns the content's nominal size in bogo-bytes.
259 */
260 public function getSize( ) { #FIXME: use! replace strlen in WikiPage.
261 $text = $this->getNativeData( );
262 return strlen( $text );
263 }
264
265 /**
266 * Returns true if this content is not a redirect, and $wgArticleCountMethod is "any".
267 *
268 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
269 * to avoid redundant parsing to find out.
270 */
271 public function isCountable( $hasLinks = null ) {
272 global $wgArticleCountMethod;
273
274 if ( $this->isRedirect( ) ) {
275 return false;
276 }
277
278 if ( $wgArticleCountMethod === 'any' ) {
279 return true;
280 }
281
282 return false;
283 }
284
285 /**
286 * Returns the text represented by this Content object, as a string.
287 *
288 * @return String the raw text
289 */
290 public function getNativeData( ) {
291 $text = $this->mText;
292 return $text;
293 }
294
295 /**
296 * Returns the text represented by this Content object, as a string.
297 *
298 * @return String the raw text
299 */
300 public function getTextForSearchIndex( ) { #FIXME: use!
301 return $this->getNativeData();
302 }
303
304 /**
305 * Returns the text represented by this Content object, as a string.
306 *
307 * @return String the raw text
308 */
309 public function getWikitextForTransclusion( ) { #FIXME: use!
310 return $this->getNativeData();
311 }
312
313 /**
314 * Returns a generic ParserOutput object, wrapping the HTML returned by getHtml().
315 *
316 * @return ParserOutput representing the HTML form of the text
317 */
318 public function getParserOutput( Title $title = null, $revId = null, ParserOptions $options = null ) {
319 # generic implementation, relying on $this->getHtml()
320
321 $html = $this->getHtml( $options );
322 $po = new ParserOutput( $html );
323
324 return $po;
325 }
326
327 protected abstract function getHtml( );
328
329 }
330
331 class WikitextContent extends TextContent {
332 public function __construct( $text ) {
333 parent::__construct($text, CONTENT_MODEL_WIKITEXT);
334
335 $this->mDefaultParserOptions = null; #TODO: use per-class static member?!
336 }
337
338 protected function getHtml( ) {
339 throw new MWException( "getHtml() not implemented for wikitext. Use getParserOutput()->getText()." );
340 }
341
342 public function getDefaultParserOptions() {
343 global $wgUser, $wgContLang;
344
345 if ( !$this->mDefaultParserOptions ) { #TODO: use per-class static member?!
346 $this->mDefaultParserOptions = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
347 }
348
349 return $this->mDefaultParserOptions;
350 }
351
352 /**
353 * Returns a ParserOutput object reesulting from parsing the content's text using $wgParser
354 *
355 * @return ParserOutput representing the HTML form of the text
356 */
357 public function getParserOutput( Title $title = null, $revId = null, ParserOptions $options = null ) {
358 global $wgParser;
359
360 if ( !$options ) {
361 $options = $this->getDefaultParserOptions();
362 }
363
364 $po = $wgParser->parse( $this->mText, $title, $options, true, true, $revId );
365
366 return $po;
367 }
368
369 /**
370 * Returns the section with the given id.
371 *
372 * @param String $sectionId the section's id
373 * @return Content|false|null the section, or false if no such section exist, or null if sections are not supported
374 */
375 public function getSection( $section ) {
376 global $wgParser;
377
378 $text = $this->getNativeData();
379 $sect = $wgParser->getSection( $text, $section, false );
380
381 return new WikitextContent( $sect );
382 }
383
384 /**
385 * Replaces a section in the wikitext
386 *
387 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
388 * @param $with Content: new content of the section
389 * @param $sectionTitle String: new section's subject, only if $section is 'new'
390 * @return string Complete article text, or null if error
391 */
392 public function replaceSection( $section, Content $with, $sectionTitle = '' ) {
393 global $wgParser;
394
395 wfProfileIn( __METHOD__ );
396
397 $myModelName = $this->getModelName();
398 $sectionModelName = $with->getModelName();
399
400 if ( $sectionModelName != $myModelName ) {
401 throw new MWException( "Incompatible content model for section: document uses $myModelName, section uses $sectionModelName." );
402 }
403
404 $oldtext = $this->getNativeData();
405 $text = $with->getNativeData();
406
407 if ( $section == 'new' ) {
408 # Inserting a new section
409 $subject = $sectionTitle ? wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
410 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
411 $text = strlen( trim( $oldtext ) ) > 0
412 ? "{$oldtext}\n\n{$subject}{$text}"
413 : "{$subject}{$text}";
414 }
415 } else {
416 # Replacing an existing section; roll out the big guns
417 global $wgParser;
418
419 $text = $wgParser->replaceSection( $oldtext, $section, $text );
420 }
421
422 $newContent = new WikitextContent( $text );
423
424 wfProfileOut( __METHOD__ );
425 return $newContent;
426 }
427
428 /**
429 * Returns a new WikitextContent object with the given section heading prepended.
430 *
431 * @param $header String
432 * @return Content
433 */
434 public function addSectionHeader( $header ) {
435 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle ) . "\n\n" . $this->getNativeData();
436
437 return new WikitextContent( $text );
438 }
439
440 /**
441 * Returns a Content object with pre-save transformations applied (or this object if no transformations apply).
442 *
443 * @param Title $title
444 * @param User $user
445 * @param null|ParserOptions $popts
446 * @return Content
447 */
448 public function preSaveTransform( Title $title, User $user, ParserOptions $popts = null ) {
449 global $wgParser;
450
451 if ( $popts == null ) $popts = $this->getDefaultParserOptions();
452
453 $text = $this->getNativeData();
454 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
455
456 return new WikitextContent( $pst );
457 }
458
459 /**
460 * Returns a Content object with preload transformations applied (or this object if no transformations apply).
461 *
462 * @param Title $title
463 * @param null|ParserOptions $popts
464 * @return Content
465 */
466 public function preloadTransform( Title $title, ParserOptions $popts = null ) {
467 global $wgParser;
468
469 if ( $popts == null ) $popts = $this->getDefaultParserOptions();
470
471 $text = $this->getNativeData();
472 $plt = $wgParser->getPreloadText( $text, $title, $popts );
473
474 return new WikitextContent( $plt );
475 }
476
477 public function getRedirectChain() {
478 $text = $this->getNativeData();
479 return Title::newFromRedirectArray( $text );
480 }
481
482 public function getRedirectTarget() {
483 $text = $this->getNativeData();
484 return Title::newFromRedirect( $text );
485 }
486
487 public function getUltimateRedirectTarget() {
488 $text = $this->getNativeData();
489 return Title::newFromRedirectRecurse( $text );
490 }
491
492 /**
493 * Returns true if this content is not a redirect, and this content's text is countable according to
494 * the criteria defiend by $wgArticleCountMethod.
495 *
496 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
497 * to avoid redundant parsing to find out.
498 */
499 public function isCountable( $hasLinks = null ) {
500 global $wgArticleCountMethod;
501
502 if ( $this->isRedirect( ) ) {
503 return false;
504 }
505
506 $text = $this->getNativeData();
507
508 switch ( $wgArticleCountMethod ) {
509 case 'any':
510 return true;
511 case 'comma':
512 if ( $text === false ) {
513 $text = $this->getRawText();
514 }
515 return strpos( $text, ',' ) !== false;
516 case 'link':
517 if ( $hasLinks === null ) { # not know, find out
518 $po = $this->getParserOutput();
519 $links = $po->getLinks();
520 $hasLinks = !empty( $links );
521 }
522
523 return $hasLinks;
524 }
525 }
526
527 public function getTextForSummary( $maxlength = 250 ) {
528 $truncatedtext = parent::getTextForSummary( $maxlength );
529
530 #clean up unfinished links
531 #XXX: make this optional? wasn't there in autosummary, but required for deletion summary.
532 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
533
534 return $truncatedtext;
535 }
536
537 }
538
539 class MessageContent extends TextContent {
540 public function __construct( $msg_key, $params = null, $options = null ) {
541 parent::__construct(null, CONTENT_MODEL_WIKITEXT); #XXX: messages may be wikitext, html or plain text! and maybe even something else entirely.
542
543 $this->mMessageKey = $msg_key;
544
545 $this->mParameters = $params;
546
547 if ( !$options ) $options = array();
548 $this->mOptions = $options;
549
550 $this->mHtmlOptions = null;
551 }
552
553 /**
554 * Returns the message as rendered HTML, using the options supplied to the constructor plus "parse".
555 */
556 protected function getHtml( ) {
557 $opt = array_merge( $this->mOptions, array('parse') );
558
559 return wfMsgExt( $this->mMessageKey, $this->mParameters, $opt );
560 }
561
562
563 /**
564 * Returns the message as raw text, using the options supplied to the constructor minus "parse" and "parseinline".
565 */
566 public function getNativeData( ) {
567 $opt = array_diff( $this->mOptions, array('parse', 'parseinline') );
568
569 return wfMsgExt( $this->mMessageKey, $this->mParameters, $opt );
570 }
571
572 }
573
574
575 class JavaScriptContent extends TextContent {
576 public function __construct( $text ) {
577 parent::__construct($text, CONTENT_MODEL_JAVASCRIPT);
578 }
579
580 protected function getHtml( ) {
581 $html = "";
582 $html .= "<pre class=\"mw-code mw-js\" dir=\"ltr\">\n";
583 $html .= htmlspecialchars( $this->getNativeData() );
584 $html .= "\n</pre>\n";
585
586 return $html;
587 }
588
589 }
590
591 class CssContent extends TextContent {
592 public function __construct( $text ) {
593 parent::__construct($text, CONTENT_MODEL_CSS);
594 }
595
596 protected function getHtml( ) {
597 $html = "";
598 $html .= "<pre class=\"mw-code mw-css\" dir=\"ltr\">\n";
599 $html .= htmlspecialchars( $this->getNativeData() );
600 $html .= "\n</pre>\n";
601
602 return $html;
603 }
604 }
605
606 #FUTURE: special type for redirects?!
607 #FUTURE: MultipartMultipart < WikipageContent (Main + Links + X)
608 #FUTURE: LinksContent < LanguageLinksContent, CategoriesContent
609 #EXAMPLE: CoordinatesContent
610 #EXAMPLE: WikidataContent