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 * @todo: test that this actually works
25 * @todo: make sure this also works with LuceneSearch / WikiSearch
27 public abstract function getTextForSearchIndex( );
32 * @return String the wikitext to include when another page includes this content, or false if the content is not
33 * includable in a wikitext page.
35 * @TODO: allow native handling, bypassing wikitext representation, like for includable special pages.
36 * @TODO: use in parser, etc!
38 public abstract function getWikitextForTransclusion( );
41 * Returns a textual representation of the content suitable for use in edit summaries and log messages.
45 * @param int $maxlength maximum length of the summary text
46 * @return String the summary text
48 public abstract function getTextForSummary( $maxlength = 250 );
51 * Returns native representation of the data. Interpretation depends on the data model used,
52 * as given by getDataModel().
56 * @return mixed the native representation of the content. Could be a string, a nested array
57 * structure, an object, a binary blob... anything, really.
59 * @NOTE: review all calls carefully, caller must be aware of content model!
61 public abstract function getNativeData( );
64 * returns the content's nominal size in bogo-bytes.
68 public abstract function getSize( );
71 * @param int $model_id
73 public function __construct( $model_id = null ) {
74 $this->model_id
= $model_id;
78 * Returns the id of the content model used by this content objects.
79 * Corresponds to the CONTENT_MODEL_XXX constants.
83 * @return int the model id
85 public function getModel() {
86 return $this->model_id
;
90 * Throws an MWException if $model_id is not the id of the content model
91 * supported by this Content object.
93 * @param int $model_id the model to check
97 protected function checkModelID( $model_id ) {
98 if ( $model_id !== $this->model_id
) {
99 $model_name = ContentHandler
::getContentModelName( $model_id );
100 $own_model_name = ContentHandler
::getContentModelName( $this->model_id
);
102 throw new MWException( "Bad content model: expected {$this->model_id} ($own_model_name) but got found $model_id ($model_name)." );
107 * Convenience method that returns the ContentHandler singleton for handling the content
108 * model this Content object uses.
110 * Shorthand for ContentHandler::getForContent( $this )
114 * @return ContentHandler
116 public function getContentHandler() {
117 return ContentHandler
::getForContent( $this );
121 * Convenience method that returns the default serialization format for the content model
122 * model this Content object uses.
124 * Shorthand for $this->getContentHandler()->getDefaultFormat()
128 * @return ContentHandler
130 public function getDefaultFormat() {
131 return $this->getContentHandler()->getDefaultFormat();
135 * Convenience method that returns the list of serialization formats supported
136 * for the content model model this Content object uses.
138 * Shorthand for $this->getContentHandler()->getSupportedFormats()
142 * @return array of supported serialization formats
144 public function getSupportedFormats() {
145 return $this->getContentHandler()->getSupportedFormats();
149 * Returns true if $format is a supported serialization format for this Content object,
152 * Note that this will always return true if $format is null, because null stands for the
153 * default serialization.
155 * Shorthand for $this->getContentHandler()->isSupportedFormat( $format )
159 * @param String $format the format to check
160 * @return bool whether the format is supported
162 public function isSupportedFormat( $format ) {
164 return true; // this means "use the default"
167 return $this->getContentHandler()->isSupportedFormat( $format );
171 * Throws an MWException if $this->isSupportedFormat( $format ) doesn't return true.
174 * @throws MWException
176 protected function checkFormat( $format ) {
177 if ( !$this->isSupportedFormat( $format ) ) {
178 throw new MWException( "Format $format is not supported for content model " . $this->getModel() );
183 * Convenience method for serializing this Content object.
185 * Shorthand for $this->getContentHandler()->serializeContent( $this, $format )
189 * @param null|String $format the desired serialization format (or null for the default format).
190 * @return String serialized form of this Content object
192 public function serialize( $format = null ) {
193 return $this->getContentHandler()->serializeContent( $this, $format );
197 * Returns true if this Content object represents empty content.
201 * @return bool whether this Content object is empty
203 public function isEmpty() {
204 return $this->getSize() == 0;
208 * Returns if the content is valid. This is intended for local validity checks, not considering global consistency.
209 * It needs to be valid before it can be saved.
211 * This default implementation always returns true.
217 public function isValid() {
222 * Returns true if this Content objects is conceptually equivalent to the given Content object.
224 * Will returns false if $that is null.
225 * Will return true if $that === $this.
226 * Will return false if $that->getModelName() != $this->getModel().
227 * Will return false if $that->getNativeData() is not equal to $this->getNativeData(),
228 * where the meaning of "equal" depends on the actual data model.
230 * Implementations should be careful to make equals() transitive and reflexive:
232 * * $a->equals( $b ) <=> $b->equals( $a )
233 * * $a->equals( $b ) && $b->equals( $c ) ==> $a->equals( $c )
237 * @param Content $that the Content object to compare to
238 * @return bool true if this Content object is euqual to $that, false otherwise.
240 public function equals( Content
$that = null ) {
241 if ( is_null( $that ) ){
245 if ( $that === $this ) {
249 if ( $that->getModel() !== $this->getModel() ) {
253 return $this->getNativeData() === $that->getNativeData();
257 * Return a copy of this Content object. The following must be true for the object returned
258 * if $copy = $original->copy()
260 * * get_class($original) === get_class($copy)
261 * * $original->getModel() === $copy->getModel()
262 * * $original->equals( $copy )
264 * If and only if the Content object is immutable, the copy() method can and should
265 * return $this. That is, $copy === $original may be true, but only for immutable content
270 * @return Content. A copy of this object
272 public abstract function copy( );
275 * Returns true if this content is countable as a "real" wiki page, provided
276 * that it's also in a countable location (e.g. a current revision in the main namespace).
280 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
281 * to avoid redundant parsing to find out.
284 public abstract function isCountable( $hasLinks = null ) ;
287 * Convenience method, shorthand for
288 * $this->getContentHandler()->getParserOutput( $this, $title, $revId, $options, $generateHtml )
290 * @note: subclasses should NOT override this to provide custom rendering.
291 * Override ContentHandler::getParserOutput() instead!
293 * @param Title $title
295 * @param null|ParserOptions $options
296 * @param Boolean $generateHtml whether to generate Html (default: true). If false,
297 * the result of calling getText() on the ParserOutput object returned by
298 * this method is undefined.
302 * @return ParserOutput
304 public function getParserOutput( Title
$title, $revId = null, ParserOptions
$options = null, $generateHtml = true ) {
305 return $this->getContentHandler()->getParserOutput( $this, $title, $revId, $options, $generateHtml );
309 * Construct the redirect destination from this content and return an
310 * array of Titles, or null if this content doesn't represent a redirect.
311 * The last element in the array is the final destination after all redirects
312 * have been resolved (up to $wgMaxRedirects times).
316 * @return Array of Titles, with the destination last
318 public function getRedirectChain() {
323 * Construct the redirect destination from this content and return a Title,
324 * or null if this content doesn't represent a redirect.
325 * This will only return the immediate redirect target, useful for
326 * the redirect table and other checks that don't need full recursion.
330 * @return Title: The corresponding Title
332 public function getRedirectTarget() {
337 * Construct the redirect destination from this content and return the
338 * Title, or null if this content doesn't represent a redirect.
339 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
340 * in order to provide (hopefully) the Title of the final destination instead of another redirect.
346 public function getUltimateRedirectTarget() {
355 public function isRedirect() {
356 return $this->getRedirectTarget() !== null;
360 * Returns the section with the given id.
362 * The default implementation returns null.
366 * @param String $sectionId the section's id, given as a numeric string. The id "0" retrieves the section before
367 * the first heading, "1" the text between the first heading (included) and the second heading (excluded), etc.
368 * @return Content|Boolean|null the section, or false if no such section exist, or null if sections are not supported
370 public function getSection( $sectionId ) {
375 * Replaces a section of the content and returns a Content object with the section replaced.
379 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
380 * @param $with Content: new content of the section
381 * @param $sectionTitle String: new section's subject, only if $section is 'new'
382 * @return string Complete article text, or null if error
384 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
389 * Returns a Content object with pre-save transformations applied (or this object if no transformations apply).
393 * @param Title $title
395 * @param null|ParserOptions $popts
398 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
403 * Returns a new WikitextContent object with the given section heading prepended, if supported.
404 * The default implementation just returns this Content object unmodified, ignoring the section header.
408 * @param $header String
411 public function addSectionHeader( $header ) {
416 * Returns a Content object with preload transformations applied (or this object if no transformations apply).
420 * @param Title $title
421 * @param null|ParserOptions $popts
424 public function preloadTransform( Title
$title, ParserOptions
$popts ) {
428 # TODO: handle ImagePage and CategoryPage
429 # TODO: make sure we cover lucene search / wikisearch.
430 # TODO: make sure ReplaceTemplates still works
431 # FUTURE: nice&sane integration of GeSHi syntax highlighting
432 # [11:59] <vvv> Hooks are ugly; make CodeHighlighter interface and a config to set the class which handles syntax highlighting
433 # [12:00] <vvv> And default it to a DummyHighlighter
435 # TODO: make sure we cover the external editor interface (does anyone actually use that?!)
437 # TODO: tie into API to provide contentModel for Revisions
438 # TODO: tie into API to provide serialized version and contentFormat for Revisions
439 # TODO: tie into API edit interface
440 # FUTURE: make EditForm plugin for EditPage
442 # FUTURE: special type for redirects?!
443 # FUTURE: MultipartMultipart < WikipageContent (Main + Links + X)
444 # FUTURE: LinksContent < LanguageLinksContent, CategoriesContent
446 // @TODO: add support for ar_content_format, ar_content_model, rev_content_format, rev_content_model to API
449 * Content object implementation for representing flat text.
451 * TextContent instances are immutable
455 abstract class TextContent
extends Content
{
457 public function __construct( $text, $model_id = null ) {
458 parent
::__construct( $model_id );
460 $this->mText
= $text;
463 public function copy() {
464 return $this; #NOTE: this is ok since TextContent are immutable.
467 public function getTextForSummary( $maxlength = 250 ) {
470 $text = $this->getNativeData();
472 $truncatedtext = $wgContLang->truncate(
473 preg_replace( "/[\n\r]/", ' ', $text ),
474 max( 0, $maxlength ) );
476 return $truncatedtext;
480 * returns the text's size in bytes.
482 * @return int the size
484 public function getSize( ) {
485 $text = $this->getNativeData( );
486 return strlen( $text );
490 * Returns true if this content is not a redirect, and $wgArticleCountMethod is "any".
492 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
493 * to avoid redundant parsing to find out.
495 * @return bool true if the content is countable
497 public function isCountable( $hasLinks = null ) {
498 global $wgArticleCountMethod;
500 if ( $this->isRedirect( ) ) {
504 if ( $wgArticleCountMethod === 'any' ) {
512 * Returns the text represented by this Content object, as a string.
514 * @return String the raw text
516 public function getNativeData( ) {
517 $text = $this->mText
;
522 * Returns the text represented by this Content object, as a string.
524 * @return String the raw text
526 public function getTextForSearchIndex( ) {
527 return $this->getNativeData();
531 * Returns the text represented by this Content object, as a string.
533 * @return String the raw text
535 public function getWikitextForTransclusion( ) {
536 return $this->getNativeData();
540 * Diff this content object with another content object..
544 * @param Content $that the other content object to compare this content object to
545 * @param Language $lang the language object to use for text segmentation. If not given, $wgContentLang is used.
547 * @return DiffResult a diff representing the changes that would have to be made to this content object
548 * to make it equal to $that.
550 public function diff( Content
$that, Language
$lang = null ) {
553 $this->checkModelID( $that->getModel() );
555 #@todo: could implement this in DifferenceEngine and just delegate here?
557 if ( !$lang ) $lang = $wgContLang;
559 $otext = $this->getNativeData();
560 $ntext = $this->getNativeData();
562 # Note: Use native PHP diff, external engines don't give us abstract output
563 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
564 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
566 $diff = new Diff( $ota, $nta );
576 class WikitextContent
extends TextContent
{
578 public function __construct( $text ) {
579 parent
::__construct($text, CONTENT_MODEL_WIKITEXT
);
583 * Returns the section with the given id.
585 * @param String $section
587 * @internal param String $sectionId the section's id
588 * @return Content|false|null the section, or false if no such section exist, or null if sections are not supported
590 public function getSection( $section ) {
593 $text = $this->getNativeData();
594 $sect = $wgParser->getSection( $text, $section, false );
596 return new WikitextContent( $sect );
600 * Replaces a section in the wikitext
602 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
603 * @param $with Content: new content of the section
604 * @param $sectionTitle String: new section's subject, only if $section is 'new'
606 * @throws MWException
607 * @return Content Complete article content, or null if error
609 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
610 wfProfileIn( __METHOD__
);
612 $myModelId = $this->getModel();
613 $sectionModelId = $with->getModel();
615 if ( $sectionModelId != $myModelId ) {
616 $myModelName = ContentHandler
::getContentModelName( $myModelId );
617 $sectionModelName = ContentHandler
::getContentModelName( $sectionModelId );
619 throw new MWException( "Incompatible content model for section: document uses $myModelId ($myModelName), "
620 . "section uses $sectionModelId ($sectionModelName)." );
623 $oldtext = $this->getNativeData();
624 $text = $with->getNativeData();
626 if ( $section === '' ) {
627 return $with; #XXX: copy first?
628 } if ( $section == 'new' ) {
629 # Inserting a new section
630 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
631 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
632 $text = strlen( trim( $oldtext ) ) > 0
633 ?
"{$oldtext}\n\n{$subject}{$text}"
634 : "{$subject}{$text}";
637 # Replacing an existing section; roll out the big guns
640 $text = $wgParser->replaceSection( $oldtext, $section, $text );
643 $newContent = new WikitextContent( $text );
645 wfProfileOut( __METHOD__
);
650 * Returns a new WikitextContent object with the given section heading prepended.
652 * @param $header String
655 public function addSectionHeader( $header ) {
656 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $header ) . "\n\n" . $this->getNativeData();
658 return new WikitextContent( $text );
662 * Returns a Content object with pre-save transformations applied (or this object if no transformations apply).
664 * @param Title $title
666 * @param ParserOptions $popts
669 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) { #FIXME: also needed for JS/CSS!
670 global $wgParser, $wgConteLang;
672 $text = $this->getNativeData();
673 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
675 return new WikitextContent( $pst );
679 * Returns a Content object with preload transformations applied (or this object if no transformations apply).
681 * @param Title $title
682 * @param ParserOptions $popts
685 public function preloadTransform( Title
$title, ParserOptions
$popts ) {
686 global $wgParser, $wgConteLang;
688 $text = $this->getNativeData();
689 $plt = $wgParser->getPreloadText( $text, $title, $popts );
691 return new WikitextContent( $plt );
694 public function getRedirectChain() {
695 $text = $this->getNativeData();
696 return Title
::newFromRedirectArray( $text );
699 public function getRedirectTarget() {
700 $text = $this->getNativeData();
701 return Title
::newFromRedirect( $text );
704 public function getUltimateRedirectTarget() {
705 $text = $this->getNativeData();
706 return Title
::newFromRedirectRecurse( $text );
710 * Returns true if this content is not a redirect, and this content's text is countable according to
711 * the criteria defined by $wgArticleCountMethod.
713 * @param Bool $hasLinks if it is known whether this content contains links, provide this information here,
714 * to avoid redundant parsing to find out.
715 * @param null|\Title $title
717 * @internal param \IContextSource $context context for parsing if necessary
719 * @return bool true if the content is countable
721 public function isCountable( $hasLinks = null, Title
$title = null ) {
722 global $wgArticleCountMethod, $wgRequest;
724 if ( $this->isRedirect( ) ) {
728 $text = $this->getNativeData();
730 switch ( $wgArticleCountMethod ) {
734 return strpos( $text, ',' ) !== false;
736 if ( $hasLinks === null ) { # not known, find out
738 $context = RequestContext
::getMain();
739 $title = $context->getTitle();
742 $po = $this->getParserOutput( $title, null, null, false );
743 $links = $po->getLinks();
744 $hasLinks = !empty( $links );
753 public function getTextForSummary( $maxlength = 250 ) {
754 $truncatedtext = parent
::getTextForSummary( $maxlength );
756 #clean up unfinished links
757 #XXX: make this optional? wasn't there in autosummary, but required for deletion summary.
758 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
760 return $truncatedtext;
768 class MessageContent
extends TextContent
{
769 public function __construct( $msg_key, $params = null, $options = null ) {
770 parent
::__construct(null, CONTENT_MODEL_WIKITEXT
); #XXX: messages may be wikitext, html or plain text! and maybe even something else entirely.
772 $this->mMessageKey
= $msg_key;
774 $this->mParameters
= $params;
776 if ( is_null( $options ) ) {
779 elseif ( is_string( $options ) ) {
780 $options = array( $options );
783 $this->mOptions
= $options;
787 * Returns the message as rendered HTML, using the options supplied to the constructor plus "parse".
788 * @return String the message text, parsed
790 public function getHtml( ) {
791 $opt = array_merge( $this->mOptions
, array('parse') );
793 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
798 * Returns the message as raw text, using the options supplied to the constructor minus "parse" and "parseinline".
800 * @return String the message text, unparsed.
802 public function getNativeData( ) {
803 $opt = array_diff( $this->mOptions
, array('parse', 'parseinline') );
805 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
813 class JavaScriptContent
extends TextContent
{
814 public function __construct( $text ) {
815 parent
::__construct($text, CONTENT_MODEL_JAVASCRIPT
);
823 class CssContent
extends TextContent
{
824 public function __construct( $text ) {
825 parent
::__construct($text, CONTENT_MODEL_CSS
);