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