161289c7d2694c439e10b39405eff1181c5b621b
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 String 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()
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
382 * A content object represents page content, e.g. the text to show on a page.
383 * Content objects have no knowledge about how they relate to Wiki pages.
387 abstract class AbstractContent
implements Content
{
390 * Name of the content model this Content object represents.
391 * Use with CONTENT_MODEL_XXX constants
393 * @var string $model_id
398 * @param String $model_id
400 public function __construct( $model_id = null ) {
401 $this->model_id
= $model_id;
405 * @see Content::getModel()
407 public function getModel() {
408 return $this->model_id
;
412 * Throws an MWException if $model_id is not the id of the content model
413 * supported by this Content object.
415 * @param $model_id int the model to check
417 * @throws MWException
419 protected function checkModelID( $model_id ) {
420 if ( $model_id !== $this->model_id
) {
421 throw new MWException( "Bad content model: " .
422 "expected {$this->model_id} " .
423 "but got $model_id." );
428 * @see Content::getContentHandler()
430 public function getContentHandler() {
431 return ContentHandler
::getForContent( $this );
435 * @see Content::getDefaultFormat()
437 public function getDefaultFormat() {
438 return $this->getContentHandler()->getDefaultFormat();
442 * @see Content::getSupportedFormats()
444 public function getSupportedFormats() {
445 return $this->getContentHandler()->getSupportedFormats();
449 * @see Content::isSupportedFormat()
451 public function isSupportedFormat( $format ) {
453 return true; // this means "use the default"
456 return $this->getContentHandler()->isSupportedFormat( $format );
460 * Throws an MWException if $this->isSupportedFormat( $format ) doesn't
464 * @throws MWException
466 protected function checkFormat( $format ) {
467 if ( !$this->isSupportedFormat( $format ) ) {
468 throw new MWException( "Format $format is not supported for content model " .
474 * @see Content::serialize
476 public function serialize( $format = null ) {
477 return $this->getContentHandler()->serializeContent( $this, $format );
481 * @see Content::isEmpty()
483 public function isEmpty() {
484 return $this->getSize() == 0;
488 * @see Content::isValid()
490 public function isValid() {
495 * @see Content::equals()
497 public function equals( Content
$that = null ) {
498 if ( is_null( $that ) ) {
502 if ( $that === $this ) {
506 if ( $that->getModel() !== $this->getModel() ) {
510 return $this->getNativeData() === $that->getNativeData();
514 * @see Content::getParserOutput()
516 public function getParserOutput( Title
$title, $revId = null, ParserOptions
$options = null,
517 $generateHtml = true )
519 return $this->getContentHandler()->getParserOutput(
520 $this, $title, $revId, $options, $generateHtml );
524 * @see Content::getRedirectChain()
526 public function getRedirectChain() {
527 global $wgMaxRedirects;
528 $title = $this->getRedirectTarget();
529 if ( is_null( $title ) ) {
532 // recursive check to follow double redirects
533 $recurse = $wgMaxRedirects;
534 $titles = array( $title );
535 while ( --$recurse > 0 ) {
536 if ( $title->isRedirect() ) {
537 $page = WikiPage
::factory( $title );
538 $newtitle = $page->getRedirectTarget();
542 // Redirects to some special pages are not permitted
543 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
544 // The new title passes the checks, so make that our current
545 // title so that further recursion can be checked
547 $titles[] = $newtitle;
556 * @see Content::getRedirectTarget()
558 public function getRedirectTarget() {
563 * @see Content::getUltimateRedirectTarget()
564 * @note: migrated here from Title::newFromRedirectRecurse
566 public function getUltimateRedirectTarget() {
567 $titles = $this->getRedirectChain();
568 return $titles ?
array_pop( $titles ) : null;
576 public function isRedirect() {
577 return $this->getRedirectTarget() !== null;
581 * @see Content::getSection()
583 public function getSection( $sectionId ) {
588 * @see Content::replaceSection()
590 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
595 * @see Content::preSaveTransform()
597 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
602 * @see Content::addSectionHeader()
604 public function addSectionHeader( $header ) {
609 * @see Content::preloadTransform()
611 public function preloadTransform( Title
$title, ParserOptions
$popts ) {
617 * Content object implementation for representing flat text.
619 * TextContent instances are immutable
623 abstract class TextContent
extends AbstractContent
{
625 public function __construct( $text, $model_id = null ) {
626 parent
::__construct( $model_id );
628 $this->mText
= $text;
631 public function copy() {
632 return $this; # NOTE: this is ok since TextContent are immutable.
635 public function getTextForSummary( $maxlength = 250 ) {
638 $text = $this->getNativeData();
640 $truncatedtext = $wgContLang->truncate(
641 preg_replace( "/[\n\r]/", ' ', $text ),
642 max( 0, $maxlength ) );
644 return $truncatedtext;
648 * returns the text's size in bytes.
650 * @return int The size
652 public function getSize( ) {
653 $text = $this->getNativeData( );
654 return strlen( $text );
658 * Returns true if this content is not a redirect, and $wgArticleCountMethod
661 * @param $hasLinks Bool: if it is known whether this content contains links,
662 * provide this information here, to avoid redundant parsing to find out.
664 * @return bool True if the content is countable
666 public function isCountable( $hasLinks = null ) {
667 global $wgArticleCountMethod;
669 if ( $this->isRedirect( ) ) {
673 if ( $wgArticleCountMethod === 'any' ) {
681 * Returns the text represented by this Content object, as a string.
683 * @param the raw text
685 public function getNativeData( ) {
686 $text = $this->mText
;
691 * Returns the text represented by this Content object, as a string.
693 * @param the raw text
695 public function getTextForSearchIndex( ) {
696 return $this->getNativeData();
700 * Returns the text represented by this Content object, as a string.
702 * @param the raw text
704 public function getWikitextForTransclusion( ) {
705 return $this->getNativeData();
709 * Diff this content object with another content object..
713 * @param $that Content the other content object to compare this content object to
714 * @param $lang Language the language object to use for text segmentation.
715 * If not given, $wgContentLang is used.
717 * @return DiffResult a diff representing the changes that would have to be
718 * made to this content object to make it equal to $that.
720 public function diff( Content
$that, Language
$lang = null ) {
723 $this->checkModelID( $that->getModel() );
725 # @todo: could implement this in DifferenceEngine and just delegate here?
727 if ( !$lang ) $lang = $wgContLang;
729 $otext = $this->getNativeData();
730 $ntext = $this->getNativeData();
732 # Note: Use native PHP diff, external engines don't give us abstract output
733 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
734 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
736 $diff = new Diff( $ota, $nta );
746 class WikitextContent
extends TextContent
{
748 public function __construct( $text ) {
749 parent
::__construct( $text, CONTENT_MODEL_WIKITEXT
);
753 * @see Content::getSection()
755 public function getSection( $section ) {
758 $text = $this->getNativeData();
759 $sect = $wgParser->getSection( $text, $section, false );
761 return new WikitextContent( $sect );
765 * @see Content::replaceSection()
767 public function replaceSection( $section, Content
$with, $sectionTitle = '' ) {
768 wfProfileIn( __METHOD__
);
770 $myModelId = $this->getModel();
771 $sectionModelId = $with->getModel();
773 if ( $sectionModelId != $myModelId ) {
774 throw new MWException( "Incompatible content model for section: " .
775 "document uses $myModelId but " .
776 "section uses $sectionModelId." );
779 $oldtext = $this->getNativeData();
780 $text = $with->getNativeData();
782 if ( $section === '' ) {
783 return $with; # XXX: copy first?
784 } if ( $section == 'new' ) {
785 # Inserting a new section
786 if ( $sectionTitle ) {
787 $subject = wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n";
791 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
792 $text = strlen( trim( $oldtext ) ) > 0
793 ?
"{$oldtext}\n\n{$subject}{$text}"
794 : "{$subject}{$text}";
797 # Replacing an existing section; roll out the big guns
800 $text = $wgParser->replaceSection( $oldtext, $section, $text );
803 $newContent = new WikitextContent( $text );
805 wfProfileOut( __METHOD__
);
810 * Returns a new WikitextContent object with the given section heading
813 * @param $header string
816 public function addSectionHeader( $header ) {
817 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $header ) . "\n\n" .
818 $this->getNativeData();
820 return new WikitextContent( $text );
824 * Returns a Content object with pre-save transformations applied using
825 * Parser::preSaveTransform().
827 * @param $title Title
829 * @param $popts ParserOptions
832 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
835 $text = $this->getNativeData();
836 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
838 return new WikitextContent( $pst );
842 * Returns a Content object with preload transformations applied (or this
843 * object if no transformations apply).
845 * @param $title Title
846 * @param $popts ParserOptions
849 public function preloadTransform( Title
$title, ParserOptions
$popts ) {
852 $text = $this->getNativeData();
853 $plt = $wgParser->getPreloadText( $text, $title, $popts );
855 return new WikitextContent( $plt );
859 * Implement redirect extraction for wikitext.
863 * @note: migrated here from Title::newFromRedirectInternal()
865 * @see Content::getRedirectTarget
866 * @see AbstractContent::getRedirectTarget
868 public function getRedirectTarget() {
869 global $wgMaxRedirects;
870 if ( $wgMaxRedirects < 1 ) {
871 // redirects are disabled, so quit early
874 $redir = MagicWord
::get( 'redirect' );
875 $text = trim( $this->getNativeData() );
876 if ( $redir->matchStartAndRemove( $text ) ) {
877 // Extract the first link and see if it's usable
878 // Ensure that it really does come directly after #REDIRECT
879 // Some older redirects included a colon, so don't freak about that!
881 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
882 // Strip preceding colon used to "escape" categories, etc.
883 // and URL-decode links
884 if ( strpos( $m[1], '%' ) !== false ) {
885 // Match behavior of inline link parsing here;
886 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
888 $title = Title
::newFromText( $m[1] );
889 // If the title is a redirect to bad special pages or is invalid, return null
890 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
900 * Returns true if this content is not a redirect, and this content's text
901 * is countable according to the criteria defined by $wgArticleCountMethod.
903 * @param $hasLinks Bool if it is known whether this content contains
904 * links, provide this information here, to avoid redundant parsing to
906 * @param $title null|\Title
908 * @internal param \IContextSource $context context for parsing if necessary
910 * @return bool True if the content is countable
912 public function isCountable( $hasLinks = null, Title
$title = null ) {
913 global $wgArticleCountMethod;
915 if ( $this->isRedirect( ) ) {
919 $text = $this->getNativeData();
921 switch ( $wgArticleCountMethod ) {
925 return strpos( $text, ',' ) !== false;
927 if ( $hasLinks === null ) { # not known, find out
929 $context = RequestContext
::getMain();
930 $title = $context->getTitle();
933 $po = $this->getParserOutput( $title, null, null, false );
934 $links = $po->getLinks();
935 $hasLinks = !empty( $links );
944 public function getTextForSummary( $maxlength = 250 ) {
945 $truncatedtext = parent
::getTextForSummary( $maxlength );
947 # clean up unfinished links
948 # XXX: make this optional? wasn't there in autosummary, but required for
950 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
952 return $truncatedtext;
960 class MessageContent
extends TextContent
{
961 public function __construct( $msg_key, $params = null, $options = null ) {
962 # XXX: messages may be wikitext, html or plain text! and maybe even
963 # something else entirely.
964 parent
::__construct( null, CONTENT_MODEL_WIKITEXT
);
966 $this->mMessageKey
= $msg_key;
968 $this->mParameters
= $params;
970 if ( is_null( $options ) ) {
973 elseif ( is_string( $options ) ) {
974 $options = array( $options );
977 $this->mOptions
= $options;
981 * Returns the message as rendered HTML, using the options supplied to the
982 * constructor plus "parse".
983 * @param the message text, parsed
985 public function getHtml( ) {
986 $opt = array_merge( $this->mOptions
, array( 'parse' ) );
988 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
993 * Returns the message as raw text, using the options supplied to the
994 * constructor minus "parse" and "parseinline".
996 * @param the message text, unparsed.
998 public function getNativeData( ) {
999 $opt = array_diff( $this->mOptions
, array( 'parse', 'parseinline' ) );
1001 return wfMsgExt( $this->mMessageKey
, $this->mParameters
, $opt );
1009 class JavaScriptContent
extends TextContent
{
1010 public function __construct( $text ) {
1011 parent
::__construct( $text, CONTENT_MODEL_JAVASCRIPT
);
1015 * Returns a Content object with pre-save transformations applied using
1016 * Parser::preSaveTransform().
1018 * @param Title $title
1020 * @param ParserOptions $popts
1023 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
1025 // @todo: make pre-save transformation optional for script pages
1028 $text = $this->getNativeData();
1029 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
1031 return new JavaScriptContent( $pst );
1039 class CssContent
extends TextContent
{
1040 public function __construct( $text ) {
1041 parent
::__construct( $text, CONTENT_MODEL_CSS
);
1045 * Returns a Content object with pre-save transformations applied using
1046 * Parser::preSaveTransform().
1048 * @param $title Title
1050 * @param $popts ParserOptions
1053 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
1055 // @todo: make pre-save transformation optional for script pages
1057 $text = $this->getNativeData();
1058 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
1060 return new CssContent( $pst );