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_name
17 protected $model_name;
22 * @return String a string representing the content in a way useful for building a full text search index.
23 * If no useful representation exists, this method returns an empty string.
25 public abstract function getTextForSearchIndex( );
30 * @return String the wikitext to include when another page includes this content, or false if the content is not
31 * includable in a wikitext page.
33 * @TODO: allow native handling, bypassing wikitext representation, like for includable special pages.
34 * @TODO: use in parser, etc!
36 public abstract function getWikitextForTransclusion( );
39 * Returns a textual representation of the content suitable for use in edit summaries and log messages.
43 * @param int $maxlength maximum length of the summary text
44 * @return String the summary text
46 public abstract function getTextForSummary( $maxlength = 250 );
49 * Returns native represenation of the data. Interpretation depends on the data model used,
50 * as given by getDataModel().
54 * @return mixed the native representation of the content. Could be a string, a nested array
55 * structure, an object, a binary blob... anything, really.
57 * @NOTE: review all calls carefully, caller must be aware of content model!
59 public abstract function getNativeData( );
62 * returns the content's nominal size in bogo-bytes.
66 public abstract function getSize( );
71 public function __construct( $model_name = null ) {
72 $this->model_name
= $model_name;
76 * Returns the name of the content model used by this content objects.
77 * Corresponds to the CONTENT_MODEL_XXX constants.
81 * @return String the model name
83 public function getModelName() {
84 return $this->model_name
;
88 * Throws an MWException if $model_name is not the name of the content model
89 * supported by this Content object.
91 * @param String $model_name the model to check
93 protected function checkModelName( $model_name ) {
94 if ( $model_name !== $this->model_name
) {
95 throw new MWException( "Bad content model: expected " . $this->model_name
. " but got found " . $model_name );
100 * Conveniance method that returns the ContentHandler singleton for handling the content
101 * model this Content object uses.
103 * Shorthand for ContentHandler::getForContent( $this )
107 * @return ContentHandler
109 public function getContentHandler() {
110 return ContentHandler
::getForContent( $this );
114 * Conveniance method that returns the default serialization format for the content model
115 * model this Content object uses.
117 * Shorthand for $this->getContentHandler()->getDefaultFormat()
121 * @return ContentHandler
123 public function getDefaultFormat() {
124 return $this->getContentHandler()->getDefaultFormat();
128 * Conveniance method that returns the list of serialization formats supported
129 * for the content model model this Content object uses.
131 * Shorthand for $this->getContentHandler()->getSupportedFormats()
135 * @return array of supported serialization formats
137 public function getSupportedFormats() {
138 return $this->getContentHandler()->getSupportedFormats();
142 * Returns true if $format is a supported serialization format for this Content object,
145 * Note that this will always return true if $format is null, because null stands for the
146 * default serialization.
148 * Shorthand for $this->getContentHandler()->isSupportedFormat( $format )
152 * @param String $format the format to check
153 * @return bool whether the format is supported
155 public function isSupportedFormat( $format ) {
157 return true; // this means "use the default"
160 return $this->getContentHandler()->isSupportedFormat( $format );
164 * Throws an MWException if $this->isSupportedFormat( $format ) doesn't return true.
167 * @throws MWException
169 protected function checkFormat( $format ) {
170 if ( !$this->isSupportedFormat( $format ) ) {
171 throw new MWException( "Format $format is not supported for content model " . $this->getModelName() );
176 * Conveniance method for serializing this Content object.
178 * Shorthand for $this->getContentHandler()->serializeContent( $this, $format )
182 * @param null|String $format the desired serialization format (or null for the default format).
183 * @return String serialized form of this Content object
185 public function serialize( $format = null ) {
186 return $this->getContentHandler()->serializeContent( $this, $format );
190 * Returns true if this Content object represents empty content.
194 * @return bool whether this Content object is empty
196 public function isEmpty() {
197 return $this->getSize() == 0;
201 * Returns true if this Content objects is conceptually equivalent to the given Content object.
203 * Will returns false if $that is null.
204 * Will return true if $that === $this.
205 * Will return false if $that->getModleName() != $this->getModelName().
206 * Will return false if $that->getNativeData() is not equal to $this->getNativeData(),
207 * where the meaning of "equal" depends on the actual data model.
209 * Implementations should be careful to make equals() transitive and reflexive:
211 * * $a->equals( $b ) <=> $b->equals( $b )
212 * * $a->equals( $b ) && $b->equals( $c ) ==> $a->equals( $c )
216 * @param Content $that the Content object to compare to
217 * @return bool true if this Content object is euqual to $that, false otherwise.
219 public function equals( Content
$that = null ) {
220 if ( is_null( $that ) ){
224 if ( $that === $this ) {
228 if ( $that->getModelName() !== $this->getModelName() ) {
232 return $this->getNativeData() === $that->getNativeData();
236 * Return a copy of this Content object. The following must be true for the object returned
237 * if $copy = $original->copy()
239 * * get_class($original) === get_class($copy)
240 * * $original->getModelName() === $copy->getModelName()
241 * * $original->equals( $copy )
243 * If and only if the Content object is imutable, the copy() method can and should
244 * return $this. That is, $copy === $original may be true, but only for imutable content
249 * @return Content. A copy of this object
251 public abstract function copy( );
254 * Returns true if this content is countable as a "real" wiki page, provided
255 * that it's also in a countable location (e.g. a current revision in the main namespace).
259 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
260 * to avoid redundant parsing to find out.
263 public abstract function isCountable( $hasLinks = null ) ;
266 * @param IContextSource $context
268 * @param null|ParserOptions $options
269 * @param Boolean $generateHtml whether to generate Html (default: true). If false,
270 * the result of calling getText() on the ParserOutput object returned by
271 * this method is undefined.
275 * @return ParserOutput
277 public abstract function getParserOutput( IContextSource
$context, $revId = null, ParserOptions
$options = NULL, $generateHtml = true );
280 * Construct the redirect destination from this content and return an
281 * array of Titles, or null if this content doesn't represent a redirect.
282 * The last element in the array is the final destination after all redirects
283 * have been resolved (up to $wgMaxRedirects times).
287 * @return Array of Titles, with the destination last
289 public function getRedirectChain() {
294 * Construct the redirect destination from this content and return an
295 * array of Titles, or null if this content doesn't represent a redirect.
296 * This will only return the immediate redirect target, useful for
297 * the redirect table and other checks that don't need full recursion.
301 * @return Title: The corresponding Title
303 public function getRedirectTarget() {
308 * Construct the redirect destination from this content and return the
309 * Title, or null if this content doesn't represent a redirect.
310 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
311 * in order to provide (hopefully) the Title of the final destination instead of another redirect.
317 public function getUltimateRedirectTarget() {
326 public function isRedirect() {
327 return $this->getRedirectTarget() !== null;
331 * Returns the section with the given id.
333 * The default implementation returns null.
337 * @param String $sectionId the section's id, given as a numeric string. The id "0" retrieves the section before
338 * the first heading, "1" the text between the first heading (inluded) and the second heading (excluded), etc.
339 * @return Content|Boolean|null the section, or false if no such section exist, or null if sections are not supported
341 public function getSection( $sectionId ) {
346 * Replaces a section of the content and returns a Content object with the section replaced.
350 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
351 * @param $with Content: new content of the section
352 * @param $sectionTitle String: new section's subject, only if $section is 'new'
353 * @return string Complete article text, or null if error
355 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
360 * Returns a Content object with pre-save transformations applied (or this object if no transformations apply).
364 * @param Title $title
366 * @param null|ParserOptions $popts
369 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
374 * Returns a new WikitextContent object with the given section heading prepended, if supported.
375 * The default implementation just returns this Content object unmodified, ignoring the section header.
379 * @param $header String
382 public function addSectionHeader( $header ) {
387 * Returns a Content object with preload transformations applied (or this object if no transformations apply).
391 * @param Title $title
392 * @param null|ParserOptions $popts
395 public function preloadTransform( Title
$title, ParserOptions
$popts ) {
399 # TODO: handle ImagePage and CategoryPage
400 # TODO: make sure we cover lucene search / wikisearch.
401 # TODO: make sure ReplaceTemplates still works
402 # FUTURE: nice&sane integration of GeSHi syntax highlighting
403 # [11:59] <vvv> Hooks are ugly; make CodeHighlighter interface and a config to set the class which handles syntax highlighting
404 # [12:00] <vvv> And default it to a DummyHighlighter
406 # TODO: make sure we cover the external editor interface (does anyone actually use that?!)
408 # TODO: tie into API to provide contentModel for Revisions
409 # TODO: tie into API to provide serialized version and contentFormat for Revisions
410 # TODO: tie into API edit interface
411 # FUTURE: make EditForm plugin for EditPage
413 # FUTURE: special type for redirects?!
414 # FUTURE: MultipartMultipart < WikipageContent (Main + Links + X)
415 # FUTURE: LinksContent < LanguageLinksContent, CategoriesContent
418 * Content object implementation for representing flat text.
420 * TextContent instances are imutable
424 abstract class TextContent
extends Content
{
426 public function __construct( $text, $model_name = null ) {
427 parent
::__construct( $model_name );
429 $this->mText
= $text;
432 public function copy() {
433 return $this; #NOTE: this is ok since TextContent are imutable.
436 public function getTextForSummary( $maxlength = 250 ) {
439 $text = $this->getNativeData();
441 $truncatedtext = $wgContLang->truncate(
442 preg_replace( "/[\n\r]/", ' ', $text ),
443 max( 0, $maxlength ) );
445 return $truncatedtext;
449 * returns the text's size in bytes.
451 * @return int the size
453 public function getSize( ) {
454 $text = $this->getNativeData( );
455 return strlen( $text );
459 * Returns true if this content is not a redirect, and $wgArticleCountMethod is "any".
461 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
462 * to avoid redundant parsing to find out.
464 * @return bool true if the content is countable
466 public function isCountable( $hasLinks = null ) {
467 global $wgArticleCountMethod;
469 if ( $this->isRedirect( ) ) {
473 if ( $wgArticleCountMethod === 'any' ) {
481 * Returns the text represented by this Content object, as a string.
483 * @return String the raw text
485 public function getNativeData( ) {
486 $text = $this->mText
;
491 * Returns the text represented by this Content object, as a string.
493 * @return String the raw text
495 public function getTextForSearchIndex( ) {
496 return $this->getNativeData();
500 * Returns the text represented by this Content object, as a string.
502 * @return String the raw text
504 public function getWikitextForTransclusion( ) {
505 return $this->getNativeData();
509 * Returns a generic ParserOutput object, wrapping the HTML returned by getHtml().
511 * @return ParserOutput representing the HTML form of the text
513 public function getParserOutput( IContextSource
$context, $revId = null, ParserOptions
$options = null, $generateHtml = true ) {
514 # generic implementation, relying on $this->getHtml()
516 if ( $generateHtml ) $html = $this->getHtml( $options );
519 $po = new ParserOutput( $html );
524 protected abstract function getHtml( );
531 class WikitextContent
extends TextContent
{
533 public function __construct( $text ) {
534 parent
::__construct($text, CONTENT_MODEL_WIKITEXT
);
537 protected function getHtml( ) {
538 throw new MWException( "getHtml() not implemented for wikitext. Use getParserOutput()->getText()." );
542 * Returns a ParserOutput object resulting from parsing the content's text using $wgParser.
546 * @param IContextSource|null $context
548 * @param null|ParserOptions $options
549 * @param bool $generateHtml
551 * @return ParserOutput representing the HTML form of the text
553 public function getParserOutput( IContextSource
$context, $revId = null, ParserOptions
$options = null, $generateHtml = true ) {
557 $options = ParserOptions
::newFromUserAndLang( $context->getUser(), $context->getLanguage() );
560 $po = $wgParser->parse( $this->mText
, $context->getTitle(), $options, true, true, $revId );
566 * Returns the section with the given id.
568 * @param String $sectionId the section's id
569 * @return Content|false|null the section, or false if no such section exist, or null if sections are not supported
571 public function getSection( $section ) {
574 $text = $this->getNativeData();
575 $sect = $wgParser->getSection( $text, $section, false );
577 return new WikitextContent( $sect );
581 * Replaces a section in the wikitext
583 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
584 * @param $with Content: new content of the section
585 * @param $sectionTitle String: new section's subject, only if $section is 'new'
586 * @return Content Complete article content, or null if error
588 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
589 wfProfileIn( __METHOD__
);
591 $myModelName = $this->getModelName();
592 $sectionModelName = $with->getModelName();
594 if ( $sectionModelName != $myModelName ) {
595 throw new MWException( "Incompatible content model for section: document uses $myModelName, section uses $sectionModelName." );
598 $oldtext = $this->getNativeData();
599 $text = $with->getNativeData();
601 if ( $section === '' ) {
602 return $with; #XXX: copy first?
603 } if ( $section == 'new' ) {
604 # Inserting a new section
605 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
606 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
607 $text = strlen( trim( $oldtext ) ) > 0
608 ?
"{$oldtext}\n\n{$subject}{$text}"
609 : "{$subject}{$text}";
612 # Replacing an existing section; roll out the big guns
615 $text = $wgParser->replaceSection( $oldtext, $section, $text );
618 $newContent = new WikitextContent( $text );
620 wfProfileOut( __METHOD__
);
625 * Returns a new WikitextContent object with the given section heading prepended.
627 * @param $header String
630 public function addSectionHeader( $header ) {
631 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $header ) . "\n\n" . $this->getNativeData();
633 return new WikitextContent( $text );
637 * Returns a Content object with pre-save transformations applied (or this object if no transformations apply).
639 * @param Title $title
641 * @param ParserOptions $popts
644 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
645 global $wgParser, $wgConteLang;
647 $text = $this->getNativeData();
648 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
650 return new WikitextContent( $pst );
654 * Returns a Content object with preload transformations applied (or this object if no transformations apply).
656 * @param Title $title
657 * @param ParserOptions $popts
660 public function preloadTransform( Title
$title, ParserOptions
$popts ) {
661 global $wgParser, $wgConteLang;
663 $text = $this->getNativeData();
664 $plt = $wgParser->getPreloadText( $text, $title, $popts );
666 return new WikitextContent( $plt );
669 public function getRedirectChain() {
670 $text = $this->getNativeData();
671 return Title
::newFromRedirectArray( $text );
674 public function getRedirectTarget() {
675 $text = $this->getNativeData();
676 return Title
::newFromRedirect( $text );
679 public function getUltimateRedirectTarget() {
680 $text = $this->getNativeData();
681 return Title
::newFromRedirectRecurse( $text );
685 * Returns true if this content is not a redirect, and this content's text is countable according to
686 * the criteria defiend by $wgArticleCountMethod.
688 * @param Bool $hasLinks if it is known whether this content contains links, provide this information here,
689 * to avoid redundant parsing to find out.
690 * @param IContextSource $context context for parsing if necessary
692 * @return bool true if the content is countable
694 public function isCountable( $hasLinks = null, IContextSource
$context = null ) {
695 global $wgArticleCountMethod, $wgRequest;
697 if ( $this->isRedirect( ) ) {
701 $text = $this->getNativeData();
703 switch ( $wgArticleCountMethod ) {
707 return strpos( $text, ',' ) !== false;
709 if ( $hasLinks === null ) { # not known, find out
710 if ( !$context ) { # make dummy context
711 //XXX: caller of this method often knows the title, but not a context...
712 $context = new RequestContext( $wgRequest );
715 $po = $this->getParserOutput( $context, null, null, false );
716 $links = $po->getLinks();
717 $hasLinks = !empty( $links );
724 public function getTextForSummary( $maxlength = 250 ) {
725 $truncatedtext = parent
::getTextForSummary( $maxlength );
727 #clean up unfinished links
728 #XXX: make this optional? wasn't there in autosummary, but required for deletion summary.
729 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
731 return $truncatedtext;
739 class MessageContent
extends TextContent
{
740 public function __construct( $msg_key, $params = null, $options = null ) {
741 parent
::__construct(null, CONTENT_MODEL_WIKITEXT
); #XXX: messages may be wikitext, html or plain text! and maybe even something else entirely.
743 $this->mMessageKey
= $msg_key;
745 $this->mParameters
= $params;
747 if ( is_null( $options ) ) {
750 elseif ( is_string( $options ) ) {
751 $options = array( $options );
754 $this->mOptions
= $options;
756 $this->mHtmlOptions
= null;
760 * Returns the message as rendered HTML, using the options supplied to the constructor plus "parse".
762 protected function getHtml( ) {
763 $opt = array_merge( $this->mOptions
, array('parse') );
765 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
770 * Returns the message as raw text, using the options supplied to the constructor minus "parse" and "parseinline".
772 public function getNativeData( ) {
773 $opt = array_diff( $this->mOptions
, array('parse', 'parseinline') );
775 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
783 class JavaScriptContent
extends TextContent
{
784 public function __construct( $text ) {
785 parent
::__construct($text, CONTENT_MODEL_JAVASCRIPT
);
788 protected function getHtml( ) {
790 $html .= "<pre class=\"mw-code mw-js\" dir=\"ltr\">\n";
791 $html .= htmlspecialchars( $this->getNativeData() );
792 $html .= "\n</pre>\n";
802 class CssContent
extends TextContent
{
803 public function __construct( $text ) {
804 parent
::__construct($text, CONTENT_MODEL_CSS
);
807 protected function getHtml( ) {
809 $html .= "<pre class=\"mw-code mw-css\" dir=\"ltr\">\n";
810 $html .= htmlspecialchars( $this->getNativeData() );
811 $html .= "\n</pre>\n";