162920352c512eeb0c5d61c3aafa9f3d9bfc8d26
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;
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( );
63 public function __construct( $model_name = null ) {
64 $this->model_name
= $model_name;
68 * Returns the name of the content model used by this content objects.
69 * Corresponds to the CONTENT_MODEL_XXX constants.
71 * @return String the model name
73 public function getModelName() {
74 return $this->model_name
;
78 * Throws an MWException if $model_name is not the name of the content model
79 * supported by this Content object.
81 * @param String $model_name the model to check
83 protected function checkModelName( $model_name ) {
84 if ( $model_name !== $this->model_name
) {
85 throw new MWException( "Bad content model: expected " . $this->model_name
. " but got found " . $model_name );
90 * Conveniance method that returns the ContentHandler singleton for handling the content
91 * model this Content object uses.
93 * Shorthand for ContentHandler::getForContent( $this )
95 * @return ContentHandler
97 public function getContentHandler() {
98 return ContentHandler
::getForContent( $this );
102 * Conveniance method that returns the default serialization format for the content model
103 * model this Content object uses.
105 * Shorthand for $this->getContentHandler()->getDefaultFormat()
107 * @return ContentHandler
109 public function getDefaultFormat() {
110 return $this->getContentHandler()->getDefaultFormat();
114 * Conveniance method that returns the list of serialization formats supported
115 * for the content model model this Content object uses.
117 * Shorthand for $this->getContentHandler()->getSupportedFormats()
119 * @return array of supported serialization formats
121 public function getSupportedFormats() {
122 return $this->getContentHandler()->getSupportedFormats();
126 * Returns true if $format is a supported serialization format for this Content object,
129 * Note that this will always return true if $format is null, because null stands for the
130 * default serialization.
132 * Shorthand for $this->getContentHandler()->isSupportedFormat( $format )
134 * @param String $format the format to check
135 * @return bool whether the format is supported
137 public function isSupportedFormat( $format ) {
139 return true; // this means "use the default"
142 return $this->getContentHandler()->isSupportedFormat( $format );
146 * Throws an MWException if $this->isSupportedFormat( $format ) doesn't return true.
149 * @throws MWException
151 protected function checkFormat( $format ) {
152 if ( !$this->isSupportedFormat( $format ) ) {
153 throw new MWException( "Format $format is not supported for content model " . $this->getModelName() );
158 * Conveniance method for serializing this Content object.
160 * Shorthand for $this->getContentHandler()->serializeContent( $this, $format )
162 * @param null|String $format the desired serialization format (or null for the default format).
163 * @return String serialized form of this Content object
165 public function serialize( $format = null ) {
166 return $this->getContentHandler()->serializeContent( $this, $format );
170 * Returns true if this Content object represents empty content.
172 * @return bool whether this Content object is empty
174 public function isEmpty() {
175 return $this->getSize() == 0;
179 * Returns true if this Content objects is conceptually equivalent to the given Content object.
181 * Will returns false if $that is null.
182 * Will return true if $that === $this.
183 * Will return false if $that->getModleName() != $this->getModelName().
184 * Will return false if $that->getNativeData() is not equal to $this->getNativeData(),
185 * where the meaning of "equal" depends on the actual data model.
187 * Implementations should be careful to make equals() transitive and reflexive:
189 * * $a->equals( $b ) <=> $b->equals( $b )
190 * * $a->equals( $b ) && $b->equals( $c ) ==> $a->equals( $c )
192 * @param Content $that the Content object to compare to
193 * @return bool true if this Content object is euqual to $that, false otherwise.
195 public function equals( Content
$that = null ) {
196 if ( is_null( $that ) ){
200 if ( $that === $this ) {
204 if ( $that->getModelName() !== $this->getModelName() ) {
208 return $this->getNativeData() === $that->getNativeData();
212 * Return a copy of this Content object. The following must be true for the object returned
213 * if $copy = $original->copy()
215 * * get_class($original) === get_class($copy)
216 * * $original->getModelName() === $copy->getModelName()
217 * * $original->equals( $copy )
219 * If and only if the Content object is imutable, the copy() method can and should
220 * return $this. That is, $copy === $original may be true, but only for imutable content
223 * @return Content. A copy of this object
225 public abstract function copy( );
228 * Returns true if this content is countable as a "real" wiki page, provided
229 * that it's also in a countable location (e.g. a current revision in the main namespace).
231 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
232 * to avoid redundant parsing to find out.
235 public abstract function isCountable( $hasLinks = null ) ;
238 * @param IContextSource $context
240 * @param null|ParserOptions $options
241 * @param Boolean $generateHtml whether to generate Html (default: true). If false,
242 * the result of calling getText() on the ParserOutput object returned by
243 * this method is undefined.
245 * @return ParserOutput
247 public abstract function getParserOutput( IContextSource
$context, $revId = null, ParserOptions
$options = NULL, $generateHtml = true );
250 * Construct the redirect destination from this content and return an
251 * array of Titles, or null if this content doesn't represent a redirect.
252 * The last element in the array is the final destination after all redirects
253 * have been resolved (up to $wgMaxRedirects times).
255 * @return Array of Titles, with the destination last
257 public function getRedirectChain() {
262 * Construct the redirect destination from this content and return an
263 * array of Titles, or null if this content doesn't represent a redirect.
264 * This will only return the immediate redirect target, useful for
265 * the redirect table and other checks that don't need full recursion.
267 * @return Title: The corresponding Title
269 public function getRedirectTarget() {
274 * Construct the redirect destination from this content and return the
275 * Title, or null if this content doesn't represent a redirect.
276 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
277 * in order to provide (hopefully) the Title of the final destination instead of another redirect.
281 public function getUltimateRedirectTarget() {
285 public function isRedirect() {
286 return $this->getRedirectTarget() != null;
290 * Returns the section with the given id.
292 * The default implementation returns null.
294 * @param String $sectionId the section's id, given as a numeric string. The id "0" retrieves the section before
295 * the first heading, "1" the text between the first heading (inluded) and the second heading (excluded), etc.
296 * @return Content|Boolean|null the section, or false if no such section exist, or null if sections are not supported
298 public function getSection( $sectionId ) {
303 * Replaces a section of the content and returns a Content object with the section replaced.
305 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
306 * @param $with Content: new content of the section
307 * @param $sectionTitle String: new section's subject, only if $section is 'new'
308 * @return string Complete article text, or null if error
310 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
315 * Returns a Content object with pre-save transformations applied (or this object if no transformations apply).
317 * @param Title $title
319 * @param null|ParserOptions $popts
322 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
327 * Returns a new WikitextContent object with the given section heading prepended, if supported.
328 * The default implementation just returns this Content object unmodified, ignoring the section header.
330 * @param $header String
333 public function addSectionHeader( $header ) {
338 * Returns a Content object with preload transformations applied (or this object if no transformations apply).
340 * @param Title $title
341 * @param null|ParserOptions $popts
344 public function preloadTransform( Title
$title, ParserOptions
$popts ) {
348 # TODO: handle ImagePage and CategoryPage
349 # TODO: make sure we cover lucene search / wikisearch.
350 # TODO: make sure ReplaceTemplates still works
351 # FUTURE: nice&sane integration of GeSHi syntax highlighting
352 # [11:59] <vvv> Hooks are ugly; make CodeHighlighter interface and a config to set the class which handles syntax highlighting
353 # [12:00] <vvv> And default it to a DummyHighlighter
355 # TODO: make sure we cover the external editor interface (does anyone actually use that?!)
357 # TODO: tie into API to provide contentModel for Revisions
358 # TODO: tie into API to provide serialized version and contentFormat for Revisions
359 # TODO: tie into API edit interface
360 # FUTURE: make EditForm plugin for EditPage
362 # FUTURE: special type for redirects?!
363 # FUTURE: MultipartMultipart < WikipageContent (Main + Links + X)
364 # FUTURE: LinksContent < LanguageLinksContent, CategoriesContent
367 * Content object implementation for representing flat text.
369 * TextContent instances are imutable
371 abstract class TextContent
extends Content
{
373 public function __construct( $text, $model_name = null ) {
374 parent
::__construct( $model_name );
376 $this->mText
= $text;
379 public function copy() {
380 return $this; #NOTE: this is ok since TextContent are imutable.
383 public function getTextForSummary( $maxlength = 250 ) {
386 $text = $this->getNativeData();
388 $truncatedtext = $wgContLang->truncate(
389 preg_replace( "/[\n\r]/", ' ', $text ),
390 max( 0, $maxlength ) );
392 return $truncatedtext;
396 * returns the text's size in bytes.
398 * @return int the size
400 public function getSize( ) {
401 $text = $this->getNativeData( );
402 return strlen( $text );
406 * Returns true if this content is not a redirect, and $wgArticleCountMethod is "any".
408 * @param $hasLinks Bool: if it is known whether this content contains links, provide this information here,
409 * to avoid redundant parsing to find out.
411 * @return bool true if the content is countable
413 public function isCountable( $hasLinks = null ) {
414 global $wgArticleCountMethod;
416 if ( $this->isRedirect( ) ) {
420 if ( $wgArticleCountMethod === 'any' ) {
428 * Returns the text represented by this Content object, as a string.
430 * @return String the raw text
432 public function getNativeData( ) {
433 $text = $this->mText
;
438 * Returns the text represented by this Content object, as a string.
440 * @return String the raw text
442 public function getTextForSearchIndex( ) {
443 return $this->getNativeData();
447 * Returns the text represented by this Content object, as a string.
449 * @return String the raw text
451 public function getWikitextForTransclusion( ) {
452 return $this->getNativeData();
456 * Returns a generic ParserOutput object, wrapping the HTML returned by getHtml().
458 * @return ParserOutput representing the HTML form of the text
460 public function getParserOutput( IContextSource
$context, $revId = null, ParserOptions
$options = null, $generateHtml = true ) {
461 # generic implementation, relying on $this->getHtml()
463 if ( $generateHtml ) $html = $this->getHtml( $options );
466 $po = new ParserOutput( $html );
471 protected abstract function getHtml( );
475 class WikitextContent
extends TextContent
{
477 public function __construct( $text ) {
478 parent
::__construct($text, CONTENT_MODEL_WIKITEXT
);
481 protected function getHtml( ) {
482 throw new MWException( "getHtml() not implemented for wikitext. Use getParserOutput()->getText()." );
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 = ParserOptions
::newFromUserAndLang( $context->getUser(), $context->getLanguage() );
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 Content Complete article content, 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 === '' ) {
546 return $with; #XXX: copy first?
547 } if ( $section == 'new' ) {
548 # Inserting a new section
549 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
550 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
551 $text = strlen( trim( $oldtext ) ) > 0
552 ?
"{$oldtext}\n\n{$subject}{$text}"
553 : "{$subject}{$text}";
556 # Replacing an existing section; roll out the big guns
559 $text = $wgParser->replaceSection( $oldtext, $section, $text );
562 $newContent = new WikitextContent( $text );
564 wfProfileOut( __METHOD__
);
569 * Returns a new WikitextContent object with the given section heading prepended.
571 * @param $header String
574 public function addSectionHeader( $header ) {
575 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $header ) . "\n\n" . $this->getNativeData();
577 return new WikitextContent( $text );
581 * Returns a Content object with pre-save transformations applied (or this object if no transformations apply).
583 * @param Title $title
585 * @param ParserOptions $popts
588 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
589 global $wgParser, $wgConteLang;
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 ParserOptions $popts
604 public function preloadTransform( Title
$title, ParserOptions
$popts ) {
605 global $wgParser, $wgConteLang;
607 $text = $this->getNativeData();
608 $plt = $wgParser->getPreloadText( $text, $title, $popts );
610 return new WikitextContent( $plt );
613 public function getRedirectChain() {
614 $text = $this->getNativeData();
615 return Title
::newFromRedirectArray( $text );
618 public function getRedirectTarget() {
619 $text = $this->getNativeData();
620 return Title
::newFromRedirect( $text );
623 public function getUltimateRedirectTarget() {
624 $text = $this->getNativeData();
625 return Title
::newFromRedirectRecurse( $text );
629 * Returns true if this content is not a redirect, and this content's text is countable according to
630 * the criteria defiend by $wgArticleCountMethod.
632 * @param Bool $hasLinks if it is known whether this content contains links, provide this information here,
633 * to avoid redundant parsing to find out.
634 * @param IContextSource $context context for parsing if necessary
636 * @return bool true if the content is countable
638 public function isCountable( $hasLinks = null, IContextSource
$context = null ) {
639 global $wgArticleCountMethod, $wgRequest;
641 if ( $this->isRedirect( ) ) {
645 $text = $this->getNativeData();
647 switch ( $wgArticleCountMethod ) {
651 return strpos( $text, ',' ) !== false;
653 if ( $hasLinks === null ) { # not known, find out
654 if ( !$context ) { # make dummy context
655 //XXX: caller of this method often knows the title, but not a context...
656 $context = new RequestContext( $wgRequest );
659 $po = $this->getParserOutput( $context, null, null, false );
660 $links = $po->getLinks();
661 $hasLinks = !empty( $links );
668 public function getTextForSummary( $maxlength = 250 ) {
669 $truncatedtext = parent
::getTextForSummary( $maxlength );
671 #clean up unfinished links
672 #XXX: make this optional? wasn't there in autosummary, but required for deletion summary.
673 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
675 return $truncatedtext;
680 class MessageContent
extends TextContent
{
681 public function __construct( $msg_key, $params = null, $options = null ) {
682 parent
::__construct(null, CONTENT_MODEL_WIKITEXT
); #XXX: messages may be wikitext, html or plain text! and maybe even something else entirely.
684 $this->mMessageKey
= $msg_key;
686 $this->mParameters
= $params;
688 if ( is_null( $options ) ) {
691 elseif ( is_string( $options ) ) {
692 $options = array( $options );
695 $this->mOptions
= $options;
697 $this->mHtmlOptions
= null;
701 * Returns the message as rendered HTML, using the options supplied to the constructor plus "parse".
703 protected function getHtml( ) {
704 $opt = array_merge( $this->mOptions
, array('parse') );
706 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
711 * Returns the message as raw text, using the options supplied to the constructor minus "parse" and "parseinline".
713 public function getNativeData( ) {
714 $opt = array_diff( $this->mOptions
, array('parse', 'parseinline') );
716 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
722 class JavaScriptContent
extends TextContent
{
723 public function __construct( $text ) {
724 parent
::__construct($text, CONTENT_MODEL_JAVASCRIPT
);
727 protected function getHtml( ) {
729 $html .= "<pre class=\"mw-code mw-js\" dir=\"ltr\">\n";
730 $html .= htmlspecialchars( $this->getNativeData() );
731 $html .= "\n</pre>\n";
738 class CssContent
extends TextContent
{
739 public function __construct( $text ) {
740 parent
::__construct($text, CONTENT_MODEL_CSS
);
743 protected function getHtml( ) {
745 $html .= "<pre class=\"mw-code mw-css\" dir=\"ltr\">\n";
746 $html .= htmlspecialchars( $this->getNativeData() );
747 $html .= "\n</pre>\n";