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.
9 abstract class Content
{
12 * Name of the content model this Content object represents.
13 * Use with CONTENT_MODEL_XXX constants
15 * @var String $model_id
20 * @return String a string representing the content in a way useful for building a full text search index.
21 * If no useful representation exists, this method returns an empty string.
23 public abstract function getTextForSearchIndex( );
26 * @return String the wikitext to include when another page includes this content, or false if the content is not
27 * includable in a wikitext page.
29 * @TODO: allow native handling, bypassing wikitext representation, like for includable special pages.
30 * @TODO: use in parser, etc!
32 public abstract function getWikitextForTransclusion( );
35 * Returns a textual representation of the content suitable for use in edit summaries and log messages.
37 * @param int $maxlength maximum length of the summary text
38 * @return String the summary text
40 public abstract function getTextForSummary( $maxlength = 250 );
43 * Returns native represenation of the data. Interpretation depends on the data model used,
44 * as given by getDataModel().
46 * @return mixed the native representation of the content. Could be a string, a nested array
47 * structure, an object, a binary blob... anything, really.
49 * @NOTE: review all calls carefully, caller must be aware of content model!
51 public abstract function getNativeData( );
54 * returns the content's nominal size in bogo-bytes.
58 public abstract function getSize( );
61 * @param int $model_id
63 public function __construct( $model_id = null ) {
64 $this->model_id
= $model_id;
68 * Returns the id of the content model used by this content objects.
69 * Corresponds to the CONTENT_MODEL_XXX constants.
71 * @return int the model id
73 public function getModel() {
74 return $this->model_id
;
78 * Throws an MWException if $model_id is not the id of the content model
79 * supported by this Content object.
81 * @param int $model_id the model to check
83 protected function checkModelID( $model_id ) {
84 if ( $model_id !== $this->model_id
) {
85 $model_name = ContentHandler
::getContentModelName( $model_id );
86 $own_model_name = ContentHandler
::getContentModelName( $this->model_id
);
88 throw new MWException( "Bad content model: expected {$this->model_id} ($own_model_name) but got found $model_id ($model_name)." );
93 * Conveniance method that returns the ContentHandler singleton for handling the content
94 * model this Content object uses.
96 * Shorthand for ContentHandler::getForContent( $this )
98 * @return ContentHandler
100 public function getContentHandler() {
101 return ContentHandler
::getForContent( $this );
105 * Conveniance method that returns the default serialization format for the content model
106 * model this Content object uses.
108 * Shorthand for $this->getContentHandler()->getDefaultFormat()
110 * @return ContentHandler
112 public function getDefaultFormat() {
113 return $this->getContentHandler()->getDefaultFormat();
117 * Conveniance method that returns the list of serialization formats supported
118 * for the content model model this Content object uses.
120 * Shorthand for $this->getContentHandler()->getSupportedFormats()
122 * @return array of supported serialization formats
124 public function getSupportedFormats() {
125 return $this->getContentHandler()->getSupportedFormats();
129 * Returns true if $format is a supported serialization format for this Content object,
132 * Note that this will always return true if $format is null, because null stands for the
133 * default serialization.
135 * Shorthand for $this->getContentHandler()->isSupportedFormat( $format )
137 * @param String $format the format to check
138 * @return bool whether the format is supported
140 public function isSupportedFormat( $format ) {
142 return true; // this means "use the default"
145 return $this->getContentHandler()->isSupportedFormat( $format );
149 * Throws an MWException if $this->isSupportedFormat( $format ) doesn't return true.
152 * @throws MWException
154 protected function checkFormat( $format ) {
155 if ( !$this->isSupportedFormat( $format ) ) {
156 throw new MWException( "Format $format is not supported for content model " . $this->getModel() );
161 * Conveniance method for serializing this Content object.
163 * Shorthand for $this->getContentHandler()->serializeContent( $this, $format )
165 * @param null|String $format the desired serialization format (or null for the default format).
166 * @return String serialized form of this Content object
168 public function serialize( $format = null ) {
169 return $this->getContentHandler()->serializeContent( $this, $format );
173 * Returns true if this Content object represents empty content.
175 * @return bool whether this Content object is empty
177 public function isEmpty() {
178 return $this->getSize() == 0;
182 * Returns true if this Content objects is conceptually equivalent to the given Content object.
184 * Will returns false if $that is null.
185 * Will return true if $that === $this.
186 * Will return false if $that->getModleName() != $this->getModel().
187 * Will return false if $that->getNativeData() is not equal to $this->getNativeData(),
188 * where the meaning of "equal" depends on the actual data model.
190 * Implementations should be careful to make equals() transitive and reflexive:
192 * * $a->equals( $b ) <=> $b->equals( $b )
193 * * $a->equals( $b ) && $b->equals( $c ) ==> $a->equals( $c )
195 * @param Content $that the Content object to compare to
196 * @return bool true if this Content object is euqual to $that, false otherwise.
198 public function equals( Content
$that = null ) {
199 if ( is_null( $that ) ){
203 if ( $that === $this ) {
207 if ( $that->getModel() !== $this->getModel() ) {
211 return $this->getNativeData() === $that->getNativeData();
215 * Return a copy of this Content object. The following must be true for the object returned
216 * if $copy = $original->copy()
218 * * get_class($original) === get_class($copy)
219 * * $original->getModel() === $copy->getModel()
220 * * $original->equals( $copy )
222 * If and only if the Content object is imutable, the copy() method can and should
223 * return $this. That is, $copy === $original may be true, but only for imutable content
226 * @return Content. A copy of this object
228 public abstract function copy( );
231 * Returns true if this content is countable as a "real" wiki page, provided
232 * that it's also in a countable location (e.g. a current revision in the main namespace).
234 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
235 * to avoid redundant parsing to find out.
238 public abstract function isCountable( $hasLinks = null ) ;
241 * @param IContextSource $context
243 * @param null|ParserOptions $options
244 * @param Boolean $generateHtml whether to generate Html (default: true). If false,
245 * the result of calling getText() on the ParserOutput object returned by
246 * this method is undefined.
248 * @return ParserOutput
250 public abstract function getParserOutput( IContextSource
$context, $revId = null, ParserOptions
$options = NULL, $generateHtml = true );
253 * Construct the redirect destination from this content and return an
254 * array of Titles, or null if this content doesn't represent a redirect.
255 * The last element in the array is the final destination after all redirects
256 * have been resolved (up to $wgMaxRedirects times).
258 * @return Array of Titles, with the destination last
260 public function getRedirectChain() {
265 * Construct the redirect destination from this content and return an
266 * array of Titles, or null if this content doesn't represent a redirect.
267 * This will only return the immediate redirect target, useful for
268 * the redirect table and other checks that don't need full recursion.
270 * @return Title: The corresponding Title
272 public function getRedirectTarget() {
277 * Construct the redirect destination from this content and return the
278 * Title, or null if this content doesn't represent a redirect.
279 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
280 * in order to provide (hopefully) the Title of the final destination instead of another redirect.
284 public function getUltimateRedirectTarget() {
288 public function isRedirect() {
289 return $this->getRedirectTarget() != null;
293 * Returns the section with the given id.
295 * The default implementation returns null.
297 * @param String $sectionId the section's id, given as a numeric string. The id "0" retrieves the section before
298 * the first heading, "1" the text between the first heading (inluded) and the second heading (excluded), etc.
299 * @return Content|Boolean|null the section, or false if no such section exist, or null if sections are not supported
301 public function getSection( $sectionId ) {
306 * Replaces a section of the content and returns a Content object with the section replaced.
308 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
309 * @param $with Content: new content of the section
310 * @param $sectionTitle String: new section's subject, only if $section is 'new'
311 * @return string Complete article text, or null if error
313 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
318 * Returns a Content object with pre-save transformations applied (or this object if no transformations apply).
320 * @param Title $title
322 * @param null|ParserOptions $popts
325 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
330 * Returns a new WikitextContent object with the given section heading prepended, if supported.
331 * The default implementation just returns this Content object unmodified, ignoring the section header.
333 * @param $header String
336 public function addSectionHeader( $header ) {
341 * Returns a Content object with preload transformations applied (or this object if no transformations apply).
343 * @param Title $title
344 * @param null|ParserOptions $popts
347 public function preloadTransform( Title
$title, ParserOptions
$popts ) {
351 # TODO: handle ImagePage and CategoryPage
352 # TODO: make sure we cover lucene search / wikisearch.
353 # TODO: make sure ReplaceTemplates still works
354 # FUTURE: nice&sane integration of GeSHi syntax highlighting
355 # [11:59] <vvv> Hooks are ugly; make CodeHighlighter interface and a config to set the class which handles syntax highlighting
356 # [12:00] <vvv> And default it to a DummyHighlighter
358 # TODO: make sure we cover the external editor interface (does anyone actually use that?!)
360 # TODO: tie into API to provide contentModel for Revisions
361 # TODO: tie into API to provide serialized version and contentFormat for Revisions
362 # TODO: tie into API edit interface
363 # FUTURE: make EditForm plugin for EditPage
365 # FUTURE: special type for redirects?!
366 # FUTURE: MultipartMultipart < WikipageContent (Main + Links + X)
367 # FUTURE: LinksContent < LanguageLinksContent, CategoriesContent
370 * Content object implementation for representing flat text.
372 * TextContent instances are imutable
374 abstract class TextContent
extends Content
{
376 public function __construct( $text, $model_id = null ) {
377 parent
::__construct( $model_id );
379 $this->mText
= $text;
382 public function copy() {
383 return $this; #NOTE: this is ok since TextContent are imutable.
386 public function getTextForSummary( $maxlength = 250 ) {
389 $text = $this->getNativeData();
391 $truncatedtext = $wgContLang->truncate(
392 preg_replace( "/[\n\r]/", ' ', $text ),
393 max( 0, $maxlength ) );
395 return $truncatedtext;
399 * returns the text's size in bytes.
401 * @return int the size
403 public function getSize( ) {
404 $text = $this->getNativeData( );
405 return strlen( $text );
409 * Returns true if this content is not a redirect, and $wgArticleCountMethod is "any".
411 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
412 * to avoid redundant parsing to find out.
414 * @return bool true if the content is countable
416 public function isCountable( $hasLinks = null ) {
417 global $wgArticleCountMethod;
419 if ( $this->isRedirect( ) ) {
423 if ( $wgArticleCountMethod === 'any' ) {
431 * Returns the text represented by this Content object, as a string.
433 * @return String the raw text
435 public function getNativeData( ) {
436 $text = $this->mText
;
441 * Returns the text represented by this Content object, as a string.
443 * @return String the raw text
445 public function getTextForSearchIndex( ) {
446 return $this->getNativeData();
450 * Returns the text represented by this Content object, as a string.
452 * @return String the raw text
454 public function getWikitextForTransclusion( ) {
455 return $this->getNativeData();
459 * Returns a generic ParserOutput object, wrapping the HTML returned by getHtml().
461 * @return ParserOutput representing the HTML form of the text
463 public function getParserOutput( IContextSource
$context, $revId = null, ParserOptions
$options = null, $generateHtml = true ) {
464 # generic implementation, relying on $this->getHtml()
466 if ( $generateHtml ) $html = $this->getHtml( $options );
469 $po = new ParserOutput( $html );
474 protected abstract function getHtml( );
478 class WikitextContent
extends TextContent
{
480 public function __construct( $text ) {
481 parent
::__construct($text, CONTENT_MODEL_WIKITEXT
);
484 protected function getHtml( ) {
485 throw new MWException( "getHtml() not implemented for wikitext. Use getParserOutput()->getText()." );
489 * Returns a ParserOutput object resulting from parsing the content's text using $wgParser.
493 * @param IContextSource|null $context
495 * @param null|ParserOptions $options
496 * @param bool $generateHtml
498 * @return ParserOutput representing the HTML form of the text
500 public function getParserOutput( IContextSource
$context, $revId = null, ParserOptions
$options = null, $generateHtml = true ) {
504 $options = ParserOptions
::newFromUserAndLang( $context->getUser(), $context->getLanguage() );
507 $po = $wgParser->parse( $this->mText
, $context->getTitle(), $options, true, true, $revId );
513 * Returns the section with the given id.
515 * @param String $sectionId the section's id
516 * @return Content|false|null the section, or false if no such section exist, or null if sections are not supported
518 public function getSection( $section ) {
521 $text = $this->getNativeData();
522 $sect = $wgParser->getSection( $text, $section, false );
524 return new WikitextContent( $sect );
528 * Replaces a section in the wikitext
530 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
531 * @param $with Content: new content of the section
532 * @param $sectionTitle String: new section's subject, only if $section is 'new'
533 * @return Content Complete article content, or null if error
535 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
536 wfProfileIn( __METHOD__
);
538 $myModelId = $this->getModel();
539 $sectionModelId = $with->getModel();
541 if ( $sectionModelId != $myModelId ) {
542 $myModelName = ContentHandler
::getContentModelName( $myModelId );
543 $sectionModelName = ContentHandler
::getContentModelName( $sectionModelId );
545 throw new MWException( "Incompatible content model for section: document uses $myModelId ($myModelName), "
546 . "section uses $sectionModelId ($sectionModelName)." );
549 $oldtext = $this->getNativeData();
550 $text = $with->getNativeData();
552 if ( $section === '' ) {
553 return $with; #XXX: copy first?
554 } if ( $section == 'new' ) {
555 # Inserting a new section
556 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
557 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
558 $text = strlen( trim( $oldtext ) ) > 0
559 ?
"{$oldtext}\n\n{$subject}{$text}"
560 : "{$subject}{$text}";
563 # Replacing an existing section; roll out the big guns
566 $text = $wgParser->replaceSection( $oldtext, $section, $text );
569 $newContent = new WikitextContent( $text );
571 wfProfileOut( __METHOD__
);
576 * Returns a new WikitextContent object with the given section heading prepended.
578 * @param $header String
581 public function addSectionHeader( $header ) {
582 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $header ) . "\n\n" . $this->getNativeData();
584 return new WikitextContent( $text );
588 * Returns a Content object with pre-save transformations applied (or this object if no transformations apply).
590 * @param Title $title
592 * @param ParserOptions $popts
595 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
596 global $wgParser, $wgConteLang;
598 $text = $this->getNativeData();
599 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
601 return new WikitextContent( $pst );
605 * Returns a Content object with preload transformations applied (or this object if no transformations apply).
607 * @param Title $title
608 * @param ParserOptions $popts
611 public function preloadTransform( Title
$title, ParserOptions
$popts ) {
612 global $wgParser, $wgConteLang;
614 $text = $this->getNativeData();
615 $plt = $wgParser->getPreloadText( $text, $title, $popts );
617 return new WikitextContent( $plt );
620 public function getRedirectChain() {
621 $text = $this->getNativeData();
622 return Title
::newFromRedirectArray( $text );
625 public function getRedirectTarget() {
626 $text = $this->getNativeData();
627 return Title
::newFromRedirect( $text );
630 public function getUltimateRedirectTarget() {
631 $text = $this->getNativeData();
632 return Title
::newFromRedirectRecurse( $text );
636 * Returns true if this content is not a redirect, and this content's text is countable according to
637 * the criteria defiend by $wgArticleCountMethod.
639 * @param Bool $hasLinks if it is known whether this content contains links, provide this information here,
640 * to avoid redundant parsing to find out.
641 * @param IContextSource $context context for parsing if necessary
643 * @return bool true if the content is countable
645 public function isCountable( $hasLinks = null, IContextSource
$context = null ) {
646 global $wgArticleCountMethod, $wgRequest;
648 if ( $this->isRedirect( ) ) {
652 $text = $this->getNativeData();
654 switch ( $wgArticleCountMethod ) {
658 return strpos( $text, ',' ) !== false;
660 if ( $hasLinks === null ) { # not known, find out
661 if ( !$context ) { # make dummy context
662 //XXX: caller of this method often knows the title, but not a context...
663 $context = new RequestContext( $wgRequest );
666 $po = $this->getParserOutput( $context, null, null, false );
667 $links = $po->getLinks();
668 $hasLinks = !empty( $links );
675 public function getTextForSummary( $maxlength = 250 ) {
676 $truncatedtext = parent
::getTextForSummary( $maxlength );
678 #clean up unfinished links
679 #XXX: make this optional? wasn't there in autosummary, but required for deletion summary.
680 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
682 return $truncatedtext;
687 class MessageContent
extends TextContent
{
688 public function __construct( $msg_key, $params = null, $options = null ) {
689 parent
::__construct(null, CONTENT_MODEL_WIKITEXT
); #XXX: messages may be wikitext, html or plain text! and maybe even something else entirely.
691 $this->mMessageKey
= $msg_key;
693 $this->mParameters
= $params;
695 if ( is_null( $options ) ) {
698 elseif ( is_string( $options ) ) {
699 $options = array( $options );
702 $this->mOptions
= $options;
704 $this->mHtmlOptions
= null;
708 * Returns the message as rendered HTML, using the options supplied to the constructor plus "parse".
710 protected function getHtml( ) {
711 $opt = array_merge( $this->mOptions
, array('parse') );
713 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
718 * Returns the message as raw text, using the options supplied to the constructor minus "parse" and "parseinline".
720 public function getNativeData( ) {
721 $opt = array_diff( $this->mOptions
, array('parse', 'parseinline') );
723 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
729 class JavaScriptContent
extends TextContent
{
730 public function __construct( $text ) {
731 parent
::__construct($text, CONTENT_MODEL_JAVASCRIPT
);
734 protected function getHtml( ) {
736 $html .= "<pre class=\"mw-code mw-js\" dir=\"ltr\">\n";
737 $html .= htmlspecialchars( $this->getNativeData() );
738 $html .= "\n</pre>\n";
745 class CssContent
extends TextContent
{
746 public function __construct( $text ) {
747 parent
::__construct($text, CONTENT_MODEL_CSS
);
750 protected function getHtml( ) {
752 $html .= "<pre class=\"mw-code mw-css\" dir=\"ltr\">\n";
753 $html .= htmlspecialchars( $this->getNativeData() );
754 $html .= "\n</pre>\n";