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