3 * A content object represents page content, e.g. the text to show on a page.
4 * Content objects have no knowledge about how they relate to Wiki pages.
8 abstract class Content
{
11 * Name of the content model this Content object represents.
12 * Use with CONTENT_MODEL_XXX constants
14 * @var String $model_id
21 * @return String a string representing the content in a way useful for building a full text search index.
22 * If no useful representation exists, this method returns an empty string.
24 public abstract function getTextForSearchIndex( );
29 * @return String the wikitext to include when another page includes this content, or false if the content is not
30 * includable in a wikitext page.
32 * @TODO: allow native handling, bypassing wikitext representation, like for includable special pages.
33 * @TODO: use in parser, etc!
35 public abstract function getWikitextForTransclusion( );
38 * Returns a textual representation of the content suitable for use in edit summaries and log messages.
42 * @param int $maxlength maximum length of the summary text
43 * @return String the summary text
45 public abstract function getTextForSummary( $maxlength = 250 );
48 * Returns native representation of the data. Interpretation depends on the data model used,
49 * as given by getDataModel().
53 * @return mixed the native representation of the content. Could be a string, a nested array
54 * structure, an object, a binary blob... anything, really.
56 * @NOTE: review all calls carefully, caller must be aware of content model!
58 public abstract function getNativeData( );
61 * returns the content's nominal size in bogo-bytes.
65 public abstract function getSize( );
68 * @param int $model_id
70 public function __construct( $model_id = null ) {
71 $this->model_id
= $model_id;
75 * Returns the id of the content model used by this content objects.
76 * Corresponds to the CONTENT_MODEL_XXX constants.
80 * @return int the model id
82 public function getModel() {
83 return $this->model_id
;
87 * Throws an MWException if $model_id is not the id of the content model
88 * supported by this Content object.
90 * @param int $model_id the model to check
94 protected function checkModelID( $model_id ) {
95 if ( $model_id !== $this->model_id
) {
96 $model_name = ContentHandler
::getContentModelName( $model_id );
97 $own_model_name = ContentHandler
::getContentModelName( $this->model_id
);
99 throw new MWException( "Bad content model: expected {$this->model_id} ($own_model_name) but got found $model_id ($model_name)." );
104 * Convenience method that returns the ContentHandler singleton for handling the content
105 * model this Content object uses.
107 * Shorthand for ContentHandler::getForContent( $this )
111 * @return ContentHandler
113 public function getContentHandler() {
114 return ContentHandler
::getForContent( $this );
118 * Convenience method that returns the default serialization format for the content model
119 * model this Content object uses.
121 * Shorthand for $this->getContentHandler()->getDefaultFormat()
125 * @return ContentHandler
127 public function getDefaultFormat() {
128 return $this->getContentHandler()->getDefaultFormat();
132 * Convenience method that returns the list of serialization formats supported
133 * for the content model model this Content object uses.
135 * Shorthand for $this->getContentHandler()->getSupportedFormats()
139 * @return array of supported serialization formats
141 public function getSupportedFormats() {
142 return $this->getContentHandler()->getSupportedFormats();
146 * Returns true if $format is a supported serialization format for this Content object,
149 * Note that this will always return true if $format is null, because null stands for the
150 * default serialization.
152 * Shorthand for $this->getContentHandler()->isSupportedFormat( $format )
156 * @param String $format the format to check
157 * @return bool whether the format is supported
159 public function isSupportedFormat( $format ) {
161 return true; // this means "use the default"
164 return $this->getContentHandler()->isSupportedFormat( $format );
168 * Throws an MWException if $this->isSupportedFormat( $format ) doesn't return true.
171 * @throws MWException
173 protected function checkFormat( $format ) {
174 if ( !$this->isSupportedFormat( $format ) ) {
175 throw new MWException( "Format $format is not supported for content model " . $this->getModel() );
180 * Convenience method for serializing this Content object.
182 * Shorthand for $this->getContentHandler()->serializeContent( $this, $format )
186 * @param null|String $format the desired serialization format (or null for the default format).
187 * @return String serialized form of this Content object
189 public function serialize( $format = null ) {
190 return $this->getContentHandler()->serializeContent( $this, $format );
194 * Returns true if this Content object represents empty content.
198 * @return bool whether this Content object is empty
200 public function isEmpty() {
201 return $this->getSize() == 0;
205 * Returns if the content is valid. This is intended for local validity checks, not considering global consistency.
206 * It needs to be valid before it can be saved.
208 * This default implementation always returns true.
214 public function isValid() {
219 * Returns true if this Content objects is conceptually equivalent to the given Content object.
221 * Will returns false if $that is null.
222 * Will return true if $that === $this.
223 * Will return false if $that->getModelName() != $this->getModel().
224 * Will return false if $that->getNativeData() is not equal to $this->getNativeData(),
225 * where the meaning of "equal" depends on the actual data model.
227 * Implementations should be careful to make equals() transitive and reflexive:
229 * * $a->equals( $b ) <=> $b->equals( $a )
230 * * $a->equals( $b ) && $b->equals( $c ) ==> $a->equals( $c )
234 * @param Content $that the Content object to compare to
235 * @return bool true if this Content object is euqual to $that, false otherwise.
237 public function equals( Content
$that = null ) {
238 if ( is_null( $that ) ){
242 if ( $that === $this ) {
246 if ( $that->getModel() !== $this->getModel() ) {
250 return $this->getNativeData() === $that->getNativeData();
254 * Return a copy of this Content object. The following must be true for the object returned
255 * if $copy = $original->copy()
257 * * get_class($original) === get_class($copy)
258 * * $original->getModel() === $copy->getModel()
259 * * $original->equals( $copy )
261 * If and only if the Content object is immutable, the copy() method can and should
262 * return $this. That is, $copy === $original may be true, but only for immutable content
267 * @return Content. A copy of this object
269 public abstract function copy( );
272 * Returns true if this content is countable as a "real" wiki page, provided
273 * that it's also in a countable location (e.g. a current revision in the main namespace).
277 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
278 * to avoid redundant parsing to find out.
281 public abstract function isCountable( $hasLinks = null ) ;
284 * @param Title $title
286 * @param null|ParserOptions $options
287 * @param Boolean $generateHtml whether to generate Html (default: true). If false,
288 * the result of calling getText() on the ParserOutput object returned by
289 * this method is undefined.
293 * @return ParserOutput
295 public abstract function getParserOutput( Title
$title, $revId = null, ParserOptions
$options = null, $generateHtml = true ); #TODO: move to ContentHandler; #TODO: rename to getRenderOutput()
296 #TODO: make RenderOutput and RenderOptions base classes
299 * Returns a list of DataUpdate objects for recording information about this Content in some secondary
300 * data store. If the optional second argument, $old, is given, the updates may model only the changes that
301 * need to be made to replace information about the old content with information about the new content.
303 * This default implementation calls $this->getParserOutput( $title, null, null, false ), and then
304 * calls getSecondaryDataUpdates( $title, $recursive ) on the resulting ParserOutput object.
306 * Subclasses may implement this to determine the necessary updates more efficiently, or make use of information
307 * about the old content.
309 * @param Title $title the context for determining the necessary updates
310 * @param Content|null $old a Content object representing the previous content, i.e. the content being
311 * replaced by this Content object.
312 * @param bool $recursive whether to include recursive updates (default: false).
314 * @return Array. A list of DataUpdate objects for putting information about this content object somewhere.
318 public function getSecondaryDataUpdates( Title
$title, Content
$old = null, $recursive = false ) {
319 $po = $this->getParserOutput( $title, null, null, false );
320 return $po->getSecondaryDataUpdates( $title, $recursive );
324 * Construct the redirect destination from this content and return an
325 * array of Titles, or null if this content doesn't represent a redirect.
326 * The last element in the array is the final destination after all redirects
327 * have been resolved (up to $wgMaxRedirects times).
331 * @return Array of Titles, with the destination last
333 public function getRedirectChain() {
338 * Construct the redirect destination from this content and return a Title,
339 * or null if this content doesn't represent a redirect.
340 * This will only return the immediate redirect target, useful for
341 * the redirect table and other checks that don't need full recursion.
345 * @return Title: The corresponding Title
347 public function getRedirectTarget() {
352 * Construct the redirect destination from this content and return the
353 * Title, or null if this content doesn't represent a redirect.
354 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
355 * in order to provide (hopefully) the Title of the final destination instead of another redirect.
361 public function getUltimateRedirectTarget() {
370 public function isRedirect() {
371 return $this->getRedirectTarget() !== null;
375 * Returns the section with the given id.
377 * The default implementation returns null.
381 * @param String $sectionId the section's id, given as a numeric string. The id "0" retrieves the section before
382 * the first heading, "1" the text between the first heading (included) and the second heading (excluded), etc.
383 * @return Content|Boolean|null the section, or false if no such section exist, or null if sections are not supported
385 public function getSection( $sectionId ) {
390 * Replaces a section of the content and returns a Content object with the section replaced.
394 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
395 * @param $with Content: new content of the section
396 * @param $sectionTitle String: new section's subject, only if $section is 'new'
397 * @return string Complete article text, or null if error
399 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
404 * Returns a Content object with pre-save transformations applied (or this object if no transformations apply).
408 * @param Title $title
410 * @param null|ParserOptions $popts
413 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
418 * Returns a new WikitextContent object with the given section heading prepended, if supported.
419 * The default implementation just returns this Content object unmodified, ignoring the section header.
423 * @param $header String
426 public function addSectionHeader( $header ) {
431 * Returns a Content object with preload transformations applied (or this object if no transformations apply).
435 * @param Title $title
436 * @param null|ParserOptions $popts
439 public function preloadTransform( Title
$title, ParserOptions
$popts ) {
443 # TODO: handle ImagePage and CategoryPage
444 # TODO: make sure we cover lucene search / wikisearch.
445 # TODO: make sure ReplaceTemplates still works
446 # FUTURE: nice&sane integration of GeSHi syntax highlighting
447 # [11:59] <vvv> Hooks are ugly; make CodeHighlighter interface and a config to set the class which handles syntax highlighting
448 # [12:00] <vvv> And default it to a DummyHighlighter
450 # TODO: make sure we cover the external editor interface (does anyone actually use that?!)
452 # TODO: tie into API to provide contentModel for Revisions
453 # TODO: tie into API to provide serialized version and contentFormat for Revisions
454 # TODO: tie into API edit interface
455 # FUTURE: make EditForm plugin for EditPage
457 # FUTURE: special type for redirects?!
458 # FUTURE: MultipartMultipart < WikipageContent (Main + Links + X)
459 # FUTURE: LinksContent < LanguageLinksContent, CategoriesContent
462 * Content object implementation for representing flat text.
464 * TextContent instances are immutable
468 abstract class TextContent
extends Content
{
470 public function __construct( $text, $model_id = null ) {
471 parent
::__construct( $model_id );
473 $this->mText
= $text;
476 public function copy() {
477 return $this; #NOTE: this is ok since TextContent are immutable.
480 public function getTextForSummary( $maxlength = 250 ) {
483 $text = $this->getNativeData();
485 $truncatedtext = $wgContLang->truncate(
486 preg_replace( "/[\n\r]/", ' ', $text ),
487 max( 0, $maxlength ) );
489 return $truncatedtext;
493 * returns the text's size in bytes.
495 * @return int the size
497 public function getSize( ) {
498 $text = $this->getNativeData( );
499 return strlen( $text );
503 * Returns true if this content is not a redirect, and $wgArticleCountMethod is "any".
505 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
506 * to avoid redundant parsing to find out.
508 * @return bool true if the content is countable
510 public function isCountable( $hasLinks = null ) {
511 global $wgArticleCountMethod;
513 if ( $this->isRedirect( ) ) {
517 if ( $wgArticleCountMethod === 'any' ) {
525 * Returns the text represented by this Content object, as a string.
527 * @return String the raw text
529 public function getNativeData( ) {
530 $text = $this->mText
;
535 * Returns the text represented by this Content object, as a string.
537 * @return String the raw text
539 public function getTextForSearchIndex( ) {
540 return $this->getNativeData();
544 * Returns the text represented by this Content object, as a string.
546 * @return String the raw text
548 public function getWikitextForTransclusion( ) {
549 return $this->getNativeData();
553 * Returns a generic ParserOutput object, wrapping the HTML returned by getHtml().
555 * @param Title $title context title for parsing
556 * @param int|null $revId revision id (the parser wants that for some reason)
557 * @param ParserOptions|null $options parser options
558 * @param bool $generateHtml whether or not to generate HTML
560 * @return ParserOutput representing the HTML form of the text
562 public function getParserOutput( Title
$title, $revId = null, ParserOptions
$options = null, $generateHtml = true ) {
563 # generic implementation, relying on $this->getHtml()
565 if ( $generateHtml ) $html = $this->getHtml( $options );
568 $po = new ParserOutput( $html );
574 * Generates an HTML version of the content, for display.
575 * Used by getParserOutput() to construct a ParserOutput object
579 protected abstract function getHtml( );
582 * Diff this content object with another content object..
586 * @param Content $that the other content object to compare this content object to
587 * @param Language $lang the language object to use for text segmentation. If not given, $wgContentLang is used.
589 * @return DiffResult a diff representing the changes that would have to be made to this content object
590 * to make it equal to $that.
592 public function diff( Content
$that, Language
$lang = null ) {
595 $this->checkModelID( $that->getModel() );
597 #@todo: could implement this in DifferenceEngine and just delegate here?
599 if ( !$lang ) $lang = $wgContLang;
601 $otext = $this->getNativeData();
602 $ntext = $this->getNativeData();
604 # Note: Use native PHP diff, external engines don't give us abstract output
605 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
606 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
608 $diff = new Diff( $ota, $nta );
618 class WikitextContent
extends TextContent
{
620 public function __construct( $text ) {
621 parent
::__construct($text, CONTENT_MODEL_WIKITEXT
);
624 protected function getHtml( ) {
625 throw new MWException( "getHtml() not implemented for wikitext. Use getParserOutput()->getText()." );
629 * Returns a ParserOutput object resulting from parsing the content's text using $wgParser.
633 * @param \Title $title
635 * @param null|ParserOptions $options
636 * @param bool $generateHtml
638 * @internal param \IContextSource|null $context
639 * @return ParserOutput representing the HTML form of the text
641 public function getParserOutput( Title
$title, $revId = null, ParserOptions
$options = null, $generateHtml = true ) {
645 $options = new ParserOptions();
648 $po = $wgParser->parse( $this->mText
, $title, $options, true, true, $revId );
654 * Returns the section with the given id.
656 * @param String $section
658 * @internal param String $sectionId the section's id
659 * @return Content|false|null the section, or false if no such section exist, or null if sections are not supported
661 public function getSection( $section ) {
664 $text = $this->getNativeData();
665 $sect = $wgParser->getSection( $text, $section, false );
667 return new WikitextContent( $sect );
671 * Replaces a section in the wikitext
673 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
674 * @param $with Content: new content of the section
675 * @param $sectionTitle String: new section's subject, only if $section is 'new'
677 * @throws MWException
678 * @return Content Complete article content, or null if error
680 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
681 wfProfileIn( __METHOD__
);
683 $myModelId = $this->getModel();
684 $sectionModelId = $with->getModel();
686 if ( $sectionModelId != $myModelId ) {
687 $myModelName = ContentHandler
::getContentModelName( $myModelId );
688 $sectionModelName = ContentHandler
::getContentModelName( $sectionModelId );
690 throw new MWException( "Incompatible content model for section: document uses $myModelId ($myModelName), "
691 . "section uses $sectionModelId ($sectionModelName)." );
694 $oldtext = $this->getNativeData();
695 $text = $with->getNativeData();
697 if ( $section === '' ) {
698 return $with; #XXX: copy first?
699 } if ( $section == 'new' ) {
700 # Inserting a new section
701 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
702 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
703 $text = strlen( trim( $oldtext ) ) > 0
704 ?
"{$oldtext}\n\n{$subject}{$text}"
705 : "{$subject}{$text}";
708 # Replacing an existing section; roll out the big guns
711 $text = $wgParser->replaceSection( $oldtext, $section, $text );
714 $newContent = new WikitextContent( $text );
716 wfProfileOut( __METHOD__
);
721 * Returns a new WikitextContent object with the given section heading prepended.
723 * @param $header String
726 public function addSectionHeader( $header ) {
727 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $header ) . "\n\n" . $this->getNativeData();
729 return new WikitextContent( $text );
733 * Returns a Content object with pre-save transformations applied (or this object if no transformations apply).
735 * @param Title $title
737 * @param ParserOptions $popts
740 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) { #FIXME: also needed for JS/CSS!
741 global $wgParser, $wgConteLang;
743 $text = $this->getNativeData();
744 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
746 return new WikitextContent( $pst );
750 * Returns a Content object with preload transformations applied (or this object if no transformations apply).
752 * @param Title $title
753 * @param ParserOptions $popts
756 public function preloadTransform( Title
$title, ParserOptions
$popts ) {
757 global $wgParser, $wgConteLang;
759 $text = $this->getNativeData();
760 $plt = $wgParser->getPreloadText( $text, $title, $popts );
762 return new WikitextContent( $plt );
765 public function getRedirectChain() {
766 $text = $this->getNativeData();
767 return Title
::newFromRedirectArray( $text );
770 public function getRedirectTarget() {
771 $text = $this->getNativeData();
772 return Title
::newFromRedirect( $text );
775 public function getUltimateRedirectTarget() {
776 $text = $this->getNativeData();
777 return Title
::newFromRedirectRecurse( $text );
781 * Returns true if this content is not a redirect, and this content's text is countable according to
782 * the criteria defined by $wgArticleCountMethod.
784 * @param Bool $hasLinks if it is known whether this content contains links, provide this information here,
785 * to avoid redundant parsing to find out.
786 * @param null|\Title $title
788 * @internal param \IContextSource $context context for parsing if necessary
790 * @return bool true if the content is countable
792 public function isCountable( $hasLinks = null, Title
$title = null ) {
793 global $wgArticleCountMethod, $wgRequest;
795 if ( $this->isRedirect( ) ) {
799 $text = $this->getNativeData();
801 switch ( $wgArticleCountMethod ) {
805 return strpos( $text, ',' ) !== false;
807 if ( $hasLinks === null ) { # not known, find out
809 $context = RequestContext
::getMain();
810 $title = $context->getTitle();
813 $po = $this->getParserOutput( $title, null, null, false );
814 $links = $po->getLinks();
815 $hasLinks = !empty( $links );
822 public function getTextForSummary( $maxlength = 250 ) {
823 $truncatedtext = parent
::getTextForSummary( $maxlength );
825 #clean up unfinished links
826 #XXX: make this optional? wasn't there in autosummary, but required for deletion summary.
827 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
829 return $truncatedtext;
837 class MessageContent
extends TextContent
{
838 public function __construct( $msg_key, $params = null, $options = null ) {
839 parent
::__construct(null, CONTENT_MODEL_WIKITEXT
); #XXX: messages may be wikitext, html or plain text! and maybe even something else entirely.
841 $this->mMessageKey
= $msg_key;
843 $this->mParameters
= $params;
845 if ( is_null( $options ) ) {
848 elseif ( is_string( $options ) ) {
849 $options = array( $options );
852 $this->mOptions
= $options;
854 $this->mHtmlOptions
= null;
858 * Returns the message as rendered HTML, using the options supplied to the constructor plus "parse".
859 * @return String the message text, parsed
861 protected function getHtml( ) {
862 $opt = array_merge( $this->mOptions
, array('parse') );
864 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
869 * Returns the message as raw text, using the options supplied to the constructor minus "parse" and "parseinline".
871 * @return String the message text, unparsed.
873 public function getNativeData( ) {
874 $opt = array_diff( $this->mOptions
, array('parse', 'parseinline') );
876 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
884 class JavaScriptContent
extends TextContent
{
885 public function __construct( $text ) {
886 parent
::__construct($text, CONTENT_MODEL_JAVASCRIPT
);
889 protected function getHtml( ) {
891 $html .= "<pre class=\"mw-code mw-js\" dir=\"ltr\">\n";
892 $html .= htmlspecialchars( $this->getNativeData() );
893 $html .= "\n</pre>\n";
903 class CssContent
extends TextContent
{
904 public function __construct( $text ) {
905 parent
::__construct($text, CONTENT_MODEL_CSS
);
908 protected function getHtml( ) {
910 $html .= "<pre class=\"mw-code mw-css\" dir=\"ltr\">\n";
911 $html .= htmlspecialchars( $this->getNativeData() );
912 $html .= "\n</pre>\n";