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.
8 abstract class Content
{
10 // TODO: create actual fields and document them
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.
16 public abstract function getTextForSearchIndex( );
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.
22 #TODO: allow native handling, bypassing wikitext representation, like for includable special pages.
23 public abstract function getWikitextForTransclusion( ); #FIXME: use in parser, etc!
26 * Returns a textual representation of the content suitable for use in edit summaries and log messages.
28 * @param int $maxlength maximum length of the summary text
29 * @return String the summary text
31 public abstract function getTextForSummary( $maxlength = 250 );
34 * Returns native represenation of the data. Interpretation depends on the data model used,
35 * as given by getDataModel().
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.
40 public abstract function getNativeData( ); #FIXME: review all calls carefully, caller must be aware of content model!
43 * returns the content's nominal size in bogo-bytes.
47 public abstract function getSize( );
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)
55 public function __construct( $modelName = null ) {
56 $this->mModelName
= $modelName;
60 * Returns the name of the content model used by this content objects.
61 * Corresponds to the CONTENT_MODEL_XXX constants.
63 * @return String the model name
65 public function getModelName() {
66 return $this->mModelName
;
70 * Throws an MWException if $modelName is not the name of the content model
71 * supported by this Content object.
73 protected function checkModelName( $modelName ) {
74 if ( $modelName !== $this->mModelName
) {
75 throw new MWException( "Bad content model: expected " . $this->mModelName
. " but got found " . $modelName );
80 * Conveniance method that returns the ContentHandler singleton for handling the content
81 * model this Content object uses.
83 * Shorthand for ContentHandler::getForContent( $this )
85 * @return ContentHandler
87 public function getContentHandler() {
88 return ContentHandler
::getForContent( $this );
92 * Conveniance method that returns the default serialization format for the content model
93 * model this Content object uses.
95 * Shorthand for $this->getContentHandler()->getDefaultFormat()
97 * @return ContentHandler
99 public function getDefaultFormat() {
100 return $this->getContentHandler()->getDefaultFormat();
104 * Conveniance method that returns the list of serialization formats supported
105 * for the content model model this Content object uses.
107 * Shorthand for $this->getContentHandler()->getSupportedFormats()
109 * @return array of supported serialization formats
111 public function getSupportedFormats() {
112 return $this->getContentHandler()->getSupportedFormats();
116 * Returns true if $format is a supported serialization format for this Content object,
119 * Note that this will always return true if $format is null, because null stands for the
120 * default serialization.
122 * Shorthand for $this->getContentHandler()->isSupportedFormat( $format )
124 * @param String $format the format to check
125 * @return bool whether the format is supported
127 public function isSupportedFormat( $format ) {
129 return true; // this means "use the default"
132 return $this->getContentHandler()->isSupportedFormat( $format );
136 * Throws an MWException if $this->isSupportedFormat( $format ) doesn't return true.
139 * @throws MWException
141 protected function checkFormat( $format ) {
142 if ( !$this->isSupportedFormat( $format ) ) {
143 throw new MWException( "Format $format is not supported for content model " . $this->getModelName() );
148 * Conveniance method for serializing this Content object.
150 * Shorthand for $this->getContentHandler()->serializeContent( $this, $format )
152 * @param null|String $format the desired serialization format (or null for the default format).
153 * @return String serialized form of this Content object
155 public function serialize( $format = null ) {
156 return $this->getContentHandler()->serializeContent( $this, $format );
160 * Returns true if this Content object represents empty content.
162 * @return bool whether this Content object is empty
164 public function isEmpty() {
165 return $this->getSize() == 0;
169 * Returns true if this Content objects is conceptually equivalent to the given Content object.
171 * Will returns false if $that is null.
172 * Will return true if $that === $this.
173 * Will return false if $that->getModleName() != $this->getModelName().
175 * Implementations should be careful to make equals() transitive and reflexive:
177 * * $a->equals( $b ) <=> $b->equals( $b )
178 * * $a->equals( $b ) && $b->equals( $c ) ==> $a->equals( $c )
180 * @param Content $that the Content object to compare to
181 * @return bool true if this Content object is euzqla to $that, false otherwise.
183 public function equals( Content
$that = null ) {
184 if ( empty( $that ) ){ // FIXME: empty on an object?
189 // FIXME: something is doing wrong here, causing the compared objects to always be the same.
190 // Hence returning false for now, so changes can actually be saved...
192 if ( $that === $this ) {
196 if ( $that->getModelName() !== $this->getModelName() ) {
200 return $this->getNativeData() === $that->getNativeData();
204 * Return a copy of this Content object. The following must be true for the object returned
205 * if $copy = $original->copy()
207 * * get_class($original) === get_class($copy)
208 * * $original->getModelName() === $copy->getModelName()
209 * * $original->equals( $copy )
211 * If and only if the Content object is imutable, the copy() method can and should
212 * return $this. That is, $copy === $original may be true, but only for imutable content
215 * @return Content. A copy of this object
217 public abstract function copy( );
220 * Returns true if this content is countable as a "real" wiki page, provided
221 * that it's also in a countable location (e.g. a current revision in the main namespace).
223 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
224 * to avoid redundant parsing to find out.
227 public abstract function isCountable( $hasLinks = null ) ;
230 * @param IContextSource $context
232 * @param null|ParserOptions $options
233 * @param Boolean $generateHtml whether to generate Html (default: true). If false,
234 * the result of calling getText() on the ParserOutput object returned by
235 * this method is undefined.
237 * @return ParserOutput
239 public abstract function getParserOutput( IContextSource
$context, $revId = null, ParserOptions
$options = NULL, $generateHtml = true );
242 * Construct the redirect destination from this content and return an
243 * array of Titles, or null if this content doesn't represent a redirect.
244 * The last element in the array is the final destination after all redirects
245 * have been resolved (up to $wgMaxRedirects times).
247 * @return Array of Titles, with the destination last
249 public function getRedirectChain() {
254 * Construct the redirect destination from this content and return an
255 * array of Titles, or null if this content doesn't represent a redirect.
256 * This will only return the immediate redirect target, useful for
257 * the redirect table and other checks that don't need full recursion.
259 * @return Title: The corresponding Title
261 public function getRedirectTarget() {
266 * Construct the redirect destination from this content and return the
267 * Title, or null if this content doesn't represent a redirect.
268 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
269 * in order to provide (hopefully) the Title of the final destination instead of another redirect.
273 public function getUltimateRedirectTarget() {
277 public function isRedirect() {
278 return $this->getRedirectTarget() != null;
282 * Returns the section with the given id.
284 * The default implementation returns null.
286 * @param String $sectionId the section's id
287 * @return Content|Boolean|null the section, or false if no such section exist, or null if sections are not supported
289 public function getSection( $sectionId ) {
294 * Replaces a section of the content and returns a Content object with the section replaced.
296 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
297 * @param $with Content: new content of the section
298 * @param $sectionTitle String: new section's subject, only if $section is 'new'
299 * @return string Complete article text, or null if error
301 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
306 * Returns a Content object with pre-save transformations applied (or this object if no transformations apply).
308 * @param Title $title
310 * @param null|ParserOptions $popts
313 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts = null ) {
318 * Returns a new WikitextContent object with the given section heading prepended, if supported.
319 * The default implementation just returns this Content object unmodified, ignoring the section header.
321 * @param $header String
324 public function addSectionHeader( $header ) {
329 * Returns a Content object with preload transformations applied (or this object if no transformations apply).
331 * @param Title $title
332 * @param null|ParserOptions $popts
335 public function preloadTransform( Title
$title, ParserOptions
$popts = null ) {
339 # TODO: handle ImagePage and CategoryPage
340 # TODO: hook into dump generation to serialize and record model and format!
342 # TODO: make sure we cover lucene search / wikisearch.
343 # TODO: make sure ReplaceTemplates still works
344 # TODO: nice&sane integration of GeSHi syntax highlighting
345 # [11:59] <vvv> Hooks are ugly; make CodeHighlighter interface and a config to set the class which handles syntax highlighting
346 # [12:00] <vvv> And default it to a DummyHighlighter
348 # TODO: make sure we cover the external editor interface (does anyone actually use that?!)
350 # TODO: tie into API to provide contentModel for Revisions
351 # TODO: tie into API to provide serialized version and contentFormat for Revisions
352 # TODO: tie into API edit interface
353 # TODO: make EditForm plugin for EditPage
355 # XXX: isCacheable( ) # can/should we do this here?
359 * Content object implementation for representing flat text.
361 * TextContent instances are imutable
363 abstract class TextContent
extends Content
{
365 public function __construct( $text, $modelName = null ) {
366 parent
::__construct( $modelName );
368 $this->mText
= $text;
371 public function copy() {
372 return $this; #NOTE: this is ok since TextContent are imutable.
375 public function getTextForSummary( $maxlength = 250 ) {
378 $text = $this->getNativeData();
380 $truncatedtext = $wgContLang->truncate(
381 preg_replace( "/[\n\r]/", ' ', $text ),
382 max( 0, $maxlength ) );
384 return $truncatedtext;
388 * returns the content's nominal size in bogo-bytes.
390 public function getSize( ) {
391 $text = $this->getNativeData( );
392 return strlen( $text );
396 * Returns true if this content is not a redirect, and $wgArticleCountMethod is "any".
398 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
399 * to avoid redundant parsing to find out.
401 public function isCountable( $hasLinks = null ) {
402 global $wgArticleCountMethod;
404 if ( $this->isRedirect( ) ) {
408 if ( $wgArticleCountMethod === 'any' ) {
416 * Returns the text represented by this Content object, as a string.
418 * @return String the raw text
420 public function getNativeData( ) {
421 $text = $this->mText
;
426 * Returns the text represented by this Content object, as a string.
428 * @return String the raw text
430 public function getTextForSearchIndex( ) { #FIXME: use!
431 return $this->getNativeData();
435 * Returns the text represented by this Content object, as a string.
437 * @return String the raw text
439 public function getWikitextForTransclusion( ) { #FIXME: use!
440 return $this->getNativeData();
444 * Returns a generic ParserOutput object, wrapping the HTML returned by getHtml().
446 * @return ParserOutput representing the HTML form of the text
448 public function getParserOutput( IContextSource
$context, $revId = null, ParserOptions
$options = null, $generateHtml = true ) {
449 # generic implementation, relying on $this->getHtml()
451 if ( $generateHtml ) $html = $this->getHtml( $options );
454 $po = new ParserOutput( $html );
459 protected abstract function getHtml( );
463 class WikitextContent
extends TextContent
{
465 public function __construct( $text ) {
466 parent
::__construct($text, CONTENT_MODEL_WIKITEXT
);
468 $this->mDefaultParserOptions
= null; #TODO: use per-class static member?!
471 protected function getHtml( ) {
472 throw new MWException( "getHtml() not implemented for wikitext. Use getParserOutput()->getText()." );
475 public function getDefaultParserOptions() {
476 global $wgUser, $wgContLang;
478 if ( !$this->mDefaultParserOptions
) { #TODO: use per-class static member?!
479 $this->mDefaultParserOptions
= ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
482 return $this->mDefaultParserOptions
;
486 * Returns a ParserOutput object resulting from parsing the content's text using $wgParser.
490 * @param IContextSource|null $context
492 * @param null|ParserOptions $options
493 * @param bool $generateHtml
495 * @return ParserOutput representing the HTML form of the text
497 public function getParserOutput( IContextSource
$context, $revId = null, ParserOptions
$options = null, $generateHtml = true ) {
501 $options = $this->getDefaultParserOptions();
504 $po = $wgParser->parse( $this->mText
, $context->getTitle(), $options, true, true, $revId );
510 * Returns the section with the given id.
512 * @param String $sectionId the section's id
513 * @return Content|false|null the section, or false if no such section exist, or null if sections are not supported
515 public function getSection( $section ) {
518 $text = $this->getNativeData();
519 $sect = $wgParser->getSection( $text, $section, false );
521 return new WikitextContent( $sect );
525 * Replaces a section in the wikitext
527 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
528 * @param $with Content: new content of the section
529 * @param $sectionTitle String: new section's subject, only if $section is 'new'
530 * @return string Complete article text, or null if error
532 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
533 wfProfileIn( __METHOD__
);
535 $myModelName = $this->getModelName();
536 $sectionModelName = $with->getModelName();
538 if ( $sectionModelName != $myModelName ) {
539 throw new MWException( "Incompatible content model for section: document uses $myModelName, section uses $sectionModelName." );
542 $oldtext = $this->getNativeData();
543 $text = $with->getNativeData();
545 if ( $section == 'new' ) {
546 # Inserting a new section
547 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
548 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
549 $text = strlen( trim( $oldtext ) ) > 0
550 ?
"{$oldtext}\n\n{$subject}{$text}"
551 : "{$subject}{$text}";
554 # Replacing an existing section; roll out the big guns
557 $text = $wgParser->replaceSection( $oldtext, $section, $text );
560 $newContent = new WikitextContent( $text );
562 wfProfileOut( __METHOD__
);
567 * Returns a new WikitextContent object with the given section heading prepended.
569 * @param $header String
572 public function addSectionHeader( $header ) {
573 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle
) . "\n\n" . $this->getNativeData();
575 return new WikitextContent( $text );
579 * Returns a Content object with pre-save transformations applied (or this object if no transformations apply).
581 * @param Title $title
583 * @param null|ParserOptions $popts
586 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts = null ) {
589 if ( $popts == null ) $popts = $this->getDefaultParserOptions();
591 $text = $this->getNativeData();
592 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
594 return new WikitextContent( $pst );
598 * Returns a Content object with preload transformations applied (or this object if no transformations apply).
600 * @param Title $title
601 * @param null|ParserOptions $popts
604 public function preloadTransform( Title
$title, ParserOptions
$popts = null ) {
607 if ( $popts == null ) $popts = $this->getDefaultParserOptions();
609 $text = $this->getNativeData();
610 $plt = $wgParser->getPreloadText( $text, $title, $popts );
612 return new WikitextContent( $plt );
615 public function getRedirectChain() {
616 $text = $this->getNativeData();
617 return Title
::newFromRedirectArray( $text );
620 public function getRedirectTarget() {
621 $text = $this->getNativeData();
622 return Title
::newFromRedirect( $text );
625 public function getUltimateRedirectTarget() {
626 $text = $this->getNativeData();
627 return Title
::newFromRedirectRecurse( $text );
631 * Returns true if this content is not a redirect, and this content's text is countable according to
632 * the criteria defiend by $wgArticleCountMethod.
634 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
635 * to avoid redundant parsing to find out.
637 public function isCountable( $hasLinks = null ) {
638 global $wgArticleCountMethod;
640 if ( $this->isRedirect( ) ) {
644 $text = $this->getNativeData();
646 switch ( $wgArticleCountMethod ) {
650 if ( $text === false ) {
651 $text = $this->getRawText();
653 return strpos( $text, ',' ) !== false;
655 if ( $hasLinks === null ) { # not know, find out
656 $po = $this->getParserOutput();
657 $links = $po->getLinks();
658 $hasLinks = !empty( $links );
665 public function getTextForSummary( $maxlength = 250 ) {
666 $truncatedtext = parent
::getTextForSummary( $maxlength );
668 #clean up unfinished links
669 #XXX: make this optional? wasn't there in autosummary, but required for deletion summary.
670 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
672 return $truncatedtext;
677 class MessageContent
extends TextContent
{
678 public function __construct( $msg_key, $params = null, $options = null ) {
679 parent
::__construct(null, CONTENT_MODEL_WIKITEXT
); #XXX: messages may be wikitext, html or plain text! and maybe even something else entirely.
681 $this->mMessageKey
= $msg_key;
683 $this->mParameters
= $params;
685 if ( is_null( $options ) ) {
688 elseif ( is_string( $options ) ) {
689 $options = array( $options );
692 $this->mOptions
= $options;
694 $this->mHtmlOptions
= null;
698 * Returns the message as rendered HTML, using the options supplied to the constructor plus "parse".
700 protected function getHtml( ) {
701 $opt = array_merge( $this->mOptions
, array('parse') );
703 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
708 * Returns the message as raw text, using the options supplied to the constructor minus "parse" and "parseinline".
710 public function getNativeData( ) {
711 $opt = array_diff( $this->mOptions
, array('parse', 'parseinline') );
713 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
719 class JavaScriptContent
extends TextContent
{
720 public function __construct( $text ) {
721 parent
::__construct($text, CONTENT_MODEL_JAVASCRIPT
);
724 protected function getHtml( ) {
726 $html .= "<pre class=\"mw-code mw-js\" dir=\"ltr\">\n";
727 $html .= htmlspecialchars( $this->getNativeData() );
728 $html .= "\n</pre>\n";
735 class CssContent
extends TextContent
{
736 public function __construct( $text ) {
737 parent
::__construct($text, CONTENT_MODEL_CSS
);
740 protected function getHtml( ) {
742 $html .= "<pre class=\"mw-code mw-css\" dir=\"ltr\">\n";
743 $html .= htmlspecialchars( $this->getNativeData() );
744 $html .= "\n</pre>\n";
750 #FUTURE: special type for redirects?!
751 #FUTURE: MultipartMultipart < WikipageContent (Main + Links + X)
752 #FUTURE: LinksContent < LanguageLinksContent, CategoriesContent
753 #EXAMPLE: CoordinatesContent
754 #EXAMPLE: WikidataContent