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.
13 * @return string A string representing the content in a way useful for
14 * building a full text search index. If no useful representation exists,
15 * this method returns an empty string.
17 * @todo: test that this actually works
18 * @todo: make sure this also works with LuceneSearch / WikiSearch
20 public function getTextForSearchIndex( );
25 * @return string The wikitext to include when another page includes this
26 * content, or false if the content is not includable in a wikitext page.
28 * @TODO: allow native handling, bypassing wikitext representation, like
29 * for includable special pages.
30 * @TODO: allow transclusion into other content models than Wikitext!
31 * @TODO: used in WikiPage and MessageCache to get message text. Not so
32 * nice. What should we use instead?!
34 public function getWikitextForTransclusion( );
37 * Returns a textual representation of the content suitable for use in edit
38 * summaries and log messages.
42 * @param $maxlength int Maximum length of the summary text
43 * @return The summary text
45 public function getTextForSummary( $maxlength = 250 );
48 * Returns native representation of the data. Interpretation depends on
49 * the data model used, as given by getDataModel().
53 * @return mixed The native representation of the content. Could be a
54 * string, a nested array structure, an object, a binary blob...
57 * @NOTE: review all calls carefully, caller must be aware of content model!
59 public function getNativeData( );
62 * Returns the content's nominal size in bogo-bytes.
66 public function getSize( );
69 * Returns the ID of the content model used by this Content object.
70 * Corresponds to the CONTENT_MODEL_XXX constants.
74 * @return int The model id
76 public function getModel();
79 * Convenience method that returns the ContentHandler singleton for handling
80 * the content model that this Content object uses.
82 * Shorthand for ContentHandler::getForContent( $this )
86 * @return ContentHandler
88 public function getContentHandler();
91 * Convenience method that returns the default serialization format for the
92 * content model that this Content object uses.
94 * Shorthand for $this->getContentHandler()->getDefaultFormat()
98 * @return ContentHandler
100 public function getDefaultFormat();
103 * Convenience method that returns the list of serialization formats
104 * supported for the content model that this Content object uses.
106 * Shorthand for $this->getContentHandler()->getSupportedFormats()
110 * @return Array of supported serialization formats
112 public function getSupportedFormats();
115 * Returns true if $format is a supported serialization format for this
116 * Content object, false if it isn't.
118 * Note that this should always return true if $format is null, because null
119 * stands for the default serialization.
121 * Shorthand for $this->getContentHandler()->isSupportedFormat( $format )
125 * @param $format string The format to check
126 * @return bool Whether the format is supported
128 public function isSupportedFormat( $format );
131 * Convenience method for serializing this Content object.
133 * Shorthand for $this->getContentHandler()->serializeContent( $this, $format )
137 * @param $format null|string The desired serialization format (or null for
138 * the default format).
139 * @return string Serialized form of this Content object
141 public function serialize( $format = null );
144 * Returns true if this Content object represents empty content.
148 * @return bool Whether this Content object is empty
150 public function isEmpty();
153 * Returns whether the content is valid. This is intended for local validity
154 * checks, not considering global consistency.
156 * Content needs to be valid before it can be saved.
158 * This default implementation always returns true.
164 public function isValid();
167 * Returns true if this Content objects is conceptually equivalent to the
168 * given Content object.
172 * - Will return false if $that is null.
173 * - Will return true if $that === $this.
174 * - Will return false if $that->getModelName() != $this->getModel().
175 * - Will return false if $that->getNativeData() is not equal to $this->getNativeData(),
176 * where the meaning of "equal" depends on the actual data model.
178 * Implementations should be careful to make equals() transitive and reflexive:
180 * - $a->equals( $b ) <=> $b->equals( $a )
181 * - $a->equals( $b ) && $b->equals( $c ) ==> $a->equals( $c )
185 * @param $that Content The Content object to compare to
186 * @return bool True if this Content object is equal to $that, false otherwise.
188 public function equals( Content
$that = null );
191 * Return a copy of this Content object. The following must be true for the
194 * if $copy = $original->copy()
196 * - get_class($original) === get_class($copy)
197 * - $original->getModel() === $copy->getModel()
198 * - $original->equals( $copy )
200 * If and only if the Content object is immutable, the copy() method can and
201 * should return $this. That is, $copy === $original may be true, but only
202 * for immutable content objects.
206 * @return Content. A copy of this object
208 public function copy( );
211 * Returns true if this content is countable as a "real" wiki page, provided
212 * that it's also in a countable location (e.g. a current revision in the
217 * @param $hasLinks Bool: If it is known whether this content contains
218 * links, provide this information here, to avoid redundant parsing to
222 public function isCountable( $hasLinks = null ) ;
225 * Convenience method, shorthand for
226 * $this->getContentHandler()->getParserOutput( $this, $title, $revId, $options, $generateHtml )
228 * @note: subclasses should NOT override this to provide custom rendering.
229 * Override ContentHandler::getParserOutput() instead!
231 * @param $title Title
233 * @param $options null|ParserOptions
234 * @param $generateHtml Boolean Whether to generate HTML (default: true).
235 * If false, the result of calling getText() on the ParserOutput object
236 * returned by this method is undefined.
240 * @return ParserOutput
242 public function getParserOutput( Title
$title, $revId = null, ParserOptions
$options = null,
243 $generateHtml = true );
246 * Construct the redirect destination from this content and return an
247 * array of Titles, or null if this content doesn't represent a redirect.
248 * The last element in the array is the final destination after all redirects
249 * have been resolved (up to $wgMaxRedirects times).
253 * @return Array of Titles, with the destination last
255 public function getRedirectChain();
258 * Construct the redirect destination from this content and return a Title,
259 * or null if this content doesn't represent a redirect.
260 * This will only return the immediate redirect target, useful for
261 * the redirect table and other checks that don't need full recursion.
265 * @return Title: The corresponding Title
267 public function getRedirectTarget();
270 * Construct the redirect destination from this content and return the
271 * Title, or null if this content doesn't represent a redirect.
273 * This will recurse down $wgMaxRedirects times or until a non-redirect
274 * target is hit in order to provide (hopefully) the Title of the final
275 * destination instead of another redirect.
277 * There is usually no need to override the default behaviour, subclasses that
278 * want to implement redirects should override getRedirectTarget().
284 public function getUltimateRedirectTarget();
287 * Returns whether this Content represents a redirect.
288 * Shorthand for getRedirectTarget() !== null.
294 public function isRedirect();
297 * Returns the section with the given ID.
301 * @param $sectionId string The section's ID, given as a numeric string.
302 * The ID "0" retrieves the section before the first heading, "1" the
303 * text between the first heading (included) and the second heading
305 * @return Content|Boolean|null The section, or false if no such section
306 * exist, or null if sections are not supported.
308 public function getSection( $sectionId );
311 * Replaces a section of the content and returns a Content object with the
316 * @param $section Empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
317 * @param $with Content: new content of the section
318 * @param $sectionTitle String: new section's subject, only if $section is 'new'
319 * @return string Complete article text, or null if error
321 public function replaceSection( $section, Content
$with, $sectionTitle = '' );
324 * Returns a Content object with pre-save transformations applied (or this
325 * object if no transformations apply).
329 * @param $title Title
331 * @param $popts null|ParserOptions
334 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts );
337 * Returns a new WikitextContent object with the given section heading
338 * prepended, if supported. The default implementation just returns this
339 * Content object unmodified, ignoring the section header.
343 * @param $header string
346 public function addSectionHeader( $header );
349 * Returns a Content object with preload transformations applied (or this
350 * object if no transformations apply).
354 * @param $title Title
355 * @param $popts null|ParserOptions
358 public function preloadTransform( Title
$title, ParserOptions
$popts );
360 # TODO: handle ImagePage and CategoryPage
361 # TODO: make sure we cover lucene search / wikisearch.
362 # TODO: make sure ReplaceTemplates still works
363 # FUTURE: nice&sane integration of GeSHi syntax highlighting
364 # [11:59] <vvv> Hooks are ugly; make CodeHighlighter interface and a
365 # config to set the class which handles syntax highlighting
366 # [12:00] <vvv> And default it to a DummyHighlighter
368 # TODO: make sure we cover the external editor interface (does anyone actually use that?!)
370 # TODO: tie into API to provide contentModel for Revisions
371 # TODO: tie into API to provide serialized version and contentFormat for Revisions
372 # TODO: tie into API edit interface
373 # FUTURE: make EditForm plugin for EditPage
375 # FUTURE: special type for redirects?!
376 # FUTURE: MultipartMultipart < WikipageContent (Main + Links + X)
377 # FUTURE: LinksContent < LanguageLinksContent, CategoriesContent
379 // @TODO: add support for ar_content_format, ar_content_model,
380 // rev_content_format, rev_content_model to API
385 * A content object represents page content, e.g. the text to show on a page.
386 * Content objects have no knowledge about how they relate to Wiki pages.
390 abstract class AbstractContent
implements Content
{
393 * Name of the content model this Content object represents.
394 * Use with CONTENT_MODEL_XXX constants
396 * @var string $model_id
401 * @param $model_id int
403 public function __construct( $model_id = null ) {
404 $this->model_id
= $model_id;
408 * @see Content::getModel()
410 public function getModel() {
411 return $this->model_id
;
415 * Throws an MWException if $model_id is not the id of the content model
416 * supported by this Content object.
418 * @param $model_id int the model to check
420 * @throws MWException
422 protected function checkModelID( $model_id ) {
423 if ( $model_id !== $this->model_id
) {
424 $model_name = ContentHandler
::getContentModelName( $model_id );
425 $own_model_name = ContentHandler
::getContentModelName( $this->model_id
);
427 throw new MWException( "Bad content model: " .
428 "expected {$this->model_id} ($own_model_name) " .
429 "but got $model_id ($model_name)." );
434 * @see Content::getContentHandler()
436 public function getContentHandler() {
437 return ContentHandler
::getForContent( $this );
441 * @see Content::getDefaultFormat()
443 public function getDefaultFormat() {
444 return $this->getContentHandler()->getDefaultFormat();
448 * @see Content::getSupportedFormats()
450 public function getSupportedFormats() {
451 return $this->getContentHandler()->getSupportedFormats();
455 * @see Content::isSupportedFormat()
457 public function isSupportedFormat( $format ) {
459 return true; // this means "use the default"
462 return $this->getContentHandler()->isSupportedFormat( $format );
466 * Throws an MWException if $this->isSupportedFormat( $format ) doesn't
470 * @throws MWException
472 protected function checkFormat( $format ) {
473 if ( !$this->isSupportedFormat( $format ) ) {
474 throw new MWException( "Format $format is not supported for content model " .
480 * @see Content::serialize
482 public function serialize( $format = null ) {
483 return $this->getContentHandler()->serializeContent( $this, $format );
487 * @see Content::isEmpty()
489 public function isEmpty() {
490 return $this->getSize() == 0;
494 * @see Content::isValid()
496 public function isValid() {
501 * @see Content::equals()
503 public function equals( Content
$that = null ) {
504 if ( is_null( $that ) ) {
508 if ( $that === $this ) {
512 if ( $that->getModel() !== $this->getModel() ) {
516 return $this->getNativeData() === $that->getNativeData();
520 * @see Content::getParserOutput()
522 public function getParserOutput( Title
$title, $revId = null, ParserOptions
$options = null,
523 $generateHtml = true )
525 return $this->getContentHandler()->getParserOutput(
526 $this, $title, $revId, $options, $generateHtml );
530 * @see Content::getRedirectChain()
532 public function getRedirectChain() {
533 global $wgMaxRedirects;
534 $title = $this->getRedirectTarget();
535 if ( is_null( $title ) ) {
538 // recursive check to follow double redirects
539 $recurse = $wgMaxRedirects;
540 $titles = array( $title );
541 while ( --$recurse > 0 ) {
542 if ( $title->isRedirect() ) {
543 $page = WikiPage
::factory( $title );
544 $newtitle = $page->getRedirectTarget();
548 // Redirects to some special pages are not permitted
549 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
550 // The new title passes the checks, so make that our current
551 // title so that further recursion can be checked
553 $titles[] = $newtitle;
562 * @see Content::getRedirectTarget()
564 public function getRedirectTarget() {
569 * @see Content::getUltimateRedirectTarget()
570 * @note: migrated here from Title::newFromRedirectRecurse
572 public function getUltimateRedirectTarget() {
573 $titles = $this->getRedirectChain();
574 return $titles ?
array_pop( $titles ) : null;
582 public function isRedirect() {
583 return $this->getRedirectTarget() !== null;
587 * @see Content::getSection()
589 public function getSection( $sectionId ) {
594 * @see Content::replaceSection()
596 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
601 * @see Content::preSaveTransform()
603 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
608 * @see Content::addSectionHeader()
610 public function addSectionHeader( $header ) {
615 * @see Content::preloadTransform()
617 public function preloadTransform( Title
$title, ParserOptions
$popts ) {
623 * Content object implementation for representing flat text.
625 * TextContent instances are immutable
629 abstract class TextContent
extends AbstractContent
{
631 public function __construct( $text, $model_id = null ) {
632 parent
::__construct( $model_id );
634 $this->mText
= $text;
637 public function copy() {
638 return $this; # NOTE: this is ok since TextContent are immutable.
641 public function getTextForSummary( $maxlength = 250 ) {
644 $text = $this->getNativeData();
646 $truncatedtext = $wgContLang->truncate(
647 preg_replace( "/[\n\r]/", ' ', $text ),
648 max( 0, $maxlength ) );
650 return $truncatedtext;
654 * returns the text's size in bytes.
656 * @return int The size
658 public function getSize( ) {
659 $text = $this->getNativeData( );
660 return strlen( $text );
664 * Returns true if this content is not a redirect, and $wgArticleCountMethod
667 * @param $hasLinks Bool: if it is known whether this content contains links,
668 * provide this information here, to avoid redundant parsing to find out.
670 * @return bool True if the content is countable
672 public function isCountable( $hasLinks = null ) {
673 global $wgArticleCountMethod;
675 if ( $this->isRedirect( ) ) {
679 if ( $wgArticleCountMethod === 'any' ) {
687 * Returns the text represented by this Content object, as a string.
689 * @param the raw text
691 public function getNativeData( ) {
692 $text = $this->mText
;
697 * Returns the text represented by this Content object, as a string.
699 * @param the raw text
701 public function getTextForSearchIndex( ) {
702 return $this->getNativeData();
706 * Returns the text represented by this Content object, as a string.
708 * @param the raw text
710 public function getWikitextForTransclusion( ) {
711 return $this->getNativeData();
715 * Diff this content object with another content object..
719 * @param $that Content the other content object to compare this content object to
720 * @param $lang Language the language object to use for text segmentation.
721 * If not given, $wgContentLang is used.
723 * @return DiffResult a diff representing the changes that would have to be
724 * made to this content object to make it equal to $that.
726 public function diff( Content
$that, Language
$lang = null ) {
729 $this->checkModelID( $that->getModel() );
731 # @todo: could implement this in DifferenceEngine and just delegate here?
733 if ( !$lang ) $lang = $wgContLang;
735 $otext = $this->getNativeData();
736 $ntext = $this->getNativeData();
738 # Note: Use native PHP diff, external engines don't give us abstract output
739 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
740 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
742 $diff = new Diff( $ota, $nta );
752 class WikitextContent
extends TextContent
{
754 public function __construct( $text ) {
755 parent
::__construct( $text, CONTENT_MODEL_WIKITEXT
);
759 * @see Content::getSection()
761 public function getSection( $section ) {
764 $text = $this->getNativeData();
765 $sect = $wgParser->getSection( $text, $section, false );
767 return new WikitextContent( $sect );
771 * @see Content::replaceSection()
773 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
774 wfProfileIn( __METHOD__
);
776 $myModelId = $this->getModel();
777 $sectionModelId = $with->getModel();
779 if ( $sectionModelId != $myModelId ) {
780 $myModelName = ContentHandler
::getContentModelName( $myModelId );
781 $sectionModelName = ContentHandler
::getContentModelName( $sectionModelId );
783 throw new MWException( "Incompatible content model for section: " .
784 "document uses $myModelId ($myModelName), " .
785 "section uses $sectionModelId ($sectionModelName)." );
788 $oldtext = $this->getNativeData();
789 $text = $with->getNativeData();
791 if ( $section === '' ) {
792 return $with; # XXX: copy first?
793 } if ( $section == 'new' ) {
794 # Inserting a new section
795 if ( $sectionTitle ) {
796 $subject = wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n";
800 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
801 $text = strlen( trim( $oldtext ) ) > 0
802 ?
"{$oldtext}\n\n{$subject}{$text}"
803 : "{$subject}{$text}";
806 # Replacing an existing section; roll out the big guns
809 $text = $wgParser->replaceSection( $oldtext, $section, $text );
812 $newContent = new WikitextContent( $text );
814 wfProfileOut( __METHOD__
);
819 * Returns a new WikitextContent object with the given section heading
822 * @param $header string
825 public function addSectionHeader( $header ) {
826 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $header ) . "\n\n" .
827 $this->getNativeData();
829 return new WikitextContent( $text );
833 * Returns a Content object with pre-save transformations applied using
834 * Parser::preSaveTransform().
836 * @param $title Title
838 * @param $popts ParserOptions
841 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
844 $text = $this->getNativeData();
845 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
847 return new WikitextContent( $pst );
851 * Returns a Content object with preload transformations applied (or this
852 * object if no transformations apply).
854 * @param $title Title
855 * @param $popts ParserOptions
858 public function preloadTransform( Title
$title, ParserOptions
$popts ) {
861 $text = $this->getNativeData();
862 $plt = $wgParser->getPreloadText( $text, $title, $popts );
864 return new WikitextContent( $plt );
868 * Implement redirect extraction for wikitext.
872 * @note: migrated here from Title::newFromRedirectInternal()
874 * @see Content::getRedirectTarget
875 * @see AbstractContent::getRedirectTarget
877 public function getRedirectTarget() {
878 global $wgMaxRedirects;
879 if ( $wgMaxRedirects < 1 ) {
880 // redirects are disabled, so quit early
883 $redir = MagicWord
::get( 'redirect' );
884 $text = trim( $this->getNativeData() );
885 if ( $redir->matchStartAndRemove( $text ) ) {
886 // Extract the first link and see if it's usable
887 // Ensure that it really does come directly after #REDIRECT
888 // Some older redirects included a colon, so don't freak about that!
890 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
891 // Strip preceding colon used to "escape" categories, etc.
892 // and URL-decode links
893 if ( strpos( $m[1], '%' ) !== false ) {
894 // Match behavior of inline link parsing here;
895 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
897 $title = Title
::newFromText( $m[1] );
898 // If the title is a redirect to bad special pages or is invalid, return null
899 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
909 * Returns true if this content is not a redirect, and this content's text
910 * is countable according to the criteria defined by $wgArticleCountMethod.
912 * @param $hasLinks Bool if it is known whether this content contains
913 * links, provide this information here, to avoid redundant parsing to
915 * @param $title null|\Title
917 * @internal param \IContextSource $context context for parsing if necessary
919 * @return bool True if the content is countable
921 public function isCountable( $hasLinks = null, Title
$title = null ) {
922 global $wgArticleCountMethod;
924 if ( $this->isRedirect( ) ) {
928 $text = $this->getNativeData();
930 switch ( $wgArticleCountMethod ) {
934 return strpos( $text, ',' ) !== false;
936 if ( $hasLinks === null ) { # not known, find out
938 $context = RequestContext
::getMain();
939 $title = $context->getTitle();
942 $po = $this->getParserOutput( $title, null, null, false );
943 $links = $po->getLinks();
944 $hasLinks = !empty( $links );
953 public function getTextForSummary( $maxlength = 250 ) {
954 $truncatedtext = parent
::getTextForSummary( $maxlength );
956 # clean up unfinished links
957 # XXX: make this optional? wasn't there in autosummary, but required for
959 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
961 return $truncatedtext;
969 class MessageContent
extends TextContent
{
970 public function __construct( $msg_key, $params = null, $options = null ) {
971 # XXX: messages may be wikitext, html or plain text! and maybe even
972 # something else entirely.
973 parent
::__construct( null, CONTENT_MODEL_WIKITEXT
);
975 $this->mMessageKey
= $msg_key;
977 $this->mParameters
= $params;
979 if ( is_null( $options ) ) {
982 elseif ( is_string( $options ) ) {
983 $options = array( $options );
986 $this->mOptions
= $options;
990 * Returns the message as rendered HTML, using the options supplied to the
991 * constructor plus "parse".
992 * @param the message text, parsed
994 public function getHtml( ) {
995 $opt = array_merge( $this->mOptions
, array( 'parse' ) );
997 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
1002 * Returns the message as raw text, using the options supplied to the
1003 * constructor minus "parse" and "parseinline".
1005 * @param the message text, unparsed.
1007 public function getNativeData( ) {
1008 $opt = array_diff( $this->mOptions
, array( 'parse', 'parseinline' ) );
1010 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
1018 class JavaScriptContent
extends TextContent
{
1019 public function __construct( $text ) {
1020 parent
::__construct( $text, CONTENT_MODEL_JAVASCRIPT
);
1024 * Returns a Content object with pre-save transformations applied using
1025 * Parser::preSaveTransform().
1027 * @param Title $title
1029 * @param ParserOptions $popts
1032 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
1034 // @todo: make pre-save transformation optional for script pages
1037 $text = $this->getNativeData();
1038 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
1040 return new JavaScriptContent( $pst );
1048 class CssContent
extends TextContent
{
1049 public function __construct( $text ) {
1050 parent
::__construct( $text, CONTENT_MODEL_CSS
);
1054 * Returns a Content object with pre-save transformations applied using
1055 * Parser::preSaveTransform().
1057 * @param $title Title
1059 * @param $popts ParserOptions
1062 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
1064 // @todo: make pre-save transformation optional for script pages
1066 $text = $this->getNativeData();
1067 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
1069 return new CssContent( $pst );